_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
c0887a018df278705002c7c57360d5e3e3c426f4147e768c9cddfa7c8eeb2c87
cmsc430/www
compile-ops.rkt
#lang racket (provide (all-defined-out)) (require "ast.rkt" "types.rkt" "utils.rkt" a86/ast) (define rax 'rax) ; return 32 - bit load / store (define rbx 'rbx) ; heap (define rdi 'rdi) ; arg1 (define rsi 'rsi) ; arg2 (define rdx 'rdx) ; arg3 (define r8 'r8) ; scratch (define r9 'r9) ; scratch (define r10 'r10) ; scratch (define r12 'r12) ; save across call to memcpy (define r15 'r15) ; stack pad (non-volatile) (define rsp 'rsp) ; stack ;; Op0 -> Asm (define (compile-op0 p) (match p ['void (seq (Mov rax val-void))] ['read-byte (seq pad-stack (Call 'read_byte) unpad-stack)] ['peek-byte (seq pad-stack (Call 'peek_byte) unpad-stack)])) ;; Op1 -> Asm (define (compile-op1 p) (match p ['add1 (seq (assert-integer rax) (Add rax (imm->bits 1)))] ['sub1 (seq (assert-integer rax) (Sub rax (imm->bits 1)))] ['zero? (seq (assert-integer rax) (eq-imm 0))] ['char? (type-pred mask-char type-char)] ['char->integer (seq (assert-char rax) (Sar rax char-shift) (Sal rax int-shift))] ['integer->char (seq (assert-codepoint rax) (Sar rax int-shift) (Sal rax char-shift) (Xor rax type-char))] ['eof-object? (eq-imm eof)] ['write-byte (seq (assert-byte rax) pad-stack (Mov rdi rax) (Call 'write_byte) unpad-stack (Mov rax val-void))] ['box (seq (Mov (Offset rbx 0) rax) (Mov rax rbx) (Or rax type-box) (Add rbx 8))] ['unbox (seq (assert-box rax) (Xor rax type-box) (Mov rax (Offset rax 0)))] ['car (seq (assert-cons rax) (Xor rax type-cons) (Mov rax (Offset rax 8)))] ['cdr (seq (assert-cons rax) (Xor rax type-cons) (Mov rax (Offset rax 0)))] ['empty? (eq-imm '())] ['box? (type-pred ptr-mask type-box)] ['cons? (type-pred ptr-mask type-cons)] ['vector? (type-pred ptr-mask type-vect)] ['string? (type-pred ptr-mask type-str)] ['symbol? (type-pred ptr-mask type-symb)] ['vector-length (let ((zero (gensym)) (done (gensym))) (seq (assert-vector rax) (Xor rax type-vect) (Cmp rax 0) (Je zero) (Mov rax (Offset rax 0)) (Sal rax int-shift) (Jmp done) (Label zero) (Mov rax 0) (Label done)))] ['string-length (let ((zero (gensym)) (done (gensym))) (seq (assert-string rax) (Xor rax type-str) (Cmp rax 0) (Je zero) (Mov rax (Offset rax 0)) (Sal rax int-shift) (Jmp done) (Label zero) (Mov rax 0) (Label done)))] ['string->symbol (seq (assert-string rax) (Xor rax type-str) (Mov rdi rax) pad-stack (Call 'intern_symbol) unpad-stack (Or rax type-symb))] ['symbol->string (seq (assert-symbol rax) (Xor rax type-symb) char-array-copy (Or rax type-str))] ['string->uninterned-symbol (seq (assert-string rax) (Xor rax type-str) char-array-copy (Or rax type-symb))])) ;; Asm ;; Copy sized array of characters pointed to by rax (define char-array-copy (seq (Mov rdi rbx) ; dst (Mov rsi rax) ; src (Mov rdx (Offset rax 0)) ; len (Add rdx 1) ; #words = 1 + (len+1)/2 (Sar rdx 1) (Add rdx 1) # bytes = 8*#words save rdx before destroyed pad-stack (Call 'memcpy) unpad-stack ; rbx should be preserved by memcpy ;(Mov rbx rax) ; dst is returned, install as heap pointer (Add rbx r12))) ;; Op2 -> Asm (define (compile-op2 p) (match p ['+ (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Add rax r8))] ['- (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Sub r8 rax) (Mov rax r8))] ['< (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Cmp r8 rax) (Mov rax val-true) (let ((true (gensym))) (seq (Jl true) (Mov rax val-false) (Label true))))] ['= (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Cmp r8 rax) (Mov rax val-true) (let ((true (gensym))) (seq (Je true) (Mov rax val-false) (Label true))))] ['cons (seq (Mov (Offset rbx 0) rax) (Pop rax) (Mov (Offset rbx 8) rax) (Mov rax rbx) (Or rax type-cons) (Add rbx 16))] ['eq? (seq (Pop r8) (eq r8 rax))] ['make-vector (let ((loop (gensym)) (done (gensym)) (empty (gensym))) (seq (Pop r8) (assert-natural r8) (Cmp r8 0) ; special case empty vector (Je empty) (Mov r9 rbx) (Or r9 type-vect) (Sar r8 int-shift) (Mov (Offset rbx 0) r8) (Add rbx 8) (Label loop) (Mov (Offset rbx 0) rax) (Add rbx 8) (Sub r8 1) (Cmp r8 0) (Jne loop) (Mov rax r9) (Jmp done) (Label empty) (Mov rax type-vect) (Label done)))] ['vector-ref (seq (Pop r8) (assert-vector r8) (assert-integer rax) (Cmp r8 type-vect) (Je 'raise_error_align) ; special case for empty vector (Cmp rax 0) (Jl 'raise_error_align) (Xor r8 type-vect) ; r8 = ptr (Mov r9 (Offset r8 0)) ; r9 = len (Sar rax int-shift) ; rax = index (Sub r9 1) (Cmp r9 rax) (Jl 'raise_error_align) (Sal rax 3) (Add r8 rax) (Mov rax (Offset r8 8)))] ['make-string (let ((loop (gensym)) (done (gensym)) (empty (gensym))) (seq (Pop r8) (assert-natural r8) (assert-char rax) (Cmp r8 0) ; special case empty string (Je empty) (Mov r9 rbx) (Or r9 type-str) (Sar r8 int-shift) (Mov (Offset rbx 0) r8) (Add rbx 8) (Sar rax char-shift) adds 1 (Sar r8 1) ; when (Sal r8 1) ; len is odd (Label loop) (Mov (Offset rbx 0) eax) (Add rbx 4) (Sub r8 1) (Cmp r8 0) (Jne loop) (Mov rax r9) (Jmp done) (Label empty) (Mov rax type-str) (Label done)))] ['string-ref (seq (Pop r8) (assert-string r8) (assert-integer rax) (Cmp r8 type-str) (Je 'raise_error_align) ; special case for empty string (Cmp rax 0) (Jl 'raise_error_align) (Xor r8 type-str) ; r8 = ptr (Mov r9 (Offset r8 0)) ; r9 = len (Sar rax int-shift) ; rax = index (Sub r9 1) (Cmp r9 rax) (Jl 'raise_error_align) (Sal rax 2) (Add r8 rax) (Mov 'eax (Offset r8 8)) (Sal rax char-shift) (Or rax type-char))])) ;; Op3 -> Asm (define (compile-op3 p) (match p ['vector-set! (seq (Pop r10) (Pop r8) (assert-vector r8) (assert-integer r10) (Cmp r10 0) (Jl 'raise_error_align) (Xor r8 type-vect) ; r8 = ptr (Mov r9 (Offset r8 0)) ; r9 = len (Sar r10 int-shift) ; r10 = index (Sub r9 1) (Cmp r9 r10) (Jl 'raise_error_align) (Sal r10 3) (Add r8 r10) (Mov (Offset r8 8) rax) (Mov rax val-void))])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (assert-type mask type) (λ (arg) (seq (Mov r9 arg) (And r9 mask) (Cmp r9 type) (Jne 'raise_error_align)))) (define (type-pred mask type) (let ((l (gensym))) (seq (And rax mask) (Cmp rax type) (Mov rax (imm->bits #t)) (Je l) (Mov rax (imm->bits #f)) (Label l)))) (define assert-integer (assert-type mask-int type-int)) (define assert-char (assert-type mask-char type-char)) (define assert-box (assert-type ptr-mask type-box)) (define assert-cons (assert-type ptr-mask type-cons)) (define assert-vector (assert-type ptr-mask type-vect)) (define assert-string (assert-type ptr-mask type-str)) (define assert-symbol (assert-type ptr-mask type-symb)) (define assert-proc (assert-type ptr-mask type-proc)) (define (assert-codepoint r) (let ((ok (gensym))) (seq (assert-integer r) (Cmp r (imm->bits 0)) (Jl 'raise_error_align) (Cmp r (imm->bits 1114111)) (Jg 'raise_error_align) (Cmp r (imm->bits 55295)) (Jl ok) (Cmp r (imm->bits 57344)) (Jg ok) (Jmp 'raise_error_align) (Label ok)))) (define (assert-byte r) (seq (assert-integer r) (Cmp r (imm->bits 0)) (Jl 'raise_error_align) (Cmp r (imm->bits 255)) (Jg 'raise_error_align))) (define (assert-natural r) (seq (assert-integer r) (Cmp r (imm->bits 0)) (Jl 'raise_error_align))) ;; Value -> Asm (define (eq-imm imm) (let ((l1 (gensym))) (seq (Cmp rax (imm->bits imm)) (Mov rax val-true) (Je l1) (Mov rax val-false) (Label l1)))) (define (eq ir1 ir2) (let ((l1 (gensym))) (seq (Cmp ir1 ir2) (Mov rax val-true) (Je l1) (Mov rax val-false) (Label l1))))
null
https://raw.githubusercontent.com/cmsc430/www/264b7961b3b9490fdff253ffeded8d54fcb3f4d4/langs/mountebank/compile-ops.rkt
racket
return heap arg1 arg2 arg3 scratch scratch scratch save across call to memcpy stack pad (non-volatile) stack Op0 -> Asm Op1 -> Asm Asm Copy sized array of characters pointed to by rax dst src len #words = 1 + (len+1)/2 rbx should be preserved by memcpy (Mov rbx rax) ; dst is returned, install as heap pointer Op2 -> Asm special case empty vector special case for empty vector r8 = ptr r9 = len rax = index special case empty string when len is odd special case for empty string r8 = ptr r9 = len rax = index Op3 -> Asm r8 = ptr r9 = len r10 = index Value -> Asm
#lang racket (provide (all-defined-out)) (require "ast.rkt" "types.rkt" "utils.rkt" a86/ast) 32 - bit load / store (define (compile-op0 p) (match p ['void (seq (Mov rax val-void))] ['read-byte (seq pad-stack (Call 'read_byte) unpad-stack)] ['peek-byte (seq pad-stack (Call 'peek_byte) unpad-stack)])) (define (compile-op1 p) (match p ['add1 (seq (assert-integer rax) (Add rax (imm->bits 1)))] ['sub1 (seq (assert-integer rax) (Sub rax (imm->bits 1)))] ['zero? (seq (assert-integer rax) (eq-imm 0))] ['char? (type-pred mask-char type-char)] ['char->integer (seq (assert-char rax) (Sar rax char-shift) (Sal rax int-shift))] ['integer->char (seq (assert-codepoint rax) (Sar rax int-shift) (Sal rax char-shift) (Xor rax type-char))] ['eof-object? (eq-imm eof)] ['write-byte (seq (assert-byte rax) pad-stack (Mov rdi rax) (Call 'write_byte) unpad-stack (Mov rax val-void))] ['box (seq (Mov (Offset rbx 0) rax) (Mov rax rbx) (Or rax type-box) (Add rbx 8))] ['unbox (seq (assert-box rax) (Xor rax type-box) (Mov rax (Offset rax 0)))] ['car (seq (assert-cons rax) (Xor rax type-cons) (Mov rax (Offset rax 8)))] ['cdr (seq (assert-cons rax) (Xor rax type-cons) (Mov rax (Offset rax 0)))] ['empty? (eq-imm '())] ['box? (type-pred ptr-mask type-box)] ['cons? (type-pred ptr-mask type-cons)] ['vector? (type-pred ptr-mask type-vect)] ['string? (type-pred ptr-mask type-str)] ['symbol? (type-pred ptr-mask type-symb)] ['vector-length (let ((zero (gensym)) (done (gensym))) (seq (assert-vector rax) (Xor rax type-vect) (Cmp rax 0) (Je zero) (Mov rax (Offset rax 0)) (Sal rax int-shift) (Jmp done) (Label zero) (Mov rax 0) (Label done)))] ['string-length (let ((zero (gensym)) (done (gensym))) (seq (assert-string rax) (Xor rax type-str) (Cmp rax 0) (Je zero) (Mov rax (Offset rax 0)) (Sal rax int-shift) (Jmp done) (Label zero) (Mov rax 0) (Label done)))] ['string->symbol (seq (assert-string rax) (Xor rax type-str) (Mov rdi rax) pad-stack (Call 'intern_symbol) unpad-stack (Or rax type-symb))] ['symbol->string (seq (assert-symbol rax) (Xor rax type-symb) char-array-copy (Or rax type-str))] ['string->uninterned-symbol (seq (assert-string rax) (Xor rax type-str) char-array-copy (Or rax type-symb))])) (define char-array-copy (Sar rdx 1) (Add rdx 1) # bytes = 8*#words save rdx before destroyed pad-stack (Call 'memcpy) unpad-stack (Add rbx r12))) (define (compile-op2 p) (match p ['+ (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Add rax r8))] ['- (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Sub r8 rax) (Mov rax r8))] ['< (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Cmp r8 rax) (Mov rax val-true) (let ((true (gensym))) (seq (Jl true) (Mov rax val-false) (Label true))))] ['= (seq (Pop r8) (assert-integer r8) (assert-integer rax) (Cmp r8 rax) (Mov rax val-true) (let ((true (gensym))) (seq (Je true) (Mov rax val-false) (Label true))))] ['cons (seq (Mov (Offset rbx 0) rax) (Pop rax) (Mov (Offset rbx 8) rax) (Mov rax rbx) (Or rax type-cons) (Add rbx 16))] ['eq? (seq (Pop r8) (eq r8 rax))] ['make-vector (let ((loop (gensym)) (done (gensym)) (empty (gensym))) (seq (Pop r8) (assert-natural r8) (Je empty) (Mov r9 rbx) (Or r9 type-vect) (Sar r8 int-shift) (Mov (Offset rbx 0) r8) (Add rbx 8) (Label loop) (Mov (Offset rbx 0) rax) (Add rbx 8) (Sub r8 1) (Cmp r8 0) (Jne loop) (Mov rax r9) (Jmp done) (Label empty) (Mov rax type-vect) (Label done)))] ['vector-ref (seq (Pop r8) (assert-vector r8) (assert-integer rax) (Cmp r8 type-vect) (Cmp rax 0) (Jl 'raise_error_align) (Sub r9 1) (Cmp r9 rax) (Jl 'raise_error_align) (Sal rax 3) (Add r8 rax) (Mov rax (Offset r8 8)))] ['make-string (let ((loop (gensym)) (done (gensym)) (empty (gensym))) (seq (Pop r8) (assert-natural r8) (assert-char rax) (Je empty) (Mov r9 rbx) (Or r9 type-str) (Sar r8 int-shift) (Mov (Offset rbx 0) r8) (Add rbx 8) (Sar rax char-shift) adds 1 (Label loop) (Mov (Offset rbx 0) eax) (Add rbx 4) (Sub r8 1) (Cmp r8 0) (Jne loop) (Mov rax r9) (Jmp done) (Label empty) (Mov rax type-str) (Label done)))] ['string-ref (seq (Pop r8) (assert-string r8) (assert-integer rax) (Cmp r8 type-str) (Cmp rax 0) (Jl 'raise_error_align) (Sub r9 1) (Cmp r9 rax) (Jl 'raise_error_align) (Sal rax 2) (Add r8 rax) (Mov 'eax (Offset r8 8)) (Sal rax char-shift) (Or rax type-char))])) (define (compile-op3 p) (match p ['vector-set! (seq (Pop r10) (Pop r8) (assert-vector r8) (assert-integer r10) (Cmp r10 0) (Jl 'raise_error_align) (Sub r9 1) (Cmp r9 r10) (Jl 'raise_error_align) (Sal r10 3) (Add r8 r10) (Mov (Offset r8 8) rax) (Mov rax val-void))])) (define (assert-type mask type) (λ (arg) (seq (Mov r9 arg) (And r9 mask) (Cmp r9 type) (Jne 'raise_error_align)))) (define (type-pred mask type) (let ((l (gensym))) (seq (And rax mask) (Cmp rax type) (Mov rax (imm->bits #t)) (Je l) (Mov rax (imm->bits #f)) (Label l)))) (define assert-integer (assert-type mask-int type-int)) (define assert-char (assert-type mask-char type-char)) (define assert-box (assert-type ptr-mask type-box)) (define assert-cons (assert-type ptr-mask type-cons)) (define assert-vector (assert-type ptr-mask type-vect)) (define assert-string (assert-type ptr-mask type-str)) (define assert-symbol (assert-type ptr-mask type-symb)) (define assert-proc (assert-type ptr-mask type-proc)) (define (assert-codepoint r) (let ((ok (gensym))) (seq (assert-integer r) (Cmp r (imm->bits 0)) (Jl 'raise_error_align) (Cmp r (imm->bits 1114111)) (Jg 'raise_error_align) (Cmp r (imm->bits 55295)) (Jl ok) (Cmp r (imm->bits 57344)) (Jg ok) (Jmp 'raise_error_align) (Label ok)))) (define (assert-byte r) (seq (assert-integer r) (Cmp r (imm->bits 0)) (Jl 'raise_error_align) (Cmp r (imm->bits 255)) (Jg 'raise_error_align))) (define (assert-natural r) (seq (assert-integer r) (Cmp r (imm->bits 0)) (Jl 'raise_error_align))) (define (eq-imm imm) (let ((l1 (gensym))) (seq (Cmp rax (imm->bits imm)) (Mov rax val-true) (Je l1) (Mov rax val-false) (Label l1)))) (define (eq ir1 ir2) (let ((l1 (gensym))) (seq (Cmp ir1 ir2) (Mov rax val-true) (Je l1) (Mov rax val-false) (Label l1))))
6d5e6ba193cd468c096a7c4ef9cc0345c3ee9860d99d3423483b20aad946ae48
2600hz/kazoo
kzd_conferences.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kzd_conferences). -export([new/0]). -export([bridge_password/1, bridge_password/2, set_bridge_password/2]). -export([bridge_username/1, bridge_username/2, set_bridge_username/2]). -export([caller_controls/1, caller_controls/2, set_caller_controls/2]). -export([conference_numbers/1, conference_numbers/2, set_conference_numbers/2]). -export([controls/1, controls/2, set_controls/2]). -export([domain/1, domain/2, set_domain/2]). -export([flags/1, flags/2, set_flags/2]). -export([focus/1, focus/2, set_focus/2]). -export([language/1, language/2, set_language/2]). -export([max_members_media/1, max_members_media/2, set_max_members_media/2]). -export([max_participants/1, max_participants/2, set_max_participants/2]). -export([member/1, member/2, set_member/2]). -export([member_join_deaf/1, member_join_deaf/2, set_member_join_deaf/2]). -export([member_join_muted/1, member_join_muted/2, set_member_join_muted/2]). -export([member_numbers/1, member_numbers/2, set_member_numbers/2]). -export([member_pins/1, member_pins/2, set_member_pins/2]). -export([member_play_entry_prompt/1, member_play_entry_prompt/2, set_member_play_entry_prompt/2]). -export([moderator/1, moderator/2, set_moderator/2]). -export([moderator_join_deaf/1, moderator_join_deaf/2, set_moderator_join_deaf/2]). -export([moderator_join_muted/1, moderator_join_muted/2, set_moderator_join_muted/2]). -export([moderator_numbers/1, moderator_numbers/2, set_moderator_numbers/2]). -export([moderator_pins/1, moderator_pins/2, set_moderator_pins/2]). -export([moderator_controls/1, moderator_controls/2, set_moderator_controls/2]). -export([name/1, name/2, set_name/2]). -export([owner_id/1, owner_id/2, set_owner_id/2]). -export([play_entry_tone/1, play_entry_tone/2, set_play_entry_tone/2]). -export([play_exit_tone/1, play_exit_tone/2, set_play_exit_tone/2]). -export([play_name/1, play_name/2, set_play_name/2]). -export([play_welcome/1, play_welcome/2, set_play_welcome/2]). -export([profile/1, profile/2, set_profile/2]). -export([profile_name/1, profile_name/2, set_profile_name/2]). -export([require_moderator/1, require_moderator/2, set_require_moderator/2]). -export([wait_for_moderator/1, wait_for_moderator/2, set_wait_for_moderator/2]). -include("kz_documents.hrl"). -type doc() :: kz_json:object(). -export_type([doc/0]). -define(SCHEMA, <<"conferences">>). -spec new() -> doc(). new() -> kz_json_schema:default_object(?SCHEMA). -spec bridge_password(doc()) -> kz_term:api_binary(). bridge_password(Doc) -> bridge_password(Doc, 'undefined'). -spec bridge_password(doc(), Default) -> binary() | Default. bridge_password(Doc, Default) -> kz_json:get_binary_value([<<"bridge_password">>], Doc, Default). -spec set_bridge_password(doc(), binary()) -> doc(). set_bridge_password(Doc, BridgePassword) -> kz_json:set_value([<<"bridge_password">>], BridgePassword, Doc). -spec bridge_username(doc()) -> kz_term:api_binary(). bridge_username(Doc) -> bridge_username(Doc, 'undefined'). -spec bridge_username(doc(), Default) -> binary() | Default. bridge_username(Doc, Default) -> kz_json:get_binary_value([<<"bridge_username">>], Doc, Default). -spec set_bridge_username(doc(), binary()) -> doc(). set_bridge_username(Doc, BridgeUsername) -> kz_json:set_value([<<"bridge_username">>], BridgeUsername, Doc). -spec caller_controls(doc()) -> kz_term:api_binary(). caller_controls(Doc) -> caller_controls(Doc, 'undefined'). -spec caller_controls(doc(), Default) -> binary() | Default. caller_controls(Doc, Default) -> kz_json:get_binary_value([<<"caller_controls">>], Doc, Default). -spec set_caller_controls(doc(), binary()) -> doc(). set_caller_controls(Doc, CallerControls) -> kz_json:set_value([<<"caller_controls">>], CallerControls, Doc). -spec conference_numbers(doc()) -> kz_term:ne_binaries(). conference_numbers(Doc) -> conference_numbers(Doc, []). -spec conference_numbers(doc(), Default) -> kz_term:ne_binaries() | Default. conference_numbers(Doc, Default) -> kz_json:get_list_value([<<"conference_numbers">>], Doc, Default). -spec set_conference_numbers(doc(), kz_term:ne_binaries()) -> doc(). set_conference_numbers(Doc, ConferenceNumbers) -> kz_json:set_value([<<"conference_numbers">>], ConferenceNumbers, Doc). -spec controls(doc()) -> kz_term:api_object(). controls(Doc) -> controls(Doc, 'undefined'). -spec controls(doc(), Default) -> kz_json:object() | Default. controls(Doc, Default) -> kz_json:get_json_value([<<"controls">>], Doc, Default). -spec set_controls(doc(), kz_json:object()) -> doc(). set_controls(Doc, Controls) -> kz_json:set_value([<<"controls">>], Controls, Doc). -spec domain(doc()) -> kz_term:api_binary(). domain(Doc) -> domain(Doc, 'undefined'). -spec domain(doc(), Default) -> binary() | Default. domain(Doc, Default) -> kz_json:get_binary_value([<<"domain">>], Doc, Default). -spec set_domain(doc(), binary()) -> doc(). set_domain(Doc, Domain) -> kz_json:set_value([<<"domain">>], Domain, Doc). -spec flags(doc()) -> kz_term:api_ne_binaries(). flags(Doc) -> flags(Doc, 'undefined'). -spec flags(doc(), Default) -> kz_term:ne_binaries() | Default. flags(Doc, Default) -> kz_json:get_list_value([<<"flags">>], Doc, Default). -spec set_flags(doc(), kz_term:ne_binaries()) -> doc(). set_flags(Doc, Flags) -> kz_json:set_value([<<"flags">>], Flags, Doc). -spec focus(doc()) -> kz_term:api_binary(). focus(Doc) -> focus(Doc, 'undefined'). -spec focus(doc(), Default) -> binary() | Default. focus(Doc, Default) -> kz_json:get_binary_value([<<"focus">>], Doc, Default). -spec set_focus(doc(), binary()) -> doc(). set_focus(Doc, Focus) -> kz_json:set_value([<<"focus">>], Focus, Doc). -spec language(doc()) -> kz_term:api_binary(). language(Doc) -> language(Doc, 'undefined'). -spec language(doc(), Default) -> binary() | Default. language(Doc, Default) -> kz_json:get_binary_value([<<"language">>], Doc, Default). -spec set_language(doc(), binary()) -> doc(). set_language(Doc, Language) -> kz_json:set_value([<<"language">>], Language, Doc). -spec max_members_media(doc()) -> kz_term:api_binary(). max_members_media(Doc) -> max_members_media(Doc, 'undefined'). -spec max_members_media(doc(), Default) -> binary() | Default. max_members_media(Doc, Default) -> kz_json:get_binary_value([<<"max_members_media">>], Doc, Default). -spec set_max_members_media(doc(), binary()) -> doc(). set_max_members_media(Doc, MaxMembersMedia) -> kz_json:set_value([<<"max_members_media">>], MaxMembersMedia, Doc). -spec max_participants(doc()) -> kz_term:api_integer(). max_participants(Doc) -> max_participants(Doc, 'undefined'). -spec max_participants(doc(), Default) -> integer() | Default. max_participants(Doc, Default) -> kz_json:get_integer_value([<<"max_participants">>], Doc, Default). -spec set_max_participants(doc(), integer()) -> doc(). set_max_participants(Doc, MaxParticipants) -> kz_json:set_value([<<"max_participants">>], MaxParticipants, Doc). -spec member(doc()) -> kz_json:object(). member(Doc) -> member(Doc, kz_json:new()). -spec member(doc(), Default) -> kz_json:object() | Default. member(Doc, Default) -> kz_json:get_json_value([<<"member">>], Doc, Default). -spec set_member(doc(), kz_json:object()) -> doc(). set_member(Doc, Member) -> kz_json:set_value([<<"member">>], Member, Doc). -spec member_join_deaf(doc()) -> boolean(). member_join_deaf(Doc) -> member_join_deaf(Doc, false). -spec member_join_deaf(doc(), Default) -> boolean() | Default. member_join_deaf(Doc, Default) -> kz_json:get_boolean_value([<<"member">>, <<"join_deaf">>], Doc, Default). -spec set_member_join_deaf(doc(), boolean()) -> doc(). set_member_join_deaf(Doc, MemberJoinDeaf) -> kz_json:set_value([<<"member">>, <<"join_deaf">>], MemberJoinDeaf, Doc). -spec member_join_muted(doc()) -> boolean(). member_join_muted(Doc) -> member_join_muted(Doc, true). -spec member_join_muted(doc(), Default) -> boolean() | Default. member_join_muted(Doc, Default) -> kz_json:get_boolean_value([<<"member">>, <<"join_muted">>], Doc, Default). -spec set_member_join_muted(doc(), boolean()) -> doc(). set_member_join_muted(Doc, MemberJoinMuted) -> kz_json:set_value([<<"member">>, <<"join_muted">>], MemberJoinMuted, Doc). -spec member_numbers(doc()) -> kz_term:ne_binaries(). member_numbers(Doc) -> member_numbers(Doc, []). -spec member_numbers(doc(), Default) -> kz_term:ne_binaries() | Default. member_numbers(Doc, Default) -> kz_json:get_list_value([<<"member">>, <<"numbers">>], Doc, Default). -spec set_member_numbers(doc(), kz_term:ne_binaries()) -> doc(). set_member_numbers(Doc, MemberNumbers) -> kz_json:set_value([<<"member">>, <<"numbers">>], MemberNumbers, Doc). -spec member_pins(doc()) -> kz_term:ne_binaries(). member_pins(Doc) -> member_pins(Doc, []). -spec member_pins(doc(), Default) -> kz_term:ne_binaries() | Default. member_pins(Doc, Default) -> kz_json:get_list_value([<<"member">>, <<"pins">>], Doc, Default). -spec set_member_pins(doc(), kz_term:ne_binaries()) -> doc(). set_member_pins(Doc, MemberPins) -> kz_json:set_value([<<"member">>, <<"pins">>], MemberPins, Doc). -spec member_play_entry_prompt(doc()) -> kz_term:api_boolean(). member_play_entry_prompt(Doc) -> member_play_entry_prompt(Doc, 'undefined'). -spec member_play_entry_prompt(doc(), Default) -> boolean() | Default. member_play_entry_prompt(Doc, Default) -> kz_json:get_boolean_value([<<"member">>, <<"play_entry_prompt">>], Doc, Default). -spec set_member_play_entry_prompt(doc(), boolean()) -> doc(). set_member_play_entry_prompt(Doc, MemberPlayEntryPrompt) -> kz_json:set_value([<<"member">>, <<"play_entry_prompt">>], MemberPlayEntryPrompt, Doc). -spec moderator(doc()) -> kz_json:object(). moderator(Doc) -> moderator(Doc, kz_json:new()). -spec moderator(doc(), Default) -> kz_json:object() | Default. moderator(Doc, Default) -> kz_json:get_json_value([<<"moderator">>], Doc, Default). -spec set_moderator(doc(), kz_json:object()) -> doc(). set_moderator(Doc, Moderator) -> kz_json:set_value([<<"moderator">>], Moderator, Doc). -spec moderator_join_deaf(doc()) -> boolean(). moderator_join_deaf(Doc) -> moderator_join_deaf(Doc, false). -spec moderator_join_deaf(doc(), Default) -> boolean() | Default. moderator_join_deaf(Doc, Default) -> kz_json:get_boolean_value([<<"moderator">>, <<"join_deaf">>], Doc, Default). -spec set_moderator_join_deaf(doc(), boolean()) -> doc(). set_moderator_join_deaf(Doc, ModeratorJoinDeaf) -> kz_json:set_value([<<"moderator">>, <<"join_deaf">>], ModeratorJoinDeaf, Doc). -spec moderator_join_muted(doc()) -> boolean(). moderator_join_muted(Doc) -> moderator_join_muted(Doc, false). -spec moderator_join_muted(doc(), Default) -> boolean() | Default. moderator_join_muted(Doc, Default) -> kz_json:get_boolean_value([<<"moderator">>, <<"join_muted">>], Doc, Default). -spec set_moderator_join_muted(doc(), boolean()) -> doc(). set_moderator_join_muted(Doc, ModeratorJoinMuted) -> kz_json:set_value([<<"moderator">>, <<"join_muted">>], ModeratorJoinMuted, Doc). -spec moderator_numbers(doc()) -> kz_term:ne_binaries(). moderator_numbers(Doc) -> moderator_numbers(Doc, []). -spec moderator_numbers(doc(), Default) -> kz_term:ne_binaries() | Default. moderator_numbers(Doc, Default) -> kz_json:get_list_value([<<"moderator">>, <<"numbers">>], Doc, Default). -spec set_moderator_numbers(doc(), kz_term:ne_binaries()) -> doc(). set_moderator_numbers(Doc, ModeratorNumbers) -> kz_json:set_value([<<"moderator">>, <<"numbers">>], ModeratorNumbers, Doc). -spec moderator_pins(doc()) -> kz_term:ne_binaries(). moderator_pins(Doc) -> moderator_pins(Doc, []). -spec moderator_pins(doc(), Default) -> kz_term:ne_binaries() | Default. moderator_pins(Doc, Default) -> kz_json:get_list_value([<<"moderator">>, <<"pins">>], Doc, Default). -spec set_moderator_pins(doc(), kz_term:ne_binaries()) -> doc(). set_moderator_pins(Doc, ModeratorPins) -> kz_json:set_value([<<"moderator">>, <<"pins">>], ModeratorPins, Doc). -spec moderator_controls(doc()) -> kz_term:api_binary(). moderator_controls(Doc) -> moderator_controls(Doc, 'undefined'). -spec moderator_controls(doc(), Default) -> binary() | Default. moderator_controls(Doc, Default) -> kz_json:get_binary_value([<<"moderator_controls">>], Doc, Default). -spec set_moderator_controls(doc(), binary()) -> doc(). set_moderator_controls(Doc, ModeratorControls) -> kz_json:set_value([<<"moderator_controls">>], ModeratorControls, Doc). -spec name(doc()) -> kz_term:api_ne_binary(). name(Doc) -> name(Doc, 'undefined'). -spec name(doc(), Default) -> kz_term:ne_binary() | Default. name(Doc, Default) -> kz_json:get_ne_binary_value([<<"name">>], Doc, Default). -spec set_name(doc(), kz_term:ne_binary()) -> doc(). set_name(Doc, Name) -> kz_json:set_value([<<"name">>], Name, Doc). -spec owner_id(doc()) -> kz_term:api_ne_binary(). owner_id(Doc) -> owner_id(Doc, 'undefined'). -spec owner_id(doc(), Default) -> kz_term:ne_binary() | Default. owner_id(Doc, Default) -> kz_json:get_ne_binary_value([<<"owner_id">>], Doc, Default). -spec set_owner_id(doc(), kz_term:ne_binary()) -> doc(). set_owner_id(Doc, OwnerId) -> kz_json:set_value([<<"owner_id">>], OwnerId, Doc). -spec play_entry_tone(doc()) -> any(). play_entry_tone(Doc) -> play_entry_tone(Doc, 'undefined'). -spec play_entry_tone(doc(), Default) -> any() | Default. play_entry_tone(Doc, Default) -> kz_json:get_value([<<"play_entry_tone">>], Doc, Default). -spec set_play_entry_tone(doc(), any()) -> doc(). set_play_entry_tone(Doc, PlayEntryTone) -> kz_json:set_value([<<"play_entry_tone">>], PlayEntryTone, Doc). -spec play_exit_tone(doc()) -> any(). play_exit_tone(Doc) -> play_exit_tone(Doc, 'undefined'). -spec play_exit_tone(doc(), Default) -> any() | Default. play_exit_tone(Doc, Default) -> kz_json:get_value([<<"play_exit_tone">>], Doc, Default). -spec set_play_exit_tone(doc(), any()) -> doc(). set_play_exit_tone(Doc, PlayExitTone) -> kz_json:set_value([<<"play_exit_tone">>], PlayExitTone, Doc). -spec play_name(doc()) -> boolean(). play_name(Doc) -> play_name(Doc, false). -spec play_name(doc(), Default) -> boolean() | Default. play_name(Doc, Default) -> kz_json:get_boolean_value([<<"play_name">>], Doc, Default). -spec set_play_name(doc(), boolean()) -> doc(). set_play_name(Doc, PlayName) -> kz_json:set_value([<<"play_name">>], PlayName, Doc). -spec play_welcome(doc()) -> kz_term:api_boolean(). play_welcome(Doc) -> play_welcome(Doc, 'undefined'). -spec play_welcome(doc(), Default) -> boolean() | Default. play_welcome(Doc, Default) -> kz_json:get_boolean_value([<<"play_welcome">>], Doc, Default). -spec set_play_welcome(doc(), boolean()) -> doc(). set_play_welcome(Doc, PlayWelcome) -> kz_json:set_value([<<"play_welcome">>], PlayWelcome, Doc). -spec profile(doc()) -> kz_term:api_object(). profile(Doc) -> profile(Doc, 'undefined'). -spec profile(doc(), Default) -> kz_json:object() | Default. profile(Doc, Default) -> kz_json:get_json_value([<<"profile">>], Doc, Default). -spec set_profile(doc(), kz_json:object()) -> doc(). set_profile(Doc, Profile) -> kz_json:set_value([<<"profile">>], Profile, Doc). -spec profile_name(doc()) -> kz_term:api_binary(). profile_name(Doc) -> profile_name(Doc, 'undefined'). -spec profile_name(doc(), Default) -> binary() | Default. profile_name(Doc, Default) -> kz_json:get_binary_value([<<"profile_name">>], Doc, Default). -spec set_profile_name(doc(), binary()) -> doc(). set_profile_name(Doc, ProfileName) -> kz_json:set_value([<<"profile_name">>], ProfileName, Doc). -spec require_moderator(doc()) -> kz_term:api_boolean(). require_moderator(Doc) -> require_moderator(Doc, 'undefined'). -spec require_moderator(doc(), Default) -> boolean() | Default. require_moderator(Doc, Default) -> kz_json:get_boolean_value([<<"require_moderator">>], Doc, Default). -spec set_require_moderator(doc(), boolean()) -> doc(). set_require_moderator(Doc, RequireModerator) -> kz_json:set_value([<<"require_moderator">>], RequireModerator, Doc). -spec wait_for_moderator(doc()) -> kz_term:api_boolean(). wait_for_moderator(Doc) -> wait_for_moderator(Doc, 'undefined'). -spec wait_for_moderator(doc(), Default) -> boolean() | Default. wait_for_moderator(Doc, Default) -> kz_json:get_boolean_value([<<"wait_for_moderator">>], Doc, Default). -spec set_wait_for_moderator(doc(), boolean()) -> doc(). set_wait_for_moderator(Doc, WaitForModerator) -> kz_json:set_value([<<"wait_for_moderator">>], WaitForModerator, Doc).
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_documents/src/kzd_conferences.erl
erlang
----------------------------------------------------------------------------- @doc @end -----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(kzd_conferences). -export([new/0]). -export([bridge_password/1, bridge_password/2, set_bridge_password/2]). -export([bridge_username/1, bridge_username/2, set_bridge_username/2]). -export([caller_controls/1, caller_controls/2, set_caller_controls/2]). -export([conference_numbers/1, conference_numbers/2, set_conference_numbers/2]). -export([controls/1, controls/2, set_controls/2]). -export([domain/1, domain/2, set_domain/2]). -export([flags/1, flags/2, set_flags/2]). -export([focus/1, focus/2, set_focus/2]). -export([language/1, language/2, set_language/2]). -export([max_members_media/1, max_members_media/2, set_max_members_media/2]). -export([max_participants/1, max_participants/2, set_max_participants/2]). -export([member/1, member/2, set_member/2]). -export([member_join_deaf/1, member_join_deaf/2, set_member_join_deaf/2]). -export([member_join_muted/1, member_join_muted/2, set_member_join_muted/2]). -export([member_numbers/1, member_numbers/2, set_member_numbers/2]). -export([member_pins/1, member_pins/2, set_member_pins/2]). -export([member_play_entry_prompt/1, member_play_entry_prompt/2, set_member_play_entry_prompt/2]). -export([moderator/1, moderator/2, set_moderator/2]). -export([moderator_join_deaf/1, moderator_join_deaf/2, set_moderator_join_deaf/2]). -export([moderator_join_muted/1, moderator_join_muted/2, set_moderator_join_muted/2]). -export([moderator_numbers/1, moderator_numbers/2, set_moderator_numbers/2]). -export([moderator_pins/1, moderator_pins/2, set_moderator_pins/2]). -export([moderator_controls/1, moderator_controls/2, set_moderator_controls/2]). -export([name/1, name/2, set_name/2]). -export([owner_id/1, owner_id/2, set_owner_id/2]). -export([play_entry_tone/1, play_entry_tone/2, set_play_entry_tone/2]). -export([play_exit_tone/1, play_exit_tone/2, set_play_exit_tone/2]). -export([play_name/1, play_name/2, set_play_name/2]). -export([play_welcome/1, play_welcome/2, set_play_welcome/2]). -export([profile/1, profile/2, set_profile/2]). -export([profile_name/1, profile_name/2, set_profile_name/2]). -export([require_moderator/1, require_moderator/2, set_require_moderator/2]). -export([wait_for_moderator/1, wait_for_moderator/2, set_wait_for_moderator/2]). -include("kz_documents.hrl"). -type doc() :: kz_json:object(). -export_type([doc/0]). -define(SCHEMA, <<"conferences">>). -spec new() -> doc(). new() -> kz_json_schema:default_object(?SCHEMA). -spec bridge_password(doc()) -> kz_term:api_binary(). bridge_password(Doc) -> bridge_password(Doc, 'undefined'). -spec bridge_password(doc(), Default) -> binary() | Default. bridge_password(Doc, Default) -> kz_json:get_binary_value([<<"bridge_password">>], Doc, Default). -spec set_bridge_password(doc(), binary()) -> doc(). set_bridge_password(Doc, BridgePassword) -> kz_json:set_value([<<"bridge_password">>], BridgePassword, Doc). -spec bridge_username(doc()) -> kz_term:api_binary(). bridge_username(Doc) -> bridge_username(Doc, 'undefined'). -spec bridge_username(doc(), Default) -> binary() | Default. bridge_username(Doc, Default) -> kz_json:get_binary_value([<<"bridge_username">>], Doc, Default). -spec set_bridge_username(doc(), binary()) -> doc(). set_bridge_username(Doc, BridgeUsername) -> kz_json:set_value([<<"bridge_username">>], BridgeUsername, Doc). -spec caller_controls(doc()) -> kz_term:api_binary(). caller_controls(Doc) -> caller_controls(Doc, 'undefined'). -spec caller_controls(doc(), Default) -> binary() | Default. caller_controls(Doc, Default) -> kz_json:get_binary_value([<<"caller_controls">>], Doc, Default). -spec set_caller_controls(doc(), binary()) -> doc(). set_caller_controls(Doc, CallerControls) -> kz_json:set_value([<<"caller_controls">>], CallerControls, Doc). -spec conference_numbers(doc()) -> kz_term:ne_binaries(). conference_numbers(Doc) -> conference_numbers(Doc, []). -spec conference_numbers(doc(), Default) -> kz_term:ne_binaries() | Default. conference_numbers(Doc, Default) -> kz_json:get_list_value([<<"conference_numbers">>], Doc, Default). -spec set_conference_numbers(doc(), kz_term:ne_binaries()) -> doc(). set_conference_numbers(Doc, ConferenceNumbers) -> kz_json:set_value([<<"conference_numbers">>], ConferenceNumbers, Doc). -spec controls(doc()) -> kz_term:api_object(). controls(Doc) -> controls(Doc, 'undefined'). -spec controls(doc(), Default) -> kz_json:object() | Default. controls(Doc, Default) -> kz_json:get_json_value([<<"controls">>], Doc, Default). -spec set_controls(doc(), kz_json:object()) -> doc(). set_controls(Doc, Controls) -> kz_json:set_value([<<"controls">>], Controls, Doc). -spec domain(doc()) -> kz_term:api_binary(). domain(Doc) -> domain(Doc, 'undefined'). -spec domain(doc(), Default) -> binary() | Default. domain(Doc, Default) -> kz_json:get_binary_value([<<"domain">>], Doc, Default). -spec set_domain(doc(), binary()) -> doc(). set_domain(Doc, Domain) -> kz_json:set_value([<<"domain">>], Domain, Doc). -spec flags(doc()) -> kz_term:api_ne_binaries(). flags(Doc) -> flags(Doc, 'undefined'). -spec flags(doc(), Default) -> kz_term:ne_binaries() | Default. flags(Doc, Default) -> kz_json:get_list_value([<<"flags">>], Doc, Default). -spec set_flags(doc(), kz_term:ne_binaries()) -> doc(). set_flags(Doc, Flags) -> kz_json:set_value([<<"flags">>], Flags, Doc). -spec focus(doc()) -> kz_term:api_binary(). focus(Doc) -> focus(Doc, 'undefined'). -spec focus(doc(), Default) -> binary() | Default. focus(Doc, Default) -> kz_json:get_binary_value([<<"focus">>], Doc, Default). -spec set_focus(doc(), binary()) -> doc(). set_focus(Doc, Focus) -> kz_json:set_value([<<"focus">>], Focus, Doc). -spec language(doc()) -> kz_term:api_binary(). language(Doc) -> language(Doc, 'undefined'). -spec language(doc(), Default) -> binary() | Default. language(Doc, Default) -> kz_json:get_binary_value([<<"language">>], Doc, Default). -spec set_language(doc(), binary()) -> doc(). set_language(Doc, Language) -> kz_json:set_value([<<"language">>], Language, Doc). -spec max_members_media(doc()) -> kz_term:api_binary(). max_members_media(Doc) -> max_members_media(Doc, 'undefined'). -spec max_members_media(doc(), Default) -> binary() | Default. max_members_media(Doc, Default) -> kz_json:get_binary_value([<<"max_members_media">>], Doc, Default). -spec set_max_members_media(doc(), binary()) -> doc(). set_max_members_media(Doc, MaxMembersMedia) -> kz_json:set_value([<<"max_members_media">>], MaxMembersMedia, Doc). -spec max_participants(doc()) -> kz_term:api_integer(). max_participants(Doc) -> max_participants(Doc, 'undefined'). -spec max_participants(doc(), Default) -> integer() | Default. max_participants(Doc, Default) -> kz_json:get_integer_value([<<"max_participants">>], Doc, Default). -spec set_max_participants(doc(), integer()) -> doc(). set_max_participants(Doc, MaxParticipants) -> kz_json:set_value([<<"max_participants">>], MaxParticipants, Doc). -spec member(doc()) -> kz_json:object(). member(Doc) -> member(Doc, kz_json:new()). -spec member(doc(), Default) -> kz_json:object() | Default. member(Doc, Default) -> kz_json:get_json_value([<<"member">>], Doc, Default). -spec set_member(doc(), kz_json:object()) -> doc(). set_member(Doc, Member) -> kz_json:set_value([<<"member">>], Member, Doc). -spec member_join_deaf(doc()) -> boolean(). member_join_deaf(Doc) -> member_join_deaf(Doc, false). -spec member_join_deaf(doc(), Default) -> boolean() | Default. member_join_deaf(Doc, Default) -> kz_json:get_boolean_value([<<"member">>, <<"join_deaf">>], Doc, Default). -spec set_member_join_deaf(doc(), boolean()) -> doc(). set_member_join_deaf(Doc, MemberJoinDeaf) -> kz_json:set_value([<<"member">>, <<"join_deaf">>], MemberJoinDeaf, Doc). -spec member_join_muted(doc()) -> boolean(). member_join_muted(Doc) -> member_join_muted(Doc, true). -spec member_join_muted(doc(), Default) -> boolean() | Default. member_join_muted(Doc, Default) -> kz_json:get_boolean_value([<<"member">>, <<"join_muted">>], Doc, Default). -spec set_member_join_muted(doc(), boolean()) -> doc(). set_member_join_muted(Doc, MemberJoinMuted) -> kz_json:set_value([<<"member">>, <<"join_muted">>], MemberJoinMuted, Doc). -spec member_numbers(doc()) -> kz_term:ne_binaries(). member_numbers(Doc) -> member_numbers(Doc, []). -spec member_numbers(doc(), Default) -> kz_term:ne_binaries() | Default. member_numbers(Doc, Default) -> kz_json:get_list_value([<<"member">>, <<"numbers">>], Doc, Default). -spec set_member_numbers(doc(), kz_term:ne_binaries()) -> doc(). set_member_numbers(Doc, MemberNumbers) -> kz_json:set_value([<<"member">>, <<"numbers">>], MemberNumbers, Doc). -spec member_pins(doc()) -> kz_term:ne_binaries(). member_pins(Doc) -> member_pins(Doc, []). -spec member_pins(doc(), Default) -> kz_term:ne_binaries() | Default. member_pins(Doc, Default) -> kz_json:get_list_value([<<"member">>, <<"pins">>], Doc, Default). -spec set_member_pins(doc(), kz_term:ne_binaries()) -> doc(). set_member_pins(Doc, MemberPins) -> kz_json:set_value([<<"member">>, <<"pins">>], MemberPins, Doc). -spec member_play_entry_prompt(doc()) -> kz_term:api_boolean(). member_play_entry_prompt(Doc) -> member_play_entry_prompt(Doc, 'undefined'). -spec member_play_entry_prompt(doc(), Default) -> boolean() | Default. member_play_entry_prompt(Doc, Default) -> kz_json:get_boolean_value([<<"member">>, <<"play_entry_prompt">>], Doc, Default). -spec set_member_play_entry_prompt(doc(), boolean()) -> doc(). set_member_play_entry_prompt(Doc, MemberPlayEntryPrompt) -> kz_json:set_value([<<"member">>, <<"play_entry_prompt">>], MemberPlayEntryPrompt, Doc). -spec moderator(doc()) -> kz_json:object(). moderator(Doc) -> moderator(Doc, kz_json:new()). -spec moderator(doc(), Default) -> kz_json:object() | Default. moderator(Doc, Default) -> kz_json:get_json_value([<<"moderator">>], Doc, Default). -spec set_moderator(doc(), kz_json:object()) -> doc(). set_moderator(Doc, Moderator) -> kz_json:set_value([<<"moderator">>], Moderator, Doc). -spec moderator_join_deaf(doc()) -> boolean(). moderator_join_deaf(Doc) -> moderator_join_deaf(Doc, false). -spec moderator_join_deaf(doc(), Default) -> boolean() | Default. moderator_join_deaf(Doc, Default) -> kz_json:get_boolean_value([<<"moderator">>, <<"join_deaf">>], Doc, Default). -spec set_moderator_join_deaf(doc(), boolean()) -> doc(). set_moderator_join_deaf(Doc, ModeratorJoinDeaf) -> kz_json:set_value([<<"moderator">>, <<"join_deaf">>], ModeratorJoinDeaf, Doc). -spec moderator_join_muted(doc()) -> boolean(). moderator_join_muted(Doc) -> moderator_join_muted(Doc, false). -spec moderator_join_muted(doc(), Default) -> boolean() | Default. moderator_join_muted(Doc, Default) -> kz_json:get_boolean_value([<<"moderator">>, <<"join_muted">>], Doc, Default). -spec set_moderator_join_muted(doc(), boolean()) -> doc(). set_moderator_join_muted(Doc, ModeratorJoinMuted) -> kz_json:set_value([<<"moderator">>, <<"join_muted">>], ModeratorJoinMuted, Doc). -spec moderator_numbers(doc()) -> kz_term:ne_binaries(). moderator_numbers(Doc) -> moderator_numbers(Doc, []). -spec moderator_numbers(doc(), Default) -> kz_term:ne_binaries() | Default. moderator_numbers(Doc, Default) -> kz_json:get_list_value([<<"moderator">>, <<"numbers">>], Doc, Default). -spec set_moderator_numbers(doc(), kz_term:ne_binaries()) -> doc(). set_moderator_numbers(Doc, ModeratorNumbers) -> kz_json:set_value([<<"moderator">>, <<"numbers">>], ModeratorNumbers, Doc). -spec moderator_pins(doc()) -> kz_term:ne_binaries(). moderator_pins(Doc) -> moderator_pins(Doc, []). -spec moderator_pins(doc(), Default) -> kz_term:ne_binaries() | Default. moderator_pins(Doc, Default) -> kz_json:get_list_value([<<"moderator">>, <<"pins">>], Doc, Default). -spec set_moderator_pins(doc(), kz_term:ne_binaries()) -> doc(). set_moderator_pins(Doc, ModeratorPins) -> kz_json:set_value([<<"moderator">>, <<"pins">>], ModeratorPins, Doc). -spec moderator_controls(doc()) -> kz_term:api_binary(). moderator_controls(Doc) -> moderator_controls(Doc, 'undefined'). -spec moderator_controls(doc(), Default) -> binary() | Default. moderator_controls(Doc, Default) -> kz_json:get_binary_value([<<"moderator_controls">>], Doc, Default). -spec set_moderator_controls(doc(), binary()) -> doc(). set_moderator_controls(Doc, ModeratorControls) -> kz_json:set_value([<<"moderator_controls">>], ModeratorControls, Doc). -spec name(doc()) -> kz_term:api_ne_binary(). name(Doc) -> name(Doc, 'undefined'). -spec name(doc(), Default) -> kz_term:ne_binary() | Default. name(Doc, Default) -> kz_json:get_ne_binary_value([<<"name">>], Doc, Default). -spec set_name(doc(), kz_term:ne_binary()) -> doc(). set_name(Doc, Name) -> kz_json:set_value([<<"name">>], Name, Doc). -spec owner_id(doc()) -> kz_term:api_ne_binary(). owner_id(Doc) -> owner_id(Doc, 'undefined'). -spec owner_id(doc(), Default) -> kz_term:ne_binary() | Default. owner_id(Doc, Default) -> kz_json:get_ne_binary_value([<<"owner_id">>], Doc, Default). -spec set_owner_id(doc(), kz_term:ne_binary()) -> doc(). set_owner_id(Doc, OwnerId) -> kz_json:set_value([<<"owner_id">>], OwnerId, Doc). -spec play_entry_tone(doc()) -> any(). play_entry_tone(Doc) -> play_entry_tone(Doc, 'undefined'). -spec play_entry_tone(doc(), Default) -> any() | Default. play_entry_tone(Doc, Default) -> kz_json:get_value([<<"play_entry_tone">>], Doc, Default). -spec set_play_entry_tone(doc(), any()) -> doc(). set_play_entry_tone(Doc, PlayEntryTone) -> kz_json:set_value([<<"play_entry_tone">>], PlayEntryTone, Doc). -spec play_exit_tone(doc()) -> any(). play_exit_tone(Doc) -> play_exit_tone(Doc, 'undefined'). -spec play_exit_tone(doc(), Default) -> any() | Default. play_exit_tone(Doc, Default) -> kz_json:get_value([<<"play_exit_tone">>], Doc, Default). -spec set_play_exit_tone(doc(), any()) -> doc(). set_play_exit_tone(Doc, PlayExitTone) -> kz_json:set_value([<<"play_exit_tone">>], PlayExitTone, Doc). -spec play_name(doc()) -> boolean(). play_name(Doc) -> play_name(Doc, false). -spec play_name(doc(), Default) -> boolean() | Default. play_name(Doc, Default) -> kz_json:get_boolean_value([<<"play_name">>], Doc, Default). -spec set_play_name(doc(), boolean()) -> doc(). set_play_name(Doc, PlayName) -> kz_json:set_value([<<"play_name">>], PlayName, Doc). -spec play_welcome(doc()) -> kz_term:api_boolean(). play_welcome(Doc) -> play_welcome(Doc, 'undefined'). -spec play_welcome(doc(), Default) -> boolean() | Default. play_welcome(Doc, Default) -> kz_json:get_boolean_value([<<"play_welcome">>], Doc, Default). -spec set_play_welcome(doc(), boolean()) -> doc(). set_play_welcome(Doc, PlayWelcome) -> kz_json:set_value([<<"play_welcome">>], PlayWelcome, Doc). -spec profile(doc()) -> kz_term:api_object(). profile(Doc) -> profile(Doc, 'undefined'). -spec profile(doc(), Default) -> kz_json:object() | Default. profile(Doc, Default) -> kz_json:get_json_value([<<"profile">>], Doc, Default). -spec set_profile(doc(), kz_json:object()) -> doc(). set_profile(Doc, Profile) -> kz_json:set_value([<<"profile">>], Profile, Doc). -spec profile_name(doc()) -> kz_term:api_binary(). profile_name(Doc) -> profile_name(Doc, 'undefined'). -spec profile_name(doc(), Default) -> binary() | Default. profile_name(Doc, Default) -> kz_json:get_binary_value([<<"profile_name">>], Doc, Default). -spec set_profile_name(doc(), binary()) -> doc(). set_profile_name(Doc, ProfileName) -> kz_json:set_value([<<"profile_name">>], ProfileName, Doc). -spec require_moderator(doc()) -> kz_term:api_boolean(). require_moderator(Doc) -> require_moderator(Doc, 'undefined'). -spec require_moderator(doc(), Default) -> boolean() | Default. require_moderator(Doc, Default) -> kz_json:get_boolean_value([<<"require_moderator">>], Doc, Default). -spec set_require_moderator(doc(), boolean()) -> doc(). set_require_moderator(Doc, RequireModerator) -> kz_json:set_value([<<"require_moderator">>], RequireModerator, Doc). -spec wait_for_moderator(doc()) -> kz_term:api_boolean(). wait_for_moderator(Doc) -> wait_for_moderator(Doc, 'undefined'). -spec wait_for_moderator(doc(), Default) -> boolean() | Default. wait_for_moderator(Doc, Default) -> kz_json:get_boolean_value([<<"wait_for_moderator">>], Doc, Default). -spec set_wait_for_moderator(doc(), boolean()) -> doc(). set_wait_for_moderator(Doc, WaitForModerator) -> kz_json:set_value([<<"wait_for_moderator">>], WaitForModerator, Doc).
2a59ac799c73d9309b1a99d0fec9d5bd60b33cfd6918764bcec4f275a17596fe
finnishtransportagency/harja
raportti.cljs
(ns harja.ui.raportti "Harjan raporttielementtien HTML näyttäminen. Harjan raportit ovat Clojuren tietorakenteita, joissa käytetään tiettyä rakennetta ja tiettyjä avainsanoja. Nämä raportit annetaan eteenpäin moottoreille, jotka luovat tietorakenteen pohjalta raportin. Tärkeä yksityiskohta on, että raporttien olisi tarkoitus sisältää ns. raakaa dataa, ja antaa raportin formatoida data oikeaan muotoon sarakkeen :fmt tiedon perusteella. Tämä moottori luo selaimessa näytettävän raportin. Alla käytetään Harjan gridiä. Kuten muissakin raporteissa, tärkein metodi on :taulukko, jonne mm. voi lisätä tuen eri tavoilla formatoitaville sarakkeille." (:require [harja.ui.grid :as grid] [harja.ui.dom :as dom] [harja.ui.yleiset :as yleiset] [harja.ui.liitteet :as liitteet] [harja.visualisointi :as vis] [harja.domain.raportointi :as raportti-domain] [harja.loki :refer [log]] [harja.asiakas.kommunikaatio :as k] [harja.ui.modal :as modal] [harja.pvm :as pvm] [harja.fmt :as fmt] [harja.ui.aikajana :as aikajana] [harja.ui.ikonit :as ikonit] [clojure.string :as str] [harja.ui.kentat :as kentat])) (defmulti muodosta-html "Muodostaa Reagent komponentin annetulle raporttielementille." (fn [elementti] (if (raportti-domain/raporttielementti? elementti) (first elementti) :vain-arvo))) (defmethod muodosta-html :vain-arvo [arvo] arvo) (defmethod muodosta-html :arvo [[_ {:keys [arvo desimaalien-maara fmt ryhmitelty? jos-tyhja] :as elementti}]] [:span (if-not (nil? arvo) (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) fmt (fmt arvo) :else arvo) jos-tyhja)]) (defmethod muodosta-html :liitteet [[_ liitteet]] (liitteet/liitteet-numeroina liitteet)) (defmethod muodosta-html :arvo-ja-osuus [[_ {:keys [arvo osuus fmt]}]] [:span.arvo-ja-osuus [:span.arvo (if fmt (fmt arvo) arvo)] [:span " "] [:span.osuus (str "(" osuus "%)")]]) Tavallisesti raportin solujen raporteissa yksittäisen solun tyyli määritteessä (: sarakkeen - luokka ) . elementin syy on se , vaaditaan . Tämä on : elementin kanssa , . (defmethod muodosta-html :arvo-ja-yksikko-korostettu [[_ {:keys [arvo yksikko fmt desimaalien-maara ryhmitelty?]}]] [:span.arvo-ja-yksikko [:span.arvo (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) fmt (fmt arvo) :else arvo)] [:span.yksikko (str "\u00A0" yksikko)]]) (defmethod muodosta-html :arvo-ja-yksikko [[_ {:keys [arvo yksikko fmt desimaalien-maara ryhmitelty?]}]] [:span.arvo-ja-yksikko [:span.arvo (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) fmt (fmt arvo) :else arvo)] [:span.yksikko (str "\u00A0" yksikko)]]) (defmethod muodosta-html :arvo-ja-selite [[_ {:keys [arvo selite]}]] [:span.arvo-ja-yksikko [:span.arvo arvo] [:div.selite.small-caption selite]]) (defmethod muodosta-html :erotus-ja-prosentti [[_ {:keys [arvo prosentti desimaalien-maara ryhmitelty?]}]] (let [etuliite (cond (neg? arvo) "- " (zero? arvo) "" :else "+ ") arvo (Math/abs arvo) prosentti (Math/abs prosentti)] [:span.erotus-ja-prosentti [:span.arvo (str etuliite (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) :else arvo))] [:div.selite.small-caption {:style {:text-align :inherit}} (str "(" etuliite (fmt/prosentti-opt prosentti) ")")]])) (defmethod muodosta-html :teksti-ja-info [[_ {:keys [arvo info]}]] [:span.teksti-ja-info [:span.arvo (str arvo "\u00A0")] [yleiset/tooltip {:suunta :oikea :leveys :levea :wrapper-luokka "tooltip-wrapper" :wrapperin-koko {:leveys 20 :korkeus 20}} [ikonit/harja-icon-status-info] info]]) (defmethod muodosta-html :varillinen-teksti : varillinen - teksti elementtiä voidaan . näyttämiseen . käyttämään ennaltamääriteltyjä tyylejä , on erikoistapaus missä halutaan , voidaan : itsepaisesti - maaritelty - oma - vari [[_ {:keys [arvo tyyli itsepaisesti-maaritelty-oma-vari fmt]}]] [:span.varillinen-teksti [:span.arvo {:style {:color (or itsepaisesti-maaritelty-oma-vari (raportti-domain/virhetyylit tyyli) "rgb(25,25,25)")}} (if fmt (fmt arvo) arvo)]]) (defmethod muodosta-html :infopallura : infopallura elementtiä käytetään näyttämään tooltip tyyppisessä infokentässä [[_ {:keys [infoteksti]}]] [yleiset/wrap-if true [yleiset/tooltip {} :% infoteksti] [:span {:style {:padding-left "4px"}} (ikonit/livicon-info-sign)]]) (defn- formatoija-fmt-mukaan [fmt] (case fmt :kokonaisluku #(raportti-domain/yrita fmt/kokonaisluku-opt %) :numero #(raportti-domain/yrita fmt/desimaaliluku-opt % 2 true) :numero-3desim #(fmt/pyorista-ehka-kolmeen %) :prosentti #(raportti-domain/yrita fmt/prosentti-opt % 1) :prosentti-0desim #(raportti-domain/yrita fmt/prosentti-opt % 0) :raha #(raportti-domain/yrita fmt/euro-opt %) :pvm #(raportti-domain/yrita fmt/pvm-opt %) str)) (defmethod muodosta-html :taulukko [[_ {:keys [otsikko viimeinen-rivi-yhteenveto? rivi-ennen tyhja korosta-rivit korostustyyli oikealle-tasattavat-kentat vetolaatikot esta-tiivis-grid? avattavat-rivit sivuttain-rullattava? ensimmainen-sarake-sticky?]} sarakkeet data]] (let [oikealle-tasattavat-kentat (or oikealle-tasattavat-kentat #{})] [grid/grid {:otsikko (or otsikko "") :tunniste (fn [rivi] (str "raportti_rivi_" (or (::rivin-indeksi rivi) (hash rivi)))) :rivi-ennen rivi-ennen :avattavat-rivit avattavat-rivit :piilota-toiminnot? true :sivuttain-rullattava? sivuttain-rullattava? :ensimmainen-sarake-sticky? ensimmainen-sarake-sticky? :esta-tiivis-grid? esta-tiivis-grid?} (into [] (map-indexed (fn [i sarake] (let [raporttielementteja? (raportti-domain/sarakkeessa-raporttielementteja? i data) format-fn (formatoija-fmt-mukaan (:fmt sarake))] (merge {:hae #(get % i) :leveys (:leveys sarake) :otsikko (:otsikko sarake) :reunus (:reunus sarake) :pakota-rivitys? (:pakota-rivitys? sarake) :otsikkorivi-luokka (str (:otsikkorivi-luokka sarake) (case (:tasaa-otsikko sarake) :keskita " grid-header-keskita" :oikea " grid-header-oikea" "")) :solun-luokka (fn [arvo _rivi] on tässä nimiavaruudessa määritetty komponentti , olla avain : varoitus ? , solu punaisella taustalla ja tekstillä . (str (when (:varoitus? (and (vector? arvo) (second arvo))) " solu-varoitus ") (when (:korosta-hennosti? (and (vector? arvo) (second arvo))) " hennosti-korostettu-solu ") (when (true? (:ala-korosta? (and (vector? arvo) (second arvo)))) " solun-korostus-estetty "))) :luokka (:sarakkeen-luokka sarake) :nimi (str "sarake" i) :fmt format-fn Valtaosa raporttien sarakkeista on puhdasta tekstiä , poikkeukset komponentteja :tyyppi (cond (= (:tyyppi sarake) :vetolaatikon-tila) :vetolaatikon-tila (= (:tyyppi sarake) :avattava-rivi) :avattava-rivi raporttielementteja? :komponentti :else :string) :tasaa (if (or (oikealle-tasattavat-kentat i) (raportti-domain/numero-fmt? (:fmt sarake))) :oikea (:tasaa sarake))} (when raporttielementteja? {:komponentti (fn [rivi] (let [elementti (get rivi i) liite? (if (vector? elementti) (= :liitteet (first elementti)) Normaalisti komponenteissa toinen elementti on mappi , . (muodosta-html (if (and (raportti-domain/formatoi-solu? elementti) (not liite?)) (raportti-domain/raporttielementti-formatterilla elementti formatoija-fmt-mukaan (:fmt sarake)) elementti))))})))) sarakkeet)) (if (empty? data) [(grid/otsikko (or tyhja "Ei tietoja"))] (let [viimeinen-rivi (last data)] (into [] (map-indexed (fn [index rivi] (if-let [otsikko (:otsikko rivi)] (grid/otsikko otsikko) (let [[rivi optiot] (if (map? rivi) [(:rivi rivi) rivi] [rivi {}]) isanta-rivin-id (:isanta-rivin-id optiot) lihavoi? (:lihavoi? optiot) korosta? (:korosta? optiot) korosta-hennosti? (:korosta-hennosti? optiot) korosta-harmaa? (:korosta-harmaa? optiot) valkoinen? (:valkoinen? optiot) rivin-luokka (:rivin-luokka optiot) mappina (assoc (zipmap (range (count sarakkeet)) rivi) ::rivin-indeksi index)] (cond-> mappina (and viimeinen-rivi-yhteenveto? (= viimeinen-rivi rivi)) (assoc :yhteenveto true) korosta-hennosti? (assoc :korosta-hennosti true) korosta-harmaa? (assoc :korosta-harmaa true) valkoinen? (assoc :valkoinen true) (or korosta? (when korosta-rivit (korosta-rivit index))) (assoc :korosta true) lihavoi? (assoc :lihavoi true) rivin-luokka (assoc :rivin-luokka rivin-luokka) isanta-rivin-id (assoc :isanta-rivin-id isanta-rivin-id)))))) data)))])) (defmethod muodosta-html :otsikko [[_ teksti]] [:h3 teksti]) (defmethod muodosta-html :jakaja [_] [:hr {:style {:margin-top "30px" :margin-bottom "30px"}}]) (defmethod muodosta-html :otsikko-kuin-pylvaissa [[_ teksti]] [:h3 teksti]) (defmethod muodosta-html :teksti [[_ teksti {:keys [vari infopallura rivita?]}]] [:div {:style (merge {:color (when vari vari)} (when rivita? {:white-space "pre-line"}))} teksti (when infopallura (muodosta-html [:infopallura infopallura]))]) (defmethod muodosta-html :teksti-paksu [[_ teksti {:keys [vari infopallura]}]] [:div {:style {:font-weight 700 :color (when vari vari)}} teksti (when infopallura (muodosta-html [:infopallura infopallura]))]) (defmethod muodosta-html :varoitusteksti [[_ teksti]] (muodosta-html [:teksti teksti {:vari "#dd0000"}])) (defmethod muodosta-html :infolaatikko [[_ teksti {:keys [tyyppi toissijainen-viesti leveys rivita?]}]] (let [tyyppi (or tyyppi :neutraali)] [:div {:style (merge {:margin-bottom "1rem"} (when rivita? {:white-space "pre-line"}))} [yleiset/info-laatikko tyyppi teksti toissijainen-viesti leveys teksti]])) (defmethod muodosta-html :pylvaat [[_ {:keys [otsikko vari fmt piilota-arvo? legend]} pylvaat]] (let [w (int (* 0.85 @dom/leveys)) h (int (/ w 2.9))] [:div.pylvaat [:h3 otsikko] [vis/bars {:width w :height h :format-amount (or fmt str) :hide-value? piilota-arvo? :legend legend } pylvaat]])) (defmethod muodosta-html :piirakka [[_ {:keys [otsikko]} data]] [:div.pylvaat [:h3 otsikko] [vis/pie {:width 230 :height 150 :radius 60 :show-text :percent :show-legend true} data]]) (defmethod muodosta-html :yhteenveto [[_ otsikot-ja-arvot]] (apply yleiset/taulukkotietonakyma {} (mapcat identity otsikot-ja-arvot))) (defmethod muodosta-html :raportti [[_ raportin-tunnistetiedot & sisalto]] (log "muodosta html raportin-tunnistetiedot " (pr-str raportin-tunnistetiedot)) [:div.raportti {:class (:tunniste raportin-tunnistetiedot)} (when (:nimi raportin-tunnistetiedot) [:h3 (:nimi raportin-tunnistetiedot)]) (keep-indexed (fn [i elementti] (when elementti ^{:key i} [muodosta-html elementti])) (mapcat (fn [sisalto] (if (list? sisalto) sisalto [sisalto])) sisalto))]) (defmethod muodosta-html :aikajana [[_ optiot rivit]] (aikajana/aikajana optiot rivit)) (defmethod muodosta-html :boolean [[_ {:keys [arvo]}]] [:div.boolean (kentat/vayla-checkbox {:data arvo :input-id (str "harja-checkbox" (gensym)) :disabled? true read only tilan ero vain : ei ole " " . :arvo arvo})]) (defmethod muodosta-html :default [elementti] (log "HTML-raportti ei tue elementtiä: " elementti) nil)
null
https://raw.githubusercontent.com/finnishtransportagency/harja/d2c3efc456f459e72943c97c369d5391b57f5536/src/cljs/harja/ui/raportti.cljs
clojure
(ns harja.ui.raportti "Harjan raporttielementtien HTML näyttäminen. Harjan raportit ovat Clojuren tietorakenteita, joissa käytetään tiettyä rakennetta ja tiettyjä avainsanoja. Nämä raportit annetaan eteenpäin moottoreille, jotka luovat tietorakenteen pohjalta raportin. Tärkeä yksityiskohta on, että raporttien olisi tarkoitus sisältää ns. raakaa dataa, ja antaa raportin formatoida data oikeaan muotoon sarakkeen :fmt tiedon perusteella. Tämä moottori luo selaimessa näytettävän raportin. Alla käytetään Harjan gridiä. Kuten muissakin raporteissa, tärkein metodi on :taulukko, jonne mm. voi lisätä tuen eri tavoilla formatoitaville sarakkeille." (:require [harja.ui.grid :as grid] [harja.ui.dom :as dom] [harja.ui.yleiset :as yleiset] [harja.ui.liitteet :as liitteet] [harja.visualisointi :as vis] [harja.domain.raportointi :as raportti-domain] [harja.loki :refer [log]] [harja.asiakas.kommunikaatio :as k] [harja.ui.modal :as modal] [harja.pvm :as pvm] [harja.fmt :as fmt] [harja.ui.aikajana :as aikajana] [harja.ui.ikonit :as ikonit] [clojure.string :as str] [harja.ui.kentat :as kentat])) (defmulti muodosta-html "Muodostaa Reagent komponentin annetulle raporttielementille." (fn [elementti] (if (raportti-domain/raporttielementti? elementti) (first elementti) :vain-arvo))) (defmethod muodosta-html :vain-arvo [arvo] arvo) (defmethod muodosta-html :arvo [[_ {:keys [arvo desimaalien-maara fmt ryhmitelty? jos-tyhja] :as elementti}]] [:span (if-not (nil? arvo) (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) fmt (fmt arvo) :else arvo) jos-tyhja)]) (defmethod muodosta-html :liitteet [[_ liitteet]] (liitteet/liitteet-numeroina liitteet)) (defmethod muodosta-html :arvo-ja-osuus [[_ {:keys [arvo osuus fmt]}]] [:span.arvo-ja-osuus [:span.arvo (if fmt (fmt arvo) arvo)] [:span " "] [:span.osuus (str "(" osuus "%)")]]) Tavallisesti raportin solujen raporteissa yksittäisen solun tyyli määritteessä (: sarakkeen - luokka ) . elementin syy on se , vaaditaan . Tämä on : elementin kanssa , . (defmethod muodosta-html :arvo-ja-yksikko-korostettu [[_ {:keys [arvo yksikko fmt desimaalien-maara ryhmitelty?]}]] [:span.arvo-ja-yksikko [:span.arvo (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) fmt (fmt arvo) :else arvo)] [:span.yksikko (str "\u00A0" yksikko)]]) (defmethod muodosta-html :arvo-ja-yksikko [[_ {:keys [arvo yksikko fmt desimaalien-maara ryhmitelty?]}]] [:span.arvo-ja-yksikko [:span.arvo (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) fmt (fmt arvo) :else arvo)] [:span.yksikko (str "\u00A0" yksikko)]]) (defmethod muodosta-html :arvo-ja-selite [[_ {:keys [arvo selite]}]] [:span.arvo-ja-yksikko [:span.arvo arvo] [:div.selite.small-caption selite]]) (defmethod muodosta-html :erotus-ja-prosentti [[_ {:keys [arvo prosentti desimaalien-maara ryhmitelty?]}]] (let [etuliite (cond (neg? arvo) "- " (zero? arvo) "" :else "+ ") arvo (Math/abs arvo) prosentti (Math/abs prosentti)] [:span.erotus-ja-prosentti [:span.arvo (str etuliite (cond desimaalien-maara (fmt/desimaaliluku-opt arvo desimaalien-maara ryhmitelty?) :else arvo))] [:div.selite.small-caption {:style {:text-align :inherit}} (str "(" etuliite (fmt/prosentti-opt prosentti) ")")]])) (defmethod muodosta-html :teksti-ja-info [[_ {:keys [arvo info]}]] [:span.teksti-ja-info [:span.arvo (str arvo "\u00A0")] [yleiset/tooltip {:suunta :oikea :leveys :levea :wrapper-luokka "tooltip-wrapper" :wrapperin-koko {:leveys 20 :korkeus 20}} [ikonit/harja-icon-status-info] info]]) (defmethod muodosta-html :varillinen-teksti : varillinen - teksti elementtiä voidaan . näyttämiseen . käyttämään ennaltamääriteltyjä tyylejä , on erikoistapaus missä halutaan , voidaan : itsepaisesti - maaritelty - oma - vari [[_ {:keys [arvo tyyli itsepaisesti-maaritelty-oma-vari fmt]}]] [:span.varillinen-teksti [:span.arvo {:style {:color (or itsepaisesti-maaritelty-oma-vari (raportti-domain/virhetyylit tyyli) "rgb(25,25,25)")}} (if fmt (fmt arvo) arvo)]]) (defmethod muodosta-html :infopallura : infopallura elementtiä käytetään näyttämään tooltip tyyppisessä infokentässä [[_ {:keys [infoteksti]}]] [yleiset/wrap-if true [yleiset/tooltip {} :% infoteksti] [:span {:style {:padding-left "4px"}} (ikonit/livicon-info-sign)]]) (defn- formatoija-fmt-mukaan [fmt] (case fmt :kokonaisluku #(raportti-domain/yrita fmt/kokonaisluku-opt %) :numero #(raportti-domain/yrita fmt/desimaaliluku-opt % 2 true) :numero-3desim #(fmt/pyorista-ehka-kolmeen %) :prosentti #(raportti-domain/yrita fmt/prosentti-opt % 1) :prosentti-0desim #(raportti-domain/yrita fmt/prosentti-opt % 0) :raha #(raportti-domain/yrita fmt/euro-opt %) :pvm #(raportti-domain/yrita fmt/pvm-opt %) str)) (defmethod muodosta-html :taulukko [[_ {:keys [otsikko viimeinen-rivi-yhteenveto? rivi-ennen tyhja korosta-rivit korostustyyli oikealle-tasattavat-kentat vetolaatikot esta-tiivis-grid? avattavat-rivit sivuttain-rullattava? ensimmainen-sarake-sticky?]} sarakkeet data]] (let [oikealle-tasattavat-kentat (or oikealle-tasattavat-kentat #{})] [grid/grid {:otsikko (or otsikko "") :tunniste (fn [rivi] (str "raportti_rivi_" (or (::rivin-indeksi rivi) (hash rivi)))) :rivi-ennen rivi-ennen :avattavat-rivit avattavat-rivit :piilota-toiminnot? true :sivuttain-rullattava? sivuttain-rullattava? :ensimmainen-sarake-sticky? ensimmainen-sarake-sticky? :esta-tiivis-grid? esta-tiivis-grid?} (into [] (map-indexed (fn [i sarake] (let [raporttielementteja? (raportti-domain/sarakkeessa-raporttielementteja? i data) format-fn (formatoija-fmt-mukaan (:fmt sarake))] (merge {:hae #(get % i) :leveys (:leveys sarake) :otsikko (:otsikko sarake) :reunus (:reunus sarake) :pakota-rivitys? (:pakota-rivitys? sarake) :otsikkorivi-luokka (str (:otsikkorivi-luokka sarake) (case (:tasaa-otsikko sarake) :keskita " grid-header-keskita" :oikea " grid-header-oikea" "")) :solun-luokka (fn [arvo _rivi] on tässä nimiavaruudessa määritetty komponentti , olla avain : varoitus ? , solu punaisella taustalla ja tekstillä . (str (when (:varoitus? (and (vector? arvo) (second arvo))) " solu-varoitus ") (when (:korosta-hennosti? (and (vector? arvo) (second arvo))) " hennosti-korostettu-solu ") (when (true? (:ala-korosta? (and (vector? arvo) (second arvo)))) " solun-korostus-estetty "))) :luokka (:sarakkeen-luokka sarake) :nimi (str "sarake" i) :fmt format-fn Valtaosa raporttien sarakkeista on puhdasta tekstiä , poikkeukset komponentteja :tyyppi (cond (= (:tyyppi sarake) :vetolaatikon-tila) :vetolaatikon-tila (= (:tyyppi sarake) :avattava-rivi) :avattava-rivi raporttielementteja? :komponentti :else :string) :tasaa (if (or (oikealle-tasattavat-kentat i) (raportti-domain/numero-fmt? (:fmt sarake))) :oikea (:tasaa sarake))} (when raporttielementteja? {:komponentti (fn [rivi] (let [elementti (get rivi i) liite? (if (vector? elementti) (= :liitteet (first elementti)) Normaalisti komponenteissa toinen elementti on mappi , . (muodosta-html (if (and (raportti-domain/formatoi-solu? elementti) (not liite?)) (raportti-domain/raporttielementti-formatterilla elementti formatoija-fmt-mukaan (:fmt sarake)) elementti))))})))) sarakkeet)) (if (empty? data) [(grid/otsikko (or tyhja "Ei tietoja"))] (let [viimeinen-rivi (last data)] (into [] (map-indexed (fn [index rivi] (if-let [otsikko (:otsikko rivi)] (grid/otsikko otsikko) (let [[rivi optiot] (if (map? rivi) [(:rivi rivi) rivi] [rivi {}]) isanta-rivin-id (:isanta-rivin-id optiot) lihavoi? (:lihavoi? optiot) korosta? (:korosta? optiot) korosta-hennosti? (:korosta-hennosti? optiot) korosta-harmaa? (:korosta-harmaa? optiot) valkoinen? (:valkoinen? optiot) rivin-luokka (:rivin-luokka optiot) mappina (assoc (zipmap (range (count sarakkeet)) rivi) ::rivin-indeksi index)] (cond-> mappina (and viimeinen-rivi-yhteenveto? (= viimeinen-rivi rivi)) (assoc :yhteenveto true) korosta-hennosti? (assoc :korosta-hennosti true) korosta-harmaa? (assoc :korosta-harmaa true) valkoinen? (assoc :valkoinen true) (or korosta? (when korosta-rivit (korosta-rivit index))) (assoc :korosta true) lihavoi? (assoc :lihavoi true) rivin-luokka (assoc :rivin-luokka rivin-luokka) isanta-rivin-id (assoc :isanta-rivin-id isanta-rivin-id)))))) data)))])) (defmethod muodosta-html :otsikko [[_ teksti]] [:h3 teksti]) (defmethod muodosta-html :jakaja [_] [:hr {:style {:margin-top "30px" :margin-bottom "30px"}}]) (defmethod muodosta-html :otsikko-kuin-pylvaissa [[_ teksti]] [:h3 teksti]) (defmethod muodosta-html :teksti [[_ teksti {:keys [vari infopallura rivita?]}]] [:div {:style (merge {:color (when vari vari)} (when rivita? {:white-space "pre-line"}))} teksti (when infopallura (muodosta-html [:infopallura infopallura]))]) (defmethod muodosta-html :teksti-paksu [[_ teksti {:keys [vari infopallura]}]] [:div {:style {:font-weight 700 :color (when vari vari)}} teksti (when infopallura (muodosta-html [:infopallura infopallura]))]) (defmethod muodosta-html :varoitusteksti [[_ teksti]] (muodosta-html [:teksti teksti {:vari "#dd0000"}])) (defmethod muodosta-html :infolaatikko [[_ teksti {:keys [tyyppi toissijainen-viesti leveys rivita?]}]] (let [tyyppi (or tyyppi :neutraali)] [:div {:style (merge {:margin-bottom "1rem"} (when rivita? {:white-space "pre-line"}))} [yleiset/info-laatikko tyyppi teksti toissijainen-viesti leveys teksti]])) (defmethod muodosta-html :pylvaat [[_ {:keys [otsikko vari fmt piilota-arvo? legend]} pylvaat]] (let [w (int (* 0.85 @dom/leveys)) h (int (/ w 2.9))] [:div.pylvaat [:h3 otsikko] [vis/bars {:width w :height h :format-amount (or fmt str) :hide-value? piilota-arvo? :legend legend } pylvaat]])) (defmethod muodosta-html :piirakka [[_ {:keys [otsikko]} data]] [:div.pylvaat [:h3 otsikko] [vis/pie {:width 230 :height 150 :radius 60 :show-text :percent :show-legend true} data]]) (defmethod muodosta-html :yhteenveto [[_ otsikot-ja-arvot]] (apply yleiset/taulukkotietonakyma {} (mapcat identity otsikot-ja-arvot))) (defmethod muodosta-html :raportti [[_ raportin-tunnistetiedot & sisalto]] (log "muodosta html raportin-tunnistetiedot " (pr-str raportin-tunnistetiedot)) [:div.raportti {:class (:tunniste raportin-tunnistetiedot)} (when (:nimi raportin-tunnistetiedot) [:h3 (:nimi raportin-tunnistetiedot)]) (keep-indexed (fn [i elementti] (when elementti ^{:key i} [muodosta-html elementti])) (mapcat (fn [sisalto] (if (list? sisalto) sisalto [sisalto])) sisalto))]) (defmethod muodosta-html :aikajana [[_ optiot rivit]] (aikajana/aikajana optiot rivit)) (defmethod muodosta-html :boolean [[_ {:keys [arvo]}]] [:div.boolean (kentat/vayla-checkbox {:data arvo :input-id (str "harja-checkbox" (gensym)) :disabled? true read only tilan ero vain : ei ole " " . :arvo arvo})]) (defmethod muodosta-html :default [elementti] (log "HTML-raportti ei tue elementtiä: " elementti) nil)
247211d669f8069da373f4d265fbcb94eaef94ddbf74cec91b23bebb28a1ec2f
MinaProtocol/mina
call_response.ml
* This file has been generated by the OCamlClientCodegen generator for openapi - generator . * * Generated by : -generator.tech * * Schema Call_response.t : CallResponse contains the result of a ` /call ` invocation . * This file has been generated by the OCamlClientCodegen generator for openapi-generator. * * Generated by: -generator.tech * * Schema Call_response.t : CallResponse contains the result of a `/call` invocation. *) type t = Result contains the result of the ` /call ` invocation . This result will not be inspected or interpreted by Rosetta tooling and is left to the caller to decode . _result : Yojson.Safe.t Idempotent indicates that if ` /call ` is invoked with the same CallRequest again , at any point in time , it will return the same CallResponse . Integrators may cache the CallResponse if this is set to true to avoid making unnecessary calls to the Rosetta implementation . For this reason , implementers should be very conservative about returning true here or they could cause issues for the caller . idempotent : bool } [@@deriving yojson { strict = false }, show, eq] * CallResponse contains the result of a ` /call ` invocation . let create (_result : Yojson.Safe.t) (idempotent : bool) : t = { _result; idempotent }
null
https://raw.githubusercontent.com/MinaProtocol/mina/a80b00221953c26ff158e7375a948b5fa9e7bd8b/src/lib/rosetta_models/call_response.ml
ocaml
* This file has been generated by the OCamlClientCodegen generator for openapi - generator . * * Generated by : -generator.tech * * Schema Call_response.t : CallResponse contains the result of a ` /call ` invocation . * This file has been generated by the OCamlClientCodegen generator for openapi-generator. * * Generated by: -generator.tech * * Schema Call_response.t : CallResponse contains the result of a `/call` invocation. *) type t = Result contains the result of the ` /call ` invocation . This result will not be inspected or interpreted by Rosetta tooling and is left to the caller to decode . _result : Yojson.Safe.t Idempotent indicates that if ` /call ` is invoked with the same CallRequest again , at any point in time , it will return the same CallResponse . Integrators may cache the CallResponse if this is set to true to avoid making unnecessary calls to the Rosetta implementation . For this reason , implementers should be very conservative about returning true here or they could cause issues for the caller . idempotent : bool } [@@deriving yojson { strict = false }, show, eq] * CallResponse contains the result of a ` /call ` invocation . let create (_result : Yojson.Safe.t) (idempotent : bool) : t = { _result; idempotent }
e72f904f69c2385b74714918d7f4fd238543fa81275fa3715c25594c1c587d99
mlabs-haskell/plutus-pioneer-program
Solution.hs
# LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeOperators #-} module Week04.Solution where import Data.Aeson (FromJSON, ToJSON) import Data.Functor (void) import Data.Text (Text, unpack) import GHC.Generics (Generic) import Ledger import Ledger.Ada as Ada import Ledger.Constraints as Constraints import Plutus.Contract as Contract import Plutus.Trace.Emulator as Emulator import Wallet.Emulator.Wallet data PayParams = PayParams { ppRecipient :: PubKeyHash , ppLovelace :: Integer } deriving (Show, Generic, FromJSON, ToJSON) type PaySchema = BlockchainActions .\/ Endpoint "pay" PayParams payContract :: Contract () PaySchema Text () payContract = do pp <- endpoint @"pay" let tx = mustPayToPubKey (ppRecipient pp) $ lovelaceValueOf $ ppLovelace pp handleError (\err -> Contract.logInfo $ "caught error: " ++ unpack err) $ void $ submitTx tx payContract payTrace :: Integer -> Integer -> EmulatorTrace () payTrace x y = do h <- activateContractWallet (Wallet 1) payContract callEndpoint @"pay" h $ PayParams { ppRecipient = pubKeyHash $ walletPubKey $ Wallet 2 , ppLovelace = x } void $ Emulator.waitNSlots 1 callEndpoint @"pay" h $ PayParams { ppRecipient = pubKeyHash $ walletPubKey $ Wallet 2 , ppLovelace = y } void $ Emulator.waitNSlots 1 payTest1 :: IO () payTest1 = runEmulatorTraceIO $ payTrace 1000000 2000000 payTest2 :: IO () payTest2 = runEmulatorTraceIO $ payTrace 1000000000 2000000
null
https://raw.githubusercontent.com/mlabs-haskell/plutus-pioneer-program/b50b196d57dc35559b7526fe17b49dd2ba4790bc/code/week04/src/Week04/Solution.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators #
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # module Week04.Solution where import Data.Aeson (FromJSON, ToJSON) import Data.Functor (void) import Data.Text (Text, unpack) import GHC.Generics (Generic) import Ledger import Ledger.Ada as Ada import Ledger.Constraints as Constraints import Plutus.Contract as Contract import Plutus.Trace.Emulator as Emulator import Wallet.Emulator.Wallet data PayParams = PayParams { ppRecipient :: PubKeyHash , ppLovelace :: Integer } deriving (Show, Generic, FromJSON, ToJSON) type PaySchema = BlockchainActions .\/ Endpoint "pay" PayParams payContract :: Contract () PaySchema Text () payContract = do pp <- endpoint @"pay" let tx = mustPayToPubKey (ppRecipient pp) $ lovelaceValueOf $ ppLovelace pp handleError (\err -> Contract.logInfo $ "caught error: " ++ unpack err) $ void $ submitTx tx payContract payTrace :: Integer -> Integer -> EmulatorTrace () payTrace x y = do h <- activateContractWallet (Wallet 1) payContract callEndpoint @"pay" h $ PayParams { ppRecipient = pubKeyHash $ walletPubKey $ Wallet 2 , ppLovelace = x } void $ Emulator.waitNSlots 1 callEndpoint @"pay" h $ PayParams { ppRecipient = pubKeyHash $ walletPubKey $ Wallet 2 , ppLovelace = y } void $ Emulator.waitNSlots 1 payTest1 :: IO () payTest1 = runEmulatorTraceIO $ payTrace 1000000 2000000 payTest2 :: IO () payTest2 = runEmulatorTraceIO $ payTrace 1000000000 2000000
a228649bb5de5b124ee6785b749d7aa6cff9003fe10998f055b21ba8de9501b6
VisionsGlobalEmpowerment/webchange
views.cljs
(ns webchange.lesson-builder.widgets.activity-title.views (:require [re-frame.core :as re-frame] [webchange.lesson-builder.widgets.activity-title.state :as state] [webchange.lesson-builder.widgets.history.state :as history-state] [webchange.lesson-builder.widgets.history.views :refer [activity-history-window]] [webchange.ui.index :as ui])) (defn- last-save [] (let [{:keys [date time]} @(re-frame/subscribe [::state/last-save]) loading? @(re-frame/subscribe [::state/versions-loading?]) open-history #(re-frame/dispatch [::history-state/open-window])] [:div {:class-name "activity-title--last-save" :on-click open-history} [:span "Last Save"] [:div.activity-title--last-save--date (if-not loading? [:<> [:span date] [:span time]] [:span "..."])]])) (defn activity-title [] (let [activity-name @(re-frame/subscribe [::state/activity-name]) saving? @(re-frame/subscribe [::state/saving?]) handle-save-click #(re-frame/dispatch [::state/save]) handle-preview-click #(re-frame/dispatch [::state/preview])] [:div.widget--activity-title [:h1.activity-title--name activity-name] [last-save] [ui/button {:shape "rounded" :class-name "activity-title--action-button" :loading? saving? :on-click handle-save-click} "Save"] [ui/button {:icon "play" :shape "rounded" :color "blue-1" :class-name "activity-title--action-button" :on-click handle-preview-click} "Preview"] [activity-history-window]]))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/0df52dd08d54f14d4ec5d2717f48031849a7ee16/src/cljs/webchange/lesson_builder/widgets/activity_title/views.cljs
clojure
(ns webchange.lesson-builder.widgets.activity-title.views (:require [re-frame.core :as re-frame] [webchange.lesson-builder.widgets.activity-title.state :as state] [webchange.lesson-builder.widgets.history.state :as history-state] [webchange.lesson-builder.widgets.history.views :refer [activity-history-window]] [webchange.ui.index :as ui])) (defn- last-save [] (let [{:keys [date time]} @(re-frame/subscribe [::state/last-save]) loading? @(re-frame/subscribe [::state/versions-loading?]) open-history #(re-frame/dispatch [::history-state/open-window])] [:div {:class-name "activity-title--last-save" :on-click open-history} [:span "Last Save"] [:div.activity-title--last-save--date (if-not loading? [:<> [:span date] [:span time]] [:span "..."])]])) (defn activity-title [] (let [activity-name @(re-frame/subscribe [::state/activity-name]) saving? @(re-frame/subscribe [::state/saving?]) handle-save-click #(re-frame/dispatch [::state/save]) handle-preview-click #(re-frame/dispatch [::state/preview])] [:div.widget--activity-title [:h1.activity-title--name activity-name] [last-save] [ui/button {:shape "rounded" :class-name "activity-title--action-button" :loading? saving? :on-click handle-save-click} "Save"] [ui/button {:icon "play" :shape "rounded" :color "blue-1" :class-name "activity-title--action-button" :on-click handle-preview-click} "Preview"] [activity-history-window]]))
e31e6be2f7ed08c5fdb32fc407bcd6e079bd031ca334e03544cf0bc6571a3318
Glue42/gateway-modules
messages.cljc
(ns gateway.domains.bus.messages (:require [gateway.common.messages :as m] #?(:cljs [gateway.reason :refer [Reason]]) [gateway.domains.bus.constants :as constants]) #?(:clj (:import [gateway.reason Reason]))) (defn event ( [recipient subscriber-id subscription-id publisher-identity data] (m/outgoing recipient (event subscriber-id subscription-id publisher-identity data))) ( [subscriber-id subscription-id publisher-identity data] {:domain constants/bus-domain-uri :type :event :peer_id subscriber-id :subscription_id subscription-id :publisher-identity publisher-identity :data data})) (defn subscribed ( [recipient request-id subscriber-id subscription-id] (m/outgoing recipient (subscribed request-id subscriber-id subscription-id))) ( [request-id subscriber-id subscription-id] {:domain constants/bus-domain-uri :type :subscribed :request_id request-id :peer_id subscriber-id :subscription_id subscription-id})) (defn subscribe [peer-id topic routing-key subscription-id] (cond-> {:domain constants/bus-domain-uri :type :subscribe :peer_id peer-id :topic topic :subscription_id subscription-id} routing-key (assoc :routing_key routing-key)))
null
https://raw.githubusercontent.com/Glue42/gateway-modules/be48a132134b5f9f41fd6a6067800da6be5e6eca/bus-domain/src/gateway/domains/bus/messages.cljc
clojure
(ns gateway.domains.bus.messages (:require [gateway.common.messages :as m] #?(:cljs [gateway.reason :refer [Reason]]) [gateway.domains.bus.constants :as constants]) #?(:clj (:import [gateway.reason Reason]))) (defn event ( [recipient subscriber-id subscription-id publisher-identity data] (m/outgoing recipient (event subscriber-id subscription-id publisher-identity data))) ( [subscriber-id subscription-id publisher-identity data] {:domain constants/bus-domain-uri :type :event :peer_id subscriber-id :subscription_id subscription-id :publisher-identity publisher-identity :data data})) (defn subscribed ( [recipient request-id subscriber-id subscription-id] (m/outgoing recipient (subscribed request-id subscriber-id subscription-id))) ( [request-id subscriber-id subscription-id] {:domain constants/bus-domain-uri :type :subscribed :request_id request-id :peer_id subscriber-id :subscription_id subscription-id})) (defn subscribe [peer-id topic routing-key subscription-id] (cond-> {:domain constants/bus-domain-uri :type :subscribe :peer_id peer-id :topic topic :subscription_id subscription-id} routing-key (assoc :routing_key routing-key)))
a9161caaf574b36179361b933c6aff4bc0da8d99243e53229473bd852d586292
bdeket/rktsicm
display-print.rkt
#lang racket (provide (except-out (all-defined-out) mk)) (require (for-syntax racket/base racket/syntax)) ;print-display needs a lot of things from kernel ;to avoid restructuring everything at this point ;I just defined stumps for the procedures and setters ;that will be overwritten in display/print (define-syntax (mk stx) (syntax-case stx () [(_ id _ ...) (with-syntax ([setter (format-id #'id "set-~a!" #'id)]) #'(begin (define (id . rst) (error "needs to come from display/print")) (define (setter fct) (set! id fct))))])) ;for quaternions (mk careful-simplify "display/print") for pseries (mk print-expression "display/print") for makenumber (mk simplify "display/print")
null
https://raw.githubusercontent.com/bdeket/rktsicm/588acaf709a0e652b6474921f85524926d0f218d/rktsicm/sicm/kernel/todo/display-print.rkt
racket
print-display needs a lot of things from kernel to avoid restructuring everything at this point I just defined stumps for the procedures and setters that will be overwritten in display/print for quaternions
#lang racket (provide (except-out (all-defined-out) mk)) (require (for-syntax racket/base racket/syntax)) (define-syntax (mk stx) (syntax-case stx () [(_ id _ ...) (with-syntax ([setter (format-id #'id "set-~a!" #'id)]) #'(begin (define (id . rst) (error "needs to come from display/print")) (define (setter fct) (set! id fct))))])) (mk careful-simplify "display/print") for pseries (mk print-expression "display/print") for makenumber (mk simplify "display/print")
c0552f8e04078ab9c3ca6d82ab2d0c7276df9cc1ca93cf03934837fe6a2760bb
metosin/eines
handler.clj
(ns eines-example.message.handler (:require [eines-example.message.login :as login] [eines-example.message.favorite :as favorite] [eines-example.message.ping :as ping] [clojure.tools.logging :as log])) (def handlers (merge login/handlers favorite/handlers ping/handlers)) (defn not-found [message] (log/error "unknown message type:" (-> message :body :type))) (defn handle-message [message] (let [message-type (-> message :body :type) handler (get handlers message-type not-found)] (handler message)))
null
https://raw.githubusercontent.com/metosin/eines/e293d0a3b29eb18fb20bdf0c234cd898e7b87ac9/example/src/clj/eines_example/message/handler.clj
clojure
(ns eines-example.message.handler (:require [eines-example.message.login :as login] [eines-example.message.favorite :as favorite] [eines-example.message.ping :as ping] [clojure.tools.logging :as log])) (def handlers (merge login/handlers favorite/handlers ping/handlers)) (defn not-found [message] (log/error "unknown message type:" (-> message :body :type))) (defn handle-message [message] (let [message-type (-> message :body :type) handler (get handlers message-type not-found)] (handler message)))
2e0c46795d8427fc35013d036190828a3dbe08d2b86452056851670572f979e3
yogthos/config
core.clj
(ns config.core (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as s]) (:import java.io.PushbackReader)) (defn parse-number [^String v] (try (Long/parseLong v) (catch NumberFormatException _ (BigInteger. v)))) originally found in cprop #L26 (defn str->value "ENV vars and system properties are strings. str->value will convert: the numbers to longs, the alphanumeric values to strings, and will use Clojure reader for the rest in case reader can't read OR it reads a symbol, the value will be returned as is (a string)" [v] (cond (re-matches #"[0-9]+" v) (parse-number v) (re-matches #"^(true|false)$" v) (Boolean/parseBoolean v) (re-matches #"\w+" v) v :else (try (let [parsed (edn/read-string v)] (if (symbol? parsed) v parsed)) (catch Throwable _ v)))) (defn keywordize [s] (-> (s/lower-case s) (s/replace "__" "/") (s/replace "_" "-") (s/replace "." "-") (keyword))) (defn read-system-env [] (->> (System/getenv) (map (fn [[k v]] [(keywordize k) (str->value v)])) (into {}))) (defn read-system-props [] (->> (System/getProperties) (map (fn [[k v]] [(keywordize k) (str->value v)])) (into {}))) (defn read-env-file [f & required] (when-let [env-file (io/file f)] (when (or (.exists env-file) required) (edn/read-string (slurp env-file))))) (defn read-config-file [f] (try (when-let [url (or (io/resource f) (io/file f))] (with-open [r (-> url io/reader PushbackReader.)] (edn/read r))) (catch java.io.FileNotFoundException _))) (defn contains-in? "checks whether the nested key exists in a map" [m k-path] (let [one-before (get-in m (drop-last k-path))] in case k - path is " longer " than a map : { : a { : b { : c 42 } } } = > [: a : b : c : d ] (contains? one-before (last k-path))))) author of " deep - merge - with " is : -contrib/commit/19613025d233b5f445b1dd3460c4128f39218741 (defn deep-merge-with "Like merge-with, but merges maps recursively, appling the given fn only when there's a non-map at a particular level. (deepmerge + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4} {:a {:b {:c 2 :d {:z 9} :z 3} :e 100}}) -> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}" [f & maps] (apply (fn m [& maps] (if (every? map? maps) (apply merge-with m maps) (apply f maps))) (remove nil? maps))) (defn merge-maps [& m] (reduce #(deep-merge-with (fn [_ v] v) %1 %2) m)) (defn load-env "Generate a map of environment variables." [& configs] (let [env-props (merge-maps (read-system-env) (read-system-props))] (apply merge-maps (read-config-file "config.edn") (read-env-file ".lein-env") (read-env-file (io/resource ".boot-env")) (when (:config env-props) (read-env-file (:config env-props) true)) env-props configs))) (defonce ^{:doc "A map of environment variables."} env (load-env)) (defn reload-env [] (alter-var-root #'env (fn [_] (load-env))))
null
https://raw.githubusercontent.com/yogthos/config/44fc4780cee097cc63c46cfadc67ddf27f82d20a/src/config/core.clj
clojure
(ns config.core (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as s]) (:import java.io.PushbackReader)) (defn parse-number [^String v] (try (Long/parseLong v) (catch NumberFormatException _ (BigInteger. v)))) originally found in cprop #L26 (defn str->value "ENV vars and system properties are strings. str->value will convert: the numbers to longs, the alphanumeric values to strings, and will use Clojure reader for the rest in case reader can't read OR it reads a symbol, the value will be returned as is (a string)" [v] (cond (re-matches #"[0-9]+" v) (parse-number v) (re-matches #"^(true|false)$" v) (Boolean/parseBoolean v) (re-matches #"\w+" v) v :else (try (let [parsed (edn/read-string v)] (if (symbol? parsed) v parsed)) (catch Throwable _ v)))) (defn keywordize [s] (-> (s/lower-case s) (s/replace "__" "/") (s/replace "_" "-") (s/replace "." "-") (keyword))) (defn read-system-env [] (->> (System/getenv) (map (fn [[k v]] [(keywordize k) (str->value v)])) (into {}))) (defn read-system-props [] (->> (System/getProperties) (map (fn [[k v]] [(keywordize k) (str->value v)])) (into {}))) (defn read-env-file [f & required] (when-let [env-file (io/file f)] (when (or (.exists env-file) required) (edn/read-string (slurp env-file))))) (defn read-config-file [f] (try (when-let [url (or (io/resource f) (io/file f))] (with-open [r (-> url io/reader PushbackReader.)] (edn/read r))) (catch java.io.FileNotFoundException _))) (defn contains-in? "checks whether the nested key exists in a map" [m k-path] (let [one-before (get-in m (drop-last k-path))] in case k - path is " longer " than a map : { : a { : b { : c 42 } } } = > [: a : b : c : d ] (contains? one-before (last k-path))))) author of " deep - merge - with " is : -contrib/commit/19613025d233b5f445b1dd3460c4128f39218741 (defn deep-merge-with "Like merge-with, but merges maps recursively, appling the given fn only when there's a non-map at a particular level. (deepmerge + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4} {:a {:b {:c 2 :d {:z 9} :z 3} :e 100}}) -> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}" [f & maps] (apply (fn m [& maps] (if (every? map? maps) (apply merge-with m maps) (apply f maps))) (remove nil? maps))) (defn merge-maps [& m] (reduce #(deep-merge-with (fn [_ v] v) %1 %2) m)) (defn load-env "Generate a map of environment variables." [& configs] (let [env-props (merge-maps (read-system-env) (read-system-props))] (apply merge-maps (read-config-file "config.edn") (read-env-file ".lein-env") (read-env-file (io/resource ".boot-env")) (when (:config env-props) (read-env-file (:config env-props) true)) env-props configs))) (defonce ^{:doc "A map of environment variables."} env (load-env)) (defn reload-env [] (alter-var-root #'env (fn [_] (load-env))))
da186344138d9eaf0805d16d317d4494f3f804bb382408147c49d79052bdfe33
umber-lang/umber
untyped.ml
open Import open Names (* TODO: Make this a CST, with it precisely representing the syntax written. This should involving adding spans (Node-ifying the tree). *) module Pattern = struct include Pattern type nonrec t = Type.Scheme.Bounded.t t [@@deriving sexp] end module Expr = struct type t = | Literal of Literal.t | Name of Value_name.Qualified.t | Qualified of Module_path.t * t | Fun_call of t * t Nonempty.t | Op_tree of (Value_name.Qualified.t, t) Btree.t | Lambda of Pattern.t Nonempty.t * t | If of t * t * t | Match of t * (Pattern.t * t) Nonempty.t | Let of (Pattern.t, t) Let_binding.t | Tuple of t list | Seq_literal of t list | Record_literal of (Value_name.t * t option) Nonempty.t | Record_update of t * (Value_name.t * t option) Nonempty.t | Record_field_access of t * Value_name.t | Type_annotation of t * Type.Scheme.Bounded.t [@@deriving sexp, variants] (** Get all the external names referenced by an expression. Names local to the expression (e.g. those bound by match expressions or lambdas) are not included. *) let names_used ~names = let add_locals init = Pattern.Names.fold ~init ~f:Set.add in let rec loop ~names used locals = function | Literal _ -> used | Name ([], name) when Set.mem locals name -> used | Name name -> Set.add used (Name_bindings.absolutify_value_name names name) | Qualified (path, expr) -> loop ~names:(Name_bindings.import_all names path) used locals expr | Fun_call (fun_, args) -> let used = loop ~names used locals fun_ in Nonempty.fold args ~init:used ~f:(fun used expr -> loop ~names used locals expr) | Op_tree tree -> let rec tree_loop acc = function | Btree.Node (op_name, left_child, right_child) -> tree_loop (tree_loop (Set.add used op_name) left_child) right_child | Leaf expr -> loop ~names acc locals expr in tree_loop used tree | Lambda (args, body) -> loop ~names used (Nonempty.fold args ~init:locals ~f:add_locals) body | If (cond, then_, else_) -> loop ~names (loop ~names (loop ~names used locals cond) locals then_) locals else_ | Match (expr, branches) -> let used = loop ~names used locals expr in Nonempty.fold branches ~init:used ~f:(fun used (pat, branch) -> loop ~names used (add_locals locals pat) branch) | Let { rec_; bindings; body } -> let new_locals = Nonempty.fold bindings ~init:locals ~f:(fun locals binding -> Node.with_value binding ~f:(fun (pat, _) -> add_locals locals pat)) in let binding_locals = if rec_ then new_locals else locals in let used = Nonempty.fold bindings ~init:used ~f:(fun used binding -> Node.with_value binding ~f:(fun (_, expr) -> loop ~names used binding_locals expr)) in loop ~names used new_locals body | Tuple items | Seq_literal items -> List.fold items ~init:used ~f:(fun used -> loop ~names used locals) | Record_literal fields -> loop_record_fields ~names used locals fields | Record_update (expr, fields) -> loop_record_fields ~names (loop ~names used locals expr) locals fields | Record_field_access (expr, _) | Type_annotation (expr, _) -> loop ~names used locals expr and loop_record_fields ~names used locals = Nonempty.fold ~init:used ~f:(fun used -> function | _, Some expr -> loop ~names used locals expr | _, None -> used) in loop ~names Value_name.Qualified.Set.empty Value_name.Set.empty ;; let match_function branches = let name = Value_name.empty in Lambda ([ Catch_all (Some name) ], Match (Name ([], name), branches)) ;; let qualified (path, expr) = match path with | [] -> expr | _ -> Qualified (Module_path.of_ustrings_unchecked path, expr) ;; let op_section_right op expr = let op = Value_name.Qualified.of_ustrings_unchecked op in let left_var = Value_name.empty in let left_var_qualified = Value_name.Qualified.with_path [] left_var in Lambda ( [ Catch_all (Some left_var) ] , Fun_call (Name op, [ Name left_var_qualified; expr ]) ) ;; let op_section_left expr op = Fun_call (Name (Value_name.Qualified.of_ustrings_unchecked op), [ expr ]) ;; end module Module = struct include Module type nonrec t = (Pattern.t, Expr.t) t [@@deriving sexp_of] type nonrec def = (Pattern.t, Expr.t) def [@@deriving sexp_of] end
null
https://raw.githubusercontent.com/umber-lang/umber/43339b87e10a704bffea16341f6285bc3cba058e/src/untyped.ml
ocaml
TODO: Make this a CST, with it precisely representing the syntax written. This should involving adding spans (Node-ifying the tree). * Get all the external names referenced by an expression. Names local to the expression (e.g. those bound by match expressions or lambdas) are not included.
open Import open Names module Pattern = struct include Pattern type nonrec t = Type.Scheme.Bounded.t t [@@deriving sexp] end module Expr = struct type t = | Literal of Literal.t | Name of Value_name.Qualified.t | Qualified of Module_path.t * t | Fun_call of t * t Nonempty.t | Op_tree of (Value_name.Qualified.t, t) Btree.t | Lambda of Pattern.t Nonempty.t * t | If of t * t * t | Match of t * (Pattern.t * t) Nonempty.t | Let of (Pattern.t, t) Let_binding.t | Tuple of t list | Seq_literal of t list | Record_literal of (Value_name.t * t option) Nonempty.t | Record_update of t * (Value_name.t * t option) Nonempty.t | Record_field_access of t * Value_name.t | Type_annotation of t * Type.Scheme.Bounded.t [@@deriving sexp, variants] let names_used ~names = let add_locals init = Pattern.Names.fold ~init ~f:Set.add in let rec loop ~names used locals = function | Literal _ -> used | Name ([], name) when Set.mem locals name -> used | Name name -> Set.add used (Name_bindings.absolutify_value_name names name) | Qualified (path, expr) -> loop ~names:(Name_bindings.import_all names path) used locals expr | Fun_call (fun_, args) -> let used = loop ~names used locals fun_ in Nonempty.fold args ~init:used ~f:(fun used expr -> loop ~names used locals expr) | Op_tree tree -> let rec tree_loop acc = function | Btree.Node (op_name, left_child, right_child) -> tree_loop (tree_loop (Set.add used op_name) left_child) right_child | Leaf expr -> loop ~names acc locals expr in tree_loop used tree | Lambda (args, body) -> loop ~names used (Nonempty.fold args ~init:locals ~f:add_locals) body | If (cond, then_, else_) -> loop ~names (loop ~names (loop ~names used locals cond) locals then_) locals else_ | Match (expr, branches) -> let used = loop ~names used locals expr in Nonempty.fold branches ~init:used ~f:(fun used (pat, branch) -> loop ~names used (add_locals locals pat) branch) | Let { rec_; bindings; body } -> let new_locals = Nonempty.fold bindings ~init:locals ~f:(fun locals binding -> Node.with_value binding ~f:(fun (pat, _) -> add_locals locals pat)) in let binding_locals = if rec_ then new_locals else locals in let used = Nonempty.fold bindings ~init:used ~f:(fun used binding -> Node.with_value binding ~f:(fun (_, expr) -> loop ~names used binding_locals expr)) in loop ~names used new_locals body | Tuple items | Seq_literal items -> List.fold items ~init:used ~f:(fun used -> loop ~names used locals) | Record_literal fields -> loop_record_fields ~names used locals fields | Record_update (expr, fields) -> loop_record_fields ~names (loop ~names used locals expr) locals fields | Record_field_access (expr, _) | Type_annotation (expr, _) -> loop ~names used locals expr and loop_record_fields ~names used locals = Nonempty.fold ~init:used ~f:(fun used -> function | _, Some expr -> loop ~names used locals expr | _, None -> used) in loop ~names Value_name.Qualified.Set.empty Value_name.Set.empty ;; let match_function branches = let name = Value_name.empty in Lambda ([ Catch_all (Some name) ], Match (Name ([], name), branches)) ;; let qualified (path, expr) = match path with | [] -> expr | _ -> Qualified (Module_path.of_ustrings_unchecked path, expr) ;; let op_section_right op expr = let op = Value_name.Qualified.of_ustrings_unchecked op in let left_var = Value_name.empty in let left_var_qualified = Value_name.Qualified.with_path [] left_var in Lambda ( [ Catch_all (Some left_var) ] , Fun_call (Name op, [ Name left_var_qualified; expr ]) ) ;; let op_section_left expr op = Fun_call (Name (Value_name.Qualified.of_ustrings_unchecked op), [ expr ]) ;; end module Module = struct include Module type nonrec t = (Pattern.t, Expr.t) t [@@deriving sexp_of] type nonrec def = (Pattern.t, Expr.t) def [@@deriving sexp_of] end
de5d1f1d3536d516cdcfbb582d506cb2540c82c9b3af2ab3ac5ea8953fad90b5
acowley/Frames
RecLens.hs
# LANGUAGE AllowAmbiguousTypes , ConstraintKinds , DataKinds , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses , PolyKinds , RankNTypes , ScopedTypeVariables , TypeApplications , TypeFamilies , TypeOperators # FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, PolyKinds, RankNTypes, ScopedTypeVariables, TypeApplications, TypeFamilies, TypeOperators #-} -- | Lens utilities for working with 'Record's. module Frames.RecLens where import Control.Applicative import qualified Data.Vinyl as V import Data.Vinyl.Functor (Compose(..), (:.), Identity(..)) import Data.Vinyl.TypeLevel import Frames.Col ((:->)(..)) import Frames.Rec (Record) -- rlens' :: forall r rs f g i. ( i ~ RIndex r rs , V.RElem r rs i , Functor f ) -- => (g r -> f (g r)) -- -> V.Rec g rs -- -> f (V.Rec g rs) -- rlens' = V.rlens -- {-# INLINE rlens' #-} -- | Getter for a 'V.Rec' field rget ' : : = > ( forall f = > ( g ( s :-> a ) - > f ( g ( s :-> a ) ) ) - > V.Rec ( V.Rec g rs ) ) - > V.Rec a rget ' l = fmap getCol . . l Const -- {-# INLINE rget' #-} rget ' : : V.Rec ( g : . ) rs - > g a rget ' = . getCompose . V.rget -- | Setter for a 'V.Rec' field. rput ' : : = > ( forall f = > ( g ( s :-> a ) - > f ( g ( s :-> a ) ) ) - > V.Rec ( V.Rec g rs ) ) - > g a - > V.Rec V.Rec g rs -- rput' l y = getIdentity . l (\_ -> Identity (fmap Col y)) { - # INLINE rput ' # - } -- * Plain records | Create a lens for accessing a field of a ' Record ' . The first -- explicit type parameter is used to help with visible type -- applications using the @TypeApplications@ language extension . Typical usage might be , @rlens \@("name " :-> String)@. rlens : : forall q s ( q ~ ( s :-> a ) , , V.RElem ( s :-> a ) rs ( RIndex ( s :-> a ) rs ) ) -- => (a -> f a) -> Record rs -> f (Record rs) rlens f = ( V.rlens . V.rfield ) f -- rlens :: forall l v record g us. ( , HasField record l us us v v , RecElemFCtx record ElField ) = > Label l - > ( v - > g v ) - > record ( record ) -- rlens = V.rlensf rlens f = rlens ' @(s :-> a ) ( fmap Identity . getIdentity . fmap f ' ) -- where f' (Col x) = fmap Col (f x) -- {-# INLINE rlens #-} -- | Getter for a 'Record' field. rget : : ( forall f = > ( a - > f a ) - > Record rs - > f ( Record rs ) ) -- -> Record rs -> a rget l = . l Const -- {-# INLINE rget #-} -- -- | Setter for a 'Record' field. rput : : ( forall f = > ( a - > f a ) - > Record rs - > f ( Record rs ) ) -- -> a -> Record rs -> Record rs -- rput l y = getIdentity . l (\_ -> Identity y) -- {-# INLINE rput #-}
null
https://raw.githubusercontent.com/acowley/Frames/aeca953fe608de38d827b8a078ebf2d329edae04/src/Frames/RecLens.hs
haskell
| Lens utilities for working with 'Record's. rlens' :: forall r rs f g i. => (g r -> f (g r)) -> V.Rec g rs -> f (V.Rec g rs) rlens' = V.rlens {-# INLINE rlens' #-} | Getter for a 'V.Rec' field {-# INLINE rget' #-} | Setter for a 'V.Rec' field. rput' l y = getIdentity . l (\_ -> Identity (fmap Col y)) * Plain records explicit type parameter is used to help with visible type applications using the @TypeApplications@ language => (a -> f a) -> Record rs -> f (Record rs) rlens :: forall l v record g us. rlens = V.rlensf where f' (Col x) = fmap Col (f x) {-# INLINE rlens #-} | Getter for a 'Record' field. -> Record rs -> a {-# INLINE rget #-} -- | Setter for a 'Record' field. -> a -> Record rs -> Record rs rput l y = getIdentity . l (\_ -> Identity y) {-# INLINE rput #-}
# LANGUAGE AllowAmbiguousTypes , ConstraintKinds , DataKinds , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses , PolyKinds , RankNTypes , ScopedTypeVariables , TypeApplications , TypeFamilies , TypeOperators # FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, PolyKinds, RankNTypes, ScopedTypeVariables, TypeApplications, TypeFamilies, TypeOperators #-} module Frames.RecLens where import Control.Applicative import qualified Data.Vinyl as V import Data.Vinyl.Functor (Compose(..), (:.), Identity(..)) import Data.Vinyl.TypeLevel import Frames.Col ((:->)(..)) import Frames.Rec (Record) ( i ~ RIndex r rs , V.RElem r rs i , Functor f ) rget ' : : = > ( forall f = > ( g ( s :-> a ) - > f ( g ( s :-> a ) ) ) - > V.Rec ( V.Rec g rs ) ) - > V.Rec a rget ' l = fmap getCol . . l Const rget ' : : V.Rec ( g : . ) rs - > g a rget ' = . getCompose . V.rget rput ' : : = > ( forall f = > ( g ( s :-> a ) - > f ( g ( s :-> a ) ) ) - > V.Rec ( V.Rec g rs ) ) - > g a - > V.Rec V.Rec g rs { - # INLINE rput ' # - } | Create a lens for accessing a field of a ' Record ' . The first extension . Typical usage might be , @rlens \@("name " :-> String)@. rlens : : forall q s ( q ~ ( s :-> a ) , , V.RElem ( s :-> a ) rs ( RIndex ( s :-> a ) rs ) ) rlens f = ( V.rlens . V.rfield ) f ( , HasField record l us us v v , RecElemFCtx record ElField ) = > Label l - > ( v - > g v ) - > record ( record ) rlens f = rlens ' @(s :-> a ) ( fmap Identity . getIdentity . fmap f ' ) rget : : ( forall f = > ( a - > f a ) - > Record rs - > f ( Record rs ) ) rget l = . l Const rput : : ( forall f = > ( a - > f a ) - > Record rs - > f ( Record rs ) )
169d3c22969478c07a1303ee2023aaa051fdc1360caf9012dce9e80402b9e564
theodormoroianu/SecondYearCourses
taburi.hs
maxim x y | x > y = x | otherwise = y max3 x y z = let { mxy = maxim x y ; m = maxim mxy z } in m -- replace tabs with spaces to make this compile max3' x y z = let mxy = maxim x y m = maxim mxy z in m
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/99185b0e97119135e7301c2c7be0f07ae7258006/Haskell/l/lab1/taburi.hs
haskell
replace tabs with spaces to make this compile
maxim x y | x > y = x | otherwise = y max3 x y z = let { mxy = maxim x y ; m = maxim mxy z } in m max3' x y z = let mxy = maxim x y m = maxim mxy z in m
6d49cfc50a846571ffd1d690698e32808d373e4e069009f3b346fdc42af4b333
exercism/clojure
squeaky_clean_test.clj
(ns squeaky-clean-test (:require [clojure.test :refer [deftest is]] squeaky-clean)) (deftest ^{:task 1} clean-single-letter (is (= "A" (squeaky-clean/clean "A")))) (deftest ^{:task 1} clean-clean-string (is (= "àḃç" (squeaky-clean/clean "àḃç")))) (deftest ^{:task 1} clean-string-with-spaces (is (= "my___Id" (squeaky-clean/clean "my Id")))) (deftest ^{:task 1} clean-string-with-no-letters (is (= "" (squeaky-clean/clean "😀😀😀")))) (deftest ^{:task 1} clean-empty-string (is (= "" (squeaky-clean/clean "")))) (deftest ^{:task 2} clean-string-with-control-char (is (= "myCTRLId" (squeaky-clean/clean "my\u0000Id")))) (deftest ^{:task 3} convert-kebab-to-camel-case (is (= "àḂç" (squeaky-clean/clean "à-ḃç")))) (deftest ^{:task 4} omit-lower-case-greek-letters (is (= "MyΟFinder" (squeaky-clean/clean "MyΟβιεγτFinder")))) (deftest ^{:task 3} combine-conversions (is (= "_AbcĐCTRL" (squeaky-clean/clean "9 -abcĐ😀ω\0"))))
null
https://raw.githubusercontent.com/exercism/clojure/7f11e4bee92c3d94fa4d65b2eef7a2b6354fea50/exercises/concept/squeaky-clean/test/squeaky_clean_test.clj
clojure
(ns squeaky-clean-test (:require [clojure.test :refer [deftest is]] squeaky-clean)) (deftest ^{:task 1} clean-single-letter (is (= "A" (squeaky-clean/clean "A")))) (deftest ^{:task 1} clean-clean-string (is (= "àḃç" (squeaky-clean/clean "àḃç")))) (deftest ^{:task 1} clean-string-with-spaces (is (= "my___Id" (squeaky-clean/clean "my Id")))) (deftest ^{:task 1} clean-string-with-no-letters (is (= "" (squeaky-clean/clean "😀😀😀")))) (deftest ^{:task 1} clean-empty-string (is (= "" (squeaky-clean/clean "")))) (deftest ^{:task 2} clean-string-with-control-char (is (= "myCTRLId" (squeaky-clean/clean "my\u0000Id")))) (deftest ^{:task 3} convert-kebab-to-camel-case (is (= "àḂç" (squeaky-clean/clean "à-ḃç")))) (deftest ^{:task 4} omit-lower-case-greek-letters (is (= "MyΟFinder" (squeaky-clean/clean "MyΟβιεγτFinder")))) (deftest ^{:task 3} combine-conversions (is (= "_AbcĐCTRL" (squeaky-clean/clean "9 -abcĐ😀ω\0"))))
72d24de71f2c804d8ca89f74f32434118b2c4cdfe9b4369fa7941c987a735610
heraldry/heraldicon
pile.cljs
(ns heraldicon.heraldry.ordinary.type.pile (:require [clojure.string :as str] [heraldicon.context :as c] [heraldicon.heraldry.cottising :as cottising] [heraldicon.heraldry.field.environment :as environment] [heraldicon.heraldry.line.core :as line] [heraldicon.heraldry.option.position :as position] [heraldicon.heraldry.ordinary.interface :as ordinary.interface] [heraldicon.heraldry.ordinary.post-process :as post-process] [heraldicon.heraldry.ordinary.shared :as ordinary.shared] [heraldicon.heraldry.shared.pile :as pile] [heraldicon.interface :as interface] [heraldicon.math.angle :as angle] [heraldicon.math.bounding-box :as bb] [heraldicon.math.core :as math] [heraldicon.math.vector :as v] [heraldicon.options :as options] [heraldicon.svg.shape :as shape])) (def ordinary-type :heraldry.ordinary.type/pile) (defmethod ordinary.interface/display-name ordinary-type [_] :string.ordinary.type/pile) (def ^:private size-mode-choices [[:string.option.size-mode-choice/thickness :thickness] [:string.option.size-mode-choice/angle :angle]]) (def size-mode-map (options/choices->map size-mode-choices)) (def ^:private orientation-type-choices [[:string.option.orientation-type-choice/edge :edge] [:string.option.orientation-type-choice/orientation-point :point]]) (defmethod ordinary.interface/options ordinary-type [context] (let [line-style (-> (line/options (c/++ context :line)) (options/override-if-exists [:offset :min] 0) (options/override-if-exists [:base-line] nil) (options/override-if-exists [:fimbriation :alignment :default] :outside)) opposite-line-style (-> (line/options (c/++ context :opposite-line) :inherited-options line-style) (options/override-if-exists [:offset :min] 0) (options/override-if-exists [:base-line] nil) (dissoc :fimbriation)) anchor-point-option {:type :option.type/choice :choices (position/anchor-choices [:chief :base :dexter :sinister :hoist :fly :top-left :top :top-right :left :center :right :bottom-left :bottom :bottom-right]) :default :top :ui/label :string.option/point} current-anchor-point (options/get-value (interface/get-raw-data (c/++ context :anchor :point)) anchor-point-option) orientation-point-option {:type :option.type/choice :choices (position/orientation-choices (filter #(not= % current-anchor-point) [:top-left :top :top-right :left :center :right :bottom-left :bottom :bottom-right :fess :chief :base :dexter :sinister :honour :nombril :hoist :fly :angle])) :default :fess :ui/label :string.option/point} current-orientation-point (options/get-value (interface/get-raw-data (c/++ context :orientation :point)) orientation-point-option) size-mode-option {:type :option.type/choice :choices size-mode-choices :default :thickness :ui/label :string.option/size-mode :ui/element :ui.element/radio-select} current-size-mode (options/get-value (interface/get-raw-data (c/++ context :geometry :size-mode)) size-mode-option)] (ordinary.shared/add-humetty-and-voided {:adapt-to-ordinaries? {:type :option.type/boolean :default true :ui/label :string.option/adapt-to-ordinaries?} :anchor {:point anchor-point-option :alignment {:type :option.type/choice :choices position/alignment-choices :default :middle :ui/label :string.option/alignment :ui/element :ui.element/radio-select} :offset-x {:type :option.type/range :min -50 :max 50 :default 0 :ui/label :string.option/offset-x :ui/step 0.1} :offset-y {:type :option.type/range :min -75 :max 75 :default 0 :ui/label :string.option/offset-y :ui/step 0.1} :ui/label :string.option/anchor :ui/element :ui.element/position} :orientation (cond-> {:point orientation-point-option :ui/label :string.option/orientation :ui/element :ui.element/position} (= current-orientation-point :angle) (assoc :angle {:type :option.type/range :min (cond (#{:top-left :top-right :bottom-left :bottom-right} current-anchor-point) 0 :else -90) :max 90 :default (cond (#{:top-left :top-right :bottom-left :bottom-right} current-anchor-point) 45 :else 0) :ui/label :string.option/angle}) (not= current-orientation-point :angle) (assoc :offset-x {:type :option.type/range :min -50 :max 50 :default 0 :ui/label :string.option/offset-x :ui/step 0.1} :offset-y {:type :option.type/range :min -75 :max 75 :default 0 :ui/label :string.option/offset-y :ui/step 0.1} :type {:type :option.type/choice :choices orientation-type-choices :default :edge :ui/label :string.render-options/mode :ui/element :ui.element/radio-select})) :line line-style :opposite-line opposite-line-style :geometry {:size-mode size-mode-option :size {:type :option.type/range :min 5 :max 120 :default (case current-size-mode :thickness 75 30) :ui/label :string.option/size :ui/step 0.1} :stretch {:type :option.type/range :min 0.33 :max 2 :default 0.85 :ui/label :string.option/stretch :ui/step 0.01} :ui/label :string.option/geometry :ui/element :ui.element/geometry} :outline? options/plain-outline?-option :cottising (cottising/add-cottising context 1)} context))) (defmethod interface/properties ordinary-type [context] (let [{:keys [width height] :as parent-environment} (interface/get-parent-field-environment context) geometry (interface/get-sanitized-data (c/++ context :geometry)) anchor (interface/get-sanitized-data (c/++ context :anchor)) orientation (interface/get-sanitized-data (c/++ context :orientation)) percentage-base (if (#{:left :right :dexter :sinister} (:point anchor)) height width) parent-shape (interface/get-parent-field-shape context) {anchor-point :anchor point :point thickness :thickness} (pile/calculate-properties parent-environment parent-shape anchor (cond-> orientation (#{:top-right :right :bottom-left} (:point anchor)) (update :angle #(when % (- %)))) geometry percentage-base (case (:point anchor) :top-left 0 :top 90 :top-right 180 :left 0 :right 180 :bottom-left 0 :bottom -90 :bottom-right 180 0)) pile-angle (angle/normalize (v/angle-to-point point anchor-point)) {left-point :left right-point :right} (pile/diagonals anchor-point point thickness) intersection-left (v/last-intersection-with-shape point left-point parent-shape :default? true) intersection-right (v/last-intersection-with-shape point right-point parent-shape :default? true) joint-angle (angle/normalize (v/angle-between-vectors (v/sub intersection-left point) (v/sub intersection-right point))) line-length (max (v/abs (v/sub intersection-left point)) (v/abs (v/sub intersection-right point)))] (post-process/properties {:type ordinary-type :upper [intersection-left point intersection-right] :pile-angle pile-angle :joint-angle joint-angle :thickness thickness :line-length line-length :percentage-base percentage-base :humetty-percentage-base (min width height) :voided-percentage-base (/ thickness 2)} context))) (defmethod interface/environment ordinary-type [context] (let [{[left point right] :upper} (interface/get-properties context) ;; TODO: needs to be improved bounding-box-points [point left right]] (environment/create (bb/from-points bounding-box-points)))) (defmethod interface/render-shape ordinary-type [context] (let [{:keys [line opposite-line] [left point right] :upper :as properties} (interface/get-properties context) {:keys [bounding-box]} (interface/get-parent-field-environment context) line-left (line/create-with-extension context line point left bounding-box :reversed? true :extend-from? false) line-right (line/create-with-extension context opposite-line point right bounding-box :extend-from? false)] (post-process/shape {:shape [(shape/build-shape context line-left line-right :clockwise-shortest)] :edges [{:lines [line-left line-right]}]} context properties))) (defmethod cottising/cottise-properties ordinary-type [context {:keys [line-length percentage-base pile-angle joint-angle humetty] [reference-left reference-point reference-right] :upper reference-line :line}] (when-not (-> (cottising/kind context) name (str/starts-with? "cottise-opposite")) (let [distance (interface/get-sanitized-data (c/++ context :distance)) distance (math/percent-of percentage-base distance) thickness (interface/get-sanitized-data (c/++ context :thickness)) band-size (math/percent-of percentage-base thickness) [base-corner base-left base-right] [reference-point reference-left reference-right] real-distance (/ (+ (:effective-height reference-line) distance) (Math/sin (-> joint-angle (* Math/PI) (/ 180) (/ 2)))) delta (/ band-size (Math/sin (-> joint-angle (* Math/PI) (/ 180) (/ 2)))) dist-vector (v/rotate (v/Vector. real-distance 0) pile-angle) band-size-vector (v/rotate (v/Vector. delta 0) pile-angle) lower-corner (v/sub base-corner dist-vector) upper-corner (v/sub lower-corner band-size-vector) [lower-left lower-right] (map #(v/sub % dist-vector) [base-left base-right]) [upper-left upper-right] (map #(v/sub % band-size-vector) [lower-left lower-right])] (post-process/properties {:type :heraldry.ordinary.type/chevron :upper [upper-left upper-corner upper-right] :lower [lower-left lower-corner lower-right] :chevron-angle pile-angle :joint-angle joint-angle :band-size band-size :line-length line-length :percentage-base percentage-base :humetty humetty} context))))
null
https://raw.githubusercontent.com/heraldry/heraldicon/0e72e14efdc6dc7f1aa059c4b10e49962cdf293c/src/heraldicon/heraldry/ordinary/type/pile.cljs
clojure
TODO: needs to be improved
(ns heraldicon.heraldry.ordinary.type.pile (:require [clojure.string :as str] [heraldicon.context :as c] [heraldicon.heraldry.cottising :as cottising] [heraldicon.heraldry.field.environment :as environment] [heraldicon.heraldry.line.core :as line] [heraldicon.heraldry.option.position :as position] [heraldicon.heraldry.ordinary.interface :as ordinary.interface] [heraldicon.heraldry.ordinary.post-process :as post-process] [heraldicon.heraldry.ordinary.shared :as ordinary.shared] [heraldicon.heraldry.shared.pile :as pile] [heraldicon.interface :as interface] [heraldicon.math.angle :as angle] [heraldicon.math.bounding-box :as bb] [heraldicon.math.core :as math] [heraldicon.math.vector :as v] [heraldicon.options :as options] [heraldicon.svg.shape :as shape])) (def ordinary-type :heraldry.ordinary.type/pile) (defmethod ordinary.interface/display-name ordinary-type [_] :string.ordinary.type/pile) (def ^:private size-mode-choices [[:string.option.size-mode-choice/thickness :thickness] [:string.option.size-mode-choice/angle :angle]]) (def size-mode-map (options/choices->map size-mode-choices)) (def ^:private orientation-type-choices [[:string.option.orientation-type-choice/edge :edge] [:string.option.orientation-type-choice/orientation-point :point]]) (defmethod ordinary.interface/options ordinary-type [context] (let [line-style (-> (line/options (c/++ context :line)) (options/override-if-exists [:offset :min] 0) (options/override-if-exists [:base-line] nil) (options/override-if-exists [:fimbriation :alignment :default] :outside)) opposite-line-style (-> (line/options (c/++ context :opposite-line) :inherited-options line-style) (options/override-if-exists [:offset :min] 0) (options/override-if-exists [:base-line] nil) (dissoc :fimbriation)) anchor-point-option {:type :option.type/choice :choices (position/anchor-choices [:chief :base :dexter :sinister :hoist :fly :top-left :top :top-right :left :center :right :bottom-left :bottom :bottom-right]) :default :top :ui/label :string.option/point} current-anchor-point (options/get-value (interface/get-raw-data (c/++ context :anchor :point)) anchor-point-option) orientation-point-option {:type :option.type/choice :choices (position/orientation-choices (filter #(not= % current-anchor-point) [:top-left :top :top-right :left :center :right :bottom-left :bottom :bottom-right :fess :chief :base :dexter :sinister :honour :nombril :hoist :fly :angle])) :default :fess :ui/label :string.option/point} current-orientation-point (options/get-value (interface/get-raw-data (c/++ context :orientation :point)) orientation-point-option) size-mode-option {:type :option.type/choice :choices size-mode-choices :default :thickness :ui/label :string.option/size-mode :ui/element :ui.element/radio-select} current-size-mode (options/get-value (interface/get-raw-data (c/++ context :geometry :size-mode)) size-mode-option)] (ordinary.shared/add-humetty-and-voided {:adapt-to-ordinaries? {:type :option.type/boolean :default true :ui/label :string.option/adapt-to-ordinaries?} :anchor {:point anchor-point-option :alignment {:type :option.type/choice :choices position/alignment-choices :default :middle :ui/label :string.option/alignment :ui/element :ui.element/radio-select} :offset-x {:type :option.type/range :min -50 :max 50 :default 0 :ui/label :string.option/offset-x :ui/step 0.1} :offset-y {:type :option.type/range :min -75 :max 75 :default 0 :ui/label :string.option/offset-y :ui/step 0.1} :ui/label :string.option/anchor :ui/element :ui.element/position} :orientation (cond-> {:point orientation-point-option :ui/label :string.option/orientation :ui/element :ui.element/position} (= current-orientation-point :angle) (assoc :angle {:type :option.type/range :min (cond (#{:top-left :top-right :bottom-left :bottom-right} current-anchor-point) 0 :else -90) :max 90 :default (cond (#{:top-left :top-right :bottom-left :bottom-right} current-anchor-point) 45 :else 0) :ui/label :string.option/angle}) (not= current-orientation-point :angle) (assoc :offset-x {:type :option.type/range :min -50 :max 50 :default 0 :ui/label :string.option/offset-x :ui/step 0.1} :offset-y {:type :option.type/range :min -75 :max 75 :default 0 :ui/label :string.option/offset-y :ui/step 0.1} :type {:type :option.type/choice :choices orientation-type-choices :default :edge :ui/label :string.render-options/mode :ui/element :ui.element/radio-select})) :line line-style :opposite-line opposite-line-style :geometry {:size-mode size-mode-option :size {:type :option.type/range :min 5 :max 120 :default (case current-size-mode :thickness 75 30) :ui/label :string.option/size :ui/step 0.1} :stretch {:type :option.type/range :min 0.33 :max 2 :default 0.85 :ui/label :string.option/stretch :ui/step 0.01} :ui/label :string.option/geometry :ui/element :ui.element/geometry} :outline? options/plain-outline?-option :cottising (cottising/add-cottising context 1)} context))) (defmethod interface/properties ordinary-type [context] (let [{:keys [width height] :as parent-environment} (interface/get-parent-field-environment context) geometry (interface/get-sanitized-data (c/++ context :geometry)) anchor (interface/get-sanitized-data (c/++ context :anchor)) orientation (interface/get-sanitized-data (c/++ context :orientation)) percentage-base (if (#{:left :right :dexter :sinister} (:point anchor)) height width) parent-shape (interface/get-parent-field-shape context) {anchor-point :anchor point :point thickness :thickness} (pile/calculate-properties parent-environment parent-shape anchor (cond-> orientation (#{:top-right :right :bottom-left} (:point anchor)) (update :angle #(when % (- %)))) geometry percentage-base (case (:point anchor) :top-left 0 :top 90 :top-right 180 :left 0 :right 180 :bottom-left 0 :bottom -90 :bottom-right 180 0)) pile-angle (angle/normalize (v/angle-to-point point anchor-point)) {left-point :left right-point :right} (pile/diagonals anchor-point point thickness) intersection-left (v/last-intersection-with-shape point left-point parent-shape :default? true) intersection-right (v/last-intersection-with-shape point right-point parent-shape :default? true) joint-angle (angle/normalize (v/angle-between-vectors (v/sub intersection-left point) (v/sub intersection-right point))) line-length (max (v/abs (v/sub intersection-left point)) (v/abs (v/sub intersection-right point)))] (post-process/properties {:type ordinary-type :upper [intersection-left point intersection-right] :pile-angle pile-angle :joint-angle joint-angle :thickness thickness :line-length line-length :percentage-base percentage-base :humetty-percentage-base (min width height) :voided-percentage-base (/ thickness 2)} context))) (defmethod interface/environment ordinary-type [context] (let [{[left point right] :upper} (interface/get-properties context) bounding-box-points [point left right]] (environment/create (bb/from-points bounding-box-points)))) (defmethod interface/render-shape ordinary-type [context] (let [{:keys [line opposite-line] [left point right] :upper :as properties} (interface/get-properties context) {:keys [bounding-box]} (interface/get-parent-field-environment context) line-left (line/create-with-extension context line point left bounding-box :reversed? true :extend-from? false) line-right (line/create-with-extension context opposite-line point right bounding-box :extend-from? false)] (post-process/shape {:shape [(shape/build-shape context line-left line-right :clockwise-shortest)] :edges [{:lines [line-left line-right]}]} context properties))) (defmethod cottising/cottise-properties ordinary-type [context {:keys [line-length percentage-base pile-angle joint-angle humetty] [reference-left reference-point reference-right] :upper reference-line :line}] (when-not (-> (cottising/kind context) name (str/starts-with? "cottise-opposite")) (let [distance (interface/get-sanitized-data (c/++ context :distance)) distance (math/percent-of percentage-base distance) thickness (interface/get-sanitized-data (c/++ context :thickness)) band-size (math/percent-of percentage-base thickness) [base-corner base-left base-right] [reference-point reference-left reference-right] real-distance (/ (+ (:effective-height reference-line) distance) (Math/sin (-> joint-angle (* Math/PI) (/ 180) (/ 2)))) delta (/ band-size (Math/sin (-> joint-angle (* Math/PI) (/ 180) (/ 2)))) dist-vector (v/rotate (v/Vector. real-distance 0) pile-angle) band-size-vector (v/rotate (v/Vector. delta 0) pile-angle) lower-corner (v/sub base-corner dist-vector) upper-corner (v/sub lower-corner band-size-vector) [lower-left lower-right] (map #(v/sub % dist-vector) [base-left base-right]) [upper-left upper-right] (map #(v/sub % band-size-vector) [lower-left lower-right])] (post-process/properties {:type :heraldry.ordinary.type/chevron :upper [upper-left upper-corner upper-right] :lower [lower-left lower-corner lower-right] :chevron-angle pile-angle :joint-angle joint-angle :band-size band-size :line-length line-length :percentage-base percentage-base :humetty humetty} context))))
570485c2b928d90d0041f83b3d8129d6e6e2e3c7152ade6979fc3bbbd1eeeaad
kirasystems/clj-browserchannel
dom-helpers.cljs
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns bc.dom-helpers (:require [clojure.string :as string] [goog.style :as style] [goog.dom :as dom] [goog.dom.classes :as classes] [goog.dom.forms :as forms] [goog.fx :as fx] [goog.fx.dom :as fx-dom] [goog.Timer :as timer] )) (defn get-element "Return the element with the passed id." [id] (dom/getElement (name id))) (defn show-element [e b] (style/showElement e b)) (defn add-remove-class [e add-classes remove-classes] (classes/addRemove e remove-classes add-classes)) (defn get-radio-value [form-name name] (forms/getValueByName (get-element form-name) name)) (defn value [element] (forms/getValue element)) (defn set-value [element] (forms/setValue element)) (defn set-disabled [element disabled] (forms/setDisabled element disabled)) (defn append "Append all children to parent." [parent & children] (do (doseq [child children] (dom/appendChild parent child)) parent)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (let [e (if (or (keyword? e) (string? e)) (get-element e) e)] (doto e (dom/setTextContent s)))) (defn normalize-args [tag args] (let [parts (string/split tag #"(\.|#)") [tag attrs] [(first parts) (apply hash-map (map #(cond (= % ".") :class (= % "#") :id :else %) (rest parts)))]] (if (map? (first args)) [tag (merge attrs (first args)) (rest args)] [tag attrs args]))) ;; TODO: replace call to .strobj with whatever we come up with for creating js objects from Clojure maps . (defn element "Create a dom element using a keyword for the element name and a map for the attributes. Append all children to parent. If the first child is a string then the string will be set as the text content of the parent and all remaining children will be appended." [tag & args] (let [[tag attrs children] (normalize-args tag args) ;; keyword/string mangling screws up (name tag) parent (dom/createDom (subs tag 1) (. (reduce (fn [m [k v]] (assoc m k v)) {} (map #(vector (name %1) %2) (keys attrs) (vals attrs))) -strobj)) [parent children] (if (string? (first children)) [(set-text (element tag attrs) (first children)) (rest children)] [parent children])] (apply append parent children))) (defn remove-children "Remove all children from the element with the passed id." [parent-el] (dom/removeChildren parent-el)) (defn html "Create a dom element from an html string." [s] (dom/htmlToDocumentFragment s)) (defn- element-arg? [x] (or (keyword? x) (map? x) (string? x))) (defn build "Build up a dom element from nested vectors." [x] (if (vector? x) (let [[parent children] (if (keyword? (first x)) [(apply element (take-while element-arg? x)) (drop-while element-arg? x)] [(first x) (rest x)]) children (map build children)] (apply append parent children)) x)) (defn insert-at "Insert a child element at a specific location." [parent child index] (dom/insertChildAt parent child index)) (defn set-timeout [func ttime] (timer/callOnce func ttime)) (defn set-position [e x y] (style/setPosition e x y)) (defn get-position [e] (style/getPosition e)) (defn toggle-class [el classname] (classes/toggle el classname)) (defn add-class [el classname] (classes/add el classname)) (defn remove-class [el classname] (classes/remove el classname))
null
https://raw.githubusercontent.com/kirasystems/clj-browserchannel/68d2ebc6336fbf7d71e6e54d61ca85bb4b2546af/chat-demo/cljs/bc/dom-helpers.cljs
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. TODO: replace call to .strobj with whatever we come up with for keyword/string mangling screws up (name tag)
Copyright ( c ) . All rights reserved . (ns bc.dom-helpers (:require [clojure.string :as string] [goog.style :as style] [goog.dom :as dom] [goog.dom.classes :as classes] [goog.dom.forms :as forms] [goog.fx :as fx] [goog.fx.dom :as fx-dom] [goog.Timer :as timer] )) (defn get-element "Return the element with the passed id." [id] (dom/getElement (name id))) (defn show-element [e b] (style/showElement e b)) (defn add-remove-class [e add-classes remove-classes] (classes/addRemove e remove-classes add-classes)) (defn get-radio-value [form-name name] (forms/getValueByName (get-element form-name) name)) (defn value [element] (forms/getValue element)) (defn set-value [element] (forms/setValue element)) (defn set-disabled [element disabled] (forms/setDisabled element disabled)) (defn append "Append all children to parent." [parent & children] (do (doseq [child children] (dom/appendChild parent child)) parent)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (let [e (if (or (keyword? e) (string? e)) (get-element e) e)] (doto e (dom/setTextContent s)))) (defn normalize-args [tag args] (let [parts (string/split tag #"(\.|#)") [tag attrs] [(first parts) (apply hash-map (map #(cond (= % ".") :class (= % "#") :id :else %) (rest parts)))]] (if (map? (first args)) [tag (merge attrs (first args)) (rest args)] [tag attrs args]))) creating js objects from Clojure maps . (defn element "Create a dom element using a keyword for the element name and a map for the attributes. Append all children to parent. If the first child is a string then the string will be set as the text content of the parent and all remaining children will be appended." [tag & args] (let [[tag attrs children] (normalize-args tag args) parent (dom/createDom (subs tag 1) (. (reduce (fn [m [k v]] (assoc m k v)) {} (map #(vector (name %1) %2) (keys attrs) (vals attrs))) -strobj)) [parent children] (if (string? (first children)) [(set-text (element tag attrs) (first children)) (rest children)] [parent children])] (apply append parent children))) (defn remove-children "Remove all children from the element with the passed id." [parent-el] (dom/removeChildren parent-el)) (defn html "Create a dom element from an html string." [s] (dom/htmlToDocumentFragment s)) (defn- element-arg? [x] (or (keyword? x) (map? x) (string? x))) (defn build "Build up a dom element from nested vectors." [x] (if (vector? x) (let [[parent children] (if (keyword? (first x)) [(apply element (take-while element-arg? x)) (drop-while element-arg? x)] [(first x) (rest x)]) children (map build children)] (apply append parent children)) x)) (defn insert-at "Insert a child element at a specific location." [parent child index] (dom/insertChildAt parent child index)) (defn set-timeout [func ttime] (timer/callOnce func ttime)) (defn set-position [e x y] (style/setPosition e x y)) (defn get-position [e] (style/getPosition e)) (defn toggle-class [el classname] (classes/toggle el classname)) (defn add-class [el classname] (classes/add el classname)) (defn remove-class [el classname] (classes/remove el classname))
84591bd7a7f42530fc5ee35d923f59ed5beca23b9d76dcb8660fa41485000b23
yuriy-chumak/ol
process.scm
(import (prefix (owl sys) sys-)) (define exit-values '(42 43 44)) (print "forking children") (define pids (map (λ (exit-val) (let ((x (sys-fork))) (cond ((not x) (print "FORK FAILED") #false) ((eq? x #true) ;; exit with given value from child processes (halt exit-val)) (else ;; return pid to parent x)))) exit-values)) (print "forked child processes") (for-each (λ (pid) (print "child exited with " (sys-wait pid))) pids) (print "done")
null
https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/disabled/process.scm
scheme
exit with given value from child processes return pid to parent
(import (prefix (owl sys) sys-)) (define exit-values '(42 43 44)) (print "forking children") (define pids (map (λ (exit-val) (let ((x (sys-fork))) (cond ((not x) (print "FORK FAILED") #false) ((eq? x #true) (halt exit-val)) (else x)))) exit-values)) (print "forked child processes") (for-each (λ (pid) (print "child exited with " (sys-wait pid))) pids) (print "done")
330dc81135118799dc1e5989838d466c070a0b64bc3f55984fd2e33a255b4cf9
manuel-serrano/bigloo
statexp.scm
;*=====================================================================*/ * ... /prgm / project / bigloo / / comptime / Module / statexp.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue Jun 4 10:58:45 1996 * / * Last change : Sun Apr 14 08:20:20 2019 ( serrano ) * / * Copyright : 1996 - 2019 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* The static clauses compilation. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module module_statexp (include "Ast/unit.sch") (import module_module module_prototype module_class expand_expander tools_error tools_args tools_location type_type object_class ast_var ast_ident ast_find-gdefs ast_glo-decl) (export (make-static-compiler) (make-export-compiler))) ;*---------------------------------------------------------------------*/ ;* make-static-compiler ... */ ;*---------------------------------------------------------------------*/ (define (make-static-compiler) (instantiate::ccomp (id 'static) (producer statexp-producer))) ;*---------------------------------------------------------------------*/ ;* make-export-compiler ... */ ;*---------------------------------------------------------------------*/ (define (make-export-compiler) (instantiate::ccomp (id 'export) (producer statexp-producer) (consumer export-consumer) (finalizer statexp-finalizer))) ;*---------------------------------------------------------------------*/ ;* statexp-producer ... */ ;*---------------------------------------------------------------------*/ (define (statexp-producer clause) (let ((mode (car clause))) (match-case clause ((?- . ?protos) (for-each (lambda (proto) (statexp-parser proto mode)) protos) '()) (else (user-error/location (find-location *module-clause*) (format "Parse error \"~a\" clause" (string-downcase (symbol->string mode))) clause '()))))) ;*---------------------------------------------------------------------*/ ;* export-consumer ... */ ;*---------------------------------------------------------------------*/ (define (export-consumer module clause) (match-case clause ((?- . ?protos) protos) (else (user-error/location (find-location *module-clause*) "Parse error" "Illegal \"export\" clause" clause '())))) ;*---------------------------------------------------------------------*/ ;* statexp-parser ... */ ;*---------------------------------------------------------------------*/ (define (statexp-parser prototype import) (let ((proto (parse-prototype prototype))) (if (not (pair? proto)) (user-error/location (find-location *module-clause*) "Parse error" "Illegal prototype" prototype '()) (case (car proto) ((sfun sifun sgfun) (to-be-define! (declare-global-sfun! (cadr proto) #f (caddr proto) *module* import (car proto) prototype #f))) ((svar) (to-be-define! (declare-global-svar! (cadr proto) #f *module* import prototype #f))) ((class) (to-be-declare! (delay (declare-class! (cdr proto) *module* import #f #f prototype #f)))) ((abstract-class) (to-be-declare! (delay (declare-class! (cdr proto) *module* import #f #t prototype #f)))) ((final-class) (to-be-declare! (delay (declare-class! (cdr proto) *module* import #t #f prototype #f)))) ((wide-class) (to-be-declare! (delay (declare-wide-class! (cdr proto) *module* import prototype #f)))) ((define-macro) (eval proto)) ((macro) (to-be-macro! (cadr proto) prototype)) ((syntax) (to-be-macro! (cadr proto) prototype)) ((expander) (to-be-macro! (cadr proto) prototype)) (else (user-error "Parse error" "Illegal prototype" prototype '())))))) ;*---------------------------------------------------------------------*/ ;* *local-classes* ... */ ;*---------------------------------------------------------------------*/ (define *local-classes* '()) ;*---------------------------------------------------------------------*/ ;* to-be-declare! ... */ ;*---------------------------------------------------------------------*/ (define (to-be-declare! exp) (set! *local-classes* (cons exp *local-classes*))) ;*---------------------------------------------------------------------*/ ;* statexp-finalizer ... */ ;* ------------------------------------------------------------- */ ;* we declare local classes. They must be declared after imported */ ;* classes (then after the finalization of imported modules) */ ;* otherwise the class declaration process would fail when checking */ ;* the super class types (saying something like they are not */ ;* classes). That why we have froozen their declaration until now. */ ;*---------------------------------------------------------------------*/ (define (statexp-finalizer) ;; we declare local classes (for-each force (reverse! *local-classes*)) (set! *local-classes* '()) ;; and we can finalize them (let ((classes (class-finalizer))) (if (pair? classes) classes 'void)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/comptime/Module/statexp.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * The static clauses compilation. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * make-static-compiler ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * make-export-compiler ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * statexp-producer ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * export-consumer ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * statexp-parser ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *local-classes* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * to-be-declare! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * statexp-finalizer ... */ * ------------------------------------------------------------- */ * we declare local classes. They must be declared after imported */ * classes (then after the finalization of imported modules) */ * otherwise the class declaration process would fail when checking */ * the super class types (saying something like they are not */ * classes). That why we have froozen their declaration until now. */ *---------------------------------------------------------------------*/ we declare local classes and we can finalize them
* ... /prgm / project / bigloo / / comptime / Module / statexp.scm * / * Author : * / * Creation : Tue Jun 4 10:58:45 1996 * / * Last change : Sun Apr 14 08:20:20 2019 ( serrano ) * / * Copyright : 1996 - 2019 , see LICENSE file * / (module module_statexp (include "Ast/unit.sch") (import module_module module_prototype module_class expand_expander tools_error tools_args tools_location type_type object_class ast_var ast_ident ast_find-gdefs ast_glo-decl) (export (make-static-compiler) (make-export-compiler))) (define (make-static-compiler) (instantiate::ccomp (id 'static) (producer statexp-producer))) (define (make-export-compiler) (instantiate::ccomp (id 'export) (producer statexp-producer) (consumer export-consumer) (finalizer statexp-finalizer))) (define (statexp-producer clause) (let ((mode (car clause))) (match-case clause ((?- . ?protos) (for-each (lambda (proto) (statexp-parser proto mode)) protos) '()) (else (user-error/location (find-location *module-clause*) (format "Parse error \"~a\" clause" (string-downcase (symbol->string mode))) clause '()))))) (define (export-consumer module clause) (match-case clause ((?- . ?protos) protos) (else (user-error/location (find-location *module-clause*) "Parse error" "Illegal \"export\" clause" clause '())))) (define (statexp-parser prototype import) (let ((proto (parse-prototype prototype))) (if (not (pair? proto)) (user-error/location (find-location *module-clause*) "Parse error" "Illegal prototype" prototype '()) (case (car proto) ((sfun sifun sgfun) (to-be-define! (declare-global-sfun! (cadr proto) #f (caddr proto) *module* import (car proto) prototype #f))) ((svar) (to-be-define! (declare-global-svar! (cadr proto) #f *module* import prototype #f))) ((class) (to-be-declare! (delay (declare-class! (cdr proto) *module* import #f #f prototype #f)))) ((abstract-class) (to-be-declare! (delay (declare-class! (cdr proto) *module* import #f #t prototype #f)))) ((final-class) (to-be-declare! (delay (declare-class! (cdr proto) *module* import #t #f prototype #f)))) ((wide-class) (to-be-declare! (delay (declare-wide-class! (cdr proto) *module* import prototype #f)))) ((define-macro) (eval proto)) ((macro) (to-be-macro! (cadr proto) prototype)) ((syntax) (to-be-macro! (cadr proto) prototype)) ((expander) (to-be-macro! (cadr proto) prototype)) (else (user-error "Parse error" "Illegal prototype" prototype '())))))) (define *local-classes* '()) (define (to-be-declare! exp) (set! *local-classes* (cons exp *local-classes*))) (define (statexp-finalizer) (for-each force (reverse! *local-classes*)) (set! *local-classes* '()) (let ((classes (class-finalizer))) (if (pair? classes) classes 'void)))
807b5ea46583a2a5ca28a86481d2185955d55afa48be3ca4fda98503725f408e
EFanZh/EOPL-Exercises
exercise-5.x-letrec-lang-registers.rkt
#lang eopl ;; Grammar. (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (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 ("-" "(" expression "," expression ")") diff-exp] [expression ("zero?" "(" expression ")") zero?-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] [expression ("letrec" identifier "(" (separated-list identifier ",") ")" "=" expression "in" expression) letrec-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) ;; Data structures. (define-datatype proc proc? [procedure [bvars (list-of symbol?)] [body expression?] [env environment?]]) (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-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval expval?] [saved-env environment?]] [extend-env-rec [p-name symbol?] [b-vars (list-of symbol?)] [p-body expression?] [saved-env environment?]]) (define identifier? symbol?) (define-datatype continuation continuation? [end-cont] [zero1-cont [saved-cont continuation?]] [let-exp-cont [var identifier?] [body expression?] [saved-env environment?] [saved-cont continuation?]] [if-test-cont [exp2 expression?] [exp3 expression?] [saved-env environment?] [saved-cont continuation?]] [diff1-cont [exp2 expression?] [saved-env environment?] [saved-cont continuation?]] [diff2-cont [val1 expval?] [saved-cont continuation?]] [rator-cont [rands (list-of expression?)] [saved-env environment?] [saved-cont continuation?]] [rand-cont [val1 expval?] [vals (list-of expval?)] [rands (list-of expression?)] [saved-env environment?] [saved-cont continuation?]]) ;; Interpreter. (define exp 'uninitialized) (define env 'uninitialized) (define cont 'uninitialized) (define val 'uninitialized) (define vals 'uninitialized) (define proc1 'uninitialized) (define apply-procedure/k (lambda () (cases proc proc1 [procedure (vars body saved-env) (set! exp body) (set! env (let loop ([env saved-env] [vars vars] [vals vals]) (if (null? vars) env (loop (extend-env (car vars) (car vals) env) (cdr vars) (cdr vals))))) (value-of/k)]))) (define used-end-conts '()) (define apply-cont (lambda () (cases continuation cont [end-cont () (if (memq cont used-end-conts) (eopl:error "Continuation is already used.") (begin (set! used-end-conts (cons cont used-end-conts)) val))] [zero1-cont (saved-cont) (set! cont saved-cont) (set! val (bool-val (zero? (expval->num val)))) (apply-cont)] [let-exp-cont (var body saved-env saved-cont) (set! cont saved-cont) (set! exp body) (set! env (extend-env var val saved-env)) (value-of/k)] [if-test-cont (exp2 exp3 saved-env saved-cont) (set! cont saved-cont) (if (expval->bool val) (set! exp exp2) (set! exp exp3)) (set! env saved-env) (value-of/k)] [diff1-cont (exp2 saved-env saved-cont) (set! cont (diff2-cont val saved-cont)) (set! exp exp2) (set! env saved-env) (value-of/k)] [diff2-cont (val1 saved-cont) (let ([num1 (expval->num val1)] [num2 (expval->num val)]) (set! cont saved-cont) (set! val (num-val (- num1 num2))) (apply-cont))] [rator-cont (rands saved-env saved-cont) (if (null? rands) (let ([rator-proc (expval->proc val)]) (set! cont saved-cont) (set! proc1 rator-proc) (apply-procedure/k)) (begin (set! cont (rand-cont val '() (cdr rands) saved-env saved-cont)) (set! exp (car rands)) (set! env saved-env) (value-of/k)))] [rand-cont (rator-val rand-vals rand-exps saved-env saved-cont) (if (null? rand-exps) (let ([rator-proc (expval->proc rator-val)]) (set! cont saved-cont) (set! proc1 rator-proc) (set! vals (reverse (cons val rand-vals))) (apply-procedure/k)) (begin (set! cont (rand-cont rator-val (cons val rand-vals) (cdr rand-exps) saved-env saved-cont)) (set! exp (car rand-exps)) (set! env saved-env) (value-of/k)))]))) (define apply-env (lambda (env search-sym) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)] [extend-env (var val saved-env) (if (eqv? search-sym var) val (apply-env saved-env search-sym))] [extend-env-rec (p-name b-var p-body saved-env) (if (eqv? search-sym p-name) (proc-val (procedure b-var p-body env)) (apply-env saved-env search-sym))]))) (define value-of/k (lambda () (cases expression exp [const-exp (num) (set! val (num-val num)) (apply-cont)] [var-exp (var) (set! val (apply-env env var)) (apply-cont)] [proc-exp (vars body) (set! val (proc-val (procedure vars body env))) (apply-cont)] [letrec-exp (p-name b-vars p-body letrec-body) (set! exp letrec-body) (set! env (extend-env-rec p-name b-vars p-body env)) (value-of/k)] [zero?-exp (exp1) (set! cont (zero1-cont cont)) (set! exp exp1) (value-of/k)] [let-exp (var exp1 body) (set! cont (let-exp-cont var body env cont)) (set! exp exp1) (value-of/k)] [if-exp (exp1 exp2 exp3) (set! cont (if-test-cont exp2 exp3 env cont)) (set! exp exp1) (value-of/k)] [diff-exp (exp1 exp2) (set! cont (diff1-cont exp2 env cont)) (set! exp exp1) (value-of/k)] [call-exp (rator rands) (set! cont (rator-cont rands env cont)) (set! exp rator) (value-of/k)]))) (define (init-env) (empty-env)) (define value-of-program (lambda (pgm) (cases program pgm [a-program (body) (set! cont (end-cont)) (set! exp body) (set! env (init-env)) (value-of/k)]))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val num-val run)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-5.x-letrec-lang-registers.rkt
racket
Grammar. Data structures. Interpreter.
#lang eopl (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (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 ("-" "(" expression "," expression ")") diff-exp] [expression ("zero?" "(" expression ")") zero?-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] [expression ("letrec" identifier "(" (separated-list identifier ",") ")" "=" expression "in" expression) letrec-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define-datatype proc proc? [procedure [bvars (list-of symbol?)] [body expression?] [env environment?]]) (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-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval expval?] [saved-env environment?]] [extend-env-rec [p-name symbol?] [b-vars (list-of symbol?)] [p-body expression?] [saved-env environment?]]) (define identifier? symbol?) (define-datatype continuation continuation? [end-cont] [zero1-cont [saved-cont continuation?]] [let-exp-cont [var identifier?] [body expression?] [saved-env environment?] [saved-cont continuation?]] [if-test-cont [exp2 expression?] [exp3 expression?] [saved-env environment?] [saved-cont continuation?]] [diff1-cont [exp2 expression?] [saved-env environment?] [saved-cont continuation?]] [diff2-cont [val1 expval?] [saved-cont continuation?]] [rator-cont [rands (list-of expression?)] [saved-env environment?] [saved-cont continuation?]] [rand-cont [val1 expval?] [vals (list-of expval?)] [rands (list-of expression?)] [saved-env environment?] [saved-cont continuation?]]) (define exp 'uninitialized) (define env 'uninitialized) (define cont 'uninitialized) (define val 'uninitialized) (define vals 'uninitialized) (define proc1 'uninitialized) (define apply-procedure/k (lambda () (cases proc proc1 [procedure (vars body saved-env) (set! exp body) (set! env (let loop ([env saved-env] [vars vars] [vals vals]) (if (null? vars) env (loop (extend-env (car vars) (car vals) env) (cdr vars) (cdr vals))))) (value-of/k)]))) (define used-end-conts '()) (define apply-cont (lambda () (cases continuation cont [end-cont () (if (memq cont used-end-conts) (eopl:error "Continuation is already used.") (begin (set! used-end-conts (cons cont used-end-conts)) val))] [zero1-cont (saved-cont) (set! cont saved-cont) (set! val (bool-val (zero? (expval->num val)))) (apply-cont)] [let-exp-cont (var body saved-env saved-cont) (set! cont saved-cont) (set! exp body) (set! env (extend-env var val saved-env)) (value-of/k)] [if-test-cont (exp2 exp3 saved-env saved-cont) (set! cont saved-cont) (if (expval->bool val) (set! exp exp2) (set! exp exp3)) (set! env saved-env) (value-of/k)] [diff1-cont (exp2 saved-env saved-cont) (set! cont (diff2-cont val saved-cont)) (set! exp exp2) (set! env saved-env) (value-of/k)] [diff2-cont (val1 saved-cont) (let ([num1 (expval->num val1)] [num2 (expval->num val)]) (set! cont saved-cont) (set! val (num-val (- num1 num2))) (apply-cont))] [rator-cont (rands saved-env saved-cont) (if (null? rands) (let ([rator-proc (expval->proc val)]) (set! cont saved-cont) (set! proc1 rator-proc) (apply-procedure/k)) (begin (set! cont (rand-cont val '() (cdr rands) saved-env saved-cont)) (set! exp (car rands)) (set! env saved-env) (value-of/k)))] [rand-cont (rator-val rand-vals rand-exps saved-env saved-cont) (if (null? rand-exps) (let ([rator-proc (expval->proc rator-val)]) (set! cont saved-cont) (set! proc1 rator-proc) (set! vals (reverse (cons val rand-vals))) (apply-procedure/k)) (begin (set! cont (rand-cont rator-val (cons val rand-vals) (cdr rand-exps) saved-env saved-cont)) (set! exp (car rand-exps)) (set! env saved-env) (value-of/k)))]))) (define apply-env (lambda (env search-sym) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)] [extend-env (var val saved-env) (if (eqv? search-sym var) val (apply-env saved-env search-sym))] [extend-env-rec (p-name b-var p-body saved-env) (if (eqv? search-sym p-name) (proc-val (procedure b-var p-body env)) (apply-env saved-env search-sym))]))) (define value-of/k (lambda () (cases expression exp [const-exp (num) (set! val (num-val num)) (apply-cont)] [var-exp (var) (set! val (apply-env env var)) (apply-cont)] [proc-exp (vars body) (set! val (proc-val (procedure vars body env))) (apply-cont)] [letrec-exp (p-name b-vars p-body letrec-body) (set! exp letrec-body) (set! env (extend-env-rec p-name b-vars p-body env)) (value-of/k)] [zero?-exp (exp1) (set! cont (zero1-cont cont)) (set! exp exp1) (value-of/k)] [let-exp (var exp1 body) (set! cont (let-exp-cont var body env cont)) (set! exp exp1) (value-of/k)] [if-exp (exp1 exp2 exp3) (set! cont (if-test-cont exp2 exp3 env cont)) (set! exp exp1) (value-of/k)] [diff-exp (exp1 exp2) (set! cont (diff1-cont exp2 env cont)) (set! exp exp1) (value-of/k)] [call-exp (rator rands) (set! cont (rator-cont rands env cont)) (set! exp rator) (value-of/k)]))) (define (init-env) (empty-env)) (define value-of-program (lambda (pgm) (cases program pgm [a-program (body) (set! cont (end-cont)) (set! exp body) (set! env (init-env)) (value-of/k)]))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val num-val run)
823dd100760fb08369ab21b1c4c958ca4cb9b6a7908625e6efff70c38b91c0b7
justinethier/nugget
lambda.scm
; TODO: the body should be surrounded by an implicit begin, but ; that is not happening in the compiler (lambda (x y) 1 (* x y) x y)
null
https://raw.githubusercontent.com/justinethier/nugget/0c4e3e9944684ea83191671d58b5c8c342f64343/cyclone/tests/lambda.scm
scheme
TODO: the body should be surrounded by an implicit begin, but that is not happening in the compiler
(lambda (x y) 1 (* x y) x y)
b660605ced3d75947cadd63385e40823a74f0bbc1d1c862acad71250dcc18a8a
Rhywun/get-programming-with-haskell
fibo.hs
fastFib :: Int -> Int -> Int -> Int fastFib n1 _ 1 = n1 fastFib _ n2 2 = n2 fastFib n1 n2 3 = n1 + n2 fastFib n1 n2 counter = fastFib (n1 + n2) n1 (counter - 1) fib 30 = = 832040 < -- 0.00 sec fib 35 = = 9227465 < -- 0.00 sec fib 1000 = = ... long number ... < -- 0.00 sec fib 30 == 832040 <-- 0.00 sec fib 35 == 9227465 <-- 0.00 sec fib 1000 == ...long number... <-- 0.00 sec -} fib :: Int -> Int fib = fastFib 1 1 main :: IO () main = do putStr "Number? " n <- getLine let result = fib $ read n putStrLn ("fib " ++ n ++ " = " ++ show result)
null
https://raw.githubusercontent.com/Rhywun/get-programming-with-haskell/b9cf06f725b2ef038d69ed49f7d2900f55e98ca3/Unit04/Lesson21/fibo.hs
haskell
0.00 sec 0.00 sec 0.00 sec 0.00 sec 0.00 sec 0.00 sec
fastFib :: Int -> Int -> Int -> Int fastFib n1 _ 1 = n1 fastFib _ n2 2 = n2 fastFib n1 n2 3 = n1 + n2 fastFib n1 n2 counter = fastFib (n1 + n2) n1 (counter - 1) -} fib :: Int -> Int fib = fastFib 1 1 main :: IO () main = do putStr "Number? " n <- getLine let result = fib $ read n putStrLn ("fib " ++ n ++ " = " ++ show result)
532168f2b28070491d7e0f1b3e43fb6627bb292f5395ed6bb0dffffbcf2bedf9
TomerAberbach/programming-in-haskell-exercises
9.hs
sum :: Num a => [a] -> a sum [] = 0 sum (n:ns) = n + Main.sum ns take :: Int -> [a] -> [a] take 0 _ = [] take _ [] = [] take n (x:xs) = x : Main.take (n - 1) xs last :: [a] -> a last [x] = x last (_:xs) = Main.last xs
null
https://raw.githubusercontent.com/TomerAberbach/programming-in-haskell-exercises/a66830529ebc9c4d84d0e4c6e0ad58041b46bc32/parts/1/chapters/6/9.hs
haskell
sum :: Num a => [a] -> a sum [] = 0 sum (n:ns) = n + Main.sum ns take :: Int -> [a] -> [a] take 0 _ = [] take _ [] = [] take n (x:xs) = x : Main.take (n - 1) xs last :: [a] -> a last [x] = x last (_:xs) = Main.last xs
a0a244dcfc7e629c6f6c8e14749846d9cd88ffe2edcacf95e0442aab7244d8a5
the-dr-lazy/cascade
TestClient.hs
| Module : Cascade . Api . Network . TestClient Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Api.Network.TestClient Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Api.Network.TestClient ( AuthToken , api , authenticated , interpret ) where import Cascade.Api.Data.Jwt ( JwtSections ) import Cascade.Api.Network.Anatomy ( Routes ) import qualified Cascade.Api.Network.Anatomy.Api as Api import Cascade.Api.Servant.Authentication import Control.Lens ( (^.) ) import Control.Monad.Free import qualified Data.Binary.Builder as Builder import qualified Data.ByteString.Lazy as LW8 import qualified Data.Sequence as Seq import qualified Network.HTTP.Client as Http import Network.HTTP.Types ( hCookie ) import Servant.API.Generic ( fromServant ) import Servant.Client.Core import Servant.Client.Free ( ClientF (..) ) import Servant.Client.Generic ( AsClientT, genericClient ) import qualified Servant.Client.Internal.HttpClient as Http ( clientResponseToResponse, defaultMakeClientRequest ) import Web.Cookie ( renderCookies ) client :: Routes (AsClientT (Free ClientF)) client = genericClient api :: Api.Routes (AsClientT (Free ClientF)) api = fromServant $ client ^. #api interpret :: Free ClientF a -> IO (ResponseF a) interpret x = case x of Pure _ -> error "ERROR: got (Pure a)." Free (Throw clientError ) -> error $ "ERROR: " <> show clientError Free (RunRequest request parse) -> do baseUrl <- parseBaseUrl ":3141" manager <- Http.newManager Http.defaultManagerSettings let request' = Http.defaultMakeClientRequest baseUrl request response' <- Http.httpLbs request' manager let response = Http.clientResponseToResponse identity response' case parse response of Pure body -> pure $ response $> body Free (Throw clientError) -> error $ "ERROR: " <> show clientError _ -> error "ERROR: didn't got response." type instance AuthClientData Auth = JwtSections type AuthToken = AuthClientData Auth authenticated :: AuthToken -> AuthenticatedRequest Auth authenticated sections@(headerAndPayload, sig) = mkAuthenticatedRequest sections \_ request -> request { requestHeaders = request |> requestHeaders |> (Seq.|> (hCookie, cookie)) } where cookie = renderCookies [(headerAndPayloadCookieName, headerAndPayload), (signatureCookieName, sig)] |> Builder.toLazyByteString |> toStrict
null
https://raw.githubusercontent.com/the-dr-lazy/cascade/7b3679639b509c5605392c124683a386c6f57c09/cascade-api/test/Cascade/Api/Network/TestClient.hs
haskell
| Module : Cascade . Api . Network . TestClient Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Api.Network.TestClient Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Api.Network.TestClient ( AuthToken , api , authenticated , interpret ) where import Cascade.Api.Data.Jwt ( JwtSections ) import Cascade.Api.Network.Anatomy ( Routes ) import qualified Cascade.Api.Network.Anatomy.Api as Api import Cascade.Api.Servant.Authentication import Control.Lens ( (^.) ) import Control.Monad.Free import qualified Data.Binary.Builder as Builder import qualified Data.ByteString.Lazy as LW8 import qualified Data.Sequence as Seq import qualified Network.HTTP.Client as Http import Network.HTTP.Types ( hCookie ) import Servant.API.Generic ( fromServant ) import Servant.Client.Core import Servant.Client.Free ( ClientF (..) ) import Servant.Client.Generic ( AsClientT, genericClient ) import qualified Servant.Client.Internal.HttpClient as Http ( clientResponseToResponse, defaultMakeClientRequest ) import Web.Cookie ( renderCookies ) client :: Routes (AsClientT (Free ClientF)) client = genericClient api :: Api.Routes (AsClientT (Free ClientF)) api = fromServant $ client ^. #api interpret :: Free ClientF a -> IO (ResponseF a) interpret x = case x of Pure _ -> error "ERROR: got (Pure a)." Free (Throw clientError ) -> error $ "ERROR: " <> show clientError Free (RunRequest request parse) -> do baseUrl <- parseBaseUrl ":3141" manager <- Http.newManager Http.defaultManagerSettings let request' = Http.defaultMakeClientRequest baseUrl request response' <- Http.httpLbs request' manager let response = Http.clientResponseToResponse identity response' case parse response of Pure body -> pure $ response $> body Free (Throw clientError) -> error $ "ERROR: " <> show clientError _ -> error "ERROR: didn't got response." type instance AuthClientData Auth = JwtSections type AuthToken = AuthClientData Auth authenticated :: AuthToken -> AuthenticatedRequest Auth authenticated sections@(headerAndPayload, sig) = mkAuthenticatedRequest sections \_ request -> request { requestHeaders = request |> requestHeaders |> (Seq.|> (hCookie, cookie)) } where cookie = renderCookies [(headerAndPayloadCookieName, headerAndPayload), (signatureCookieName, sig)] |> Builder.toLazyByteString |> toStrict
d031f3380280a57f913fc2ead3099430bf0f3c1c37965772e43c8ec5a2d72340
thierry-martinez/stdcompat
stdcompat__native.mli
val native : bool
null
https://raw.githubusercontent.com/thierry-martinez/stdcompat/83d786cdb17fae0caadf5c342e283c3dcfee2279/stdcompat__native.mli
ocaml
val native : bool
684e178090de8b421629b382a74d5e5fa78dd088487ba8bc2a6b180b3bf38bdd
yuriy-chumak/ol
por-prime-rand.scm
(import (owl math-prime)) (define num (+ (band (time-ms) #b1111111111) 2)) (define por-opts (map (λ (try) (λ () (ediv num try))) (lrange 2 1 (+ 1 (isqrt num))))) (define (xor a b) (if a b (if b #false (not a)))) (print (if (equal? (prime? num) (not (por* por-opts))) "OK" num))
null
https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/por-prime-rand.scm
scheme
(import (owl math-prime)) (define num (+ (band (time-ms) #b1111111111) 2)) (define por-opts (map (λ (try) (λ () (ediv num try))) (lrange 2 1 (+ 1 (isqrt num))))) (define (xor a b) (if a b (if b #false (not a)))) (print (if (equal? (prime? num) (not (por* por-opts))) "OK" num))
ddac139ec8720964a2c4ecef70619f69af78c5a9daba5996a216d600ad78c345
shayne-fletcher/zen
sub_array.ml
module type LIST_UTILS = sig val take : int -> 'a list -> 'a list val drop : int -> 'a list -> 'a list val slice : 'a list -> int -> int -> 'a list val range : int -> int -> int list val sum : int list -> int end module List_utils : LIST_UTILS = struct let rec take (k : int) (l : 'a list) : 'a list = match (k, l) with | n, _ when n <= 0 -> [] | _, [] -> [] | n, (x :: xs) -> x :: take (n - 1) xs let rec drop (k : int) (l : 'a list) : 'a list = match (k, l) with | n, xs when n <= 0 -> xs | _, [] -> [] | n, (_ :: xs) -> drop (n - 1) xs let slice (l : 'a list) (i : int) (j : int) = take (j - i) (drop i l) let range (s : int) (e : int) : int list = let rec loop acc s e = if s >= e then acc else loop (s :: acc) (s + 1) e in List.rev (loop [] s e) let sum : int list -> int = List.fold_left (fun x y -> x + y) 0 end open List_utils let intervals (l : 'a list) = (*The set of intervals starting at position [i]*) let from (i : int) (l : 'a list) = let s = slice l i (List.length l) in let f acc j = ((i, i + j - 1), sum (slice s 0 j)) :: acc in List.fold_left f [] (range 1 (List.length s + 1)) in The set of all intervals ( [ i = 0 ] to [ i = l - 1 ] List.rev ( List.concat ( List.fold_left (fun acc i -> from i l :: acc) [] (range 0 (List.length l)) ) ) let sub_array_max_sum (l : int list) : ((int * int) * int) list = let t = intervals l in let m = List.fold_left (fun acc (_, s) -> max acc s) min_int t in List.fold_left (fun acc (((_, _), z) as e) -> if z = m then e :: acc else acc) [] t # sub_array_max_sum [ 1 ; 3 ; -8 ; 2 ; -1 ; 10 ; -2 ; 1 ] ; ; - : ( ( int * int ) * int ) list = [ ( ( 3 , 5 ) , 11 ) ] # sub_array_max_sum [1; 3; -8; 2; -1; 10; -2; 1] ;; - : ((int * int) * int) list = [((3, 5), 11)] *)
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/sub_array_max_sum/sub_array.ml
ocaml
The set of intervals starting at position [i]
module type LIST_UTILS = sig val take : int -> 'a list -> 'a list val drop : int -> 'a list -> 'a list val slice : 'a list -> int -> int -> 'a list val range : int -> int -> int list val sum : int list -> int end module List_utils : LIST_UTILS = struct let rec take (k : int) (l : 'a list) : 'a list = match (k, l) with | n, _ when n <= 0 -> [] | _, [] -> [] | n, (x :: xs) -> x :: take (n - 1) xs let rec drop (k : int) (l : 'a list) : 'a list = match (k, l) with | n, xs when n <= 0 -> xs | _, [] -> [] | n, (_ :: xs) -> drop (n - 1) xs let slice (l : 'a list) (i : int) (j : int) = take (j - i) (drop i l) let range (s : int) (e : int) : int list = let rec loop acc s e = if s >= e then acc else loop (s :: acc) (s + 1) e in List.rev (loop [] s e) let sum : int list -> int = List.fold_left (fun x y -> x + y) 0 end open List_utils let intervals (l : 'a list) = let from (i : int) (l : 'a list) = let s = slice l i (List.length l) in let f acc j = ((i, i + j - 1), sum (slice s 0 j)) :: acc in List.fold_left f [] (range 1 (List.length s + 1)) in The set of all intervals ( [ i = 0 ] to [ i = l - 1 ] List.rev ( List.concat ( List.fold_left (fun acc i -> from i l :: acc) [] (range 0 (List.length l)) ) ) let sub_array_max_sum (l : int list) : ((int * int) * int) list = let t = intervals l in let m = List.fold_left (fun acc (_, s) -> max acc s) min_int t in List.fold_left (fun acc (((_, _), z) as e) -> if z = m then e :: acc else acc) [] t # sub_array_max_sum [ 1 ; 3 ; -8 ; 2 ; -1 ; 10 ; -2 ; 1 ] ; ; - : ( ( int * int ) * int ) list = [ ( ( 3 , 5 ) , 11 ) ] # sub_array_max_sum [1; 3; -8; 2; -1; 10; -2; 1] ;; - : ((int * int) * int) list = [((3, 5), 11)] *)
69c8d818ff6ed25f488c32a309c30d531f79b0fc5c1d713277c0298a7aa2834d
acorrenson/Oratio
debuger.ml
(** {1 Debuger} An rewrite of the {! kernel} module to trace executions in stdout. *) open Kernel type thm = Rules.thm type prop = Rules.prop let intro_impl t p = Printf.printf "intro IMPL on (%s) and (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.intro_impl t p let intro_and t1 t2 = Printf.printf "intro AND on (%s) and (%s)\n" (Rules.show_thm t1) (Rules.show_thm t2); Rules.intro_and t1 t2 let intro_or_l t p = Printf.printf "intro OR (left) on (%s) and (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.intro_or_l t p let intro_or_r t p = Printf.printf "intro OR (right) on (%s) and (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.intro_or_r t p let elim_bot t p = Printf.printf "elim BOT from (%s) to get (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.elim_bot t p let elim_impl t1 t2 = let q = Rules.elim_impl t1 t2 in Printf.printf "elim IMPL from (%s) and (%s) to get %s\n" (Rules.show_thm t1) (Rules.show_thm t2) (Rules.show_thm q); q let elim_and_l t = Printf.printf "elim AND (left) from (%s)\n" (Rules.show_thm t); Rules.elim_and_l t let elim_and_r t = Printf.printf "elim AND (right) from (%s)\n" (Rules.show_thm t); Rules.elim_and_r t let elim_or t1 t2 t3 = Printf.printf "elim OR from %s, %s and (%s)\n" (Rules.show_thm t1) (Rules.show_thm t2) (Rules.show_thm t3); Rules.elim_or t1 t2 t3 let axiom l p = Printf.printf "%s is in [%s ]\n" (Logic.show_prop p) (List.fold_left (fun a p -> a ^ " " ^ (Logic.show_prop p)) "" l); Rules.axiom l p
null
https://raw.githubusercontent.com/acorrenson/Oratio/ade8d9a3253270e311ebbcff10cb955bd2c8af42/src/translators/debuger.ml
ocaml
* {1 Debuger} An rewrite of the {! kernel} module to trace executions in stdout.
open Kernel type thm = Rules.thm type prop = Rules.prop let intro_impl t p = Printf.printf "intro IMPL on (%s) and (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.intro_impl t p let intro_and t1 t2 = Printf.printf "intro AND on (%s) and (%s)\n" (Rules.show_thm t1) (Rules.show_thm t2); Rules.intro_and t1 t2 let intro_or_l t p = Printf.printf "intro OR (left) on (%s) and (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.intro_or_l t p let intro_or_r t p = Printf.printf "intro OR (right) on (%s) and (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.intro_or_r t p let elim_bot t p = Printf.printf "elim BOT from (%s) to get (%s)\n" (Rules.show_thm t) (Logic.show_prop p); Rules.elim_bot t p let elim_impl t1 t2 = let q = Rules.elim_impl t1 t2 in Printf.printf "elim IMPL from (%s) and (%s) to get %s\n" (Rules.show_thm t1) (Rules.show_thm t2) (Rules.show_thm q); q let elim_and_l t = Printf.printf "elim AND (left) from (%s)\n" (Rules.show_thm t); Rules.elim_and_l t let elim_and_r t = Printf.printf "elim AND (right) from (%s)\n" (Rules.show_thm t); Rules.elim_and_r t let elim_or t1 t2 t3 = Printf.printf "elim OR from %s, %s and (%s)\n" (Rules.show_thm t1) (Rules.show_thm t2) (Rules.show_thm t3); Rules.elim_or t1 t2 t3 let axiom l p = Printf.printf "%s is in [%s ]\n" (Logic.show_prop p) (List.fold_left (fun a p -> a ^ " " ^ (Logic.show_prop p)) "" l); Rules.axiom l p
feed6207112d00b6d52eaf60f3d75b425ca5679e0d70a9ba58a22b2734431d33
mtesseract/nakadi-client
Problem.hs
| Module : Network . . Types . Problem Description : Nakadi Problem Type Copyright : ( c ) 2017 License : : Stability : experimental Portability : POSIX This module provides the Problem Type . Module : Network.Nakadi.Types.Problem Description : Nakadi Problem Type Copyright : (c) Moritz Clasmeier 2017 License : BSD3 Maintainer : Stability : experimental Portability : POSIX This module provides the Nakadi Problem Type. -} module Network.Nakadi.Types.Problem ( Problem(..) ) where import Network.Nakadi.Internal.Types.Problem
null
https://raw.githubusercontent.com/mtesseract/nakadi-client/f8eef3ac215459081b01b0b48f0b430ae7701f52/src/Network/Nakadi/Types/Problem.hs
haskell
| Module : Network . . Types . Problem Description : Nakadi Problem Type Copyright : ( c ) 2017 License : : Stability : experimental Portability : POSIX This module provides the Problem Type . Module : Network.Nakadi.Types.Problem Description : Nakadi Problem Type Copyright : (c) Moritz Clasmeier 2017 License : BSD3 Maintainer : Stability : experimental Portability : POSIX This module provides the Nakadi Problem Type. -} module Network.Nakadi.Types.Problem ( Problem(..) ) where import Network.Nakadi.Internal.Types.Problem
7716f99731207313a15517c550696b7d90a06c137d2c6354308e904bee42b081
ragkousism/Guix-on-Hurd
github.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix import github) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:use-module (srfi srfi-34) #:use-module (json) #:use-module (guix utils) #:use-module ((guix download) #:prefix download:) #:use-module (guix import utils) #:use-module (guix packages) #:use-module (guix upstream) #:use-module (guix http-client) #:use-module (web uri) #:export (%github-updater)) (define (json-fetch* url) "Return a representation of the JSON resource URL (a list or hash table), or #f if URL returns 403 or 404." (guard (c ((and (http-get-error? c) (let ((error (http-get-error-code c))) (or (= 403 error) (= 404 error)))) " expected " if there is an authentification error ( 403 ) , or if package is unknown ( 404 ) . Note : github.com returns 403 if we omit a ' User - Agent ' header . (let* ((port (http-fetch url)) (result (json->scm port))) (close-port port) result))) (define (find-extension url) "Return the extension of the archive e.g. '.tar.gz' given a URL, or false if none is recognized" (find (lambda (x) (string-suffix? x url)) (list ".tar.gz" ".tar.bz2" ".tar.xz" ".zip" ".tar" ".tgz" ".tbz" ".love"))) (define (updated-github-url old-package new-version) ;; Return a url for the OLD-PACKAGE with NEW-VERSION. If no source url in the OLD - PACKAGE is a GitHub url , then return false . (define (updated-url url) (if (string-prefix? "/" url) (let ((ext (or (find-extension url) "")) (name (package-name old-package)) (version (package-version old-package)) (prefix (string-append "/" (github-user-slash-repository url))) (repo (github-repository url))) (cond ((string-suffix? (string-append "/tarball/v" version) url) (string-append prefix "/tarball/v" new-version)) ((string-suffix? (string-append "/tarball/" version) url) (string-append prefix "/tarball/" new-version)) ((string-suffix? (string-append "/archive/v" version ext) url) (string-append prefix "/archive/v" new-version ext)) ((string-suffix? (string-append "/archive/" version ext) url) (string-append prefix "/archive/" new-version ext)) ((string-suffix? (string-append "/archive/" name "-" version ext) url) (string-append prefix "/archive/" name "-" new-version ext)) ((string-suffix? (string-append "/releases/download/v" version "/" name "-" version ext) url) (string-append prefix "/releases/download/v" new-version "/" name "-" new-version ext)) ((string-suffix? (string-append "/releases/download/" version "/" name "-" version ext) url) (string-append prefix "/releases/download/" new-version "/" name "-" new-version ext)) ((string-suffix? (string-append "/releases/download/" version "/" repo "-" version ext) url) (string-append prefix "/releases/download/" new-version "/" repo "-" new-version ext)) ((string-suffix? (string-append "/releases/download/" repo "-" version "/" repo "-" version ext) url) (string-append "/releases/download/" repo "-" version "/" repo "-" version ext)) (#t #f))) ; Some URLs are not recognised. #f)) (let ((source-url (and=> (package-source old-package) origin-uri)) (fetch-method (and=> (package-source old-package) origin-method))) (if (eq? fetch-method download:url-fetch) (match source-url ((? string?) (updated-url source-url)) ((source-url ...) (find updated-url source-url))) #f))) (define (github-package? package) "Return true if PACKAGE is a package from GitHub, else false." (not (eq? #f (updated-github-url package "dummy")))) (define (github-repository url) "Return a string e.g. bedtools2 of the name of the repository, from a string URL of the form ''" (match (string-split (uri-path (string->uri url)) #\/) ((_ owner project . rest) (string-append project)))) (define (github-user-slash-repository url) "Return a string e.g. arq5x/bedtools2 of the owner and the name of the repository separated by a forward slash, from a string URL of the form ''" (match (string-split (uri-path (string->uri url)) #\/) ((_ owner project . rest) (string-append owner "/" project)))) (define %github-token Token to be passed to Github.com to avoid the 60 - request per hour limit , or # f. (make-parameter (getenv "GUIX_GITHUB_TOKEN"))) (define (latest-released-version url package-name) "Return a string of the newest released version name given a string URL like '' and the name of the package e.g. 'bedtools2'. Return #f if there is no releases" (let* ((token (%github-token)) (api-url (string-append "/" (github-user-slash-repository url) "/releases")) (json (json-fetch* (if token (string-append api-url "?access_token=" token) api-url)))) (if (eq? json #f) (if token (error "Error downloading release information through the GitHub API when using a GitHub token") (error "Error downloading release information through the GitHub API. This may be fixed by using an access token and setting the environment variable GUIX_GITHUB_TOKEN, for instance one procured from ")) (let ((proper-releases (filter (lambda (x) ;; example pre-release: ;; ;; or an all-prerelease set ;; (not (hash-ref x "prerelease"))) json))) (match proper-releases (() ;empty release list #f) one or more releases (let ((tag (hash-ref release "tag_name")) (name-length (string-length package-name))) ;; some tags include the name of the package e.g. "fdupes-1.51" ;; so remove these (if (and (< name-length (string-length tag)) (string=? (string-append package-name "-") (substring tag 0 (+ name-length 1)))) (substring tag (+ name-length 1)) ;; some tags start with a "v" e.g. "v0.25.0" ;; where some are just the version number (if (eq? (string-ref tag 0) #\v) (substring tag 1) tag))))))))) (define (latest-release pkg) "Return an <upstream-source> for the latest release of PKG." (let* ((source-uri (origin-uri (package-source pkg))) (name (package-name pkg)) (newest-version (latest-released-version source-uri name))) (if newest-version (upstream-source (package name) (version newest-version) (urls (list (updated-github-url pkg newest-version)))) On GitHub but no proper releases (define %github-updater (upstream-updater (name 'github) (description "Updater for GitHub packages") (pred github-package?) (latest latest-release)))
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/guix/import/github.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Return a url for the OLD-PACKAGE with NEW-VERSION. If no source url in Some URLs are not recognised. example pre-release: or an all-prerelease set empty release list some tags include the name of the package e.g. "fdupes-1.51" so remove these some tags start with a "v" e.g. "v0.25.0" where some are just the version number
Copyright © 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix import github) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:use-module (srfi srfi-34) #:use-module (json) #:use-module (guix utils) #:use-module ((guix download) #:prefix download:) #:use-module (guix import utils) #:use-module (guix packages) #:use-module (guix upstream) #:use-module (guix http-client) #:use-module (web uri) #:export (%github-updater)) (define (json-fetch* url) "Return a representation of the JSON resource URL (a list or hash table), or #f if URL returns 403 or 404." (guard (c ((and (http-get-error? c) (let ((error (http-get-error-code c))) (or (= 403 error) (= 404 error)))) " expected " if there is an authentification error ( 403 ) , or if package is unknown ( 404 ) . Note : github.com returns 403 if we omit a ' User - Agent ' header . (let* ((port (http-fetch url)) (result (json->scm port))) (close-port port) result))) (define (find-extension url) "Return the extension of the archive e.g. '.tar.gz' given a URL, or false if none is recognized" (find (lambda (x) (string-suffix? x url)) (list ".tar.gz" ".tar.bz2" ".tar.xz" ".zip" ".tar" ".tgz" ".tbz" ".love"))) (define (updated-github-url old-package new-version) the OLD - PACKAGE is a GitHub url , then return false . (define (updated-url url) (if (string-prefix? "/" url) (let ((ext (or (find-extension url) "")) (name (package-name old-package)) (version (package-version old-package)) (prefix (string-append "/" (github-user-slash-repository url))) (repo (github-repository url))) (cond ((string-suffix? (string-append "/tarball/v" version) url) (string-append prefix "/tarball/v" new-version)) ((string-suffix? (string-append "/tarball/" version) url) (string-append prefix "/tarball/" new-version)) ((string-suffix? (string-append "/archive/v" version ext) url) (string-append prefix "/archive/v" new-version ext)) ((string-suffix? (string-append "/archive/" version ext) url) (string-append prefix "/archive/" new-version ext)) ((string-suffix? (string-append "/archive/" name "-" version ext) url) (string-append prefix "/archive/" name "-" new-version ext)) ((string-suffix? (string-append "/releases/download/v" version "/" name "-" version ext) url) (string-append prefix "/releases/download/v" new-version "/" name "-" new-version ext)) ((string-suffix? (string-append "/releases/download/" version "/" name "-" version ext) url) (string-append prefix "/releases/download/" new-version "/" name "-" new-version ext)) ((string-suffix? (string-append "/releases/download/" version "/" repo "-" version ext) url) (string-append prefix "/releases/download/" new-version "/" repo "-" new-version ext)) ((string-suffix? (string-append "/releases/download/" repo "-" version "/" repo "-" version ext) url) (string-append "/releases/download/" repo "-" version "/" repo "-" version ext)) #f)) (let ((source-url (and=> (package-source old-package) origin-uri)) (fetch-method (and=> (package-source old-package) origin-method))) (if (eq? fetch-method download:url-fetch) (match source-url ((? string?) (updated-url source-url)) ((source-url ...) (find updated-url source-url))) #f))) (define (github-package? package) "Return true if PACKAGE is a package from GitHub, else false." (not (eq? #f (updated-github-url package "dummy")))) (define (github-repository url) "Return a string e.g. bedtools2 of the name of the repository, from a string URL of the form ''" (match (string-split (uri-path (string->uri url)) #\/) ((_ owner project . rest) (string-append project)))) (define (github-user-slash-repository url) "Return a string e.g. arq5x/bedtools2 of the owner and the name of the repository separated by a forward slash, from a string URL of the form ''" (match (string-split (uri-path (string->uri url)) #\/) ((_ owner project . rest) (string-append owner "/" project)))) (define %github-token Token to be passed to Github.com to avoid the 60 - request per hour limit , or # f. (make-parameter (getenv "GUIX_GITHUB_TOKEN"))) (define (latest-released-version url package-name) "Return a string of the newest released version name given a string URL like '' and the name of the package e.g. 'bedtools2'. Return #f if there is no releases" (let* ((token (%github-token)) (api-url (string-append "/" (github-user-slash-repository url) "/releases")) (json (json-fetch* (if token (string-append api-url "?access_token=" token) api-url)))) (if (eq? json #f) (if token (error "Error downloading release information through the GitHub API when using a GitHub token") (error "Error downloading release information through the GitHub API. This may be fixed by using an access token and setting the environment variable GUIX_GITHUB_TOKEN, for instance one procured from ")) (let ((proper-releases (filter (lambda (x) (not (hash-ref x "prerelease"))) json))) (match proper-releases #f) one or more releases (let ((tag (hash-ref release "tag_name")) (name-length (string-length package-name))) (if (and (< name-length (string-length tag)) (string=? (string-append package-name "-") (substring tag 0 (+ name-length 1)))) (substring tag (+ name-length 1)) (if (eq? (string-ref tag 0) #\v) (substring tag 1) tag))))))))) (define (latest-release pkg) "Return an <upstream-source> for the latest release of PKG." (let* ((source-uri (origin-uri (package-source pkg))) (name (package-name pkg)) (newest-version (latest-released-version source-uri name))) (if newest-version (upstream-source (package name) (version newest-version) (urls (list (updated-github-url pkg newest-version)))) On GitHub but no proper releases (define %github-updater (upstream-updater (name 'github) (description "Updater for GitHub packages") (pred github-package?) (latest latest-release)))
11c70b4fbca682078e857b63fc8eb4d98cb48fd961342041a55e7d4b35cae893
borodust/mortar-combat
packages.lisp
(in-package :mortar-combat.def) (defpackage :mortar-combat.common (:use :cl :ge.util) (:export +ok-reply+ process-command encode-message decode-message with-message))
null
https://raw.githubusercontent.com/borodust/mortar-combat/548bdda21594185f36c365f25015c5edcc37b828/common/packages.lisp
lisp
(in-package :mortar-combat.def) (defpackage :mortar-combat.common (:use :cl :ge.util) (:export +ok-reply+ process-command encode-message decode-message with-message))
3029e6d0166c127d7b06173e72f9a6a10d133c722d0361e597b24669d9c1419a
Factual/sosueme
io.clj
(ns sosueme.test.io (:use [sosueme.io]) (:use [clojure.test])) (deftest test-slurp-cp (is (= (slurp-cp "somefile.txt") "This is somefile!\n")))
null
https://raw.githubusercontent.com/Factual/sosueme/1c2e9b7eb4df8ae67012dc2a398b4ec63c9bd6cd/test/sosueme/test/io.clj
clojure
(ns sosueme.test.io (:use [sosueme.io]) (:use [clojure.test])) (deftest test-slurp-cp (is (= (slurp-cp "somefile.txt") "This is somefile!\n")))
82138c21a65c59389dd86d180ed288e2500afccb9ca6dceb4438c03028232e7e
7theta/via
core_test.clj
(ns via.core-test (:require [via.endpoint :as e] [via.subs :as vs] [via.events :as ve] [signum.events :refer [reg-event]] [signum.subs :refer [reg-sub]] [signum.signal :as sig] [vectio.util.stream :as vus] [vectio.netty.http1.websocket :refer [unsafe-self-signed-ssl-context]] [vectio.http :as http] [vectio.netty.server :as ns] [tempus.core :as tempus] [clojure.java.io :as io] [clojure.test :as t] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true] [clojure.test.check.clojure-test :refer [defspec]] [fluxus.flow :as f] [clojure.string :as st]) (:import [io.netty.handler.ssl ApplicationProtocolConfig ApplicationProtocolConfig$Protocol ApplicationProtocolConfig$SelectorFailureBehavior ApplicationProtocolConfig$SelectedListenerFailureBehavior ApplicationProtocolNames SslContextBuilder SslProvider SupportedCipherSuiteFilter] [io.netty.handler.codec.http2 Http2SecurityUtil] [java.net ServerSocket])) (f/set-default-on-error! (fn [stream error] (locking Object (println :fluxus.flow/on-error {:stream stream :error error})))) (defn- allocate-free-port! [] (locking Object (let [socket (ServerSocket. 0)] (.setReuseAddress socket true) (let [port (.getLocalPort socket)] (try (.close socket) (catch Exception _)) port)))) (defn endpoint ([] (endpoint nil)) ([{:keys [on-close on-handshake on-handshake-reply] :as args}] (let [endpoint (vs/init (e/init (merge {:on-error (fn [_])} (dissoc args :on-close :on-handshake :on-handshake-reply)))) ring-handler (fn [request] (when-let [{:keys [stream response]} (ns/websocket-stream-response request)] (f/on-close stream (fn [_] (when on-close (on-close)))) (e/register endpoint stream {:on-handshake on-handshake :on-handshake-reply on-handshake-reply}) response)) port (allocate-free-port!) server (http/server {:host "localhost" :port port :handler ring-handler :ssl-context (-> (SslContextBuilder/forServer (io/file "dev-resources/certs/server.crt") (io/file "dev-resources/certs/server.key")) (.sslProvider SslProvider/JDK) (.ciphers Http2SecurityUtil/CIPHERS SupportedCipherSuiteFilter/INSTANCE) (.applicationProtocolConfig (ApplicationProtocolConfig. ApplicationProtocolConfig$Protocol/ALPN ApplicationProtocolConfig$SelectorFailureBehavior/NO_ADVERTISE ApplicationProtocolConfig$SelectedListenerFailureBehavior/ACCEPT ^"[Ljava.lang.String;" (into-array [ApplicationProtocolNames/HTTP_2]))) .build)})] {:endpoint endpoint :http-server server :port port}))) (defn wait-for ([p] (wait-for p 3000)) ([p timeout-ms] (let [result (deref p timeout-ms ::timed-out)] (if (= result ::timed-out) (throw (ex-info "Timed out waiting for promise" {})) result)))) (defn connect ([e1 e2] (connect e1 e2 nil)) ([{:keys [endpoint]} {:keys [port]} {:keys [on-close on-handshake on-handshake-reply reconnect on-client]}] (let [stream-fn #(let [client (http/websocket-client {:host "localhost" :port port :path "/" :ssl-context (unsafe-self-signed-ssl-context)})] (when on-client (on-client @client)) client)] (if reconnect (let [connection (promise)] (e/reconnecting-stream endpoint (vus/reconnecting-stream stream-fn) {:on-connect (partial deliver connection)}) (wait-for connection)) (let [stream @(stream-fn)] (when on-close (f/on-close stream (fn [_] (on-close)))) (e/register endpoint stream {:on-handshake on-handshake :on-handshake-reply on-handshake-reply})))))) (defn shutdown [{:keys [http-server endpoint]}] (try (.close ^java.io.Closeable http-server) (catch Exception e (locking Object (println e)))) (try (e/halt endpoint) (catch Exception e (locking Object (println e))))) (defspec test-send-directly-to-peer 10 (prop/for-all [value gen/any-printable-equatable] (let [event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint {:exports {:events #{event-id}}})] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (= value (:body @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000}))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-send-dates-directly-to-peer 10 (prop/for-all [value (gen/map gen/keyword gen/string)] (let [value (assoc value :date-time (tempus/now)) event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint {:exports {:events #{event-id}}})] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (let [result @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000})] (= (tempus/into :long (:date-time value)) (tempus/into :long (:date-time (:body result))))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-sub-updates-on-change 10 (prop/for-all [value (gen/sized (fn [size] (gen/vector gen/any-printable-equatable (max size 1))))] (let [sub-id (str (gensym) "/sub") e1 (endpoint) e2 (endpoint {:exports {:subs #{sub-id}}}) value-signal (sig/signal ::init) promises (mapv (fn [_] (promise)) value)] (reg-sub sub-id (fn [_] @value-signal)) (try (let [sub (vs/subscribe (connect e1 e2) [sub-id])] (add-watch sub ::watch (fn [_ _ _ {:keys [value i]}] (when (number? i) (deliver (nth promises i) value)))) (doseq [[index value] (map-indexed vector value)] (sig/alter! value-signal (constantly {:i index :value value})) (wait-for (nth promises index))) (let [result (mapv wait-for promises)] (remove-watch sub ::watch) (= result (vec value)))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-subs-cleanup-properly 10 (prop/for-all [value gen/any-printable-equatable] (let [sub-id (str (gensym) "/sub") e1-promise (promise) e1 (endpoint) e2-promise (promise) e2 (endpoint {:exports {:subs #{sub-id}} :on-close (fn [] (deliver e2-promise true))}) value-signal (sig/signal)] (reg-sub sub-id (fn [_] @value-signal)) (try (let [sub (vs/subscribe (connect e1 e2 {:on-close (fn [] (deliver e1-promise true))}) [sub-id])] (add-watch sub ::watch (fn [_ _ _ value])) (sig/alter! value-signal (constantly value)) (remove-watch sub ::watch) (shutdown e2) (wait-for e1-promise) (wait-for e2-promise) (and (empty? @(:connections (:endpoint e2))) (empty? @(:connections (:endpoint e1))))) (catch Exception e (locking Object (println e)) (shutdown e2) false) (finally (shutdown e1)))))) (defspec test-export-api-prevents-event-access 10 (prop/for-all [value gen/any-printable-equatable] (let [event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint)] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (= {:status 400} (select-keys @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000}) [:status])) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-export-api-prevents-sub-access 10 (prop/for-all [value gen/any-printable-equatable] (let [sub-id (str (gensym) "/sub") e1 (endpoint) e2 (endpoint)] (reg-sub sub-id (fn [_] ::unauthorized)) (try (let [sub (vs/subscribe (connect e1 e2) [sub-id])] (try (add-watch sub ::watch (fn [_ _ _ _])) (catch Exception _)) (Thread/sleep 100) (= (-> (try @sub (catch Exception e (ex-data e))) :reply :body (select-keys [:status :error])) {:status :error :error :invalid-subscription})) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-sub-reconnect-works 10 (prop/for-all [[value1 value2] (gen/vector-distinct gen/any-printable-equatable {:num-elements 2})] (let [sub-id (str (gensym) "/sub") disconnected-promise (promise) e1 (endpoint) e2 (endpoint {:exports {:subs #{sub-id}}}) value-signal (sig/signal ::init) value-promise-1 (promise) value-promise-2 (promise) current-promise (atom value-promise-1) initial-client (promise) connection (connect e1 e2 {:reconnect true :on-client #(when (not (realized? initial-client)) (f/on-close % (fn [_] (deliver disconnected-promise true))) (deliver initial-client %))})] (reg-sub sub-id (fn [_] @value-signal)) (wait-for initial-client) (try (let [sub (vs/subscribe connection [sub-id])] (add-watch sub ::watch (fn [_ _ _ value] (when-let [p @current-promise] (deliver p value)))) (sig/alter! value-signal (constantly value1)) (wait-for value-promise-1) (Thread/sleep 500) (f/close! @initial-client) (wait-for disconnected-promise) (Thread/sleep 500) (reset! current-promise value-promise-2) (sig/alter! value-signal (constantly value2)) (Thread/sleep 500) (= @value-promise-2 value2)) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-handshake-transmits 10 (prop/for-all [value gen/any-printable-equatable] (let [e1-hs (promise) e1-hs-reply (promise) e1 (endpoint) e2-hs (promise) e2-hs-reply (promise) e2 (endpoint {:on-handshake #(deliver e2-hs %) :on-handshake-reply #(deliver e2-hs-reply %)})] (connect e1 e2 {:on-handshake #(deliver e1-hs %) :on-handshake-reply #(deliver e1-hs-reply %)}) (try (and (wait-for e1-hs) (wait-for e1-hs-reply) (wait-for e2-hs) (wait-for e2-hs-reply)) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-send-large-message 10 (prop/for-all [_value gen/any-printable-equatable] (let [value (st/join "" (repeatedly 75000 #(rand-int 10))) event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint {:exports {:events #{event-id}}})] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (= value (:body @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000}))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defn test-all [] (println :test-send-directly-to-peer) (test-send-directly-to-peer 10) (println :test-send-dates-directly-to-peer) (test-send-dates-directly-to-peer 10) (println :test-sub-updates-on-change) (test-sub-updates-on-change 10) (prn :test-subs-cleanup-properly) (test-subs-cleanup-properly 10) (prn :test-export-api-prevents-event-access) (test-export-api-prevents-event-access 10) (prn :test-export-api-prevents-sub-access) (test-export-api-prevents-sub-access 10) (prn :test-handshake-transmits) (test-handshake-transmits 10) (prn :test-sub-reconnect-works) (test-sub-reconnect-works 10) (prn :test-send-large-message) (test-send-large-message 10))
null
https://raw.githubusercontent.com/7theta/via/172c51824ebfd76827161312c42c11cf39b6a389/test/via/core_test.clj
clojure
(ns via.core-test (:require [via.endpoint :as e] [via.subs :as vs] [via.events :as ve] [signum.events :refer [reg-event]] [signum.subs :refer [reg-sub]] [signum.signal :as sig] [vectio.util.stream :as vus] [vectio.netty.http1.websocket :refer [unsafe-self-signed-ssl-context]] [vectio.http :as http] [vectio.netty.server :as ns] [tempus.core :as tempus] [clojure.java.io :as io] [clojure.test :as t] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true] [clojure.test.check.clojure-test :refer [defspec]] [fluxus.flow :as f] [clojure.string :as st]) (:import [io.netty.handler.ssl ApplicationProtocolConfig ApplicationProtocolConfig$Protocol ApplicationProtocolConfig$SelectorFailureBehavior ApplicationProtocolConfig$SelectedListenerFailureBehavior ApplicationProtocolNames SslContextBuilder SslProvider SupportedCipherSuiteFilter] [io.netty.handler.codec.http2 Http2SecurityUtil] [java.net ServerSocket])) (f/set-default-on-error! (fn [stream error] (locking Object (println :fluxus.flow/on-error {:stream stream :error error})))) (defn- allocate-free-port! [] (locking Object (let [socket (ServerSocket. 0)] (.setReuseAddress socket true) (let [port (.getLocalPort socket)] (try (.close socket) (catch Exception _)) port)))) (defn endpoint ([] (endpoint nil)) ([{:keys [on-close on-handshake on-handshake-reply] :as args}] (let [endpoint (vs/init (e/init (merge {:on-error (fn [_])} (dissoc args :on-close :on-handshake :on-handshake-reply)))) ring-handler (fn [request] (when-let [{:keys [stream response]} (ns/websocket-stream-response request)] (f/on-close stream (fn [_] (when on-close (on-close)))) (e/register endpoint stream {:on-handshake on-handshake :on-handshake-reply on-handshake-reply}) response)) port (allocate-free-port!) server (http/server {:host "localhost" :port port :handler ring-handler :ssl-context (-> (SslContextBuilder/forServer (io/file "dev-resources/certs/server.crt") (io/file "dev-resources/certs/server.key")) (.sslProvider SslProvider/JDK) (.ciphers Http2SecurityUtil/CIPHERS SupportedCipherSuiteFilter/INSTANCE) (.applicationProtocolConfig (ApplicationProtocolConfig. ApplicationProtocolConfig$Protocol/ALPN ApplicationProtocolConfig$SelectorFailureBehavior/NO_ADVERTISE ApplicationProtocolConfig$SelectedListenerFailureBehavior/ACCEPT ^"[Ljava.lang.String;" (into-array [ApplicationProtocolNames/HTTP_2]))) .build)})] {:endpoint endpoint :http-server server :port port}))) (defn wait-for ([p] (wait-for p 3000)) ([p timeout-ms] (let [result (deref p timeout-ms ::timed-out)] (if (= result ::timed-out) (throw (ex-info "Timed out waiting for promise" {})) result)))) (defn connect ([e1 e2] (connect e1 e2 nil)) ([{:keys [endpoint]} {:keys [port]} {:keys [on-close on-handshake on-handshake-reply reconnect on-client]}] (let [stream-fn #(let [client (http/websocket-client {:host "localhost" :port port :path "/" :ssl-context (unsafe-self-signed-ssl-context)})] (when on-client (on-client @client)) client)] (if reconnect (let [connection (promise)] (e/reconnecting-stream endpoint (vus/reconnecting-stream stream-fn) {:on-connect (partial deliver connection)}) (wait-for connection)) (let [stream @(stream-fn)] (when on-close (f/on-close stream (fn [_] (on-close)))) (e/register endpoint stream {:on-handshake on-handshake :on-handshake-reply on-handshake-reply})))))) (defn shutdown [{:keys [http-server endpoint]}] (try (.close ^java.io.Closeable http-server) (catch Exception e (locking Object (println e)))) (try (e/halt endpoint) (catch Exception e (locking Object (println e))))) (defspec test-send-directly-to-peer 10 (prop/for-all [value gen/any-printable-equatable] (let [event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint {:exports {:events #{event-id}}})] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (= value (:body @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000}))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-send-dates-directly-to-peer 10 (prop/for-all [value (gen/map gen/keyword gen/string)] (let [value (assoc value :date-time (tempus/now)) event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint {:exports {:events #{event-id}}})] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (let [result @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000})] (= (tempus/into :long (:date-time value)) (tempus/into :long (:date-time (:body result))))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-sub-updates-on-change 10 (prop/for-all [value (gen/sized (fn [size] (gen/vector gen/any-printable-equatable (max size 1))))] (let [sub-id (str (gensym) "/sub") e1 (endpoint) e2 (endpoint {:exports {:subs #{sub-id}}}) value-signal (sig/signal ::init) promises (mapv (fn [_] (promise)) value)] (reg-sub sub-id (fn [_] @value-signal)) (try (let [sub (vs/subscribe (connect e1 e2) [sub-id])] (add-watch sub ::watch (fn [_ _ _ {:keys [value i]}] (when (number? i) (deliver (nth promises i) value)))) (doseq [[index value] (map-indexed vector value)] (sig/alter! value-signal (constantly {:i index :value value})) (wait-for (nth promises index))) (let [result (mapv wait-for promises)] (remove-watch sub ::watch) (= result (vec value)))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-subs-cleanup-properly 10 (prop/for-all [value gen/any-printable-equatable] (let [sub-id (str (gensym) "/sub") e1-promise (promise) e1 (endpoint) e2-promise (promise) e2 (endpoint {:exports {:subs #{sub-id}} :on-close (fn [] (deliver e2-promise true))}) value-signal (sig/signal)] (reg-sub sub-id (fn [_] @value-signal)) (try (let [sub (vs/subscribe (connect e1 e2 {:on-close (fn [] (deliver e1-promise true))}) [sub-id])] (add-watch sub ::watch (fn [_ _ _ value])) (sig/alter! value-signal (constantly value)) (remove-watch sub ::watch) (shutdown e2) (wait-for e1-promise) (wait-for e2-promise) (and (empty? @(:connections (:endpoint e2))) (empty? @(:connections (:endpoint e1))))) (catch Exception e (locking Object (println e)) (shutdown e2) false) (finally (shutdown e1)))))) (defspec test-export-api-prevents-event-access 10 (prop/for-all [value gen/any-printable-equatable] (let [event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint)] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (= {:status 400} (select-keys @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000}) [:status])) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-export-api-prevents-sub-access 10 (prop/for-all [value gen/any-printable-equatable] (let [sub-id (str (gensym) "/sub") e1 (endpoint) e2 (endpoint)] (reg-sub sub-id (fn [_] ::unauthorized)) (try (let [sub (vs/subscribe (connect e1 e2) [sub-id])] (try (add-watch sub ::watch (fn [_ _ _ _])) (catch Exception _)) (Thread/sleep 100) (= (-> (try @sub (catch Exception e (ex-data e))) :reply :body (select-keys [:status :error])) {:status :error :error :invalid-subscription})) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-sub-reconnect-works 10 (prop/for-all [[value1 value2] (gen/vector-distinct gen/any-printable-equatable {:num-elements 2})] (let [sub-id (str (gensym) "/sub") disconnected-promise (promise) e1 (endpoint) e2 (endpoint {:exports {:subs #{sub-id}}}) value-signal (sig/signal ::init) value-promise-1 (promise) value-promise-2 (promise) current-promise (atom value-promise-1) initial-client (promise) connection (connect e1 e2 {:reconnect true :on-client #(when (not (realized? initial-client)) (f/on-close % (fn [_] (deliver disconnected-promise true))) (deliver initial-client %))})] (reg-sub sub-id (fn [_] @value-signal)) (wait-for initial-client) (try (let [sub (vs/subscribe connection [sub-id])] (add-watch sub ::watch (fn [_ _ _ value] (when-let [p @current-promise] (deliver p value)))) (sig/alter! value-signal (constantly value1)) (wait-for value-promise-1) (Thread/sleep 500) (f/close! @initial-client) (wait-for disconnected-promise) (Thread/sleep 500) (reset! current-promise value-promise-2) (sig/alter! value-signal (constantly value2)) (Thread/sleep 500) (= @value-promise-2 value2)) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-handshake-transmits 10 (prop/for-all [value gen/any-printable-equatable] (let [e1-hs (promise) e1-hs-reply (promise) e1 (endpoint) e2-hs (promise) e2-hs-reply (promise) e2 (endpoint {:on-handshake #(deliver e2-hs %) :on-handshake-reply #(deliver e2-hs-reply %)})] (connect e1 e2 {:on-handshake #(deliver e1-hs %) :on-handshake-reply #(deliver e1-hs-reply %)}) (try (and (wait-for e1-hs) (wait-for e1-hs-reply) (wait-for e2-hs) (wait-for e2-hs-reply)) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defspec test-send-large-message 10 (prop/for-all [_value gen/any-printable-equatable] (let [value (st/join "" (repeatedly 75000 #(rand-int 10))) event-id (str (gensym) "/event") e1 (endpoint) e2 (endpoint {:exports {:events #{event-id}}})] (reg-event event-id (fn [_ [_ value]] {:via/reply {:status 200 :body value}})) (try (= value (:body @(ve/invoke (connect e1 e2) [event-id value] {:timeout 1000}))) (catch Exception e (locking Object (println e)) false) (finally (shutdown e1) (shutdown e2)))))) (defn test-all [] (println :test-send-directly-to-peer) (test-send-directly-to-peer 10) (println :test-send-dates-directly-to-peer) (test-send-dates-directly-to-peer 10) (println :test-sub-updates-on-change) (test-sub-updates-on-change 10) (prn :test-subs-cleanup-properly) (test-subs-cleanup-properly 10) (prn :test-export-api-prevents-event-access) (test-export-api-prevents-event-access 10) (prn :test-export-api-prevents-sub-access) (test-export-api-prevents-sub-access 10) (prn :test-handshake-transmits) (test-handshake-transmits 10) (prn :test-sub-reconnect-works) (test-sub-reconnect-works 10) (prn :test-send-large-message) (test-send-large-message 10))
6cb76f6db6eea8b042f9a82b0bad60b2965646d1adf6fe9c564e4c7f7eea2db6
mstksg/functor-combinators
Spec.hs
import Test.Tasty import Tests.HBifunctor import Tests.HFunctor main :: IO () main = defaultMain $ testGroup "Tests" [ hfunctorTests , hbifunctorTests ]
null
https://raw.githubusercontent.com/mstksg/functor-combinators/e8158b6055be08f37525414068884a9d94b3bcf9/test/Spec.hs
haskell
import Test.Tasty import Tests.HBifunctor import Tests.HFunctor main :: IO () main = defaultMain $ testGroup "Tests" [ hfunctorTests , hbifunctorTests ]
88dbc53ddb1edab4d03234f11002e4b893380e886d94f024d93343bf13844690
Drezil/pioneers
Creation.hs
module Map.Creation where import Map.Types import Data.Array import System.Random -- entirely empty map, only uses the minimal constructor mapEmpty :: PlayMap mapEmpty = array ((0,0), (199,199)) [((a,b), Node (a,b) (fromIntegral a, (if even b then (fromIntegral b) else(fromIntegral b) - 0.5), 1) Grass BNothing NoPlayer NoPath Plain []) | a <- [0..199], b <- [0..199]] exportedMap :: IO PlayMap exportedMap = do mounts <- mnt return $ aplAll mounts mapEmpty | Generate a new Map of given Type and -- TODO : -- 1. Should take Size -> Type -> Playmap 2 . plug together helper - functions for that terraintype newMap :: MapType -> (Int, Int) -> PlayMap newMap = undefined aplByPlace :: (Node -> Node) -> ((Int,Int) -> Bool) -> PlayMap -> PlayMap aplByPlace f g mp = array (bounds mp) (map (\(ab,c) -> if g ab then (ab, f c) else (ab,c)) (assocs mp)) aplByNode :: (Node -> Node) -> (Node -> Bool) -> PlayMap -> PlayMap aplByNode f g mp = array (bounds mp) (map (\(ab,c) -> (if g c then (ab, f c) else (ab,c))) (assocs mp)) aplAll :: [a -> a] -> a -> a aplAll fs m = foldl (\ n f -> f n) m fs aplAllM :: Monad m => [m a -> m a] -> m a -> m a aplAllM fs x = foldl (\ n f -> f n) x fs general 3D - Gaussian gauss3Dgeneral :: Floating q => q -- ^ Amplitude -> q -- ^ Origin on X-Achsis -> q -- ^ Origin on Z-Achsis -> q -- ^ Sigma on X -> q -- ^ Sigma on Z -> q -- ^ Coordinate in question on X -> q -- ^ Coordinate in question on Z -> q -- ^ elevation on coordinate in question gauss3Dgeneral amp x0 z0 sX sZ x z = amp * exp(-(((x-x0)^(2 :: Int)/(2 * sX^(2 :: Int)))+((z-z0)^(2 :: Int)/(2 * sZ^(2 :: Int))))) | Basic Terrain - Generator . Will not implement " abnormal " Stuff for given Biome ( like Deserts on Grass - Islands or Grass on Deserts ) -- -- TODO: Implement Desert-Generator heightToTerrain :: MapType -> YCoord -> TileType heightToTerrain GrassIslandMap y | y < 0.1 = Ocean | y < 0.2 = Beach | y < 1.5 = Grass | y < 3 = Hill | otherwise = Mountain heightToTerrain _ _ = undefined lake :: Int -> PlayMap -> PlayMap lake = undefined river :: Int -> PlayMap -> PlayMap river = undefined mnt :: IO [PlayMap -> PlayMap] mnt = do g <- newStdGen let seeds = take 50 $ randoms g return $ map gaussMountain seeds gaussMountain :: Int -> PlayMap -> PlayMap gaussMountain seed mp = aplByPlace (liftUp c) (\(_,_) -> True) mp where gs = map mkStdGen (map (*seed) [1..]) c = let ((a,b), (x,y)) = bounds mp in (head (randomRs (a,x) (gs !! 0)), (head (randomRs (b,y) (gs !! 1)))) amp = head $ randomRs ((2.0, 5.0) :: (Double, Double)) (gs !! 2) sig = head $ randomRs ((2.0, 8.0) :: (Double, Double)) (gs !! 3) htt = heightToTerrain -- TODO: Fix Lambda to True with sensible function, maybe rework giveNeighbourhood in Map.Map liftUp :: (Int, Int) -> Node -> Node liftUp (gx,gz) (Node (x,z) (rx,rz,y) _ b pl pa r s) = let y_neu = max y e in Node (x,z) (rx, rz, y_neu) (htt GrassIslandMap y_neu) b pl pa r s where e = gauss3Dgeneral amp (fromIntegral gx) (fromIntegral gz) sig sig rx rz
null
https://raw.githubusercontent.com/Drezil/pioneers/2a9de00213144cfa870e9b71255a92a905dec3a9/src/Map/Creation.hs
haskell
entirely empty map, only uses the minimal constructor 1. Should take Size -> Type -> Playmap ^ Amplitude ^ Origin on X-Achsis ^ Origin on Z-Achsis ^ Sigma on X ^ Sigma on Z ^ Coordinate in question on X ^ Coordinate in question on Z ^ elevation on coordinate in question TODO: Implement Desert-Generator TODO: Fix Lambda to True with sensible function, maybe rework giveNeighbourhood in Map.Map
module Map.Creation where import Map.Types import Data.Array import System.Random mapEmpty :: PlayMap mapEmpty = array ((0,0), (199,199)) [((a,b), Node (a,b) (fromIntegral a, (if even b then (fromIntegral b) else(fromIntegral b) - 0.5), 1) Grass BNothing NoPlayer NoPath Plain []) | a <- [0..199], b <- [0..199]] exportedMap :: IO PlayMap exportedMap = do mounts <- mnt return $ aplAll mounts mapEmpty | Generate a new Map of given Type and TODO : 2 . plug together helper - functions for that terraintype newMap :: MapType -> (Int, Int) -> PlayMap newMap = undefined aplByPlace :: (Node -> Node) -> ((Int,Int) -> Bool) -> PlayMap -> PlayMap aplByPlace f g mp = array (bounds mp) (map (\(ab,c) -> if g ab then (ab, f c) else (ab,c)) (assocs mp)) aplByNode :: (Node -> Node) -> (Node -> Bool) -> PlayMap -> PlayMap aplByNode f g mp = array (bounds mp) (map (\(ab,c) -> (if g c then (ab, f c) else (ab,c))) (assocs mp)) aplAll :: [a -> a] -> a -> a aplAll fs m = foldl (\ n f -> f n) m fs aplAllM :: Monad m => [m a -> m a] -> m a -> m a aplAllM fs x = foldl (\ n f -> f n) x fs general 3D - Gaussian gauss3Dgeneral :: Floating q => gauss3Dgeneral amp x0 z0 sX sZ x z = amp * exp(-(((x-x0)^(2 :: Int)/(2 * sX^(2 :: Int)))+((z-z0)^(2 :: Int)/(2 * sZ^(2 :: Int))))) | Basic Terrain - Generator . Will not implement " abnormal " Stuff for given Biome ( like Deserts on Grass - Islands or Grass on Deserts ) heightToTerrain :: MapType -> YCoord -> TileType heightToTerrain GrassIslandMap y | y < 0.1 = Ocean | y < 0.2 = Beach | y < 1.5 = Grass | y < 3 = Hill | otherwise = Mountain heightToTerrain _ _ = undefined lake :: Int -> PlayMap -> PlayMap lake = undefined river :: Int -> PlayMap -> PlayMap river = undefined mnt :: IO [PlayMap -> PlayMap] mnt = do g <- newStdGen let seeds = take 50 $ randoms g return $ map gaussMountain seeds gaussMountain :: Int -> PlayMap -> PlayMap gaussMountain seed mp = aplByPlace (liftUp c) (\(_,_) -> True) mp where gs = map mkStdGen (map (*seed) [1..]) c = let ((a,b), (x,y)) = bounds mp in (head (randomRs (a,x) (gs !! 0)), (head (randomRs (b,y) (gs !! 1)))) amp = head $ randomRs ((2.0, 5.0) :: (Double, Double)) (gs !! 2) sig = head $ randomRs ((2.0, 8.0) :: (Double, Double)) (gs !! 3) htt = heightToTerrain liftUp :: (Int, Int) -> Node -> Node liftUp (gx,gz) (Node (x,z) (rx,rz,y) _ b pl pa r s) = let y_neu = max y e in Node (x,z) (rx, rz, y_neu) (htt GrassIslandMap y_neu) b pl pa r s where e = gauss3Dgeneral amp (fromIntegral gx) (fromIntegral gz) sig sig rx rz
6df5a5ae8f0bb09ccc8601db62e82a32bfc223f2b1f30d528e31e090bf948395
wdebeaum/step
warrant.lisp
;;;; ;;;; W::warrant ;;;; (define-words :pos W::V :TEMPL AGENT-FORMAL-XP-TEMPL :words ( (W::warrant (SENSES ((meta-data :origin "verbnet-1.5" :entry-date 20051219 :change-date nil :comments nil :vn ("declare-29.4-2")) (LF-PARENT ONT::believe) (TEMPL experiencer-formal-xp-templ (xp (% w::cp (w::ctype w::s-finite)))) ; like think ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/warrant.lisp
lisp
W::warrant like think
(define-words :pos W::V :TEMPL AGENT-FORMAL-XP-TEMPL :words ( (W::warrant (SENSES ((meta-data :origin "verbnet-1.5" :entry-date 20051219 :change-date nil :comments nil :vn ("declare-29.4-2")) (LF-PARENT ONT::believe) ) ) ) ))
f7a4c75851861ed242d63c24113c456b7c5915fface26177e4c190dfa3ec57c8
dradtke/Lisp-Text-Editor
cffi-allegro.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; cffi-allegro.lisp --- CFFI - SYS implementation for Allegro CL . ;;; Copyright ( C ) 2005 - 2009 , loliveira(@)common - lisp.net > ;;; ;;; 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. ;;; # Administrivia (defpackage #:cffi-sys (:use #:common-lisp) (:import-from #:alexandria #:if-let #:with-unique-names #:once-only) (:export #:canonicalize-symbol-name-case #:foreign-pointer #:pointerp #:pointer-eq #:null-pointer #:null-pointer-p #:inc-pointer #:make-pointer #:pointer-address #:%foreign-alloc #:foreign-free #:with-foreign-pointer #:%foreign-funcall #:%foreign-funcall-pointer #:%foreign-type-alignment #:%foreign-type-size #:%load-foreign-library #:%close-foreign-library #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:defcfun-helper-forms #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Mis-features #-64bit (pushnew 'no-long-long *features*) (pushnew 'flat-namespace *features*) ;;;# Symbol Case (defun canonicalize-symbol-name-case (name) (declare (string name)) (if (eq excl:*current-case-mode* :case-sensitive-lower) (string-downcase name) (string-upcase name))) ;;;# Basic Pointer Operations (deftype foreign-pointer () 'ff:foreign-address) (defun pointerp (ptr) "Return true if PTR is a foreign pointer." (ff:foreign-address-p ptr)) (defun pointer-eq (ptr1 ptr2) "Return true if PTR1 and PTR2 point to the same address." (eql ptr1 ptr2)) (defun null-pointer () "Return a null pointer." 0) (defun null-pointer-p (ptr) "Return true if PTR is a null pointer." (zerop ptr)) (defun inc-pointer (ptr offset) "Return a pointer pointing OFFSET bytes past PTR." (+ ptr offset)) (defun make-pointer (address) "Return a pointer pointing to ADDRESS." (check-type address ff:foreign-address) address) (defun pointer-address (ptr) "Return the address pointed to by PTR." (check-type ptr ff:foreign-address) ptr) ;;;# Allocation ;;; ;;; Functions and macros for allocating foreign memory on the stack and on the heap . The main CFFI package defines macros that wrap ;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage ;;; when the memory has dynamic extent. (defun %foreign-alloc (size) "Allocate SIZE bytes on the heap and return a pointer." (ff:allocate-fobject :char :c size)) (defun foreign-free (ptr) "Free a PTR allocated by FOREIGN-ALLOC." (ff:free-fobject ptr)) (defmacro with-foreign-pointer ((var size &optional size-var) &body body) "Bind VAR to SIZE bytes of foreign memory during BODY. The pointer in VAR is invalid beyond the dynamic extent of BODY, and may be stack-allocated if supported by the implementation. If SIZE-VAR is supplied, it will be bound to SIZE during BODY." (unless size-var (setf size-var (gensym "SIZE"))) #+(version>= 8 1) (when (and (constantp size) (<= (eval size) ff:*max-stack-fobject-bytes*)) (return-from with-foreign-pointer `(let ((,size-var ,(eval size))) (declare (ignorable ,size-var)) (ff:with-static-fobject (,var '(:array :char ,(eval size)) :allocation :foreign-static-gc) ;; (excl::stack-allocated-p var) => T (let ((,var (ff:fslot-address ,var))) ,@body))))) `(let* ((,size-var ,size) (,var (ff:allocate-fobject :char :c ,size-var))) (unwind-protect (progn ,@body) (ff:free-fobject ,var)))) ;;;# Shareable Vectors ;;; ;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA ;;; should be defined to perform a copy-in/copy-out if the Lisp ;;; implementation can't do this. (defun make-shareable-byte-vector (size) "Create a Lisp vector of SIZE bytes can passed to WITH-POINTER-TO-VECTOR-DATA." (make-array size :element-type '(unsigned-byte 8) :allocation :static-reclaimable)) (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body) "Bind PTR-VAR to a foreign pointer to the data in VECTOR." ;; An array allocated in static-reclamable is a non-simple array in ;; the normal Lisp allocation area, pointing to a simple array in ;; the static-reclaimable allocation area. Therefore we have to get ;; out the simple-array to find the pointer to the actual contents. (with-unique-names (simple-vec) `(excl:with-underlying-simple-vector (,vector ,simple-vec) (let ((,ptr-var (ff:fslot-address-typed :unsigned-char :lisp ,simple-vec))) ,@body)))) ;;;# Dereferencing (defun convert-foreign-type (type-keyword) "Convert a CFFI type keyword to an Allegro type." (ecase type-keyword (:char :char) (:unsigned-char :unsigned-char) (:short :short) (:unsigned-short :unsigned-short) (:int :int) (:unsigned-int :unsigned-int) (:long :long) (:unsigned-long :unsigned-long) #+64bit (:long-long :nat) #+64bit (:unsigned-long-long :unsigned-nat) (:float :float) (:double :double) (:pointer :unsigned-nat) (:void :void))) (defun %mem-ref (ptr type &optional (offset 0)) "Dereference an object of TYPE at OFFSET bytes from PTR." (unless (zerop offset) (setf ptr (inc-pointer ptr offset))) (ff:fslot-value-typed (convert-foreign-type type) :c ptr)) Compiler macro to open - code the call to FSLOT - VALUE - TYPED when the CFFI type is constant . Allegro does its own transformation on the ;;; call that results in efficient code. (define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0)) (if (constantp type) (let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off)))) `(ff:fslot-value-typed ',(convert-foreign-type (eval type)) :c ,ptr-form)) form)) (defun %mem-set (value ptr type &optional (offset 0)) "Set the object of TYPE at OFFSET bytes from PTR." (unless (zerop offset) (setf ptr (inc-pointer ptr offset))) (setf (ff:fslot-value-typed (convert-foreign-type type) :c ptr) value)) Compiler macro to open - code the call to ( SETF FSLOT - VALUE - TYPED ) when the CFFI type is constant . Allegro does its own ;;; transformation on the call that results in efficient code. (define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0)) (if (constantp type) (once-only (val) (let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off)))) `(setf (ff:fslot-value-typed ',(convert-foreign-type (eval type)) :c ,ptr-form) ,val))) form)) ;;;# Calling Foreign Functions (defun %foreign-type-size (type-keyword) "Return the size in bytes of a foreign type." (ff:sizeof-fobject (convert-foreign-type type-keyword))) (defun %foreign-type-alignment (type-keyword) "Returns the alignment in bytes of a foreign type." #+(and powerpc macosx32) (when (eq type-keyword :double) (return-from %foreign-type-alignment 8)) ;; No override necessary for the remaining types.... (ff::sized-ftype-prim-align (ff::iforeign-type-sftype (ff:get-foreign-type (convert-foreign-type type-keyword))))) (defun foreign-funcall-type-and-args (args) "Returns a list of types, list of args and return type." (let ((return-type :void)) (loop for (type arg) on args by #'cddr if arg collect type into types and collect arg into fargs else do (setf return-type type) finally (return (values types fargs return-type))))) (defun convert-to-lisp-type (type) (ecase type ((:char :short :int :long) `(signed-byte ,(* 8 (ff:sizeof-fobject type)))) ((:unsigned-char :unsigned-short :unsigned-int :unsigned-long :unsigned-nat) `(unsigned-byte ,(* 8 (ff:sizeof-fobject type)))) (:float 'single-float) (:double 'double-float) (:void 'null))) (defun allegro-type-pair (cffi-type) ;; the :FOREIGN-ADDRESS pseudo-type accepts both pointers and ;; arrays. We need the latter for shareable byte vector support. (if (eq cffi-type :pointer) (list :foreign-address) (let ((ftype (convert-foreign-type cffi-type))) (list ftype (convert-to-lisp-type ftype))))) #+ignore (defun note-named-foreign-function (symbol name types rettype) "Give Allegro's compiler a hint to perform a direct call." `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (get ',symbol 'system::direct-ff-call) (list '(,name :language :c) t ; callback :c ; convention ;; return type '(:c-type lisp-type) ',(allegro-type-pair rettype) ;; arg types '({(:c-type lisp-type)}*) '(,@(mapcar #'allegro-type-pair types)) nil ; arg-checking ff::ep-flag-never-release)))) (defmacro %foreign-funcall (name args &key convention library) (declare (ignore convention library)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(system::ff-funcall (load-time-value (excl::determine-foreign-address '(,name :language :c) ff::ep-flag-never-release nil ; method-index )) ;; arg types {'(:c-type lisp-type) argN}* ,@(mapcan (lambda (type arg) `(',(allegro-type-pair type) ,arg)) types fargs) ;; return type '(:c-type lisp-type) ',(allegro-type-pair rettype)))) (defun defcfun-helper-forms (name lisp-name rettype args types options) "Return 2 values for DEFCFUN. A prelude form and a caller form." (declare (ignore options)) (let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name)))) (values `(ff:def-foreign-call (,ff-name ,name) ,(loop for type in types collect (list* (gensym) (allegro-type-pair type))) :returning ,(allegro-type-pair rettype) ;; Don't use call-direct when there are no arguments. ,@(unless (null args) '(:call-direct t)) :arg-checking nil :strings-convert nil) `(,ff-name ,@args)))) ;;; See doc/allegro-internals.txt for a clue about entry-vec. (defmacro %foreign-funcall-pointer (ptr args &key convention) (declare (ignore convention)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) (with-unique-names (entry-vec) `(let ((,entry-vec (excl::make-entry-vec-boa))) (setf (aref ,entry-vec 1) ,ptr) ; set jump address (system::ff-funcall ,entry-vec ;; arg types {'(:c-type lisp-type) argN}* ,@(mapcan (lambda (type arg) `(',(allegro-type-pair type) ,arg)) types fargs) ;; return type '(:c-type lisp-type) ',(allegro-type-pair rettype)))))) ;;;# Callbacks ;;; The *CALLBACKS* hash table contains information about a callback ;;; for the Allegro FFI. The key is the name of the CFFI callback, ;;; and the value is a cons, the car containing the symbol the ;;; callback was defined on in the CFFI-CALLBACKS package, the cdr ;;; being an Allegro FFI pointer (a fixnum) that can be passed to C ;;; functions. ;;; ;;; These pointers must be restored when a saved Lisp image is loaded. ;;; The RESTORE-CALLBACKS function is added to *RESTART-ACTIONS* to ;;; re-register the callbacks during Lisp startup. (defvar *callbacks* (make-hash-table)) ;;; Register a callback in the *CALLBACKS* hash table. (defun register-callback (cffi-name callback-name) (setf (gethash cffi-name *callbacks*) (cons callback-name (ff:register-foreign-callable callback-name :reuse t)))) ;;; Restore the saved pointers in *CALLBACKS* when loading an image. (defun restore-callbacks () (maphash (lambda (key value) (register-callback key (car value))) *callbacks*)) ;;; Arrange for RESTORE-CALLBACKS to run when a saved image containing CFFI is restarted . (eval-when (:load-toplevel :execute) (pushnew 'restore-callbacks excl:*restart-actions*)) ;;; Create a package to contain the symbols for callback functions. (defpackage #:cffi-callbacks (:use)) (defun intern-callback (name) (intern (format nil "~A::~A" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks)) (defun convert-calling-convention (convention) (ecase convention (:cdecl :c) (:stdcall :stdcall))) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (declare (ignore rettype)) (let ((cb-name (intern-callback name))) `(progn (ff:defun-foreign-callable ,cb-name ,(mapcar (lambda (sym type) (list sym (convert-foreign-type type))) arg-names arg-types) (declare (:convention ,(convert-calling-convention convention))) ,body) (register-callback ',name ',cb-name)))) ;;; Return the saved Lisp callback pointer from *CALLBACKS* for the ;;; CFFI callback named NAME. (defun %callback (name) (or (cdr (gethash name *callbacks*)) (error "Undefined callback: ~S" name))) # Loading and Closing Foreign Libraries (defun %load-foreign-library (name path) "Load a foreign library." ACL 8.0 honors the : FOREIGN option and always tries to foreign load ;; the argument. However, previous versions do not and will only ;; foreign load the argument if its type is a member of the ;; EXCL::*LOAD-FOREIGN-TYPES* list. Therefore, we bind that special ;; to a list containing whatever type NAME has. (declare (ignore name)) (let ((excl::*load-foreign-types* (list (pathname-type (parse-namestring path))))) (handler-case (progn #+(version>= 7) (load path :foreign t) #-(version>= 7) (load path)) (file-error (fe) (error (change-class fe 'simple-error)))) path)) (defun %close-foreign-library (name) "Close the foreign library NAME." (ff:unload-foreign-library name)) (defun native-namestring (pathname) (namestring pathname)) ;;;# Foreign Globals (defun convert-external-name (name) "Add an underscore to NAME if necessary for the ABI." #+macosx (concatenate 'string "_" name) #-macosx name) (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (prog1 (ff:get-entry-point (convert-external-name name))))
null
https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/dists/quicklisp/software/cffi_0.10.6/src/cffi-allegro.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 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. # Mis-features # Symbol Case # Basic Pointer Operations # Allocation Functions and macros for allocating foreign memory on the stack FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage when the memory has dynamic extent. (excl::stack-allocated-p var) => T # Shareable Vectors This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA should be defined to perform a copy-in/copy-out if the Lisp implementation can't do this. An array allocated in static-reclamable is a non-simple array in the normal Lisp allocation area, pointing to a simple array in the static-reclaimable allocation area. Therefore we have to get out the simple-array to find the pointer to the actual contents. # Dereferencing call that results in efficient code. transformation on the call that results in efficient code. # Calling Foreign Functions No override necessary for the remaining types.... the :FOREIGN-ADDRESS pseudo-type accepts both pointers and arrays. We need the latter for shareable byte vector support. callback convention return type '(:c-type lisp-type) arg types '({(:c-type lisp-type)}*) arg-checking method-index arg types {'(:c-type lisp-type) argN}* return type '(:c-type lisp-type) Don't use call-direct when there are no arguments. See doc/allegro-internals.txt for a clue about entry-vec. set jump address arg types {'(:c-type lisp-type) argN}* return type '(:c-type lisp-type) # Callbacks The *CALLBACKS* hash table contains information about a callback for the Allegro FFI. The key is the name of the CFFI callback, and the value is a cons, the car containing the symbol the callback was defined on in the CFFI-CALLBACKS package, the cdr being an Allegro FFI pointer (a fixnum) that can be passed to C functions. These pointers must be restored when a saved Lisp image is loaded. The RESTORE-CALLBACKS function is added to *RESTART-ACTIONS* to re-register the callbacks during Lisp startup. Register a callback in the *CALLBACKS* hash table. Restore the saved pointers in *CALLBACKS* when loading an image. Arrange for RESTORE-CALLBACKS to run when a saved image containing Create a package to contain the symbols for callback functions. Return the saved Lisp callback pointer from *CALLBACKS* for the CFFI callback named NAME. the argument. However, previous versions do not and will only foreign load the argument if its type is a member of the EXCL::*LOAD-FOREIGN-TYPES* list. Therefore, we bind that special to a list containing whatever type NAME has. # Foreign Globals
cffi-allegro.lisp --- CFFI - SYS implementation for Allegro CL . Copyright ( C ) 2005 - 2009 , loliveira(@)common - lisp.net > files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , # Administrivia (defpackage #:cffi-sys (:use #:common-lisp) (:import-from #:alexandria #:if-let #:with-unique-names #:once-only) (:export #:canonicalize-symbol-name-case #:foreign-pointer #:pointerp #:pointer-eq #:null-pointer #:null-pointer-p #:inc-pointer #:make-pointer #:pointer-address #:%foreign-alloc #:foreign-free #:with-foreign-pointer #:%foreign-funcall #:%foreign-funcall-pointer #:%foreign-type-alignment #:%foreign-type-size #:%load-foreign-library #:%close-foreign-library #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:defcfun-helper-forms #:%defcallback #:%callback)) (in-package #:cffi-sys) #-64bit (pushnew 'no-long-long *features*) (pushnew 'flat-namespace *features*) (defun canonicalize-symbol-name-case (name) (declare (string name)) (if (eq excl:*current-case-mode* :case-sensitive-lower) (string-downcase name) (string-upcase name))) (deftype foreign-pointer () 'ff:foreign-address) (defun pointerp (ptr) "Return true if PTR is a foreign pointer." (ff:foreign-address-p ptr)) (defun pointer-eq (ptr1 ptr2) "Return true if PTR1 and PTR2 point to the same address." (eql ptr1 ptr2)) (defun null-pointer () "Return a null pointer." 0) (defun null-pointer-p (ptr) "Return true if PTR is a null pointer." (zerop ptr)) (defun inc-pointer (ptr offset) "Return a pointer pointing OFFSET bytes past PTR." (+ ptr offset)) (defun make-pointer (address) "Return a pointer pointing to ADDRESS." (check-type address ff:foreign-address) address) (defun pointer-address (ptr) "Return the address pointed to by PTR." (check-type ptr ff:foreign-address) ptr) and on the heap . The main CFFI package defines macros that wrap (defun %foreign-alloc (size) "Allocate SIZE bytes on the heap and return a pointer." (ff:allocate-fobject :char :c size)) (defun foreign-free (ptr) "Free a PTR allocated by FOREIGN-ALLOC." (ff:free-fobject ptr)) (defmacro with-foreign-pointer ((var size &optional size-var) &body body) "Bind VAR to SIZE bytes of foreign memory during BODY. The pointer in VAR is invalid beyond the dynamic extent of BODY, and may be stack-allocated if supported by the implementation. If SIZE-VAR is supplied, it will be bound to SIZE during BODY." (unless size-var (setf size-var (gensym "SIZE"))) #+(version>= 8 1) (when (and (constantp size) (<= (eval size) ff:*max-stack-fobject-bytes*)) (return-from with-foreign-pointer `(let ((,size-var ,(eval size))) (declare (ignorable ,size-var)) (ff:with-static-fobject (,var '(:array :char ,(eval size)) :allocation :foreign-static-gc) (let ((,var (ff:fslot-address ,var))) ,@body))))) `(let* ((,size-var ,size) (,var (ff:allocate-fobject :char :c ,size-var))) (unwind-protect (progn ,@body) (ff:free-fobject ,var)))) (defun make-shareable-byte-vector (size) "Create a Lisp vector of SIZE bytes can passed to WITH-POINTER-TO-VECTOR-DATA." (make-array size :element-type '(unsigned-byte 8) :allocation :static-reclaimable)) (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body) "Bind PTR-VAR to a foreign pointer to the data in VECTOR." (with-unique-names (simple-vec) `(excl:with-underlying-simple-vector (,vector ,simple-vec) (let ((,ptr-var (ff:fslot-address-typed :unsigned-char :lisp ,simple-vec))) ,@body)))) (defun convert-foreign-type (type-keyword) "Convert a CFFI type keyword to an Allegro type." (ecase type-keyword (:char :char) (:unsigned-char :unsigned-char) (:short :short) (:unsigned-short :unsigned-short) (:int :int) (:unsigned-int :unsigned-int) (:long :long) (:unsigned-long :unsigned-long) #+64bit (:long-long :nat) #+64bit (:unsigned-long-long :unsigned-nat) (:float :float) (:double :double) (:pointer :unsigned-nat) (:void :void))) (defun %mem-ref (ptr type &optional (offset 0)) "Dereference an object of TYPE at OFFSET bytes from PTR." (unless (zerop offset) (setf ptr (inc-pointer ptr offset))) (ff:fslot-value-typed (convert-foreign-type type) :c ptr)) Compiler macro to open - code the call to FSLOT - VALUE - TYPED when the CFFI type is constant . Allegro does its own transformation on the (define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0)) (if (constantp type) (let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off)))) `(ff:fslot-value-typed ',(convert-foreign-type (eval type)) :c ,ptr-form)) form)) (defun %mem-set (value ptr type &optional (offset 0)) "Set the object of TYPE at OFFSET bytes from PTR." (unless (zerop offset) (setf ptr (inc-pointer ptr offset))) (setf (ff:fslot-value-typed (convert-foreign-type type) :c ptr) value)) Compiler macro to open - code the call to ( SETF FSLOT - VALUE - TYPED ) when the CFFI type is constant . Allegro does its own (define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0)) (if (constantp type) (once-only (val) (let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off)))) `(setf (ff:fslot-value-typed ',(convert-foreign-type (eval type)) :c ,ptr-form) ,val))) form)) (defun %foreign-type-size (type-keyword) "Return the size in bytes of a foreign type." (ff:sizeof-fobject (convert-foreign-type type-keyword))) (defun %foreign-type-alignment (type-keyword) "Returns the alignment in bytes of a foreign type." #+(and powerpc macosx32) (when (eq type-keyword :double) (return-from %foreign-type-alignment 8)) (ff::sized-ftype-prim-align (ff::iforeign-type-sftype (ff:get-foreign-type (convert-foreign-type type-keyword))))) (defun foreign-funcall-type-and-args (args) "Returns a list of types, list of args and return type." (let ((return-type :void)) (loop for (type arg) on args by #'cddr if arg collect type into types and collect arg into fargs else do (setf return-type type) finally (return (values types fargs return-type))))) (defun convert-to-lisp-type (type) (ecase type ((:char :short :int :long) `(signed-byte ,(* 8 (ff:sizeof-fobject type)))) ((:unsigned-char :unsigned-short :unsigned-int :unsigned-long :unsigned-nat) `(unsigned-byte ,(* 8 (ff:sizeof-fobject type)))) (:float 'single-float) (:double 'double-float) (:void 'null))) (defun allegro-type-pair (cffi-type) (if (eq cffi-type :pointer) (list :foreign-address) (let ((ftype (convert-foreign-type cffi-type))) (list ftype (convert-to-lisp-type ftype))))) #+ignore (defun note-named-foreign-function (symbol name types rettype) "Give Allegro's compiler a hint to perform a direct call." `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (get ',symbol 'system::direct-ff-call) (list '(,name :language :c) ',(allegro-type-pair rettype) '(,@(mapcar #'allegro-type-pair types)) ff::ep-flag-never-release)))) (defmacro %foreign-funcall (name args &key convention library) (declare (ignore convention library)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(system::ff-funcall (load-time-value (excl::determine-foreign-address '(,name :language :c) ff::ep-flag-never-release )) ,@(mapcan (lambda (type arg) `(',(allegro-type-pair type) ,arg)) types fargs) ',(allegro-type-pair rettype)))) (defun defcfun-helper-forms (name lisp-name rettype args types options) "Return 2 values for DEFCFUN. A prelude form and a caller form." (declare (ignore options)) (let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name)))) (values `(ff:def-foreign-call (,ff-name ,name) ,(loop for type in types collect (list* (gensym) (allegro-type-pair type))) :returning ,(allegro-type-pair rettype) ,@(unless (null args) '(:call-direct t)) :arg-checking nil :strings-convert nil) `(,ff-name ,@args)))) (defmacro %foreign-funcall-pointer (ptr args &key convention) (declare (ignore convention)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) (with-unique-names (entry-vec) `(let ((,entry-vec (excl::make-entry-vec-boa))) (system::ff-funcall ,entry-vec ,@(mapcan (lambda (type arg) `(',(allegro-type-pair type) ,arg)) types fargs) ',(allegro-type-pair rettype)))))) (defvar *callbacks* (make-hash-table)) (defun register-callback (cffi-name callback-name) (setf (gethash cffi-name *callbacks*) (cons callback-name (ff:register-foreign-callable callback-name :reuse t)))) (defun restore-callbacks () (maphash (lambda (key value) (register-callback key (car value))) *callbacks*)) CFFI is restarted . (eval-when (:load-toplevel :execute) (pushnew 'restore-callbacks excl:*restart-actions*)) (defpackage #:cffi-callbacks (:use)) (defun intern-callback (name) (intern (format nil "~A::~A" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks)) (defun convert-calling-convention (convention) (ecase convention (:cdecl :c) (:stdcall :stdcall))) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (declare (ignore rettype)) (let ((cb-name (intern-callback name))) `(progn (ff:defun-foreign-callable ,cb-name ,(mapcar (lambda (sym type) (list sym (convert-foreign-type type))) arg-names arg-types) (declare (:convention ,(convert-calling-convention convention))) ,body) (register-callback ',name ',cb-name)))) (defun %callback (name) (or (cdr (gethash name *callbacks*)) (error "Undefined callback: ~S" name))) # Loading and Closing Foreign Libraries (defun %load-foreign-library (name path) "Load a foreign library." ACL 8.0 honors the : FOREIGN option and always tries to foreign load (declare (ignore name)) (let ((excl::*load-foreign-types* (list (pathname-type (parse-namestring path))))) (handler-case (progn #+(version>= 7) (load path :foreign t) #-(version>= 7) (load path)) (file-error (fe) (error (change-class fe 'simple-error)))) path)) (defun %close-foreign-library (name) "Close the foreign library NAME." (ff:unload-foreign-library name)) (defun native-namestring (pathname) (namestring pathname)) (defun convert-external-name (name) "Add an underscore to NAME if necessary for the ABI." #+macosx (concatenate 'string "_" name) #-macosx name) (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (prog1 (ff:get-entry-point (convert-external-name name))))
b3b63150949e33f26f1e663dc4f1dc9da0a87fb2fe8dd4ab669915832fd96c12
input-output-hk/hydra
StateSpec.hs
# LANGUAGE DuplicateRecordFields # # LANGUAGE PatternSynonyms # # LANGUAGE TypeApplications # # OPTIONS_GHC -Wno - orphans # module Hydra.Chain.Direct.StateSpec where import Hydra.Prelude hiding (label) import Test.Hydra.Prelude import qualified Cardano.Api.UTxO as UTxO import Cardano.Binary (serialize) import qualified Data.ByteString.Lazy as LBS import Data.List (intersect) import qualified Data.List as List import qualified Data.Set as Set import Hydra.Cardano.Api ( Tx, UTxO, hashScript, renderUTxO, scriptPolicyId, toPlutusCurrencySymbol, txInputSet, txOutValue, txOuts', valueSize, pattern PlutusScript, pattern PlutusScriptSerialised, ) import Hydra.Cardano.Api.Pretty (renderTx) import Hydra.Chain (OnChainTx (..), PostTxError (..)) import Hydra.Chain.Direct.Contract.Mutation ( Mutation (ChangeMintingPolicy, ChangeOutput, Changes), applyMutation, changeHeadOutputDatum, propTransactionEvaluates, propTransactionFailsEvaluation, replaceHeadId, ) import Hydra.Chain.Direct.State ( ChainContext (..), ChainState, HasKnownUTxO (getKnownUTxO), HydraContext (..), InitialState (..), abort, close, closedThreadOutput, collect, commit, ctxHeadParameters, ctxParties, fanout, genChainStateWithTx, genCloseTx, genCollectComTx, genCommit, genCommits, genCommits', genContestTx, genFanoutTx, genHydraContext, genInitTx, genStInitial, getContestationDeadline, getKnownUTxO, initialize, observeAbort, observeClose, observeCollect, observeCommit, observeInit, observeSomeTx, pickChainContext, unsafeCommit, unsafeObserveInitAndCommits, ) import Hydra.Chain.Direct.Tx (ClosedThreadOutput (closedContesters), NotAnInitReason (..)) import Hydra.ContestationPeriod (toNominalDiffTime) import Hydra.Ledger.Cardano ( genOutput, genTxIn, genTxOutAdaOnly, genTxOutByron, genTxOutWithReferenceScript, genUTxO1, genUTxOSized, ) import Hydra.Ledger.Cardano.Evaluate ( evaluateTx, genValidityBoundsFromContestationPeriod, maxTxSize, ) import qualified Hydra.Ledger.Cardano.Evaluate as Fixture import Hydra.Options (maximumNumberOfParties) import Hydra.Snapshot (ConfirmedSnapshot (InitialSnapshot, initialUTxO)) import qualified Plutus.V1.Ledger.Examples as Plutus import qualified Plutus.V2.Ledger.Api as Plutus import Test.Aeson.GenericSpecs (roundtripAndGoldenSpecs) import Test.Consensus.Cardano.Generators () import Test.QuickCheck ( Property, Testable (property), checkCoverage, classify, conjoin, counterexample, cover, discard, forAll, forAllBlind, forAllShow, label, sized, sublistOf, tabulate, (.||.), (=/=), (===), (==>), ) import Test.QuickCheck.Monadic (monadicIO, monadicST, pick) import qualified Prelude spec :: Spec spec = parallel $ do describe "ChainState" $ roundtripAndGoldenSpecs (Proxy @ChainState) describe "Plutus.PubKeyHash" $ roundtripAndGoldenSpecs (Proxy @Plutus.PubKeyHash) describe "observeTx" $ do prop "All valid transitions for all possible states can be observed." $ checkCoverage $ forAll genChainStateWithTx $ \(ctx, st, tx, transition) -> genericCoverTable [transition] $ isJust (observeSomeTx ctx st tx) & counterexample "observeSomeTx returned Nothing" describe "init" $ do propBelowSizeLimit maxTxSize forAllInit propIsValid forAllInit it "only proper head is observed" $ monadicIO $ do ctx <- pickBlind (genHydraContext maximumNumberOfParties) cctx <- pickBlind $ pickChainContext ctx seedInput <- pickBlind arbitrary seedTxOut <- pickBlind genTxOutAdaOnly let tx = initialize cctx (ctxHeadParameters ctx) seedInput originalIsObserved = property $ isRight (observeInit cctx tx) -- We do replace the minting policy and datum of a head output to -- simulate a faked init transaction. let alwaysSucceedsV2 = PlutusScriptSerialised $ Plutus.alwaysSucceedingNAryFunction 2 let fakeHeadId = toPlutusCurrencySymbol . scriptPolicyId $ PlutusScript alwaysSucceedsV2 let headTxOut = List.head (txOuts' tx) let mutation = Changes [ ChangeMintingPolicy alwaysSucceedsV2 , ChangeOutput 0 $ changeHeadOutputDatum (replaceHeadId fakeHeadId) headTxOut ] let utxo = UTxO.singleton (seedInput, seedTxOut) let (tx', utxo') = applyMutation mutation (tx, utxo) -- We expected mutated transaction to still be valid, but not observed. mutatedIsValid = property $ case evaluateTx tx' utxo' of Left _ -> False Right ok | all isRight ok -> True | otherwise -> False mutatedIsNotObserved = observeInit cctx tx' === Left NotAHeadPolicy pure $ conjoin [ originalIsObserved & counterexample (renderTx tx) & counterexample "Original transaction is not observed." , mutatedIsValid & counterexample (renderTx tx') & counterexample "Mutated transaction is not valid." , mutatedIsNotObserved & counterexample (renderTx tx') & counterexample "Should not observe mutated transaction" ] & counterexample ("new minting policy: " <> show (hashScript $ PlutusScript alwaysSucceedsV2)) prop "is not observed if not invited" $ forAll2 (genHydraContext maximumNumberOfParties) (genHydraContext maximumNumberOfParties) $ \(ctxA, ctxB) -> null (ctxParties ctxA `intersect` ctxParties ctxB) ==> forAll2 (pickChainContext ctxA) (pickChainContext ctxB) $ \(cctxA, cctxB) -> forAll genTxIn $ \seedInput -> let tx = initialize cctxA (ctxHeadParameters ctxA) seedInput in isLeft (observeInit cctxB tx) describe "commit" $ do propBelowSizeLimit maxTxSize forAllCommit propIsValid forAllCommit prop "consumes all inputs that are committed" $ forAllCommit' $ \ctx st _ tx -> case observeCommit ctx st tx of Just (_, st') -> let knownInputs = UTxO.inputSet (getKnownUTxO st') in knownInputs `Set.disjoint` txInputSet tx Nothing -> False prop "can only be applied / observed once" $ forAllCommit' $ \ctx st _ tx -> case observeCommit ctx st tx of Just (_, st') -> case observeCommit ctx st' tx of Just{} -> False Nothing -> True Nothing -> False prop "reject committing outputs with byron addresses" $ monadicST $ do hctx <- pickBlind $ genHydraContext maximumNumberOfParties (ctx, stInitial) <- pickBlind $ genStInitial hctx utxo <- pick $ genUTxO1 genTxOutByron pure $ case commit ctx stInitial utxo of Left UnsupportedLegacyOutput{} -> property True _ -> property False prop "reject committing outputs with reference scripts" $ monadicST $ do hctx <- pickBlind $ genHydraContext maximumNumberOfParties (ctx, stInitial) <- pickBlind $ genStInitial hctx utxo <- pick $ genUTxO1 genTxOutWithReferenceScript pure $ case commit ctx stInitial utxo of Left CannotCommitReferenceScript{} -> property True _ -> property False describe "abort" $ do propBelowSizeLimit maxTxSize forAllAbort propIsValid forAllAbort prop "ignore aborts of other heads" $ do let twoDistinctHeads = do ctx <- genHydraContext maximumNumberOfParties (ctx1, st1@InitialState{headId = h1}) <- genStInitial ctx (ctx2, st2@InitialState{headId = h2}) <- genStInitial ctx when (h1 == h2) discard pure ((ctx1, st1), (ctx2, st2)) forAll twoDistinctHeads $ \((ctx1, stHead1), (ctx2, stHead2)) -> let observedIn1 = observeAbort stHead1 (abort ctx1 stHead1 mempty) observedIn2 = observeAbort stHead2 (abort ctx2 stHead1 mempty) in conjoin [ observedIn1 =/= Nothing , observedIn2 === Nothing ] describe "collectCom" $ do propBelowSizeLimit maxTxSize forAllCollectCom propIsValid forAllCollectCom describe "close" $ do propBelowSizeLimit maxTxSize forAllClose propIsValid forAllClose describe "contest" $ do propBelowSizeLimit maxTxSize forAllContest propIsValid forAllContest describe "fanout" $ do propBelowSizeLimit maxTxSize forAllFanout propIsValid forAllFanout describe "acceptance" $ do it "can close & fanout every collected head" $ do prop_canCloseFanoutEveryCollect -- * Properties prop_canCloseFanoutEveryCollect :: Property prop_canCloseFanoutEveryCollect = monadicST $ do let maxParties = 10 ctx@HydraContext{ctxContestationPeriod} <- pickBlind $ genHydraContext maxParties cctx <- pickBlind $ pickChainContext ctx Init txInit <- pickBlind $ genInitTx ctx -- Commits commits <- pickBlind $ genCommits' (genUTxOSized 1) ctx txInit let (committed, stInitial) = unsafeObserveInitAndCommits cctx txInit commits -- Collect let initialUTxO = fold committed let txCollect = collect cctx stInitial stOpen <- mfail $ snd <$> observeCollect stInitial txCollect -- Close (closeLower, closeUpper) <- pickBlind $ genValidityBoundsFromContestationPeriod ctxContestationPeriod let txClose = close cctx stOpen InitialSnapshot{initialUTxO} closeLower closeUpper (deadline, stClosed) <- case observeClose stOpen txClose of Just (OnCloseTx{contestationDeadline}, st) -> pure (contestationDeadline, st) _ -> fail "not observed close" -- Fanout let txFanout = fanout cctx stClosed initialUTxO (Fixture.slotNoFromUTCTime deadline) -- Properties let collectFails = propTransactionFailsEvaluation (txCollect, getKnownUTxO cctx <> getKnownUTxO stInitial) & counterexample "collect passed, but others failed?" & cover 10 True "collect failed already" let collectCloseAndFanoutPass = conjoin [ propTransactionEvaluates (txCollect, getKnownUTxO cctx <> getKnownUTxO stInitial) & counterexample "collect failed" , propTransactionEvaluates (txClose, getKnownUTxO cctx <> getKnownUTxO stOpen) & counterexample "close failed" , propTransactionEvaluates (txFanout, getKnownUTxO cctx <> getKnownUTxO stClosed) & counterexample "fanout failed" ] & cover 10 True "collect, close and fanout passed" pure $ -- XXX: Coverage does not work if we only collectFails checkCoverage (collectFails .||. collectCloseAndFanoutPass) -- -- Generic Properties -- propBelowSizeLimit :: Natural -> ((UTxO -> Tx -> Property) -> Property) -> SpecWith () propBelowSizeLimit txSizeLimit forAllTx = prop ("transaction size is below " <> showKB txSizeLimit) $ forAllTx $ \_ tx -> let cbor = serialize tx len = LBS.length cbor in len < fromIntegral txSizeLimit & label (showKB len) & counterexample (renderTx tx) & counterexample ("Actual size: " <> show len) where showKB nb = show (nb `div` 1024) <> "kB" propIsValid :: ((UTxO -> Tx -> Property) -> Property) -> SpecWith () propIsValid forAllTx = prop "validates within maxTxExecutionUnits" $ forAllTx $ \utxo tx -> propTransactionEvaluates (tx, utxo) -- -- QuickCheck Extras -- -- TODO: These forAllXX functions are hard to use and understand. Maybe simple -- 'Gen' or functions in 'PropertyM' are better combinable? forAllInit :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllInit action = forAllBlind (genHydraContext maximumNumberOfParties) $ \ctx -> forAll (pickChainContext ctx) $ \cctx -> do forAll ((,) <$> genTxIn <*> genOutput (ownVerificationKey cctx)) $ \(seedIn, seedOut) -> do let tx = initialize cctx (ctxHeadParameters ctx) seedIn utxo = UTxO.singleton (seedIn, seedOut) <> getKnownUTxO cctx in action utxo tx & classify (length (peerVerificationKeys cctx) == 0) "1 party" & classify (length (peerVerificationKeys cctx) > 0) "2+ parties" forAllCommit :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllCommit action = forAllCommit' $ \ctx st toCommit tx -> let utxo = getKnownUTxO st <> toCommit <> getKnownUTxO ctx in action utxo tx forAllCommit' :: (Testable property) => (ChainContext -> InitialState -> UTxO -> Tx -> property) -> Property forAllCommit' action = do forAll (genHydraContext maximumNumberOfParties) $ \hctx -> forAll (genStInitial hctx) $ \(ctx, stInitial) -> forAllShow genCommit renderUTxO $ \toCommit -> let tx = unsafeCommit ctx stInitial toCommit in action ctx stInitial toCommit tx & classify (null toCommit) "Empty commit" & classify (not (null toCommit)) "Non-empty commit" & counterexample ("tx: " <> renderTx tx) forAllAbort :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllAbort action = do forAll (genHydraContext maximumNumberOfParties) $ \ctx -> forAll (pickChainContext ctx) $ \cctx -> forAllBlind (genInitTx ctx) $ \initTx -> do forAllBlind (sublistOf =<< genCommits ctx initTx) $ \commits -> let (committed, stInitialized) = unsafeObserveInitAndCommits cctx initTx commits utxo = getKnownUTxO stInitialized <> getKnownUTxO cctx in action utxo (abort cctx stInitialized (fold committed)) & classify (null commits) "Abort immediately, after 0 commits" & classify (not (null commits) && length commits < length (ctxParties ctx)) "Abort after some (but not all) commits" & classify (length commits == length (ctxParties ctx)) "Abort after all commits" forAllCollectCom :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllCollectCom action = forAllBlind genCollectComTx $ \(ctx, committedUTxO, stInitialized, tx) -> let utxo = getKnownUTxO stInitialized <> getKnownUTxO ctx in action utxo tx & counterexample ("Committed UTxO: " <> show committedUTxO) forAllClose :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllClose action = do -- FIXME: we should not hardcode number of parties but generate it within bounds forAll (genCloseTx maximumNumberOfParties) $ \(ctx, st, tx, sn) -> let utxo = getKnownUTxO st <> getKnownUTxO ctx in action utxo tx & label (Prelude.head . Prelude.words . show $ sn) forAllContest :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllContest action = forAllBlind genContestTx $ \(hctx@HydraContext{ctxContestationPeriod}, closePointInTime, stClosed, tx) -> -- XXX: Pick an arbitrary context to contest. We will stumble over this when -- we make contests only possible once per party. forAllBlind (pickChainContext hctx) $ \ctx -> let utxo = getKnownUTxO stClosed <> getKnownUTxO ctx in action utxo tx & counterexample ("Contestation deadline: " <> show (getContestationDeadline stClosed)) & counterexample ("Contestation period: " <> show ctxContestationPeriod) & counterexample ("Close point: " <> show closePointInTime) & counterexample ("Closed contesters: " <> show (getClosedContesters stClosed)) & tabulate "Contestation period" (tabulateContestationPeriod ctxContestationPeriod) & tabulate "Close point (slot)" (tabulateNum $ fst closePointInTime) where tabulateNum x | x > 0 = ["> 0"] | x < 0 = ["< 0"] | otherwise = ["== 0"] tabulateContestationPeriod (toNominalDiffTime -> cp) | cp == confirmedHorizon = ["k blocks on mainnet"] | cp == oneDay = ["one day"] | cp == oneWeek = ["one week"] | cp == oneMonth = ["one month"] | cp == oneYear = ["one year"] | cp < confirmedHorizon = ["< k blocks"] | otherwise = ["> k blocks"] confirmedHorizon = 2160 * 20 -- k blocks on mainnet oneDay = 3600 * 24 oneWeek = oneDay * 7 oneMonth = oneDay * 30 oneYear = oneDay * 365 getClosedContesters stClosed = closedContesters . closedThreadOutput $ stClosed forAllFanout :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllFanout action = -- TODO: The utxo to fanout should be more arbitrary to have better test coverage forAll (sized $ \n -> genFanoutTx maximumNumberOfParties (n `min` maxSupported)) $ \(hctx, stClosed, tx) -> forAllBlind (pickChainContext hctx) $ \ctx -> let utxo = getKnownUTxO stClosed <> getKnownUTxO ctx in action utxo tx & label ("Fanout size: " <> prettyLength (countAssets $ txOuts' tx)) where maxSupported = 58 countAssets = getSum . foldMap (Sum . valueSize . txOutValue) prettyLength len | len > maxSupported = "> " <> show maxSupported <> " ???" | len >= 40 = "40-" <> show maxSupported | len >= 10 = "10-40" | len >= 1 = "1-10" | otherwise = "0" -- * Helpers mfail :: MonadFail m => Maybe a -> m a mfail = \case Nothing -> fail "encountered Nothing" Just a -> pure a
null
https://raw.githubusercontent.com/input-output-hk/hydra/79da8556b0b60c7bca0c0aec308761a3c23e27e5/hydra-node/test/Hydra/Chain/Direct/StateSpec.hs
haskell
We do replace the minting policy and datum of a head output to simulate a faked init transaction. We expected mutated transaction to still be valid, but not observed. * Properties Commits Collect Close Fanout Properties XXX: Coverage does not work if we only collectFails Generic Properties QuickCheck Extras TODO: These forAllXX functions are hard to use and understand. Maybe simple 'Gen' or functions in 'PropertyM' are better combinable? FIXME: we should not hardcode number of parties but generate it within bounds XXX: Pick an arbitrary context to contest. We will stumble over this when we make contests only possible once per party. k blocks on mainnet TODO: The utxo to fanout should be more arbitrary to have better test coverage * Helpers
# LANGUAGE DuplicateRecordFields # # LANGUAGE PatternSynonyms # # LANGUAGE TypeApplications # # OPTIONS_GHC -Wno - orphans # module Hydra.Chain.Direct.StateSpec where import Hydra.Prelude hiding (label) import Test.Hydra.Prelude import qualified Cardano.Api.UTxO as UTxO import Cardano.Binary (serialize) import qualified Data.ByteString.Lazy as LBS import Data.List (intersect) import qualified Data.List as List import qualified Data.Set as Set import Hydra.Cardano.Api ( Tx, UTxO, hashScript, renderUTxO, scriptPolicyId, toPlutusCurrencySymbol, txInputSet, txOutValue, txOuts', valueSize, pattern PlutusScript, pattern PlutusScriptSerialised, ) import Hydra.Cardano.Api.Pretty (renderTx) import Hydra.Chain (OnChainTx (..), PostTxError (..)) import Hydra.Chain.Direct.Contract.Mutation ( Mutation (ChangeMintingPolicy, ChangeOutput, Changes), applyMutation, changeHeadOutputDatum, propTransactionEvaluates, propTransactionFailsEvaluation, replaceHeadId, ) import Hydra.Chain.Direct.State ( ChainContext (..), ChainState, HasKnownUTxO (getKnownUTxO), HydraContext (..), InitialState (..), abort, close, closedThreadOutput, collect, commit, ctxHeadParameters, ctxParties, fanout, genChainStateWithTx, genCloseTx, genCollectComTx, genCommit, genCommits, genCommits', genContestTx, genFanoutTx, genHydraContext, genInitTx, genStInitial, getContestationDeadline, getKnownUTxO, initialize, observeAbort, observeClose, observeCollect, observeCommit, observeInit, observeSomeTx, pickChainContext, unsafeCommit, unsafeObserveInitAndCommits, ) import Hydra.Chain.Direct.Tx (ClosedThreadOutput (closedContesters), NotAnInitReason (..)) import Hydra.ContestationPeriod (toNominalDiffTime) import Hydra.Ledger.Cardano ( genOutput, genTxIn, genTxOutAdaOnly, genTxOutByron, genTxOutWithReferenceScript, genUTxO1, genUTxOSized, ) import Hydra.Ledger.Cardano.Evaluate ( evaluateTx, genValidityBoundsFromContestationPeriod, maxTxSize, ) import qualified Hydra.Ledger.Cardano.Evaluate as Fixture import Hydra.Options (maximumNumberOfParties) import Hydra.Snapshot (ConfirmedSnapshot (InitialSnapshot, initialUTxO)) import qualified Plutus.V1.Ledger.Examples as Plutus import qualified Plutus.V2.Ledger.Api as Plutus import Test.Aeson.GenericSpecs (roundtripAndGoldenSpecs) import Test.Consensus.Cardano.Generators () import Test.QuickCheck ( Property, Testable (property), checkCoverage, classify, conjoin, counterexample, cover, discard, forAll, forAllBlind, forAllShow, label, sized, sublistOf, tabulate, (.||.), (=/=), (===), (==>), ) import Test.QuickCheck.Monadic (monadicIO, monadicST, pick) import qualified Prelude spec :: Spec spec = parallel $ do describe "ChainState" $ roundtripAndGoldenSpecs (Proxy @ChainState) describe "Plutus.PubKeyHash" $ roundtripAndGoldenSpecs (Proxy @Plutus.PubKeyHash) describe "observeTx" $ do prop "All valid transitions for all possible states can be observed." $ checkCoverage $ forAll genChainStateWithTx $ \(ctx, st, tx, transition) -> genericCoverTable [transition] $ isJust (observeSomeTx ctx st tx) & counterexample "observeSomeTx returned Nothing" describe "init" $ do propBelowSizeLimit maxTxSize forAllInit propIsValid forAllInit it "only proper head is observed" $ monadicIO $ do ctx <- pickBlind (genHydraContext maximumNumberOfParties) cctx <- pickBlind $ pickChainContext ctx seedInput <- pickBlind arbitrary seedTxOut <- pickBlind genTxOutAdaOnly let tx = initialize cctx (ctxHeadParameters ctx) seedInput originalIsObserved = property $ isRight (observeInit cctx tx) let alwaysSucceedsV2 = PlutusScriptSerialised $ Plutus.alwaysSucceedingNAryFunction 2 let fakeHeadId = toPlutusCurrencySymbol . scriptPolicyId $ PlutusScript alwaysSucceedsV2 let headTxOut = List.head (txOuts' tx) let mutation = Changes [ ChangeMintingPolicy alwaysSucceedsV2 , ChangeOutput 0 $ changeHeadOutputDatum (replaceHeadId fakeHeadId) headTxOut ] let utxo = UTxO.singleton (seedInput, seedTxOut) let (tx', utxo') = applyMutation mutation (tx, utxo) mutatedIsValid = property $ case evaluateTx tx' utxo' of Left _ -> False Right ok | all isRight ok -> True | otherwise -> False mutatedIsNotObserved = observeInit cctx tx' === Left NotAHeadPolicy pure $ conjoin [ originalIsObserved & counterexample (renderTx tx) & counterexample "Original transaction is not observed." , mutatedIsValid & counterexample (renderTx tx') & counterexample "Mutated transaction is not valid." , mutatedIsNotObserved & counterexample (renderTx tx') & counterexample "Should not observe mutated transaction" ] & counterexample ("new minting policy: " <> show (hashScript $ PlutusScript alwaysSucceedsV2)) prop "is not observed if not invited" $ forAll2 (genHydraContext maximumNumberOfParties) (genHydraContext maximumNumberOfParties) $ \(ctxA, ctxB) -> null (ctxParties ctxA `intersect` ctxParties ctxB) ==> forAll2 (pickChainContext ctxA) (pickChainContext ctxB) $ \(cctxA, cctxB) -> forAll genTxIn $ \seedInput -> let tx = initialize cctxA (ctxHeadParameters ctxA) seedInput in isLeft (observeInit cctxB tx) describe "commit" $ do propBelowSizeLimit maxTxSize forAllCommit propIsValid forAllCommit prop "consumes all inputs that are committed" $ forAllCommit' $ \ctx st _ tx -> case observeCommit ctx st tx of Just (_, st') -> let knownInputs = UTxO.inputSet (getKnownUTxO st') in knownInputs `Set.disjoint` txInputSet tx Nothing -> False prop "can only be applied / observed once" $ forAllCommit' $ \ctx st _ tx -> case observeCommit ctx st tx of Just (_, st') -> case observeCommit ctx st' tx of Just{} -> False Nothing -> True Nothing -> False prop "reject committing outputs with byron addresses" $ monadicST $ do hctx <- pickBlind $ genHydraContext maximumNumberOfParties (ctx, stInitial) <- pickBlind $ genStInitial hctx utxo <- pick $ genUTxO1 genTxOutByron pure $ case commit ctx stInitial utxo of Left UnsupportedLegacyOutput{} -> property True _ -> property False prop "reject committing outputs with reference scripts" $ monadicST $ do hctx <- pickBlind $ genHydraContext maximumNumberOfParties (ctx, stInitial) <- pickBlind $ genStInitial hctx utxo <- pick $ genUTxO1 genTxOutWithReferenceScript pure $ case commit ctx stInitial utxo of Left CannotCommitReferenceScript{} -> property True _ -> property False describe "abort" $ do propBelowSizeLimit maxTxSize forAllAbort propIsValid forAllAbort prop "ignore aborts of other heads" $ do let twoDistinctHeads = do ctx <- genHydraContext maximumNumberOfParties (ctx1, st1@InitialState{headId = h1}) <- genStInitial ctx (ctx2, st2@InitialState{headId = h2}) <- genStInitial ctx when (h1 == h2) discard pure ((ctx1, st1), (ctx2, st2)) forAll twoDistinctHeads $ \((ctx1, stHead1), (ctx2, stHead2)) -> let observedIn1 = observeAbort stHead1 (abort ctx1 stHead1 mempty) observedIn2 = observeAbort stHead2 (abort ctx2 stHead1 mempty) in conjoin [ observedIn1 =/= Nothing , observedIn2 === Nothing ] describe "collectCom" $ do propBelowSizeLimit maxTxSize forAllCollectCom propIsValid forAllCollectCom describe "close" $ do propBelowSizeLimit maxTxSize forAllClose propIsValid forAllClose describe "contest" $ do propBelowSizeLimit maxTxSize forAllContest propIsValid forAllContest describe "fanout" $ do propBelowSizeLimit maxTxSize forAllFanout propIsValid forAllFanout describe "acceptance" $ do it "can close & fanout every collected head" $ do prop_canCloseFanoutEveryCollect prop_canCloseFanoutEveryCollect :: Property prop_canCloseFanoutEveryCollect = monadicST $ do let maxParties = 10 ctx@HydraContext{ctxContestationPeriod} <- pickBlind $ genHydraContext maxParties cctx <- pickBlind $ pickChainContext ctx Init txInit <- pickBlind $ genInitTx ctx commits <- pickBlind $ genCommits' (genUTxOSized 1) ctx txInit let (committed, stInitial) = unsafeObserveInitAndCommits cctx txInit commits let initialUTxO = fold committed let txCollect = collect cctx stInitial stOpen <- mfail $ snd <$> observeCollect stInitial txCollect (closeLower, closeUpper) <- pickBlind $ genValidityBoundsFromContestationPeriod ctxContestationPeriod let txClose = close cctx stOpen InitialSnapshot{initialUTxO} closeLower closeUpper (deadline, stClosed) <- case observeClose stOpen txClose of Just (OnCloseTx{contestationDeadline}, st) -> pure (contestationDeadline, st) _ -> fail "not observed close" let txFanout = fanout cctx stClosed initialUTxO (Fixture.slotNoFromUTCTime deadline) let collectFails = propTransactionFailsEvaluation (txCollect, getKnownUTxO cctx <> getKnownUTxO stInitial) & counterexample "collect passed, but others failed?" & cover 10 True "collect failed already" let collectCloseAndFanoutPass = conjoin [ propTransactionEvaluates (txCollect, getKnownUTxO cctx <> getKnownUTxO stInitial) & counterexample "collect failed" , propTransactionEvaluates (txClose, getKnownUTxO cctx <> getKnownUTxO stOpen) & counterexample "close failed" , propTransactionEvaluates (txFanout, getKnownUTxO cctx <> getKnownUTxO stClosed) & counterexample "fanout failed" ] & cover 10 True "collect, close and fanout passed" pure $ checkCoverage (collectFails .||. collectCloseAndFanoutPass) propBelowSizeLimit :: Natural -> ((UTxO -> Tx -> Property) -> Property) -> SpecWith () propBelowSizeLimit txSizeLimit forAllTx = prop ("transaction size is below " <> showKB txSizeLimit) $ forAllTx $ \_ tx -> let cbor = serialize tx len = LBS.length cbor in len < fromIntegral txSizeLimit & label (showKB len) & counterexample (renderTx tx) & counterexample ("Actual size: " <> show len) where showKB nb = show (nb `div` 1024) <> "kB" propIsValid :: ((UTxO -> Tx -> Property) -> Property) -> SpecWith () propIsValid forAllTx = prop "validates within maxTxExecutionUnits" $ forAllTx $ \utxo tx -> propTransactionEvaluates (tx, utxo) forAllInit :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllInit action = forAllBlind (genHydraContext maximumNumberOfParties) $ \ctx -> forAll (pickChainContext ctx) $ \cctx -> do forAll ((,) <$> genTxIn <*> genOutput (ownVerificationKey cctx)) $ \(seedIn, seedOut) -> do let tx = initialize cctx (ctxHeadParameters ctx) seedIn utxo = UTxO.singleton (seedIn, seedOut) <> getKnownUTxO cctx in action utxo tx & classify (length (peerVerificationKeys cctx) == 0) "1 party" & classify (length (peerVerificationKeys cctx) > 0) "2+ parties" forAllCommit :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllCommit action = forAllCommit' $ \ctx st toCommit tx -> let utxo = getKnownUTxO st <> toCommit <> getKnownUTxO ctx in action utxo tx forAllCommit' :: (Testable property) => (ChainContext -> InitialState -> UTxO -> Tx -> property) -> Property forAllCommit' action = do forAll (genHydraContext maximumNumberOfParties) $ \hctx -> forAll (genStInitial hctx) $ \(ctx, stInitial) -> forAllShow genCommit renderUTxO $ \toCommit -> let tx = unsafeCommit ctx stInitial toCommit in action ctx stInitial toCommit tx & classify (null toCommit) "Empty commit" & classify (not (null toCommit)) "Non-empty commit" & counterexample ("tx: " <> renderTx tx) forAllAbort :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllAbort action = do forAll (genHydraContext maximumNumberOfParties) $ \ctx -> forAll (pickChainContext ctx) $ \cctx -> forAllBlind (genInitTx ctx) $ \initTx -> do forAllBlind (sublistOf =<< genCommits ctx initTx) $ \commits -> let (committed, stInitialized) = unsafeObserveInitAndCommits cctx initTx commits utxo = getKnownUTxO stInitialized <> getKnownUTxO cctx in action utxo (abort cctx stInitialized (fold committed)) & classify (null commits) "Abort immediately, after 0 commits" & classify (not (null commits) && length commits < length (ctxParties ctx)) "Abort after some (but not all) commits" & classify (length commits == length (ctxParties ctx)) "Abort after all commits" forAllCollectCom :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllCollectCom action = forAllBlind genCollectComTx $ \(ctx, committedUTxO, stInitialized, tx) -> let utxo = getKnownUTxO stInitialized <> getKnownUTxO ctx in action utxo tx & counterexample ("Committed UTxO: " <> show committedUTxO) forAllClose :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllClose action = do forAll (genCloseTx maximumNumberOfParties) $ \(ctx, st, tx, sn) -> let utxo = getKnownUTxO st <> getKnownUTxO ctx in action utxo tx & label (Prelude.head . Prelude.words . show $ sn) forAllContest :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllContest action = forAllBlind genContestTx $ \(hctx@HydraContext{ctxContestationPeriod}, closePointInTime, stClosed, tx) -> forAllBlind (pickChainContext hctx) $ \ctx -> let utxo = getKnownUTxO stClosed <> getKnownUTxO ctx in action utxo tx & counterexample ("Contestation deadline: " <> show (getContestationDeadline stClosed)) & counterexample ("Contestation period: " <> show ctxContestationPeriod) & counterexample ("Close point: " <> show closePointInTime) & counterexample ("Closed contesters: " <> show (getClosedContesters stClosed)) & tabulate "Contestation period" (tabulateContestationPeriod ctxContestationPeriod) & tabulate "Close point (slot)" (tabulateNum $ fst closePointInTime) where tabulateNum x | x > 0 = ["> 0"] | x < 0 = ["< 0"] | otherwise = ["== 0"] tabulateContestationPeriod (toNominalDiffTime -> cp) | cp == confirmedHorizon = ["k blocks on mainnet"] | cp == oneDay = ["one day"] | cp == oneWeek = ["one week"] | cp == oneMonth = ["one month"] | cp == oneYear = ["one year"] | cp < confirmedHorizon = ["< k blocks"] | otherwise = ["> k blocks"] oneDay = 3600 * 24 oneWeek = oneDay * 7 oneMonth = oneDay * 30 oneYear = oneDay * 365 getClosedContesters stClosed = closedContesters . closedThreadOutput $ stClosed forAllFanout :: (Testable property) => (UTxO -> Tx -> property) -> Property forAllFanout action = forAll (sized $ \n -> genFanoutTx maximumNumberOfParties (n `min` maxSupported)) $ \(hctx, stClosed, tx) -> forAllBlind (pickChainContext hctx) $ \ctx -> let utxo = getKnownUTxO stClosed <> getKnownUTxO ctx in action utxo tx & label ("Fanout size: " <> prettyLength (countAssets $ txOuts' tx)) where maxSupported = 58 countAssets = getSum . foldMap (Sum . valueSize . txOutValue) prettyLength len | len > maxSupported = "> " <> show maxSupported <> " ???" | len >= 40 = "40-" <> show maxSupported | len >= 10 = "10-40" | len >= 1 = "1-10" | otherwise = "0" mfail :: MonadFail m => Maybe a -> m a mfail = \case Nothing -> fail "encountered Nothing" Just a -> pure a
23bb961e3df7e17ed5cdbaf254f895eaee16357b4c346d88ea788f3095ba707b
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
GetChargesCharge.hs
{-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} -- | Contains the different functions to run the operation getChargesCharge module StripeAPI.Operations.GetChargesCharge where import qualified Control.Monad.Fail import qualified Control.Monad.Trans.Reader import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Either import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified Data.Vector import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified Network.HTTP.Client import qualified Network.HTTP.Client as Network.HTTP.Client.Request import qualified Network.HTTP.Client as Network.HTTP.Client.Types import qualified Network.HTTP.Simple import qualified Network.HTTP.Types import qualified Network.HTTP.Types as Network.HTTP.Types.Status import qualified Network.HTTP.Types as Network.HTTP.Types.URI import qualified StripeAPI.Common import StripeAPI.Types import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe -- | > GET /v1/charges/{charge} -- \<p > Retrieves the details of a charge that has previously been created . Supply the unique charge ID that was returned from your previous request , and Stripe will return the corresponding charge information . The same information is returned when creating or refunding the charge.\<\/p > getChargesCharge :: forall m. StripeAPI.Common.MonadHTTP m => -- | Contains all available parameters of this operation (query and path parameters) GetChargesChargeParameters -> -- | Monadic computation which returns the result of the operation StripeAPI.Common.ClientT m (Network.HTTP.Client.Types.Response GetChargesChargeResponse) getChargesCharge parameters = GHC.Base.fmap ( \response_0 -> GHC.Base.fmap ( Data.Either.either GetChargesChargeResponseError GHC.Base.id GHC.Base.. ( \response body -> if | (\status_1 -> Network.HTTP.Types.Status.statusCode status_1 GHC.Classes.== 200) (Network.HTTP.Client.Types.responseStatus response) -> GetChargesChargeResponse200 Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String Charge ) | GHC.Base.const GHC.Types.True (Network.HTTP.Client.Types.responseStatus response) -> GetChargesChargeResponseDefault Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String Error ) | GHC.Base.otherwise -> Data.Either.Left "Missing default response type" ) response_0 ) response_0 ) (StripeAPI.Common.doCallWithConfigurationM (Data.Text.toUpper GHC.Base.$ Data.Text.pack "GET") (Data.Text.pack ("/v1/charges/" GHC.Base.++ (Data.ByteString.Char8.unpack (Network.HTTP.Types.URI.urlEncode GHC.Types.True GHC.Base.$ (Data.ByteString.Char8.pack GHC.Base.$ StripeAPI.Common.stringifyModel (getChargesChargeParametersPathCharge parameters))) GHC.Base.++ ""))) [StripeAPI.Common.QueryParameter (Data.Text.pack "expand") (Data.Aeson.Types.ToJSON.toJSON Data.Functor.<$> getChargesChargeParametersQueryExpand parameters) (Data.Text.pack "deepObject") GHC.Types.True]) | Defines the object schema located at @paths.\/v1\/charges\/{charge}.GET.parameters@ in the specification . data GetChargesChargeParameters = GetChargesChargeParameters { -- | pathCharge: Represents the parameter named \'charge\' -- -- Constraints: -- * Maximum length of 5000 getChargesChargeParametersPathCharge :: Data.Text.Internal.Text, -- | queryExpand: Represents the parameter named \'expand\' -- -- Specifies which fields in the response should be expanded. getChargesChargeParametersQueryExpand :: (GHC.Maybe.Maybe ([Data.Text.Internal.Text])) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON GetChargesChargeParameters where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["pathCharge" Data.Aeson.Types.ToJSON..= getChargesChargeParametersPathCharge obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getChargesChargeParametersQueryExpand obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["pathCharge" Data.Aeson.Types.ToJSON..= getChargesChargeParametersPathCharge obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getChargesChargeParametersQueryExpand obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON GetChargesChargeParameters where parseJSON = Data.Aeson.Types.FromJSON.withObject "GetChargesChargeParameters" (\obj -> (GHC.Base.pure GetChargesChargeParameters GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "pathCharge")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "queryExpand")) | Create a new ' GetChargesChargeParameters ' with all required fields . mkGetChargesChargeParameters :: -- | 'getChargesChargeParametersPathCharge' Data.Text.Internal.Text -> GetChargesChargeParameters mkGetChargesChargeParameters getChargesChargeParametersPathCharge = GetChargesChargeParameters { getChargesChargeParametersPathCharge = getChargesChargeParametersPathCharge, getChargesChargeParametersQueryExpand = GHC.Maybe.Nothing } -- | Represents a response of the operation 'getChargesCharge'. -- -- The response constructor is chosen by the status code of the response. If no case matches (no specific case for the response code, no range case, no default case), 'GetChargesChargeResponseError' is used. data GetChargesChargeResponse = -- | Means either no matching case available or a parse error GetChargesChargeResponseError GHC.Base.String | -- | Successful response. GetChargesChargeResponse200 Charge | -- | Error response. GetChargesChargeResponseDefault Error deriving (GHC.Show.Show, GHC.Classes.Eq)
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Operations/GetChargesCharge.hs
haskell
# LANGUAGE ExplicitForAll # # LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | Contains the different functions to run the operation getChargesCharge | > GET /v1/charges/{charge} | Contains all available parameters of this operation (query and path parameters) | Monadic computation which returns the result of the operation | pathCharge: Represents the parameter named \'charge\' Constraints: | queryExpand: Represents the parameter named \'expand\' Specifies which fields in the response should be expanded. | 'getChargesChargeParametersPathCharge' | Represents a response of the operation 'getChargesCharge'. The response constructor is chosen by the status code of the response. If no case matches (no specific case for the response code, no range case, no default case), 'GetChargesChargeResponseError' is used. | Means either no matching case available or a parse error | Successful response. | Error response.
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . module StripeAPI.Operations.GetChargesCharge where import qualified Control.Monad.Fail import qualified Control.Monad.Trans.Reader import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Either import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified Data.Vector import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified Network.HTTP.Client import qualified Network.HTTP.Client as Network.HTTP.Client.Request import qualified Network.HTTP.Client as Network.HTTP.Client.Types import qualified Network.HTTP.Simple import qualified Network.HTTP.Types import qualified Network.HTTP.Types as Network.HTTP.Types.Status import qualified Network.HTTP.Types as Network.HTTP.Types.URI import qualified StripeAPI.Common import StripeAPI.Types import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe \<p > Retrieves the details of a charge that has previously been created . Supply the unique charge ID that was returned from your previous request , and Stripe will return the corresponding charge information . The same information is returned when creating or refunding the charge.\<\/p > getChargesCharge :: forall m. StripeAPI.Common.MonadHTTP m => GetChargesChargeParameters -> StripeAPI.Common.ClientT m (Network.HTTP.Client.Types.Response GetChargesChargeResponse) getChargesCharge parameters = GHC.Base.fmap ( \response_0 -> GHC.Base.fmap ( Data.Either.either GetChargesChargeResponseError GHC.Base.id GHC.Base.. ( \response body -> if | (\status_1 -> Network.HTTP.Types.Status.statusCode status_1 GHC.Classes.== 200) (Network.HTTP.Client.Types.responseStatus response) -> GetChargesChargeResponse200 Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String Charge ) | GHC.Base.const GHC.Types.True (Network.HTTP.Client.Types.responseStatus response) -> GetChargesChargeResponseDefault Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String Error ) | GHC.Base.otherwise -> Data.Either.Left "Missing default response type" ) response_0 ) response_0 ) (StripeAPI.Common.doCallWithConfigurationM (Data.Text.toUpper GHC.Base.$ Data.Text.pack "GET") (Data.Text.pack ("/v1/charges/" GHC.Base.++ (Data.ByteString.Char8.unpack (Network.HTTP.Types.URI.urlEncode GHC.Types.True GHC.Base.$ (Data.ByteString.Char8.pack GHC.Base.$ StripeAPI.Common.stringifyModel (getChargesChargeParametersPathCharge parameters))) GHC.Base.++ ""))) [StripeAPI.Common.QueryParameter (Data.Text.pack "expand") (Data.Aeson.Types.ToJSON.toJSON Data.Functor.<$> getChargesChargeParametersQueryExpand parameters) (Data.Text.pack "deepObject") GHC.Types.True]) | Defines the object schema located at @paths.\/v1\/charges\/{charge}.GET.parameters@ in the specification . data GetChargesChargeParameters = GetChargesChargeParameters * Maximum length of 5000 getChargesChargeParametersPathCharge :: Data.Text.Internal.Text, getChargesChargeParametersQueryExpand :: (GHC.Maybe.Maybe ([Data.Text.Internal.Text])) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON GetChargesChargeParameters where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["pathCharge" Data.Aeson.Types.ToJSON..= getChargesChargeParametersPathCharge obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getChargesChargeParametersQueryExpand obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["pathCharge" Data.Aeson.Types.ToJSON..= getChargesChargeParametersPathCharge obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("queryExpand" Data.Aeson.Types.ToJSON..=)) (getChargesChargeParametersQueryExpand obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON GetChargesChargeParameters where parseJSON = Data.Aeson.Types.FromJSON.withObject "GetChargesChargeParameters" (\obj -> (GHC.Base.pure GetChargesChargeParameters GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "pathCharge")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "queryExpand")) | Create a new ' GetChargesChargeParameters ' with all required fields . mkGetChargesChargeParameters :: Data.Text.Internal.Text -> GetChargesChargeParameters mkGetChargesChargeParameters getChargesChargeParametersPathCharge = GetChargesChargeParameters { getChargesChargeParametersPathCharge = getChargesChargeParametersPathCharge, getChargesChargeParametersQueryExpand = GHC.Maybe.Nothing } data GetChargesChargeResponse GetChargesChargeResponseError GHC.Base.String GetChargesChargeResponse200 Charge GetChargesChargeResponseDefault Error deriving (GHC.Show.Show, GHC.Classes.Eq)
e3cd5d9ea8ba8cd988e4b3224347b2e434ba283d725c778d59cc8d564e287e48
rootmos/silly-ml
eval.ml
open Core_kernel.Std open Printf module Ctx = struct type t = { typed_ctx: Typed.Ctx.t; lambda_ctx: Lambda.Ctx.t; interpret_ctx: Interpret.Ctx.t; } let empty = { typed_ctx = Typed.Ctx.empty; lambda_ctx = Lambda.Ctx.empty; interpret_ctx = Interpret.Ctx.empty; } end let step ctx s = let open Ctx in let parsed = Parsed_helpers.parse s in let typed = Typed.introduce_types parsed in let typed', typed_ctx, ot = Typed.unify_and_substitute ~ctx:ctx.typed_ctx typed in let lambda, lambda_ctx = Lambda.transform_to_lambda ~ctx:ctx.lambda_ctx typed' in let v, interpret_ctx = Interpret.interpret ~ctx:ctx.interpret_ctx lambda in let ctx' = { typed_ctx; lambda_ctx; interpret_ctx } in v, ctx', ot let eval s = step Ctx.empty s |> fun (x, _, _) -> x let rec repl ?(ctx=Ctx.empty) () = let open Ctx in let rec pretty ?(wrap=false) v t = match v, t with | Interpret.I.V_int i, Typed.T_ident id -> let td = Typed.Ctx.lookup_type ctx.typed_ctx id in Lambda.Ctx.reconstruct_constructor td i | Interpret.I.V_tag (i, v'), Typed.T_ident id -> let td = Typed.Ctx.lookup_type ctx.typed_ctx id in let c = Lambda.Ctx.reconstruct_constructor td i in begin match List.Assoc.find ~equal:(=) (List.(td >>| fun (Typed.V_constr x) -> x)) c with | Some (Some t) when wrap -> sprintf "(%s %s)" c (pretty ~wrap:true v' t) | Some (Some t) -> sprintf "%s %s" c (pretty ~wrap:true v' t) | _ -> failwith "eval whoopsie" end | v, _ -> Interpret.I.to_string v in Pervasives.flush_all (); print_string "> "; let go () = let s = Pervasives.read_line () in let v, ctx', ot = step ctx s in begin match v, ot with | _, None -> () | v, Some t -> printf "%s: %s\n" (pretty v t) (Typed.format_typ t) end; repl ~ctx:ctx' () in try Errors.run_with_pretty_errors ~err:(fun _ -> repl ~ctx ()) go with | Sys.Break -> Pervasives.print_newline (); repl ~ctx () | End_of_file -> ()
null
https://raw.githubusercontent.com/rootmos/silly-ml/716664a0e81fc354d93b645b4bc017e7f6227c25/src/eval.ml
ocaml
open Core_kernel.Std open Printf module Ctx = struct type t = { typed_ctx: Typed.Ctx.t; lambda_ctx: Lambda.Ctx.t; interpret_ctx: Interpret.Ctx.t; } let empty = { typed_ctx = Typed.Ctx.empty; lambda_ctx = Lambda.Ctx.empty; interpret_ctx = Interpret.Ctx.empty; } end let step ctx s = let open Ctx in let parsed = Parsed_helpers.parse s in let typed = Typed.introduce_types parsed in let typed', typed_ctx, ot = Typed.unify_and_substitute ~ctx:ctx.typed_ctx typed in let lambda, lambda_ctx = Lambda.transform_to_lambda ~ctx:ctx.lambda_ctx typed' in let v, interpret_ctx = Interpret.interpret ~ctx:ctx.interpret_ctx lambda in let ctx' = { typed_ctx; lambda_ctx; interpret_ctx } in v, ctx', ot let eval s = step Ctx.empty s |> fun (x, _, _) -> x let rec repl ?(ctx=Ctx.empty) () = let open Ctx in let rec pretty ?(wrap=false) v t = match v, t with | Interpret.I.V_int i, Typed.T_ident id -> let td = Typed.Ctx.lookup_type ctx.typed_ctx id in Lambda.Ctx.reconstruct_constructor td i | Interpret.I.V_tag (i, v'), Typed.T_ident id -> let td = Typed.Ctx.lookup_type ctx.typed_ctx id in let c = Lambda.Ctx.reconstruct_constructor td i in begin match List.Assoc.find ~equal:(=) (List.(td >>| fun (Typed.V_constr x) -> x)) c with | Some (Some t) when wrap -> sprintf "(%s %s)" c (pretty ~wrap:true v' t) | Some (Some t) -> sprintf "%s %s" c (pretty ~wrap:true v' t) | _ -> failwith "eval whoopsie" end | v, _ -> Interpret.I.to_string v in Pervasives.flush_all (); print_string "> "; let go () = let s = Pervasives.read_line () in let v, ctx', ot = step ctx s in begin match v, ot with | _, None -> () | v, Some t -> printf "%s: %s\n" (pretty v t) (Typed.format_typ t) end; repl ~ctx:ctx' () in try Errors.run_with_pretty_errors ~err:(fun _ -> repl ~ctx ()) go with | Sys.Break -> Pervasives.print_newline (); repl ~ctx () | End_of_file -> ()
4dc08c12b2a6e41390d941a1d4f0443bee5e90fdd07104116d1bc09bcd5df897
bsansouci/bsb-native
reload.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1998 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) (* Reloading for the ARM *) let fundecl f = (new Reloadgen.reload_generic)#fundecl f
null
https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/asmcomp/arm/reload.ml
ocaml
********************************************************************* OCaml ********************************************************************* Reloading for the ARM
, projet Cristal , INRIA Rocquencourt Copyright 1998 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . let fundecl f = (new Reloadgen.reload_generic)#fundecl f
476f4bae8059f94a511610c06b921de652ea0d347e0478ff11f9b2af9b533e9f
jordanthayer/ocaml-search
vector_search.ml
(** Search code using offline learned information in the form of arbitrary vectors *) let h_ind = 0 and d_ind = 1 and g_ind = 2 and depth_ind = 3 and h_rev = 4 and d_rev = 5 type 'a node = { data : 'a; features : float array; cost : float; f : float; mutable pos: int;} let setpos n i = (** Updates the [pos] of node [n], setting it to [i] *) n.pos <- i let getpos n = (** returns the current [pos] of node [n] *) n.pos let better_p a b = (** Determines which of the nodes represents a better solution *) a.features.(g_ind) <= b.features.(g_ind) let ordered_p a b = * sorts nodes in order of estimated f , breaking ties in favor of high g values high g values *) a.cost < b.cost || (a.cost = b.cost && (not (better_p a b))) let unwrap_sol n = (** Decomposes the solution [s] into a form which the domains are expecting when doing validation *) match n with Limit.Nothing -> None | Limit.Incumbent (q, n) -> Some (n.data, n.features.(g_ind)) let calc_cost vector features = (** taking a weight [vector] and a [features] array, returs an estimate of the true cost to go from this node *) (assert ((Array.length vector) <= (Array.length features))); let sum = ref 0. in for i = 0 to ((Array.length vector) - 1) do sum := !sum +. vector.(i) *. features.(i); done; !sum let wrap_expand expand hd rev_hd vector = (** Returns an expand function to be used by optimistic framework requires the domain [expand] a cost and distance heuristic estimator [hd] and the weight [vector] which was learned offline *) (fun n -> let nd = n.features.(depth_ind) +. 1. in List.map (fun (c,g) -> (let (h,d) = hd c and (rh,rd) = rev_hd c in let feat = [| h; g; d; nd; rh; rd;|] in { data = c; features = feat; cost = calc_cost vector feat; f = feat.(g_ind) +. feat.(h_ind); pos = Dpq.no_position;})) (expand n.data n.features.(g_ind))) let make_init data = (** returns the root of the search space *) { data = data; features = [| infinity; infinity; 0.; 0.|]; cost = neg_infinity; f = neg_infinity; pos = Dpq.no_position;} let wrap fn = (** Wraps a function [f] which works on domain data and makes it so that it can be applied to nodes *) (fun n -> fn n.data) (******************************** Searches *********************************) let alt_col_name = "wt_vector" let output_col_hdr () = Datafile.write_alt_colnames stdout alt_col_name ["h"; "d"; "g"; "depth"; "rev_h"; "rev_d";] let output_vector v = Datafile.write_alt_row_prefix stdout alt_col_name; Verb.pr Verb.always "%f\t%f\t%f\t%f\t%f\t%f\n" v.(h_ind) v.(d_ind) v.(g_ind) v.(depth_ind) v.(h_rev) v.(d_rev) let output v = output_col_hdr (); output_vector v let no_dups sface vector = (** Performs a search in domains where there are no duplicates. [sface] is the domain's search interface [vector] is a list of weights to be used *) output vector; let search_interface = Search_interface.make ~node_expand:(wrap_expand sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd vector) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_init sface.Search_interface.initial) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol5 unwrap_sol (Best_first.search search_interface ordered_p better_p) let dups sface vector = (** Performs a search in domains where there are no duplicates. [sface] is the domain's search interface [vector] is a list of weights to be used *) output vector; let search_interface = Search_interface.make ~node_expand:(wrap_expand sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd vector) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_init sface.Search_interface.initial) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol6 unwrap_sol (Best_first.search_dups search_interface ordered_p better_p setpos getpos) let drop_dups sface vector = (** Performs a search in domains where there are no duplicates. Duplicate states are never reexamined. [sface] is the domain's search interface [vector] is a list of weights to be used *) output vector; let search_interface = Search_interface.make ~node_expand:(wrap_expand sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd vector) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_init sface.Search_interface.initial) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol6 unwrap_sol (Best_first.search_drop_dups search_interface ordered_p better_p setpos getpos) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/adaptive/vector_search.ml
ocaml
* Search code using offline learned information in the form of arbitrary vectors * Updates the [pos] of node [n], setting it to [i] * returns the current [pos] of node [n] * Determines which of the nodes represents a better solution * Decomposes the solution [s] into a form which the domains are expecting when doing validation * taking a weight [vector] and a [features] array, returs an estimate of the true cost to go from this node * Returns an expand function to be used by optimistic framework requires the domain [expand] a cost and distance heuristic estimator [hd] and the weight [vector] which was learned offline * returns the root of the search space * Wraps a function [f] which works on domain data and makes it so that it can be applied to nodes ******************************* Searches ******************************** * Performs a search in domains where there are no duplicates. [sface] is the domain's search interface [vector] is a list of weights to be used * Performs a search in domains where there are no duplicates. [sface] is the domain's search interface [vector] is a list of weights to be used * Performs a search in domains where there are no duplicates. Duplicate states are never reexamined. [sface] is the domain's search interface [vector] is a list of weights to be used
let h_ind = 0 and d_ind = 1 and g_ind = 2 and depth_ind = 3 and h_rev = 4 and d_rev = 5 type 'a node = { data : 'a; features : float array; cost : float; f : float; mutable pos: int;} let setpos n i = n.pos <- i let getpos n = n.pos let better_p a b = a.features.(g_ind) <= b.features.(g_ind) let ordered_p a b = * sorts nodes in order of estimated f , breaking ties in favor of high g values high g values *) a.cost < b.cost || (a.cost = b.cost && (not (better_p a b))) let unwrap_sol n = match n with Limit.Nothing -> None | Limit.Incumbent (q, n) -> Some (n.data, n.features.(g_ind)) let calc_cost vector features = (assert ((Array.length vector) <= (Array.length features))); let sum = ref 0. in for i = 0 to ((Array.length vector) - 1) do sum := !sum +. vector.(i) *. features.(i); done; !sum let wrap_expand expand hd rev_hd vector = (fun n -> let nd = n.features.(depth_ind) +. 1. in List.map (fun (c,g) -> (let (h,d) = hd c and (rh,rd) = rev_hd c in let feat = [| h; g; d; nd; rh; rd;|] in { data = c; features = feat; cost = calc_cost vector feat; f = feat.(g_ind) +. feat.(h_ind); pos = Dpq.no_position;})) (expand n.data n.features.(g_ind))) let make_init data = { data = data; features = [| infinity; infinity; 0.; 0.|]; cost = neg_infinity; f = neg_infinity; pos = Dpq.no_position;} let wrap fn = (fun n -> fn n.data) let alt_col_name = "wt_vector" let output_col_hdr () = Datafile.write_alt_colnames stdout alt_col_name ["h"; "d"; "g"; "depth"; "rev_h"; "rev_d";] let output_vector v = Datafile.write_alt_row_prefix stdout alt_col_name; Verb.pr Verb.always "%f\t%f\t%f\t%f\t%f\t%f\n" v.(h_ind) v.(d_ind) v.(g_ind) v.(depth_ind) v.(h_rev) v.(d_rev) let output v = output_col_hdr (); output_vector v let no_dups sface vector = output vector; let search_interface = Search_interface.make ~node_expand:(wrap_expand sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd vector) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_init sface.Search_interface.initial) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol5 unwrap_sol (Best_first.search search_interface ordered_p better_p) let dups sface vector = output vector; let search_interface = Search_interface.make ~node_expand:(wrap_expand sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd vector) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_init sface.Search_interface.initial) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol6 unwrap_sol (Best_first.search_dups search_interface ordered_p better_p setpos getpos) let drop_dups sface vector = output vector; let search_interface = Search_interface.make ~node_expand:(wrap_expand sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd vector) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_init sface.Search_interface.initial) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol6 unwrap_sol (Best_first.search_drop_dups search_interface ordered_p better_p setpos getpos) EOF
2fbb5c54a6ef125de8fb93da4768503d580cde25acc87f1c38c01135a1ea42bf
avras/nsime
nsime_internet_stack_helper_SUITE.erl
%% Copyright ( C ) 2012 < > %% %% This file is part of nsime. %% nsime is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or %% (at your option) any later version. %% %% nsime is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% You should have received a copy of the GNU General Public License %% along with nsime. If not, see </>. %% Purpose : Test module for nsime_internet_stack_helper Author : -module(nsime_internet_stack_helper_SUITE). -author("Saravanan Vijayakumaran"). -compile(export_all). -include("ct.hrl"). -include_lib("eunit/include/eunit.hrl"). all() -> [ test_install ]. init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. test_install(_) -> nsime_simulator:start(), NodePidList = nsime_node:create(2), ?assertEqual(nsime_internet_stack_helper:install(NodePidList), ok), ?assertError( ipv4_already_present, nsime_internet_stack_helper:install(NodePidList) ), nsime_simulator:stop().
null
https://raw.githubusercontent.com/avras/nsime/fc5c164272aa649541bb3895d9f4bea34f45beec/test/nsime_internet_stack_helper_SUITE.erl
erlang
This file is part of nsime. (at your option) any later version. nsime is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with nsime. If not, see </>.
Copyright ( C ) 2012 < > nsime is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License Purpose : Test module for nsime_internet_stack_helper Author : -module(nsime_internet_stack_helper_SUITE). -author("Saravanan Vijayakumaran"). -compile(export_all). -include("ct.hrl"). -include_lib("eunit/include/eunit.hrl"). all() -> [ test_install ]. init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. test_install(_) -> nsime_simulator:start(), NodePidList = nsime_node:create(2), ?assertEqual(nsime_internet_stack_helper:install(NodePidList), ok), ?assertError( ipv4_already_present, nsime_internet_stack_helper:install(NodePidList) ), nsime_simulator:stop().
ac76580bd47f25703c092572ead014fe5ca721ed534aa145c93f4be7718aaefd
BranchTaken/Hemlock
path.mli
(** Abstract filesystem path manipulation. *) (** Path segment. *) module Segment: sig type t (** Path segment type. *) include FormattableIntf.SMono with type t := t val to_string: t -> string option * [ to_string t ] converts [ t ] to a string , or returns [ None ] if the segment can not be represented as UTF-8 . as UTF-8. *) val to_string_replace: t -> string * [ to_string t ] converts [ t ] to a string , with invalid UTF-8 converted to one or more ' � ' replacement codepoints . replacement codepoints. *) val to_string_hlt: t -> string * [ to_string_hlt t ] converts [ t ] to a string , or halts if the segment can not be represented as UTF-8 . UTF-8. *) val to_bytes: t -> Bytes.Slice.t (** [to_bytes t] converts [t] to a bytes slice. *) val is_empty: t -> bool * [ is_current t ] returns true if the segment is empty ( zero length string representation ) . val is_current: t -> bool (** [is_current t] returns true if the segment is [.]. *) val is_parent: t -> bool (** [is_current t] returns true if the segment is [..]. *) val split: t -> t list (** [split t] splits the segment into its stem and [.]-initiated suffixes, if any. *) val stem: t -> t (** [stem t] returns [List.hd (split t)]. *) val suffixes: t -> t list (** [suffixes t] returns [List.tl (split t)]. *) val suffix: t -> t (** [suffix t] returns the last [.]-initiated suffix of [t], or an empty segment if [t] has no suffixes. *) val join: t list -> t (** [join split] joins [split] into a single segment. Halt on any multi-segment input which contains a current or parent segment. *) end type t (** Path type. *) include FormattableIntf.SMono with type t := t val of_string: string -> t (** [of_string s] creates a path by splitting [s] at [/] segment separators. *) val of_bytes: Bytes.Slice.t -> t * [ of_bytes ] creates a path by splitting [ bslice ] at [ / ] segment separators . val of_segment: Segment.t -> t (** [of_segment segment] creates a path from a single segment. *) val is_abs: t -> bool (** [is_abs t] returns true if [t] is an absolute path. *) val is_empty: t -> bool (** [is_empty t] returns true if [t] is an empty path. *) val dirname: t -> t * [ t ] returns the path leading to the last segment of [ t ] , if any . val basename: t -> Segment.t option (** [basename t] returns the last segment of [t], or [None] if an empty path. *) val split: t -> t * Segment.t option * [ split t ] is equivalent to [ ( t ) , ( basename t ) ] . val normalize: t -> t * [ normalize t ] performs the following path transformations : - [ ///a ] - > [ /a ] : Reduce three or more leading separators to one separator ( absolute path ) . - [ a//b ] - > [ a / b ] : Remove internal empty segments . - [ a/ ] - > [ a ] : Remove trailing empty segments . - [ ./a/./b/. ] - > [ a / b ] : Remove [ . ] segments . - [ / .. /a/ .. /b ] - > [ b ] : Collapse parent directory segments with parents . This may change how the path resolves if the parent is a symbolic link . - [///a] -> [/a]: Reduce three or more leading separators to one separator (absolute path). - [a//b] -> [a/b]: Remove internal empty segments. - [a/] -> [a]: Remove trailing empty segments. - [./a/./b/.] -> [a/b]: Remove [.] segments. - [/../a/../b] -> [b]: Collapse parent directory segments with parents. This may change how the path resolves if the parent is a symbolic link. *) val join: t list -> t * [ join paths ] joins [ paths ] into a single path . NB : Absolute paths start with an empty segment , but only the first non - empty path in a join affects whether the result is an absolute path . Leading empty segments in the other input path(s ) may be interpreted in a variety of potentially surprising contextually dependent ways . but only the first non-empty path in a join affects whether the result is an absolute path. Leading empty segments in the other input path(s) may be interpreted in a variety of potentially surprising contextually dependent ways. *) val to_string: t -> string option (** [to_string t] converts [t] to a string, or returns [None] if the path cannot be represented as UTF-8. *) val to_string_replace: t -> string * [ to_string t ] converts [ t ] to a string , with invalid UTF-8 converted to one or more ' � ' replacement codepoints . replacement codepoints. *) val to_string_hlt: t -> string * [ to_string_hlt t ] converts [ t ] to a string , or halts if the path can not be represented as UTF-8 . *) val to_bytes: t -> Bytes.Slice.t (** [to_bytes t] converts [t] to a bytes slice. *)
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/ed397cf3294ca397024e69eb3b1ed5f1db773db6/bootstrap/src/basis/path.mli
ocaml
* Abstract filesystem path manipulation. * Path segment. * Path segment type. * [to_bytes t] converts [t] to a bytes slice. * [is_current t] returns true if the segment is [.]. * [is_current t] returns true if the segment is [..]. * [split t] splits the segment into its stem and [.]-initiated suffixes, if any. * [stem t] returns [List.hd (split t)]. * [suffixes t] returns [List.tl (split t)]. * [suffix t] returns the last [.]-initiated suffix of [t], or an empty segment if [t] has no suffixes. * [join split] joins [split] into a single segment. Halt on any multi-segment input which contains a current or parent segment. * Path type. * [of_string s] creates a path by splitting [s] at [/] segment separators. * [of_segment segment] creates a path from a single segment. * [is_abs t] returns true if [t] is an absolute path. * [is_empty t] returns true if [t] is an empty path. * [basename t] returns the last segment of [t], or [None] if an empty path. * [to_string t] converts [t] to a string, or returns [None] if the path cannot be represented as UTF-8. * [to_bytes t] converts [t] to a bytes slice.
module Segment: sig type t include FormattableIntf.SMono with type t := t val to_string: t -> string option * [ to_string t ] converts [ t ] to a string , or returns [ None ] if the segment can not be represented as UTF-8 . as UTF-8. *) val to_string_replace: t -> string * [ to_string t ] converts [ t ] to a string , with invalid UTF-8 converted to one or more ' � ' replacement codepoints . replacement codepoints. *) val to_string_hlt: t -> string * [ to_string_hlt t ] converts [ t ] to a string , or halts if the segment can not be represented as UTF-8 . UTF-8. *) val to_bytes: t -> Bytes.Slice.t val is_empty: t -> bool * [ is_current t ] returns true if the segment is empty ( zero length string representation ) . val is_current: t -> bool val is_parent: t -> bool val split: t -> t list val stem: t -> t val suffixes: t -> t list val suffix: t -> t val join: t list -> t end type t include FormattableIntf.SMono with type t := t val of_string: string -> t val of_bytes: Bytes.Slice.t -> t * [ of_bytes ] creates a path by splitting [ bslice ] at [ / ] segment separators . val of_segment: Segment.t -> t val is_abs: t -> bool val is_empty: t -> bool val dirname: t -> t * [ t ] returns the path leading to the last segment of [ t ] , if any . val basename: t -> Segment.t option val split: t -> t * Segment.t option * [ split t ] is equivalent to [ ( t ) , ( basename t ) ] . val normalize: t -> t * [ normalize t ] performs the following path transformations : - [ ///a ] - > [ /a ] : Reduce three or more leading separators to one separator ( absolute path ) . - [ a//b ] - > [ a / b ] : Remove internal empty segments . - [ a/ ] - > [ a ] : Remove trailing empty segments . - [ ./a/./b/. ] - > [ a / b ] : Remove [ . ] segments . - [ / .. /a/ .. /b ] - > [ b ] : Collapse parent directory segments with parents . This may change how the path resolves if the parent is a symbolic link . - [///a] -> [/a]: Reduce three or more leading separators to one separator (absolute path). - [a//b] -> [a/b]: Remove internal empty segments. - [a/] -> [a]: Remove trailing empty segments. - [./a/./b/.] -> [a/b]: Remove [.] segments. - [/../a/../b] -> [b]: Collapse parent directory segments with parents. This may change how the path resolves if the parent is a symbolic link. *) val join: t list -> t * [ join paths ] joins [ paths ] into a single path . NB : Absolute paths start with an empty segment , but only the first non - empty path in a join affects whether the result is an absolute path . Leading empty segments in the other input path(s ) may be interpreted in a variety of potentially surprising contextually dependent ways . but only the first non-empty path in a join affects whether the result is an absolute path. Leading empty segments in the other input path(s) may be interpreted in a variety of potentially surprising contextually dependent ways. *) val to_string: t -> string option val to_string_replace: t -> string * [ to_string t ] converts [ t ] to a string , with invalid UTF-8 converted to one or more ' � ' replacement codepoints . replacement codepoints. *) val to_string_hlt: t -> string * [ to_string_hlt t ] converts [ t ] to a string , or halts if the path can not be represented as UTF-8 . *) val to_bytes: t -> Bytes.Slice.t
477edadf6d1e0f16c293911cb6971e905da3ce9857bfff412df509d75d4d6ffd
nyu-acsys/drift
zip.ml
let rec zip (xs:int list) (ys:int list) = match xs with [] -> ( match ys with [] -> [] | y::ys' -> assert(false) ; [] ) | x::xs' -> (match ys with [] -> assert(false) ; [] | y::ys' -> (x, y)::(zip xs' ys')) let rec make_list n = if n < 0 then [] else n :: make_list (n - 1) let main (n:int) = if n > 0 then let xs = make_list n in let ys = zip xs xs in assert(List.length ys = List.length xs) else () let _ = main 1
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/DOrder/list/zip.ml
ocaml
let rec zip (xs:int list) (ys:int list) = match xs with [] -> ( match ys with [] -> [] | y::ys' -> assert(false) ; [] ) | x::xs' -> (match ys with [] -> assert(false) ; [] | y::ys' -> (x, y)::(zip xs' ys')) let rec make_list n = if n < 0 then [] else n :: make_list (n - 1) let main (n:int) = if n > 0 then let xs = make_list n in let ys = zip xs xs in assert(List.length ys = List.length xs) else () let _ = main 1
0771cd7b6073f185d4145274b1a595899fd0e7d9caf1b412824a7a13effa6899
bootstrapworld/curr
Review.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname Review) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Bootstrap Review ; ; (define NUM 4) (define NUM2 0.6) (define NUM3 -90) (define S1 "Bootstrap") (define S2 "Coding is fun!") (define S3 "2500") (define BOOL true) (define SHAPE (triangle 40 "outline" "red")) (define OUTLINE (star 80 "solid" "green")) (define SQUARE (rectangle 50 50 "solid" "blue"))
null
https://raw.githubusercontent.com/bootstrapworld/curr/443015255eacc1c902a29978df0e3e8e8f3b9430/courses/reactive/resources/source-files/Review.rkt
racket
about the language level of this file in a form that our tools can easily process. ;
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname Review) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") (define NUM 4) (define NUM2 0.6) (define NUM3 -90) (define S1 "Bootstrap") (define S2 "Coding is fun!") (define S3 "2500") (define BOOL true) (define SHAPE (triangle 40 "outline" "red")) (define OUTLINE (star 80 "solid" "green")) (define SQUARE (rectangle 50 50 "solid" "blue"))
d566037e0acf2acada63f7e49cd019a9c6e846da3e48baee0a4c59d74d32d77e
parapluu/nifty
nifty_utils.erl
-*- erlang - indent - level : 2 -*- %%% ------------------------------------------------------------------- Copyright ( c ) 2014 - 2016 , < > and < > %%% All rights reserved. %%% This file is distributed under the Simplified BSD License . %%% Details can be found in the LICENSE file. %%% ------------------------------------------------------------------- -module(nifty_utils). -export([expand/1, new_config/0, add_sources/2, add_cflags/2, add_ldflags/2, merge_nif_spec/2]). -type env() :: {'env', [{nonempty_string(), string()}]}. -type target_options() :: [env()]. -type arch() :: nonempty_string(). -type target_name() :: nonempty_string(). -type source() :: nonempty_string(). -type target() :: {arch(), target_name(), [source()]} | {arch(), target_name(), [source()], target_options()}. %%-type port_specs() :: {'port_specs', [target()]}. -type config() :: proplists:proplist(). % port_specs() is an element here... @doc Merges two configurations -spec merge_nif_spec(config(), target()) -> config(). merge_nif_spec(Config, {".*", "$NIF", Sources, [{env, Env}]} = Spec) -> case proplists:get_value(port_specs, Config) of undefined -> [{port_specs, [Spec]} | Config]; Specs -> NewSpecs = case get_nifspec(Specs) of {".*", "$NIF", OldSources} -> store_nifspec({".*", "$NIF", OldSources ++ Sources, [{env, Env}]}, Specs); {".*", "$NIF", OldSources, [{env, OldEnv}]} -> store_nifspec({".*", "$NIF", OldSources ++ Sources, [{env, OldEnv ++ Env}]}, Specs); undefined -> store_nifspec({".*", "$NIF", Sources, [{env, []}] }, Specs) end, [{port_specs, NewSpecs} | proplists:delete(port_specs, Config)] end. get_nifspec([]) -> undefined; get_nifspec([H|T]) -> case H of {".*", "$NIF", _} -> H; {".*", "$NIF", _, _} -> H; _ -> get_nifspec(T) end. store_nifspec(NifSpec, Specs) -> store_nifspec(Specs, NifSpec, []). store_nifspec([], _, Acc) -> Acc; store_nifspec([H|T], Spec, Acc) -> case H of {".*", "$NIF", _} -> store_nifspec(T, Spec, [Spec|Acc]); {".*", "$NIF", _, _} -> store_nifspec(T, Spec, [Spec|Acc]); _ -> store_nifspec(T, Spec, [H|Acc]) end. %% @doc Returns an empty configuration -spec new_config() -> config(). new_config() -> []. @doc Adds the sources < code > S</code > to the NIF module -spec add_sources([source()], config()) -> config(). add_sources(S, C) -> merge_nif_spec(C, {".*", "$NIF", S, [{env, []}]}). @doc Adds the compile flags < code > F</code > to the NIF module -spec add_cflags(string(), config()) -> config(). add_cflags(F, C) -> merge_nif_spec(C, {".*", "$NIF", [], [{env, [{"CFLAGS", "$CFLAGS "++F}]}]}). @doc Adds link flags < code > F</code > to the NIF module -spec add_ldflags(string(), config()) -> config(). add_ldflags(F, C) -> merge_nif_spec(C, {".*", "$NIF", [], [{env, [{"LDFLAGS", "$LDFLAGS "++F}]}]}). %% @doc Returns <code>Path</code> with all environment variables %% expanded -spec expand(string()) -> string(). expand(Path) -> S = lists:foldr(fun(A, Acc) -> A ++ " " ++ Acc end, [], tokenize(Path)), string:strip(S). -define(IS_WHITESPACE(Char), ((Char) =:= $\s orelse (Char) =:= $\t orelse (Char) =:= $\n orelse (Char) =:= $\r)). -spec tokenize(CmdLine :: string()) -> [nonempty_string()]. tokenize(CmdLine) -> tokenize(CmdLine, [], []). -spec tokenize(CmdLine :: string(), Acc :: [string()], ArgAcc :: string()) -> [string()]. tokenize([Sep | Tail], Acc, ArgAcc) when ?IS_WHITESPACE(Sep) -> NewAcc = case ArgAcc of [_ | _] -> %% Found separator: add to the list of arguments. [lists:reverse(ArgAcc) | Acc]; [] -> %% Found separator with no accumulated argument; discard it. Acc end, tokenize(Tail, NewAcc, []); tokenize([QuotationMark | Tail], Acc, ArgAcc) when QuotationMark =:= $"; QuotationMark =:= $' -> %% Quoted argument (might contain spaces, tabs, etc.) tokenize_quoted_arg(QuotationMark, Tail, Acc, ArgAcc); tokenize([Char | _Tail] = CmdLine, Acc, ArgAcc) when Char =:= $$; Char =:= $% -> Unix and Windows environment variable expansion : $ { VAR } ; ; % VAR% {NewCmdLine, Var} = expand_env_var(CmdLine), tokenize(NewCmdLine, Acc, lists:reverse(Var, ArgAcc)); tokenize([$\\, Char | Tail], Acc, ArgAcc) -> %% Escaped char. tokenize(Tail, Acc, [Char | ArgAcc]); tokenize([Char | Tail], Acc, ArgAcc) -> tokenize(Tail, Acc, [Char | ArgAcc]); tokenize([], Acc, []) -> lists:reverse(Acc); tokenize([], Acc, ArgAcc) -> lists:reverse([lists:reverse(ArgAcc) | Acc]). -spec tokenize_quoted_arg(QuotationMark :: char(), CmdLine :: string(), Acc :: [string()], ArgAcc :: string()) -> [string()]. tokenize_quoted_arg(QuotationMark, [QuotationMark | Tail], Acc, ArgAcc) -> %% End of quoted argument tokenize(Tail, Acc, ArgAcc); tokenize_quoted_arg(QuotationMark, [$\\, Char | Tail], Acc, ArgAcc) -> %% Escaped char. tokenize_quoted_arg(QuotationMark, Tail, Acc, [Char | ArgAcc]); tokenize_quoted_arg($" = QuotationMark, [Char | _Tail] = CmdLine, Acc, ArgAcc) when Char =:= $$; Char =:= $% -> Unix and Windows environment variable expansion ( only for double - quoted arguments ): $ { VAR } ; ; % VAR% {NewCmdLine, Var} = expand_env_var(CmdLine), tokenize_quoted_arg(QuotationMark, NewCmdLine, Acc, lists:reverse(Var, ArgAcc)); tokenize_quoted_arg(QuotationMark, [Char | Tail], Acc, ArgAcc) -> tokenize_quoted_arg(QuotationMark, Tail, Acc, [Char | ArgAcc]); tokenize_quoted_arg(_QuotationMark, CmdLine, Acc, ArgAcc) -> tokenize(CmdLine, Acc, ArgAcc). -spec expand_env_var(CmdLine :: nonempty_string()) -> {string(), string()}. expand_env_var(CmdLine) -> case CmdLine of "${" ++ Tail -> expand_env_var("${", $}, Tail, []); "$" ++ Tail -> expand_env_var("$", Tail, []); "%" ++ Tail -> expand_env_var("%", $%, Tail, []) end. -spec expand_env_var(Prefix :: string(), EndMark :: char(), CmdLine :: string(), Acc :: string()) -> {string(), string()}. expand_env_var(Prefix, EndMark, [Char | Tail], Acc) when (Char >= $A andalso Char =< $Z) orelse (Char >= $a andalso Char =< $z) orelse (Char >= $0 andalso Char =< $9) orelse (Char =:= $_) -> expand_env_var(Prefix, EndMark, Tail, [Char | Acc]); expand_env_var(Prefix, EndMark, [EndMark | Tail], Acc) -> {Tail, get_env_var(Prefix, [EndMark], Acc)}; expand_env_var(Prefix, _EndMark, CmdLine, Acc) -> {CmdLine, Prefix ++ lists:reverse(Acc)}. -spec expand_env_var(Prefix :: string(), CmdLine :: string(), Acc :: string()) -> {string(), string()}. expand_env_var(Prefix, [Char | Tail], Acc) when (Char >= $A andalso Char =< $Z) orelse (Char >= $a andalso Char =< $z) orelse (Char >= $0 andalso Char =< $9) orelse (Char =:= $_) -> expand_env_var(Prefix, Tail, [Char | Acc]); expand_env_var(Prefix, CmdLine, Acc) -> {CmdLine, get_env_var(Prefix, "", Acc)}. -spec get_env_var(Prefix :: string(), Suffix :: string(), Acc :: string()) -> string(). get_env_var(Prefix, Suffix, [_ | _] = Acc) -> Name = lists:reverse(Acc), %% Only expand valid/existing variables. case os:getenv(Name) of false -> Prefix ++ Name ++ Suffix; Value -> Value end; get_env_var(Prefix, Suffix, []) -> Prefix ++ Suffix.
null
https://raw.githubusercontent.com/parapluu/nifty/9d478d93bf655cb5bb6fc69c07eac1296e45020f/src/nifty_utils.erl
erlang
------------------------------------------------------------------- All rights reserved. Details can be found in the LICENSE file. ------------------------------------------------------------------- -type port_specs() :: {'port_specs', [target()]}. port_specs() is an element here... @doc Returns an empty configuration @doc Returns <code>Path</code> with all environment variables expanded Found separator: add to the list of arguments. Found separator with no accumulated argument; discard it. Quoted argument (might contain spaces, tabs, etc.) -> VAR% Escaped char. End of quoted argument Escaped char. -> VAR% , Tail, []) Only expand valid/existing variables.
-*- erlang - indent - level : 2 -*- Copyright ( c ) 2014 - 2016 , < > and < > This file is distributed under the Simplified BSD License . -module(nifty_utils). -export([expand/1, new_config/0, add_sources/2, add_cflags/2, add_ldflags/2, merge_nif_spec/2]). -type env() :: {'env', [{nonempty_string(), string()}]}. -type target_options() :: [env()]. -type arch() :: nonempty_string(). -type target_name() :: nonempty_string(). -type source() :: nonempty_string(). -type target() :: {arch(), target_name(), [source()]} | {arch(), target_name(), [source()], target_options()}. @doc Merges two configurations -spec merge_nif_spec(config(), target()) -> config(). merge_nif_spec(Config, {".*", "$NIF", Sources, [{env, Env}]} = Spec) -> case proplists:get_value(port_specs, Config) of undefined -> [{port_specs, [Spec]} | Config]; Specs -> NewSpecs = case get_nifspec(Specs) of {".*", "$NIF", OldSources} -> store_nifspec({".*", "$NIF", OldSources ++ Sources, [{env, Env}]}, Specs); {".*", "$NIF", OldSources, [{env, OldEnv}]} -> store_nifspec({".*", "$NIF", OldSources ++ Sources, [{env, OldEnv ++ Env}]}, Specs); undefined -> store_nifspec({".*", "$NIF", Sources, [{env, []}] }, Specs) end, [{port_specs, NewSpecs} | proplists:delete(port_specs, Config)] end. get_nifspec([]) -> undefined; get_nifspec([H|T]) -> case H of {".*", "$NIF", _} -> H; {".*", "$NIF", _, _} -> H; _ -> get_nifspec(T) end. store_nifspec(NifSpec, Specs) -> store_nifspec(Specs, NifSpec, []). store_nifspec([], _, Acc) -> Acc; store_nifspec([H|T], Spec, Acc) -> case H of {".*", "$NIF", _} -> store_nifspec(T, Spec, [Spec|Acc]); {".*", "$NIF", _, _} -> store_nifspec(T, Spec, [Spec|Acc]); _ -> store_nifspec(T, Spec, [H|Acc]) end. -spec new_config() -> config(). new_config() -> []. @doc Adds the sources < code > S</code > to the NIF module -spec add_sources([source()], config()) -> config(). add_sources(S, C) -> merge_nif_spec(C, {".*", "$NIF", S, [{env, []}]}). @doc Adds the compile flags < code > F</code > to the NIF module -spec add_cflags(string(), config()) -> config(). add_cflags(F, C) -> merge_nif_spec(C, {".*", "$NIF", [], [{env, [{"CFLAGS", "$CFLAGS "++F}]}]}). @doc Adds link flags < code > F</code > to the NIF module -spec add_ldflags(string(), config()) -> config(). add_ldflags(F, C) -> merge_nif_spec(C, {".*", "$NIF", [], [{env, [{"LDFLAGS", "$LDFLAGS "++F}]}]}). -spec expand(string()) -> string(). expand(Path) -> S = lists:foldr(fun(A, Acc) -> A ++ " " ++ Acc end, [], tokenize(Path)), string:strip(S). -define(IS_WHITESPACE(Char), ((Char) =:= $\s orelse (Char) =:= $\t orelse (Char) =:= $\n orelse (Char) =:= $\r)). -spec tokenize(CmdLine :: string()) -> [nonempty_string()]. tokenize(CmdLine) -> tokenize(CmdLine, [], []). -spec tokenize(CmdLine :: string(), Acc :: [string()], ArgAcc :: string()) -> [string()]. tokenize([Sep | Tail], Acc, ArgAcc) when ?IS_WHITESPACE(Sep) -> NewAcc = case ArgAcc of [_ | _] -> [lists:reverse(ArgAcc) | Acc]; [] -> Acc end, tokenize(Tail, NewAcc, []); tokenize([QuotationMark | Tail], Acc, ArgAcc) when QuotationMark =:= $"; QuotationMark =:= $' -> tokenize_quoted_arg(QuotationMark, Tail, Acc, ArgAcc); {NewCmdLine, Var} = expand_env_var(CmdLine), tokenize(NewCmdLine, Acc, lists:reverse(Var, ArgAcc)); tokenize([$\\, Char | Tail], Acc, ArgAcc) -> tokenize(Tail, Acc, [Char | ArgAcc]); tokenize([Char | Tail], Acc, ArgAcc) -> tokenize(Tail, Acc, [Char | ArgAcc]); tokenize([], Acc, []) -> lists:reverse(Acc); tokenize([], Acc, ArgAcc) -> lists:reverse([lists:reverse(ArgAcc) | Acc]). -spec tokenize_quoted_arg(QuotationMark :: char(), CmdLine :: string(), Acc :: [string()], ArgAcc :: string()) -> [string()]. tokenize_quoted_arg(QuotationMark, [QuotationMark | Tail], Acc, ArgAcc) -> tokenize(Tail, Acc, ArgAcc); tokenize_quoted_arg(QuotationMark, [$\\, Char | Tail], Acc, ArgAcc) -> tokenize_quoted_arg(QuotationMark, Tail, Acc, [Char | ArgAcc]); {NewCmdLine, Var} = expand_env_var(CmdLine), tokenize_quoted_arg(QuotationMark, NewCmdLine, Acc, lists:reverse(Var, ArgAcc)); tokenize_quoted_arg(QuotationMark, [Char | Tail], Acc, ArgAcc) -> tokenize_quoted_arg(QuotationMark, Tail, Acc, [Char | ArgAcc]); tokenize_quoted_arg(_QuotationMark, CmdLine, Acc, ArgAcc) -> tokenize(CmdLine, Acc, ArgAcc). -spec expand_env_var(CmdLine :: nonempty_string()) -> {string(), string()}. expand_env_var(CmdLine) -> case CmdLine of "${" ++ Tail -> expand_env_var("${", $}, Tail, []); "$" ++ Tail -> expand_env_var("$", Tail, []); "%" ++ Tail -> end. -spec expand_env_var(Prefix :: string(), EndMark :: char(), CmdLine :: string(), Acc :: string()) -> {string(), string()}. expand_env_var(Prefix, EndMark, [Char | Tail], Acc) when (Char >= $A andalso Char =< $Z) orelse (Char >= $a andalso Char =< $z) orelse (Char >= $0 andalso Char =< $9) orelse (Char =:= $_) -> expand_env_var(Prefix, EndMark, Tail, [Char | Acc]); expand_env_var(Prefix, EndMark, [EndMark | Tail], Acc) -> {Tail, get_env_var(Prefix, [EndMark], Acc)}; expand_env_var(Prefix, _EndMark, CmdLine, Acc) -> {CmdLine, Prefix ++ lists:reverse(Acc)}. -spec expand_env_var(Prefix :: string(), CmdLine :: string(), Acc :: string()) -> {string(), string()}. expand_env_var(Prefix, [Char | Tail], Acc) when (Char >= $A andalso Char =< $Z) orelse (Char >= $a andalso Char =< $z) orelse (Char >= $0 andalso Char =< $9) orelse (Char =:= $_) -> expand_env_var(Prefix, Tail, [Char | Acc]); expand_env_var(Prefix, CmdLine, Acc) -> {CmdLine, get_env_var(Prefix, "", Acc)}. -spec get_env_var(Prefix :: string(), Suffix :: string(), Acc :: string()) -> string(). get_env_var(Prefix, Suffix, [_ | _] = Acc) -> Name = lists:reverse(Acc), case os:getenv(Name) of false -> Prefix ++ Name ++ Suffix; Value -> Value end; get_env_var(Prefix, Suffix, []) -> Prefix ++ Suffix.
924dca2aba2d9c32cd9216ff9e80cd4d0dd55a8b96df7d01ce62322b33f8977c
avsm/platform
uucp_white_data.ml
--------------------------------------------------------------------------- Copyright ( c ) 2014 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % NAME% % VERSION% --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %NAME% %VERSION% ---------------------------------------------------------------------------*) (* WARNING do not edit. This file was automatically generated. *) open Uucp_tmapbool let white_space_map = { default = false; l0 = [|[| "\x00\x3E\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x20\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;|];[|snil; snil;snil;snil;snil;snil; "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;|];[| "\xFF\x07\x00\x00\x00\x83\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;|];[| "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;|];nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; |]} --------------------------------------------------------------------------- Copyright ( c ) 2014 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/uucp.12.0.0%2Bdune/src/uucp_white_data.ml
ocaml
WARNING do not edit. This file was automatically generated.
--------------------------------------------------------------------------- Copyright ( c ) 2014 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % NAME% % VERSION% --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %NAME% %VERSION% ---------------------------------------------------------------------------*) open Uucp_tmapbool let white_space_map = { default = false; l0 = [|[| "\x00\x3E\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x20\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;|];[|snil; snil;snil;snil;snil;snil; "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;|];[| "\xFF\x07\x00\x00\x00\x83\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;|];[| "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";snil;snil; snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;snil;|];nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil;nil; |]} --------------------------------------------------------------------------- Copyright ( c ) 2014 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2014 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
39f06aebdfde1d805b096be568735e1644b903efda55683df1e6a7561db9ac2d
nikivazou/verified_string_matching
MonoidEmptyLeft.hs
# LANGUAGE CPP # #ifdef MainCall #else {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE GADTs # {-# LANGUAGE DeriveTraversable #-} # LANGUAGE CPP # {-@ LIQUID "--higherorder" @-} {-@ LIQUID "--totality" @-} {-@ LIQUID "--exactdc" @-} {-@ LIQUID "--no-measure-fields" @-} {-@ LIQUID "--trust-internals" @-} {-@ LIQUID "--automatic-instances=liquidinstanceslocal" @-} {-@ infix <+> @-} {-@ infix <> @-} import Data.RString.RString import Language.Haskell.Liquid.ProofCombinators import Data.Proxy import GHC.TypeLits import Prelude hiding ( mempty, mappend, id, mconcat, map , take, drop , error, undefined ) #define MainCall #include "../Data/List/RList.hs" #include "../Data/StringMatching/StringMatching.hs" #include "../AutoProofs/ListMonoidLemmata.hs" #define CheckMonoidEmptyLeft #endif #ifdef IncludedmakeNewIndicesNullLeft #else #include "../AutoProofs/makeNewIndicesNullLeft.hs" #endif #ifdef IncludedmapCastId #else #include "../AutoProofs/mapCastId.hs" #endif #define IncludedMonoidEmptyLeft #ifdef CheckMonoidEmptyLeft {-@ automatic-instances smLeftId @-} smLeftId :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof @ smLeftId : : xs : SM target - > { xs < > = = xs } @ smLeftId (SM i is) = let tg = fromString (symbolVal (Proxy :: Proxy target)) in stringLeftId i &&& mapCastId tg i stringEmp is &&& makeNewIndicesNullLeft i tg &&& listLeftId is mempty_left :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof @ mempty_left : : xs : SM target - > { xs < > = = xs } @ mempty_left = smLeftId #else mempty_left :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof @ mempty_left : : xs : SM target - > { xs < > = = xs } @ mempty_left _ = trivial #endif
null
https://raw.githubusercontent.com/nikivazou/verified_string_matching/abdd611a0758467f776c59c3d6c9e4705d36a3a0/src/AutoProofs/MonoidEmptyLeft.hs
haskell
# LANGUAGE KindSignatures # # LANGUAGE DataKinds # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # # LANGUAGE DeriveTraversable # @ LIQUID "--higherorder" @ @ LIQUID "--totality" @ @ LIQUID "--exactdc" @ @ LIQUID "--no-measure-fields" @ @ LIQUID "--trust-internals" @ @ LIQUID "--automatic-instances=liquidinstanceslocal" @ @ infix <+> @ @ infix <> @ @ automatic-instances smLeftId @
# LANGUAGE CPP # #ifdef MainCall #else # LANGUAGE ScopedTypeVariables # # LANGUAGE GADTs # # LANGUAGE CPP # import Data.RString.RString import Language.Haskell.Liquid.ProofCombinators import Data.Proxy import GHC.TypeLits import Prelude hiding ( mempty, mappend, id, mconcat, map , take, drop , error, undefined ) #define MainCall #include "../Data/List/RList.hs" #include "../Data/StringMatching/StringMatching.hs" #include "../AutoProofs/ListMonoidLemmata.hs" #define CheckMonoidEmptyLeft #endif #ifdef IncludedmakeNewIndicesNullLeft #else #include "../AutoProofs/makeNewIndicesNullLeft.hs" #endif #ifdef IncludedmapCastId #else #include "../AutoProofs/mapCastId.hs" #endif #define IncludedMonoidEmptyLeft #ifdef CheckMonoidEmptyLeft smLeftId :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof @ smLeftId : : xs : SM target - > { xs < > = = xs } @ smLeftId (SM i is) = let tg = fromString (symbolVal (Proxy :: Proxy target)) in stringLeftId i &&& mapCastId tg i stringEmp is &&& makeNewIndicesNullLeft i tg &&& listLeftId is mempty_left :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof @ mempty_left : : xs : SM target - > { xs < > = = xs } @ mempty_left = smLeftId #else mempty_left :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof @ mempty_left : : xs : SM target - > { xs < > = = xs } @ mempty_left _ = trivial #endif
70380cb46111a969e4c51898a724efce0ed943dfbab206cbf38535d033c4baf6
kazu-yamamoto/domain-auth
Domain.hs
{-# LANGUAGE OverloadedStrings #-} module Network.DomainAuth.PRD.Domain ( extractDomain ) where import Network.DNS (Domain) import Network.DomainAuth.Mail import Network.DomainAuth.PRD.Lexer import qualified Data.Attoparsec.ByteString as P import qualified Data.ByteString.Char8 as BS -- | Extract a domain from a value of a header field. -- > > > extractDomain " < > " -- Just "example.com" > > > extractDomain " \"Alice . Brown\ " < > ( Nickname here ) " -- Just "example.com" -- >>> extractDomain "" -- Just "example.com" > > > extractDomain " < example.com > " -- Nothing extractDomain :: RawFieldValue -> Maybe Domain extractDomain bs = case P.parseOnly structured bs of Left _ -> Nothing Right st -> takeDomain st where takeDomain = dropTail . dropWhile (/="@") dropTail [] = Nothing dropTail xs = (Just . BS.concat . takeWhile (/=">") . tail) xs
null
https://raw.githubusercontent.com/kazu-yamamoto/domain-auth/d13145709a558145ac38e28e0b339c48b950b4e0/Network/DomainAuth/PRD/Domain.hs
haskell
# LANGUAGE OverloadedStrings # | Extract a domain from a value of a header field. Just "example.com" Just "example.com" >>> extractDomain "" Just "example.com" Nothing
module Network.DomainAuth.PRD.Domain ( extractDomain ) where import Network.DNS (Domain) import Network.DomainAuth.Mail import Network.DomainAuth.PRD.Lexer import qualified Data.Attoparsec.ByteString as P import qualified Data.ByteString.Char8 as BS > > > extractDomain " < > " > > > extractDomain " \"Alice . Brown\ " < > ( Nickname here ) " > > > extractDomain " < example.com > " extractDomain :: RawFieldValue -> Maybe Domain extractDomain bs = case P.parseOnly structured bs of Left _ -> Nothing Right st -> takeDomain st where takeDomain = dropTail . dropWhile (/="@") dropTail [] = Nothing dropTail xs = (Just . BS.concat . takeWhile (/=">") . tail) xs
99f7dd71415528f96883b2bfadcbaeb04359d43cb5dabdb9a645dd6fb91ffbee
cheecheeo/haskell-cgi
upload.hs
-- Accepts file uploads and saves the files in the given directory. -- WARNING: this script is a SECURITY RISK and only for -- demo purposes. Do not put it on a public web server. import Data.Maybe (fromJust) import qualified Data.ByteString.Lazy as BS (writeFile) import Network.CGI import Text.XHtml ( Html, paragraph, (!), href, (+++), form, method, enctype, afile, submit , renderHtml, header, thetitle, body, (<<), anchor ) dir :: String dir = "../upload" saveFile :: (MonadCGI m, MonadIO m) => String -> m Html saveFile n = do cont <- fromJust <$> getInputFPS "file" let p = dir ++ "/" ++ basename n liftIO $ BS.writeFile p cont return $ paragraph << ("Saved as " +++ anchor ! [href p] << p +++ ".") fileForm :: Html fileForm = form ! [method "post", enctype "multipart/form-data"] << [afile "file", submit "" "Upload"] basename :: String -> String basename = reverse . takeWhile (`notElem` "/\\") . reverse cgiMain :: CGI CGIResult cgiMain = do mn <- getInputFilename "file" h <- maybe (return fileForm) saveFile mn output $ renderHtml $ header << thetitle << "Upload example" +++ body << h main :: IO () main = runCGI cgiMain
null
https://raw.githubusercontent.com/cheecheeo/haskell-cgi/a49660abdc5b711fcc99989f121eb4404bbde66c/examples/upload.hs
haskell
Accepts file uploads and saves the files in the given directory. WARNING: this script is a SECURITY RISK and only for demo purposes. Do not put it on a public web server.
import Data.Maybe (fromJust) import qualified Data.ByteString.Lazy as BS (writeFile) import Network.CGI import Text.XHtml ( Html, paragraph, (!), href, (+++), form, method, enctype, afile, submit , renderHtml, header, thetitle, body, (<<), anchor ) dir :: String dir = "../upload" saveFile :: (MonadCGI m, MonadIO m) => String -> m Html saveFile n = do cont <- fromJust <$> getInputFPS "file" let p = dir ++ "/" ++ basename n liftIO $ BS.writeFile p cont return $ paragraph << ("Saved as " +++ anchor ! [href p] << p +++ ".") fileForm :: Html fileForm = form ! [method "post", enctype "multipart/form-data"] << [afile "file", submit "" "Upload"] basename :: String -> String basename = reverse . takeWhile (`notElem` "/\\") . reverse cgiMain :: CGI CGIResult cgiMain = do mn <- getInputFilename "file" h <- maybe (return fileForm) saveFile mn output $ renderHtml $ header << thetitle << "Upload example" +++ body << h main :: IO () main = runCGI cgiMain
4d135f548af25ed485a97eb5b22e50d01646fcccb60cf11c83da51740d85710e
TrustInSoft/tis-interpreter
logic_utils.mli
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) ( Institut National de Recherche en Informatique et en (* Automatique) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * Utilities for ACSL constructs . @plugin development guide @plugin development guide *) open Cil_types (** exception raised when a parsed logic expression is syntactically not well-formed. *) exception Not_well_formed of Cil_types.location * string * basic utilities for logic terms and predicates . See also { ! } to build terms and predicates . @plugin development guide to build terms and predicates. @plugin development guide *) * add a logic function in the environment . See { ! } See {!Logic_env.add_logic_function_gen}*) val add_logic_function : logic_info -> unit (** {2 Types} *) (** instantiate type variables in a logic type. *) val instantiate : (string * logic_type) list -> logic_type -> logic_type (** [is_instance_of poly t1 t2] returns [true] if [t1] can be derived from [t2] by instantiating some of the type variable in [poly]. @since Magnesium-20151001 *) val is_instance_of: string list -> logic_type -> logic_type -> bool (** expands logic type definitions. If the [unroll_typedef] flag is set to [true] (this is the default), C typedef will be expanded as well. *) val unroll_type : ?unroll_typedef:bool -> logic_type -> logic_type (** [isLogicType test typ] is [false] for pure logic types and the result of test for C types. *) (* BY: seriously? *) val isLogicType : (typ -> bool) -> logic_type -> bool * { 3 Predefined tests over types } val isLogicArrayType : logic_type -> bool val isLogicCharType : logic_type -> bool val isLogicVoidType : logic_type -> bool val isLogicPointerType : logic_type -> bool val isLogicVoidPointerType : logic_type -> bool * { 3 Type conversions } (** @return the equivalent C type. @raise Failure if the type is purely logical *) val logicCType : logic_type -> typ (** transforms an array into pointer. *) val array_to_ptr : logic_type -> logic_type (** C type to logic type, with implicit conversion for arithmetic types. *) val typ_to_logic_type : typ -> logic_type * { 2 Predicates } val named_of_identified_predicate: identified_predicate -> predicate named * transforms \old and \at(,Old ) into \at(,L ) for L a label pointing to the given statement , creating one if needed . to the given statement, creating one if needed. *) val translate_old_label: stmt -> predicate named -> predicate named * { 2 Terms } (** [true] if the term denotes a C array. *) val is_C_array : term -> bool (** creates a TStartOf from an TLval. *) val mk_logic_StartOf : term -> term * creates an from a TLval . The given logic type is the type of the lval . @since Neon-20140301 type of the lval. @since Neon-20140301 *) val mk_logic_AddrOf: ?loc:Cil_types.location -> term_lval -> logic_type -> term (** [true] if the term is a pointer. *) val isLogicPointer : term -> bool (** creates either a TStartOf or the corresponding TLval. *) val mk_logic_pointer_or_StartOf : term -> term (** creates a logic cast if required, with some automatic simplifications being performed automatically *) val mk_cast: ?loc:location -> typ -> term -> term (** [array_with_range arr size] returns the logic term [array'+{0..(size-1)}], [array'] being [array] cast to a pointer to char *) val array_with_range: exp -> term -> term (** Removes TLogic_coerce at head of term. *) val remove_logic_coerce: term -> term (** [numeric_coerce typ t] returns a term with the same value as [t] and of type [typ]. [typ] which should be [Linteger] or [Lreal]. [numeric_coerce] tries to avoid unnecessary type conversions in [t]. In particular, [numeric_coerce (int)cst Linteger], where [cst] fits in int will be directly [cst], without any coercion. @since Magnesium-20151001 *) val numeric_coerce: logic_type -> term -> term * { 2 Predicates } (** \valid_index *) val mk_pvalid_index : ? loc : location - > term * term - > predicate named (** \valid_range *) (* val mk_pvalid_range: ?loc:location -> term * term * term -> predicate named *) val pointer_comparable: ?loc:location -> term -> term -> predicate named (** \pointer_comparable @since Fluorine-20130401 *) val points_to_valid_string: ?loc:location -> term -> predicate named (** builds predicate \points_to_valid_string(p) @since Neon-20140301 *) val inside_object: ?loc:location -> term -> predicate named (** builds predicate \stays_inside_object(p) *) * { 3 Conversion from exp to term } (** translates a C expression into an "equivalent" logical term. [cast] specifies how C arithmetic operators are translated. When [cast] is [true], the translation returns a logic [term] having the same semantics of the C [expr] by introducing casts (i.e. the C expr [a+b] can be translated as [(char)(((char)a)+(char)b)] to preserve the modulo feature of the C addition). Otherwise, no such casts are introduced and the C arithmetic operators are translated into perfect mathematical operators (i.e. a floating point addition is translated into an addition of [real] numbers). @plugin development guide *) val expr_to_term : cast:bool -> exp -> term (** same as {!expr_to_term}, except that if the new term has an arithmetic type, it is automatically coerced into real (or integer for integral types). @since Magnesium-20151001 *) val expr_to_term_coerce: cast:bool -> exp -> term val lval_to_term_lval : cast:bool -> lval -> term_lval val host_to_term_host : cast:bool -> lhost -> term_lhost val offset_to_term_offset : cast:bool -> offset -> term_offset val constant_to_lconstant: constant -> logic_constant val lconstant_to_constant: logic_constant-> constant * the given string as a float logic constant , taking into account the fact that the constant may not be exactly representable . This function should only be called on strings that have been recognized by the parser as valid floats the fact that the constant may not be exactly representable. This function should only be called on strings that have been recognized by the parser as valid floats *) val string_to_float_lconstant: string -> logic_constant (** [remove_term_offset o] returns [o] without its last offset and this last offset. *) val remove_term_offset : term_offset -> term_offset * term_offset * true if \result is included in the lval . val lval_contains_result : term_lhost -> bool * true if \result is included in the offset . val loffset_contains_result : term_offset -> bool * true if \result is included in the term val contains_result : term -> bool (** returns the body of the given predicate. @raise Not_found if the logic_info is not the definition of a predicate. *) val get_pred_body : logic_info -> predicate named * true if the term is \result or an offset of \result . val is_result : term -> bool val lhost_c_type : term_lhost -> typ * { 2 Predicates } * [ true ] if the predicate is Ptrue . @since @since Nitrogen-20111001 *) val is_trivially_true: predicate named -> bool * [ true ] if the predicate is Pfalse @since @since Nitrogen-20111001 *) val is_trivially_false: predicate named -> bool * { 2 Structural equality between annotations } val is_same_list: ('a -> 'a -> bool) -> 'a list -> 'a list -> bool val is_same_logic_label : logic_label -> logic_label -> bool * @since @since Nitrogen-20111001 *) val is_same_pconstant: Logic_ptree.constant -> Logic_ptree.constant -> bool val is_same_type : logic_type -> logic_type -> bool val is_same_var : logic_var -> logic_var -> bool val is_same_logic_signature : logic_info -> logic_info -> bool val is_same_logic_profile : logic_info -> logic_info -> bool val is_same_builtin_profile : builtin_logic_info -> builtin_logic_info -> bool val is_same_logic_ctor_info : logic_ctor_info -> logic_ctor_info -> bool (** @deprecated Nitrogen-20111001 use {!Cil.compareConstant} instead. *) val is_same_constant : constant -> constant -> bool val is_same_term : term -> term -> bool val is_same_logic_info : logic_info -> logic_info -> bool val is_same_logic_body : logic_body -> logic_body -> bool val is_same_indcase : string * logic_label list * string list * predicate named -> string * logic_label list * string list * predicate named -> bool val is_same_tlval : term_lval -> term_lval -> bool val is_same_lhost : term_lhost -> term_lhost -> bool val is_same_offset : term_offset -> term_offset -> bool val is_same_predicate : predicate -> predicate -> bool val is_same_named_predicate : predicate named -> predicate named -> bool val is_same_identified_predicate : identified_predicate -> identified_predicate -> bool val is_same_identified_term : identified_term -> identified_term -> bool val is_same_deps : identified_term deps -> identified_term deps -> bool val is_same_allocation : identified_term allocation -> identified_term allocation -> bool val is_same_assigns : identified_term assigns -> identified_term assigns -> bool val is_same_variant : term variant -> term variant -> bool val is_same_post_cond : termination_kind * identified_predicate -> termination_kind * identified_predicate -> bool val is_same_behavior : funbehavior -> funbehavior -> bool val is_same_spec : funspec -> funspec -> bool val is_same_logic_type_def : logic_type_def -> logic_type_def -> bool val is_same_logic_type_info : logic_type_info -> logic_type_info -> bool val is_same_loop_pragma : term loop_pragma -> term loop_pragma -> bool val is_same_slice_pragma : term slice_pragma -> term slice_pragma -> bool val is_same_impact_pragma : term impact_pragma -> term impact_pragma -> bool val is_same_pragma : term pragma -> term pragma -> bool val is_same_code_annotation : code_annotation -> code_annotation -> bool val is_same_global_annotation : global_annotation -> global_annotation -> bool val is_same_axiomatic : global_annotation list -> global_annotation list -> bool (** @since Oxygen-20120901 *) val is_same_model_info: model_info -> model_info -> bool val is_same_lexpr: Logic_ptree.lexpr -> Logic_ptree.lexpr -> bool (** hash function compatible with is_same_term *) val hash_term: term -> int (** comparison compatible with is_same_term *) val compare_term: term -> term -> int * { 2 Merging contracts } val get_behavior_names : ('a, 'b, 'c) spec -> string list * Concatenates two assigns if both are defined , returns WritesAny if one ( or both ) of them is WritesAny . @since returns WritesAny if one (or both) of them is WritesAny. @since Nitrogen-20111001 *) val concat_assigns: identified_term assigns -> identified_term assigns -> identified_term assigns (** merge assigns: take the one that is defined and select an arbitrary one if both are, emitting a warning unless both are syntactically the same. *) val merge_assigns : identified_term assigns -> identified_term assigns -> identified_term assigns * Concatenates two allocation clauses if both are defined , returns FreeAllocAny if one ( or both ) of them is FreeAllocAny . @since returns FreeAllocAny if one (or both) of them is FreeAllocAny. @since Nitrogen-20111001 *) val concat_allocation: identified_term allocation -> identified_term allocation -> identified_term allocation (** merge allocation: take the one that is defined and select an arbitrary one if both are, emitting a warning unless both are syntactically the same. @since Oxygen-20120901 *) val merge_allocation : identified_term allocation -> identified_term allocation -> identified_term allocation val merge_behaviors : silent:bool -> funbehavior list -> funbehavior list -> funbehavior list * [ merge_funspec ] merges [ newspec ] into [ oldspec ] . If the funspec belongs to a kernel function , do not forget to call { ! } after merging . If the funspec belongs to a kernel function, do not forget to call {!Kernel_function.set_spec} after merging. *) val merge_funspec : ?silent_about_merging_behav:bool -> funspec -> funspec -> unit * Reset the given funspec to empty . @since @since Nitrogen-20111001 *) val clear_funspec: funspec -> unit * { 2 Discriminating code_annotations } (** Functions below allows to test a special kind of code_annotation. Use them in conjunction with {!Annotations.get_filter} to retrieve a particular kind of annotations associated to a statement. *) val is_assert : code_annotation -> bool val is_contract : code_annotation -> bool val is_stmt_invariant : code_annotation -> bool val is_loop_invariant : code_annotation -> bool val is_invariant : code_annotation -> bool val is_variant : code_annotation -> bool val is_assigns : code_annotation -> bool val is_pragma : code_annotation -> bool val is_loop_pragma : code_annotation -> bool val is_slice_pragma : code_annotation -> bool val is_impact_pragma : code_annotation -> bool val is_loop_annot : code_annotation -> bool val is_trivial_annotation : code_annotation -> bool val is_property_pragma : term pragma -> bool (** Should this pragma be proved by plugins *) val extract_loop_pragma : code_annotation list -> term loop_pragma list val extract_contract : code_annotation list -> (string list * funspec) list * { 2 Constant folding } val constFoldTermToInt: ?machdep:bool -> term -> Integer.t option * { 2 Type - checking hackery } (** give complete types to terms that refer to a variable whose type has been completed after its use in an annotation. Internal use only. @since Neon-20140301 *) val complete_types: file -> unit * { 2 Parsing hackery } (** Values that control the various modes of the parser and lexer for logic. Use with care. *) (** register a given name as a clause name for extended contract. *) val register_extension: string -> unit val is_extension: string -> bool val kw_c_mode : bool ref val enter_kw_c_mode : unit -> unit val exit_kw_c_mode : unit -> unit val is_kw_c_mode : unit -> bool val rt_type_mode : bool ref val enter_rt_type_mode : unit -> unit val exit_rt_type_mode : unit -> unit val is_rt_type_mode : unit -> bool (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/kernel_services/ast_queries/logic_utils.mli
ocaml
************************************************************************ alternatives) Automatique) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * exception raised when a parsed logic expression is syntactically not well-formed. * {2 Types} * instantiate type variables in a logic type. * [is_instance_of poly t1 t2] returns [true] if [t1] can be derived from [t2] by instantiating some of the type variable in [poly]. @since Magnesium-20151001 * expands logic type definitions. If the [unroll_typedef] flag is set to [true] (this is the default), C typedef will be expanded as well. * [isLogicType test typ] is [false] for pure logic types and the result of test for C types. BY: seriously? * @return the equivalent C type. @raise Failure if the type is purely logical * transforms an array into pointer. * C type to logic type, with implicit conversion for arithmetic types. * [true] if the term denotes a C array. * creates a TStartOf from an TLval. * [true] if the term is a pointer. * creates either a TStartOf or the corresponding TLval. * creates a logic cast if required, with some automatic simplifications being performed automatically * [array_with_range arr size] returns the logic term [array'+{0..(size-1)}], [array'] being [array] cast to a pointer to char * Removes TLogic_coerce at head of term. * [numeric_coerce typ t] returns a term with the same value as [t] and of type [typ]. [typ] which should be [Linteger] or [Lreal]. [numeric_coerce] tries to avoid unnecessary type conversions in [t]. In particular, [numeric_coerce (int)cst Linteger], where [cst] fits in int will be directly [cst], without any coercion. @since Magnesium-20151001 * \valid_index * \valid_range val mk_pvalid_range: ?loc:location -> term * term * term -> predicate named * \pointer_comparable @since Fluorine-20130401 * builds predicate \points_to_valid_string(p) @since Neon-20140301 * builds predicate \stays_inside_object(p) * translates a C expression into an "equivalent" logical term. [cast] specifies how C arithmetic operators are translated. When [cast] is [true], the translation returns a logic [term] having the same semantics of the C [expr] by introducing casts (i.e. the C expr [a+b] can be translated as [(char)(((char)a)+(char)b)] to preserve the modulo feature of the C addition). Otherwise, no such casts are introduced and the C arithmetic operators are translated into perfect mathematical operators (i.e. a floating point addition is translated into an addition of [real] numbers). @plugin development guide * same as {!expr_to_term}, except that if the new term has an arithmetic type, it is automatically coerced into real (or integer for integral types). @since Magnesium-20151001 * [remove_term_offset o] returns [o] without its last offset and this last offset. * returns the body of the given predicate. @raise Not_found if the logic_info is not the definition of a predicate. * @deprecated Nitrogen-20111001 use {!Cil.compareConstant} instead. * @since Oxygen-20120901 * hash function compatible with is_same_term * comparison compatible with is_same_term * merge assigns: take the one that is defined and select an arbitrary one if both are, emitting a warning unless both are syntactically the same. * merge allocation: take the one that is defined and select an arbitrary one if both are, emitting a warning unless both are syntactically the same. @since Oxygen-20120901 * Functions below allows to test a special kind of code_annotation. Use them in conjunction with {!Annotations.get_filter} to retrieve a particular kind of annotations associated to a statement. * Should this pragma be proved by plugins * give complete types to terms that refer to a variable whose type has been completed after its use in an annotation. Internal use only. @since Neon-20140301 * Values that control the various modes of the parser and lexer for logic. Use with care. * register a given name as a clause name for extended contract. Local Variables: compile-command: "make -C ../../.." End:
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies ( Institut National de Recherche en Informatique et en Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * Utilities for ACSL constructs . @plugin development guide @plugin development guide *) open Cil_types exception Not_well_formed of Cil_types.location * string * basic utilities for logic terms and predicates . See also { ! } to build terms and predicates . @plugin development guide to build terms and predicates. @plugin development guide *) * add a logic function in the environment . See { ! } See {!Logic_env.add_logic_function_gen}*) val add_logic_function : logic_info -> unit val instantiate : (string * logic_type) list -> logic_type -> logic_type val is_instance_of: string list -> logic_type -> logic_type -> bool val unroll_type : ?unroll_typedef:bool -> logic_type -> logic_type val isLogicType : (typ -> bool) -> logic_type -> bool * { 3 Predefined tests over types } val isLogicArrayType : logic_type -> bool val isLogicCharType : logic_type -> bool val isLogicVoidType : logic_type -> bool val isLogicPointerType : logic_type -> bool val isLogicVoidPointerType : logic_type -> bool * { 3 Type conversions } val logicCType : logic_type -> typ val array_to_ptr : logic_type -> logic_type val typ_to_logic_type : typ -> logic_type * { 2 Predicates } val named_of_identified_predicate: identified_predicate -> predicate named * transforms \old and \at(,Old ) into \at(,L ) for L a label pointing to the given statement , creating one if needed . to the given statement, creating one if needed. *) val translate_old_label: stmt -> predicate named -> predicate named * { 2 Terms } val is_C_array : term -> bool val mk_logic_StartOf : term -> term * creates an from a TLval . The given logic type is the type of the lval . @since Neon-20140301 type of the lval. @since Neon-20140301 *) val mk_logic_AddrOf: ?loc:Cil_types.location -> term_lval -> logic_type -> term val isLogicPointer : term -> bool val mk_logic_pointer_or_StartOf : term -> term val mk_cast: ?loc:location -> typ -> term -> term val array_with_range: exp -> term -> term val remove_logic_coerce: term -> term val numeric_coerce: logic_type -> term -> term * { 2 Predicates } val mk_pvalid_index : ? loc : location - > term * term - > predicate named val pointer_comparable: ?loc:location -> term -> term -> predicate named val points_to_valid_string: ?loc:location -> term -> predicate named val inside_object: ?loc:location -> term -> predicate named * { 3 Conversion from exp to term } val expr_to_term : cast:bool -> exp -> term val expr_to_term_coerce: cast:bool -> exp -> term val lval_to_term_lval : cast:bool -> lval -> term_lval val host_to_term_host : cast:bool -> lhost -> term_lhost val offset_to_term_offset : cast:bool -> offset -> term_offset val constant_to_lconstant: constant -> logic_constant val lconstant_to_constant: logic_constant-> constant * the given string as a float logic constant , taking into account the fact that the constant may not be exactly representable . This function should only be called on strings that have been recognized by the parser as valid floats the fact that the constant may not be exactly representable. This function should only be called on strings that have been recognized by the parser as valid floats *) val string_to_float_lconstant: string -> logic_constant val remove_term_offset : term_offset -> term_offset * term_offset * true if \result is included in the lval . val lval_contains_result : term_lhost -> bool * true if \result is included in the offset . val loffset_contains_result : term_offset -> bool * true if \result is included in the term val contains_result : term -> bool val get_pred_body : logic_info -> predicate named * true if the term is \result or an offset of \result . val is_result : term -> bool val lhost_c_type : term_lhost -> typ * { 2 Predicates } * [ true ] if the predicate is Ptrue . @since @since Nitrogen-20111001 *) val is_trivially_true: predicate named -> bool * [ true ] if the predicate is Pfalse @since @since Nitrogen-20111001 *) val is_trivially_false: predicate named -> bool * { 2 Structural equality between annotations } val is_same_list: ('a -> 'a -> bool) -> 'a list -> 'a list -> bool val is_same_logic_label : logic_label -> logic_label -> bool * @since @since Nitrogen-20111001 *) val is_same_pconstant: Logic_ptree.constant -> Logic_ptree.constant -> bool val is_same_type : logic_type -> logic_type -> bool val is_same_var : logic_var -> logic_var -> bool val is_same_logic_signature : logic_info -> logic_info -> bool val is_same_logic_profile : logic_info -> logic_info -> bool val is_same_builtin_profile : builtin_logic_info -> builtin_logic_info -> bool val is_same_logic_ctor_info : logic_ctor_info -> logic_ctor_info -> bool val is_same_constant : constant -> constant -> bool val is_same_term : term -> term -> bool val is_same_logic_info : logic_info -> logic_info -> bool val is_same_logic_body : logic_body -> logic_body -> bool val is_same_indcase : string * logic_label list * string list * predicate named -> string * logic_label list * string list * predicate named -> bool val is_same_tlval : term_lval -> term_lval -> bool val is_same_lhost : term_lhost -> term_lhost -> bool val is_same_offset : term_offset -> term_offset -> bool val is_same_predicate : predicate -> predicate -> bool val is_same_named_predicate : predicate named -> predicate named -> bool val is_same_identified_predicate : identified_predicate -> identified_predicate -> bool val is_same_identified_term : identified_term -> identified_term -> bool val is_same_deps : identified_term deps -> identified_term deps -> bool val is_same_allocation : identified_term allocation -> identified_term allocation -> bool val is_same_assigns : identified_term assigns -> identified_term assigns -> bool val is_same_variant : term variant -> term variant -> bool val is_same_post_cond : termination_kind * identified_predicate -> termination_kind * identified_predicate -> bool val is_same_behavior : funbehavior -> funbehavior -> bool val is_same_spec : funspec -> funspec -> bool val is_same_logic_type_def : logic_type_def -> logic_type_def -> bool val is_same_logic_type_info : logic_type_info -> logic_type_info -> bool val is_same_loop_pragma : term loop_pragma -> term loop_pragma -> bool val is_same_slice_pragma : term slice_pragma -> term slice_pragma -> bool val is_same_impact_pragma : term impact_pragma -> term impact_pragma -> bool val is_same_pragma : term pragma -> term pragma -> bool val is_same_code_annotation : code_annotation -> code_annotation -> bool val is_same_global_annotation : global_annotation -> global_annotation -> bool val is_same_axiomatic : global_annotation list -> global_annotation list -> bool val is_same_model_info: model_info -> model_info -> bool val is_same_lexpr: Logic_ptree.lexpr -> Logic_ptree.lexpr -> bool val hash_term: term -> int val compare_term: term -> term -> int * { 2 Merging contracts } val get_behavior_names : ('a, 'b, 'c) spec -> string list * Concatenates two assigns if both are defined , returns WritesAny if one ( or both ) of them is WritesAny . @since returns WritesAny if one (or both) of them is WritesAny. @since Nitrogen-20111001 *) val concat_assigns: identified_term assigns -> identified_term assigns -> identified_term assigns val merge_assigns : identified_term assigns -> identified_term assigns -> identified_term assigns * Concatenates two allocation clauses if both are defined , returns FreeAllocAny if one ( or both ) of them is FreeAllocAny . @since returns FreeAllocAny if one (or both) of them is FreeAllocAny. @since Nitrogen-20111001 *) val concat_allocation: identified_term allocation -> identified_term allocation -> identified_term allocation val merge_allocation : identified_term allocation -> identified_term allocation -> identified_term allocation val merge_behaviors : silent:bool -> funbehavior list -> funbehavior list -> funbehavior list * [ merge_funspec ] merges [ newspec ] into [ oldspec ] . If the funspec belongs to a kernel function , do not forget to call { ! } after merging . If the funspec belongs to a kernel function, do not forget to call {!Kernel_function.set_spec} after merging. *) val merge_funspec : ?silent_about_merging_behav:bool -> funspec -> funspec -> unit * Reset the given funspec to empty . @since @since Nitrogen-20111001 *) val clear_funspec: funspec -> unit * { 2 Discriminating code_annotations } val is_assert : code_annotation -> bool val is_contract : code_annotation -> bool val is_stmt_invariant : code_annotation -> bool val is_loop_invariant : code_annotation -> bool val is_invariant : code_annotation -> bool val is_variant : code_annotation -> bool val is_assigns : code_annotation -> bool val is_pragma : code_annotation -> bool val is_loop_pragma : code_annotation -> bool val is_slice_pragma : code_annotation -> bool val is_impact_pragma : code_annotation -> bool val is_loop_annot : code_annotation -> bool val is_trivial_annotation : code_annotation -> bool val is_property_pragma : term pragma -> bool val extract_loop_pragma : code_annotation list -> term loop_pragma list val extract_contract : code_annotation list -> (string list * funspec) list * { 2 Constant folding } val constFoldTermToInt: ?machdep:bool -> term -> Integer.t option * { 2 Type - checking hackery } val complete_types: file -> unit * { 2 Parsing hackery } val register_extension: string -> unit val is_extension: string -> bool val kw_c_mode : bool ref val enter_kw_c_mode : unit -> unit val exit_kw_c_mode : unit -> unit val is_kw_c_mode : unit -> bool val rt_type_mode : bool ref val enter_rt_type_mode : unit -> unit val exit_rt_type_mode : unit -> unit val is_rt_type_mode : unit -> bool
a7ac11e20bc853b51dd77d35e9e6bdca060b79a9a9da9bfb91ab1ba1ea1536a7
lisp/de.setf.cassandra
cassandra-8-1-0-vars.lisp
;;; -*- Package: cassandra -*- ;;; Autogenerated by Thrift ;;; DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING (cl:in-package :cassandra-8-1-0) (thrift:def-constant "VERSION" "8.1.0")
null
https://raw.githubusercontent.com/lisp/de.setf.cassandra/b8744258f310784245da0771d53ffb3a0062fd31/gen-cl/cassandra-8-1-0-vars.lisp
lisp
-*- Package: cassandra -*- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
Autogenerated by Thrift (cl:in-package :cassandra-8-1-0) (thrift:def-constant "VERSION" "8.1.0")
3f9ab023b0113983a719367b1a0114fd2407e01b9d3981c135214372022f0c4d
stchang/macrotypes
stlc+sum+rec-tests.rkt
#lang s-exp turnstile/examples/cmu15-814/stlc+sum+rec (require rackunit/turnstile) (define-type-alias IntList (μ (X) (+ Unit (× Int X)))) (define-type-alias ILBody (+ Unit (× Int IntList))) ;; nil (define nil (fld {IntList} (inl (void) as ILBody))) (check-type nil : IntList) (check-type nil : (mu (X) (+ Unit (x Int X)))) ;; cons (define cons (λ ([n : Int] [lst : IntList]) (fld {IntList} (inr (pair n lst) as ILBody)))) (check-type cons : (→ Int IntList IntList)) (check-type (cons 1 nil) : IntList) (typecheck-fail (cons 1 2)) (typecheck-fail (cons "1" nil)) ;; isnil (define isnil (λ ([lst : IntList]) (case (unfld {IntList} lst) [inl n => #t] [inr p => #f]))) (check-type isnil : (→ IntList Bool)) (check-type (isnil nil) : Bool ⇒ #t) (check-type (isnil (cons 1 nil)) : Bool ⇒ #f) (typecheck-fail (isnil 1)) (typecheck-fail (isnil (cons 1 2))) (check-type (λ ([f : (→ IntList Bool)]) (f nil)) : (→ (→ IntList Bool) Bool)) (check-type ((λ ([f : (→ IntList Bool)]) (f nil)) isnil) : Bool ⇒ #t) ;; hd (define hd (λ ([lst : IntList]) (case (unfld {IntList} lst) [inl n => 0] [inr p => (fst p)]))) (check-type hd : (→ IntList Int)) (check-type (hd nil) : Int ⇒ 0) (typecheck-fail (hd 1)) (check-type (hd (cons 11 nil)) : Int ⇒ 11) ;; tl (define tl (λ ([lst : IntList]) (case (unfld {IntList} lst) [inl n => lst] [inr p => (snd p)]))) (check-type tl : (→ IntList IntList)) (check-type (tl nil) : IntList ⇒ nil) (check-type (tl (cons 1 nil)) : IntList ⇒ nil) (check-type (tl (cons 1 (cons 2 nil))) : IntList ⇒ (cons 2 nil)) (typecheck-fail (tl 1)) some typecheck failure (typecheck-fail (fld {Int} 1) #:with-msg "Expected μ type, got: Int") (typecheck-fail (unfld {Int} 1) #:with-msg "Expected μ type, got: Int") ;; old tests: should still pass ;; tests for pairs (check-type (pair 1 2) : (× Int Int)) (check-type (pair 1 #f) : (× Int Bool)) (check-type (pair #f plus) : (× Bool (→ Int Int Int))) (check-type (fst (pair 1 #f)) : Int ⇒ 1) (check-type (snd (pair 1 #f)) : Bool ⇒ #f) (check-type ((snd (pair #f plus)) 1 2) : Int ⇒ 3) (typecheck-fail (fst 1)) # : with - msg " proj : Expected × type or × * type , got : Int " ) ; ; TODO : check this ;; lazy pairs (check-type (pair* 1 2) : (×* Int Int)) (check-type (pair* 1 #f) : (×* Int Bool)) (check-type (pair* #f plus) : (×* Bool (→ Int Int Int))) (check-type (fst (pair* 1 #f)) : Int ⇒ 1) (check-type (snd (pair* 1 #f)) : Bool ⇒ #f) (check-type ((snd (pair* #f plus)) 1 2) : Int ⇒ 3) ;; test laziness (check-type (fst (pair* 1 (/ 1 0))) : Int -> 1) (check-runtime-exn (fst (pair 1 (/ 1 0)))) ;; sums (check-type (inl "Steve" as (+ String Int)) : (+ String Int)) (check-type (inl "Steve" as (+ String Bool)) : (+ String Bool)) (typecheck-fail (inl "Steve" as (+ Bool String)) #:with-msg "expected Bool, given String") (check-type (inl "Steve") : (+ String Bool)) ; testing form triggers ⇐ (typecheck-fail (inl "Steve") ; but not if no expected type supplied #:with-msg "no expected type, add annotations") (check-type (inr "Matthias" as (+ Int String)) : (+ Int String)) (check-type (inr "Matthias" as (+ Bool String)) : (+ Bool String)) (typecheck-fail (inr "Steve" as (+ String Bool)) #:with-msg "expected Bool, given String") (check-type (inr "Matthias") : (+ Bool String)) ; testing form triggers ⇐ (typecheck-fail (inr "Matthias") ; but not if no expected type supplied #:with-msg "no expected type, add annotations") (typecheck-fail (inr "Matthias" as Int) #:with-msg "Expected \\+ type") (check-type (case (inl "Steve" as (+ String Int)) [inl x => x] [inr x => (number->string x)]) : String -> "Steve") (check-type (case (inr "Steve" as (+ Int String)) [inl x => (number->string x)] [inr x => x]) : String -> "Steve") (check-type (case (inl 1 as (+ Int String)) [inl x => (number->string x)] [inr x => x]) : String -> "1") (typecheck-fail (case (inr "Steve" as (+ Int String)) [inl x => x] [inr y => y]) #:with-msg "expected Int, given String.* expression: y") (typecheck-fail (case (inr "Steve" as (+ Int String)) [bad x => x] [inr y => y]) #:with-msg "expected the identifier.*inl.*at: bad") (typecheck-fail (case (inr "Steve" as (+ Int String)) [inl x => x] [inr y => y] [bad z => z]) #:with-msg "unexpected term.*at: \\(bad z => z\\)") ;; old stlc tests: ;; - make sure extension didnt break anything ;; - Bool and String tests should now pass (typecheck-fail (λ ([x : Undef]) x) #:with-msg "Undef: unbound identifier") (typecheck-fail (λ ([x : →]) x) #:with-msg "Improper usage of type constructor →.+expected >= 1 arguments") (typecheck-fail (λ ([x : (→)]) x) #:with-msg "Improper usage of type constructor →.+expected >= 1 arguments") (typecheck-fail (λ ([x : (→ →)]) x) #:with-msg "Improper usage of type constructor →.+expected >= 1 arguments") (check-type 1 : Int) (check-not-type 1 : (→ Int Int)) (check-type "one" : String) (check-type #f : Bool) (check-type (λ ([x : Int] [y : Int]) x) : (→ Int Int Int)) (check-not-type (λ ([x : Int]) x) : Int) (check-type (λ ([x : Int]) x) : (→ Int Int)) (check-type (λ ([f : (→ Int Int)]) 1) : (→ (→ Int Int) Int)) (check-type ((λ ([x : Int]) x) 1) : Int ⇒ 1) (typecheck-fail ((λ ([x : Bool]) x) 1) #:with-msg "expected Bool, given Int") (check-type (λ ([x : (→ Bool Bool)]) x) : (→ (→ Bool Bool) (→ Bool Bool))) (check-type (λ ([x : Bool]) x) : (→ Bool Bool)) (typecheck-fail (λ ([f : Int]) (f 1 2)) #:with-msg "Expected → type, got: Int") (check-type plus : (→ Int Int Int)) (check-type (λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y)) : (→ (→ Int Int Int) Int Int Int)) (check-type ((λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y)) plus 1 2) : Int ⇒ 3) (typecheck-fail (plus 1 (λ ([x : Int]) x)) #:with-msg "expected Int, given \\(→ Int Int\\)\n *expression: \\(λ \\(\\(x : Int\\)\\) x\\)") (typecheck-fail (λ ([x : (→ Int Int)]) (plus x x)) #:with-msg "expected Int, given \\(→ Int Int\\)\n *expression: x") (typecheck-fail ((λ ([x : Int] [y : Int]) y) 1) #:with-msg "wrong number of arguments: expected 2, given 1") (check-type ((λ ([x : Int]) (plus x x)) 10) : Int ⇒ 20) (typecheck-fail (λ ([x : (→ 1 2)]) x) #:with-msg "not a well-formed type") (typecheck-fail (λ ([x : 1]) x) #:with-msg "not a well-formed type") (typecheck-fail (λ ([x : (plus 1 2)]) x) #:with-msg "not a well-formed type") (typecheck-fail (λ ([x : (λ ([y : Int]) y)]) x) #:with-msg "not a well-formed type") (typecheck-fail (ann (ann 5 : Int) : (→ Int)) #:with-msg "expected \\(→ Int\\), given Int\n *expression: \\(ann 5 : Int\\)")
null
https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-test/tests/turnstile/cmu15-814/stlc%2Bsum%2Brec-tests.rkt
racket
nil cons isnil hd tl old tests: should still pass tests for pairs ; TODO : check this lazy pairs test laziness sums testing form triggers ⇐ but not if no expected type supplied testing form triggers ⇐ but not if no expected type supplied old stlc tests: - make sure extension didnt break anything - Bool and String tests should now pass
#lang s-exp turnstile/examples/cmu15-814/stlc+sum+rec (require rackunit/turnstile) (define-type-alias IntList (μ (X) (+ Unit (× Int X)))) (define-type-alias ILBody (+ Unit (× Int IntList))) (define nil (fld {IntList} (inl (void) as ILBody))) (check-type nil : IntList) (check-type nil : (mu (X) (+ Unit (x Int X)))) (define cons (λ ([n : Int] [lst : IntList]) (fld {IntList} (inr (pair n lst) as ILBody)))) (check-type cons : (→ Int IntList IntList)) (check-type (cons 1 nil) : IntList) (typecheck-fail (cons 1 2)) (typecheck-fail (cons "1" nil)) (define isnil (λ ([lst : IntList]) (case (unfld {IntList} lst) [inl n => #t] [inr p => #f]))) (check-type isnil : (→ IntList Bool)) (check-type (isnil nil) : Bool ⇒ #t) (check-type (isnil (cons 1 nil)) : Bool ⇒ #f) (typecheck-fail (isnil 1)) (typecheck-fail (isnil (cons 1 2))) (check-type (λ ([f : (→ IntList Bool)]) (f nil)) : (→ (→ IntList Bool) Bool)) (check-type ((λ ([f : (→ IntList Bool)]) (f nil)) isnil) : Bool ⇒ #t) (define hd (λ ([lst : IntList]) (case (unfld {IntList} lst) [inl n => 0] [inr p => (fst p)]))) (check-type hd : (→ IntList Int)) (check-type (hd nil) : Int ⇒ 0) (typecheck-fail (hd 1)) (check-type (hd (cons 11 nil)) : Int ⇒ 11) (define tl (λ ([lst : IntList]) (case (unfld {IntList} lst) [inl n => lst] [inr p => (snd p)]))) (check-type tl : (→ IntList IntList)) (check-type (tl nil) : IntList ⇒ nil) (check-type (tl (cons 1 nil)) : IntList ⇒ nil) (check-type (tl (cons 1 (cons 2 nil))) : IntList ⇒ (cons 2 nil)) (typecheck-fail (tl 1)) some typecheck failure (typecheck-fail (fld {Int} 1) #:with-msg "Expected μ type, got: Int") (typecheck-fail (unfld {Int} 1) #:with-msg "Expected μ type, got: Int") (check-type (pair 1 2) : (× Int Int)) (check-type (pair 1 #f) : (× Int Bool)) (check-type (pair #f plus) : (× Bool (→ Int Int Int))) (check-type (fst (pair 1 #f)) : Int ⇒ 1) (check-type (snd (pair 1 #f)) : Bool ⇒ #f) (check-type ((snd (pair #f plus)) 1 2) : Int ⇒ 3) (typecheck-fail (fst 1)) (check-type (pair* 1 2) : (×* Int Int)) (check-type (pair* 1 #f) : (×* Int Bool)) (check-type (pair* #f plus) : (×* Bool (→ Int Int Int))) (check-type (fst (pair* 1 #f)) : Int ⇒ 1) (check-type (snd (pair* 1 #f)) : Bool ⇒ #f) (check-type ((snd (pair* #f plus)) 1 2) : Int ⇒ 3) (check-type (fst (pair* 1 (/ 1 0))) : Int -> 1) (check-runtime-exn (fst (pair 1 (/ 1 0)))) (check-type (inl "Steve" as (+ String Int)) : (+ String Int)) (check-type (inl "Steve" as (+ String Bool)) : (+ String Bool)) (typecheck-fail (inl "Steve" as (+ Bool String)) #:with-msg "expected Bool, given String") #:with-msg "no expected type, add annotations") (check-type (inr "Matthias" as (+ Int String)) : (+ Int String)) (check-type (inr "Matthias" as (+ Bool String)) : (+ Bool String)) (typecheck-fail (inr "Steve" as (+ String Bool)) #:with-msg "expected Bool, given String") #:with-msg "no expected type, add annotations") (typecheck-fail (inr "Matthias" as Int) #:with-msg "Expected \\+ type") (check-type (case (inl "Steve" as (+ String Int)) [inl x => x] [inr x => (number->string x)]) : String -> "Steve") (check-type (case (inr "Steve" as (+ Int String)) [inl x => (number->string x)] [inr x => x]) : String -> "Steve") (check-type (case (inl 1 as (+ Int String)) [inl x => (number->string x)] [inr x => x]) : String -> "1") (typecheck-fail (case (inr "Steve" as (+ Int String)) [inl x => x] [inr y => y]) #:with-msg "expected Int, given String.* expression: y") (typecheck-fail (case (inr "Steve" as (+ Int String)) [bad x => x] [inr y => y]) #:with-msg "expected the identifier.*inl.*at: bad") (typecheck-fail (case (inr "Steve" as (+ Int String)) [inl x => x] [inr y => y] [bad z => z]) #:with-msg "unexpected term.*at: \\(bad z => z\\)") (typecheck-fail (λ ([x : Undef]) x) #:with-msg "Undef: unbound identifier") (typecheck-fail (λ ([x : →]) x) #:with-msg "Improper usage of type constructor →.+expected >= 1 arguments") (typecheck-fail (λ ([x : (→)]) x) #:with-msg "Improper usage of type constructor →.+expected >= 1 arguments") (typecheck-fail (λ ([x : (→ →)]) x) #:with-msg "Improper usage of type constructor →.+expected >= 1 arguments") (check-type 1 : Int) (check-not-type 1 : (→ Int Int)) (check-type "one" : String) (check-type #f : Bool) (check-type (λ ([x : Int] [y : Int]) x) : (→ Int Int Int)) (check-not-type (λ ([x : Int]) x) : Int) (check-type (λ ([x : Int]) x) : (→ Int Int)) (check-type (λ ([f : (→ Int Int)]) 1) : (→ (→ Int Int) Int)) (check-type ((λ ([x : Int]) x) 1) : Int ⇒ 1) (typecheck-fail ((λ ([x : Bool]) x) 1) #:with-msg "expected Bool, given Int") (check-type (λ ([x : (→ Bool Bool)]) x) : (→ (→ Bool Bool) (→ Bool Bool))) (check-type (λ ([x : Bool]) x) : (→ Bool Bool)) (typecheck-fail (λ ([f : Int]) (f 1 2)) #:with-msg "Expected → type, got: Int") (check-type plus : (→ Int Int Int)) (check-type (λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y)) : (→ (→ Int Int Int) Int Int Int)) (check-type ((λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y)) plus 1 2) : Int ⇒ 3) (typecheck-fail (plus 1 (λ ([x : Int]) x)) #:with-msg "expected Int, given \\(→ Int Int\\)\n *expression: \\(λ \\(\\(x : Int\\)\\) x\\)") (typecheck-fail (λ ([x : (→ Int Int)]) (plus x x)) #:with-msg "expected Int, given \\(→ Int Int\\)\n *expression: x") (typecheck-fail ((λ ([x : Int] [y : Int]) y) 1) #:with-msg "wrong number of arguments: expected 2, given 1") (check-type ((λ ([x : Int]) (plus x x)) 10) : Int ⇒ 20) (typecheck-fail (λ ([x : (→ 1 2)]) x) #:with-msg "not a well-formed type") (typecheck-fail (λ ([x : 1]) x) #:with-msg "not a well-formed type") (typecheck-fail (λ ([x : (plus 1 2)]) x) #:with-msg "not a well-formed type") (typecheck-fail (λ ([x : (λ ([y : Int]) y)]) x) #:with-msg "not a well-formed type") (typecheck-fail (ann (ann 5 : Int) : (→ Int)) #:with-msg "expected \\(→ Int\\), given Int\n *expression: \\(ann 5 : Int\\)")
072472ae51fba8570ee1bde30654eb8f518cc7f3e1577b19e52507fc83283cc2
reactiveml/rml
firebug.mli
Js_of_ocaml library * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) * Firebug API ( debugging console ) . @see < > the Firebug console API @see <> the Firebug console API *) open Js class type console = object method log : _ -> unit meth method log_2 : _ -> _ -> unit meth method log_3 : _ -> _ -> _ -> unit meth method log_4 : _ -> _ -> _ -> _ -> unit meth method log_5 : _ -> _ -> _ -> _ -> _ -> unit meth method log_6 : _ -> _ -> _ -> _ -> _ -> _ -> unit meth method log_7 : _ -> _ -> _ -> _ -> _ -> _ -> _ -> unit meth method log_8 : _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> unit meth method debug : _ -> unit meth method debug_2 : _ -> _ -> unit meth method debug_3 : _ -> _ -> _ -> unit meth method debug_4 : _ -> _ -> _ -> _ -> unit meth method debug_5 : _ -> _ -> _ -> _ -> _ -> unit meth method info : _ -> unit meth method info_2 : _ -> _ -> unit meth method info_3 : _ -> _ -> _ -> unit meth method info_4 : _ -> _ -> _ -> _ -> unit meth method info_5 : _ -> _ -> _ -> _ -> _ -> unit meth method warn : _ -> unit meth method warn_2 : _ -> _ -> unit meth method warn_3 : _ -> _ -> _ -> unit meth method warn_4 : _ -> _ -> _ -> _ -> unit meth method warn_5 : _ -> _ -> _ -> _ -> _ -> unit meth method error : _ -> unit meth method error_2 : _ -> _ -> unit meth method error_3 : _ -> _ -> _ -> unit meth method error_4 : _ -> _ -> _ -> _ -> unit meth method error_5 : _ -> _ -> _ -> _ -> _ -> unit meth method assert_ : bool t -> unit meth method assert_1 : bool t -> _ -> unit meth method assert_2 : bool t -> _ -> _ -> unit meth method assert_3 : bool t -> _ -> _ -> _ -> unit meth method assert_4 : bool t -> _ -> _ -> _ -> _ -> unit meth method assert_5 : bool t -> _ -> _ -> _ -> _ -> _ -> unit meth method dir : _ -> unit meth method dirxml : Dom.node t -> unit meth method trace : unit meth method group : _ -> unit meth method group_2 : _ -> _ -> unit meth method group_3 : _ -> _ -> _ -> unit meth method group_4 : _ -> _ -> _ -> _ -> unit meth method group_5 : _ -> _ -> _ -> _ -> _ -> unit meth method groupCollapsed : _ -> unit meth method groupCollapsed_2 : _ -> _ -> unit meth method groupCollapsed_3 : _ -> _ -> _ -> unit meth method groupCollapsed_4 : _ -> _ -> _ -> _ -> unit meth method groupCollapsed_5 : _ -> _ -> _ -> _ -> _ -> unit meth method groupEnd : unit meth method time : js_string t -> unit meth method timeEnd : js_string t -> unit meth end val console : console t
null
https://raw.githubusercontent.com/reactiveml/rml/d178d49ed923290fa7eee642541bdff3ee90b3b4/toplevel-alt/js/js-of-ocaml/lib/firebug.mli
ocaml
Js_of_ocaml library * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) * Firebug API ( debugging console ) . @see < > the Firebug console API @see <> the Firebug console API *) open Js class type console = object method log : _ -> unit meth method log_2 : _ -> _ -> unit meth method log_3 : _ -> _ -> _ -> unit meth method log_4 : _ -> _ -> _ -> _ -> unit meth method log_5 : _ -> _ -> _ -> _ -> _ -> unit meth method log_6 : _ -> _ -> _ -> _ -> _ -> _ -> unit meth method log_7 : _ -> _ -> _ -> _ -> _ -> _ -> _ -> unit meth method log_8 : _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> unit meth method debug : _ -> unit meth method debug_2 : _ -> _ -> unit meth method debug_3 : _ -> _ -> _ -> unit meth method debug_4 : _ -> _ -> _ -> _ -> unit meth method debug_5 : _ -> _ -> _ -> _ -> _ -> unit meth method info : _ -> unit meth method info_2 : _ -> _ -> unit meth method info_3 : _ -> _ -> _ -> unit meth method info_4 : _ -> _ -> _ -> _ -> unit meth method info_5 : _ -> _ -> _ -> _ -> _ -> unit meth method warn : _ -> unit meth method warn_2 : _ -> _ -> unit meth method warn_3 : _ -> _ -> _ -> unit meth method warn_4 : _ -> _ -> _ -> _ -> unit meth method warn_5 : _ -> _ -> _ -> _ -> _ -> unit meth method error : _ -> unit meth method error_2 : _ -> _ -> unit meth method error_3 : _ -> _ -> _ -> unit meth method error_4 : _ -> _ -> _ -> _ -> unit meth method error_5 : _ -> _ -> _ -> _ -> _ -> unit meth method assert_ : bool t -> unit meth method assert_1 : bool t -> _ -> unit meth method assert_2 : bool t -> _ -> _ -> unit meth method assert_3 : bool t -> _ -> _ -> _ -> unit meth method assert_4 : bool t -> _ -> _ -> _ -> _ -> unit meth method assert_5 : bool t -> _ -> _ -> _ -> _ -> _ -> unit meth method dir : _ -> unit meth method dirxml : Dom.node t -> unit meth method trace : unit meth method group : _ -> unit meth method group_2 : _ -> _ -> unit meth method group_3 : _ -> _ -> _ -> unit meth method group_4 : _ -> _ -> _ -> _ -> unit meth method group_5 : _ -> _ -> _ -> _ -> _ -> unit meth method groupCollapsed : _ -> unit meth method groupCollapsed_2 : _ -> _ -> unit meth method groupCollapsed_3 : _ -> _ -> _ -> unit meth method groupCollapsed_4 : _ -> _ -> _ -> _ -> unit meth method groupCollapsed_5 : _ -> _ -> _ -> _ -> _ -> unit meth method groupEnd : unit meth method time : js_string t -> unit meth method timeEnd : js_string t -> unit meth end val console : console t
febc5bcbcd1a6e022f04ae64ae64fa3cca11155b08292d01b237be8c3ee3ed9b
hunt-framework/hunt
Common3.hs
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverlappingInstances #-} # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Common3 where import Control.Applicative ((<$>)) import Control.Arrow (first, second) import GHC.Exts (Constraint) import qualified Data.StringMap as SM import AssocTypes2 (Index(..), ContextWordMap, Compression(..), ByteString) -- ---------------------------------------- -- type aliases type DocId = Int type Context = String type Word = String type Document = String type Result = Maybe Occs type Occs = [(DocId, Positions)] type WordList = [(Word, Positions)] type Positions = [Int] -------------------------------------------- -- StringMap as index ... simple instance Index SM.StringMap where type IKey SM.StringMap v = Word type IVal SM.StringMap v = v type IToL SM.StringMap v = [(Word,v)] insert = SM.insert delete = SM.delete empty = SM.empty fromList = SM.fromList toList = SM.toList search = SM.prefixFindWithKey -------------------------------------------- -- how to integrate enum for different search operations? -- -- another "type" declaration? like: -- -- type IOp i v :: * search : : ( ICon i v ) = > IOp i v - > ... type IOp SM.StringMap v = TextIndex -- -- or with another composed key, like this: newtype PTText v = PTText (SM.StringMap v) data TextIndex = Case | NoCase -- | .. | .. | .. instance Index PTText where type IKey PTText v = (TextIndex, Word) type IVal PTText v = v type IToL PTText v = [(Word, v)] insert (_,k) v (PTText i) = PTText $ SM.insert k v i delete (_,k) (PTText i) = PTText $ SM.delete k i empty = PTText $ SM.empty fromList l = PTText $ SM.fromList l toList (PTText i) = SM.toList i search (Case,k) (PTText i) = SM.prefixFindWithKey k i search (NoCase,k) (PTText i) = SM.prefixFindWithKeyBF k i occs :: Occs occs = [(1, [1,2,6,8,44,77,32])] xs1, xs2 :: [(String, Occs)] xs1 = [("word1", [(1, [1,5,7])])] xs2 = [("word2", [(4, [3,5,7])])] type Inverted = ContextWordMap SM.StringMap Occs cx1, cx2, cx3, cx4, cx5, cx6, cx7, cx8 :: Inverted cx1 = fromList [("A",xs1),("B",xs2)] cx2 = insert (Just "C", Just "111") occs cx1 cx3 = insert (Just "A", Just "111") occs cx2 cx4 = insert (Nothing, Just "ddd") occs cx3 cx5 = delete (Nothing, Just "ddd") cx4 cx6 = delete (Just "A", Just "abc") cx5 cx7 = delete (Just "A", Nothing) cx6 cx8 = delete (Nothing, Nothing) cx7
null
https://raw.githubusercontent.com/hunt-framework/hunt/d692aae756b7bdfb4c99f5a3951aec12893649a8/hunt-test/test/Common3.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE OverlappingInstances # ---------------------------------------- type aliases ------------------------------------------ StringMap as index ... simple ------------------------------------------ how to integrate enum for different search operations? another "type" declaration? like: type IOp i v :: * or with another composed key, like this: | .. | .. | ..
# LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Common3 where import Control.Applicative ((<$>)) import Control.Arrow (first, second) import GHC.Exts (Constraint) import qualified Data.StringMap as SM import AssocTypes2 (Index(..), ContextWordMap, Compression(..), ByteString) type DocId = Int type Context = String type Word = String type Document = String type Result = Maybe Occs type Occs = [(DocId, Positions)] type WordList = [(Word, Positions)] type Positions = [Int] instance Index SM.StringMap where type IKey SM.StringMap v = Word type IVal SM.StringMap v = v type IToL SM.StringMap v = [(Word,v)] insert = SM.insert delete = SM.delete empty = SM.empty fromList = SM.fromList toList = SM.toList search = SM.prefixFindWithKey search : : ( ICon i v ) = > IOp i v - > ... type IOp SM.StringMap v = TextIndex newtype PTText v = PTText (SM.StringMap v) instance Index PTText where type IKey PTText v = (TextIndex, Word) type IVal PTText v = v type IToL PTText v = [(Word, v)] insert (_,k) v (PTText i) = PTText $ SM.insert k v i delete (_,k) (PTText i) = PTText $ SM.delete k i empty = PTText $ SM.empty fromList l = PTText $ SM.fromList l toList (PTText i) = SM.toList i search (Case,k) (PTText i) = SM.prefixFindWithKey k i search (NoCase,k) (PTText i) = SM.prefixFindWithKeyBF k i occs :: Occs occs = [(1, [1,2,6,8,44,77,32])] xs1, xs2 :: [(String, Occs)] xs1 = [("word1", [(1, [1,5,7])])] xs2 = [("word2", [(4, [3,5,7])])] type Inverted = ContextWordMap SM.StringMap Occs cx1, cx2, cx3, cx4, cx5, cx6, cx7, cx8 :: Inverted cx1 = fromList [("A",xs1),("B",xs2)] cx2 = insert (Just "C", Just "111") occs cx1 cx3 = insert (Just "A", Just "111") occs cx2 cx4 = insert (Nothing, Just "ddd") occs cx3 cx5 = delete (Nothing, Just "ddd") cx4 cx6 = delete (Just "A", Just "abc") cx5 cx7 = delete (Just "A", Nothing) cx6 cx8 = delete (Nothing, Nothing) cx7
a483eec7f7954a99e44f85e777bdfd95a36647cc7912d625faa3c0e9586731bb
ygrek/ocaml-extlib
refList.ml
* RefList - List reference * Copyright ( C ) 2003 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * RefList - List reference * Copyright (C) 2003 Nicolas Cannasse * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) open ExtList exception Empty_list exception Invalid_index of int type 'a t = 'a list ref let empty () = ref [] let is_empty x = match !x with | [] -> true | _ -> false let of_list l = ref l let to_list rl = !rl let copy ~dst ~src = dst := !src let copy_list ~dst ~src = dst := src let add rl item = rl := List.append !rl [item] let push rl item = rl := item::!rl let clear rl = rl := [] let length rl = List.length !rl let hd rl = try List.hd !rl with _ -> raise Empty_list let tl rl = try ref (List.tl !rl) with _ -> raise Empty_list let iter f rl = List.iter f !rl let for_all f rl = List.for_all f !rl let map f rl = ref (List.map f !rl) let transform f rl = rl := List.map f !rl let map_list f rl = List.map f !rl let find f rl = List.find f !rl let rev rl = rl := List.rev !rl let find_exc f exn rl = try List.find f !rl with _ -> raise exn let exists f rl = List.exists f !rl let sort ?(cmp=compare) rl = rl := List.sort ~cmp !rl let rfind f rl = List.rfind f !rl let first = hd let last rl = let rec loop = function | x :: [] -> x | x :: l -> loop l | [] -> assert false in match !rl with | [] -> raise Empty_list | l -> loop l let remove rl item = rl := List.remove !rl item let remove_if pred rl = rl := List.remove_if pred !rl let remove_all rl item = rl := List.remove_all !rl item let filter pred rl = rl := List.filter pred !rl let add_sort ?(cmp=compare) rl item = let rec add_aux = function | x::lnext as l -> let r = cmp x item in if r < 0 then item::l else x::(add_aux lnext) | [] -> [item] in rl := add_aux !rl let pop rl = match !rl with | [] -> raise Empty_list | e::l -> rl := l; e let npop rl n = let rec pop_aux l n = if n = 0 then begin rl := l; [] end else match l with | [] -> raise Empty_list | x::l -> x::(pop_aux l (n-1)) in pop_aux !rl n let copy_enum ~dst ~src = dst := List.of_enum src let enum rl = List.enum !rl let of_enum e = ref (List.of_enum e) module Index = struct let remove_at rl pos = let p = ref (-1) in let rec del_aux = function | x::l -> incr p; if !p = pos then l else x::(del_aux l) | [] -> raise (Invalid_index pos) in rl := del_aux !rl let index pred rl = let index = ref (-1) in let _ = List.find (fun it -> incr index; pred it; ) !rl in !index let index_of rl item = let index = ref (-1) in let _ = List.find (fun it -> incr index; it = item; ) !rl in !index let at_index rl pos = try List.nth !rl pos with _ -> raise (Invalid_index pos) let set rl pos newitem = let p = ref (-1) in rl := List.map (fun item -> incr p; if !p = pos then newitem else item) !rl; if !p < pos || pos < 0 then raise (Invalid_index pos) end
null
https://raw.githubusercontent.com/ygrek/ocaml-extlib/0779f7a881c76f9aca3d5445e2f063ba38a76167/src/refList.ml
ocaml
* RefList - List reference * Copyright ( C ) 2003 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * RefList - List reference * Copyright (C) 2003 Nicolas Cannasse * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) open ExtList exception Empty_list exception Invalid_index of int type 'a t = 'a list ref let empty () = ref [] let is_empty x = match !x with | [] -> true | _ -> false let of_list l = ref l let to_list rl = !rl let copy ~dst ~src = dst := !src let copy_list ~dst ~src = dst := src let add rl item = rl := List.append !rl [item] let push rl item = rl := item::!rl let clear rl = rl := [] let length rl = List.length !rl let hd rl = try List.hd !rl with _ -> raise Empty_list let tl rl = try ref (List.tl !rl) with _ -> raise Empty_list let iter f rl = List.iter f !rl let for_all f rl = List.for_all f !rl let map f rl = ref (List.map f !rl) let transform f rl = rl := List.map f !rl let map_list f rl = List.map f !rl let find f rl = List.find f !rl let rev rl = rl := List.rev !rl let find_exc f exn rl = try List.find f !rl with _ -> raise exn let exists f rl = List.exists f !rl let sort ?(cmp=compare) rl = rl := List.sort ~cmp !rl let rfind f rl = List.rfind f !rl let first = hd let last rl = let rec loop = function | x :: [] -> x | x :: l -> loop l | [] -> assert false in match !rl with | [] -> raise Empty_list | l -> loop l let remove rl item = rl := List.remove !rl item let remove_if pred rl = rl := List.remove_if pred !rl let remove_all rl item = rl := List.remove_all !rl item let filter pred rl = rl := List.filter pred !rl let add_sort ?(cmp=compare) rl item = let rec add_aux = function | x::lnext as l -> let r = cmp x item in if r < 0 then item::l else x::(add_aux lnext) | [] -> [item] in rl := add_aux !rl let pop rl = match !rl with | [] -> raise Empty_list | e::l -> rl := l; e let npop rl n = let rec pop_aux l n = if n = 0 then begin rl := l; [] end else match l with | [] -> raise Empty_list | x::l -> x::(pop_aux l (n-1)) in pop_aux !rl n let copy_enum ~dst ~src = dst := List.of_enum src let enum rl = List.enum !rl let of_enum e = ref (List.of_enum e) module Index = struct let remove_at rl pos = let p = ref (-1) in let rec del_aux = function | x::l -> incr p; if !p = pos then l else x::(del_aux l) | [] -> raise (Invalid_index pos) in rl := del_aux !rl let index pred rl = let index = ref (-1) in let _ = List.find (fun it -> incr index; pred it; ) !rl in !index let index_of rl item = let index = ref (-1) in let _ = List.find (fun it -> incr index; it = item; ) !rl in !index let at_index rl pos = try List.nth !rl pos with _ -> raise (Invalid_index pos) let set rl pos newitem = let p = ref (-1) in rl := List.map (fun item -> incr p; if !p = pos then newitem else item) !rl; if !p < pos || pos < 0 then raise (Invalid_index pos) end
55b3d1c5e933c75bce9d07478627a8f500ae07b3ecc82780660d37017c3d6fdc
grin-compiler/ghc-wpc-sample-programs
Null.hs
# OPTIONS_GHC -fno - warn - orphans # | Overloaded @null@ and @empty@ for collections and sequences . module Agda.Utils.Null where import Prelude hiding (null) import Control.Monad import Control.Monad.Reader import Control.Monad.State import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as ByteString import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.HashSet (HashSet) import qualified Data.HashSet as HashSet import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.Set (Set) import qualified Data.Set as Set import Text.PrettyPrint (Doc) import Agda.Utils.Bag (Bag) import qualified Agda.Utils.Bag as Bag import Agda.Utils.Impossible class Null a where empty :: a null :: a -> Bool ^ Satisfying @null empty = = True@. default null :: Eq a => a -> Bool null = (== empty) instance Null () where empty = () null _ = True instance (Null a, Null b) => Null (a,b) where empty = (empty, empty) null (a,b) = null a && null b instance Null ByteString where empty = ByteString.empty null = ByteString.null instance Null [a] where empty = [] null = List.null instance Null (Bag a) where empty = Bag.empty null = Bag.null instance Null (IntMap a) where empty = IntMap.empty null = IntMap.null instance Null IntSet where empty = IntSet.empty null = IntSet.null instance Null (Map k a) where empty = Map.empty null = Map.null instance Null (HashMap k a) where empty = HashMap.empty null = HashMap.null instance Null (HashSet a) where empty = HashSet.empty null = HashSet.null instance Null (Seq a) where empty = Seq.empty null = Seq.null instance Null (Set a) where empty = Set.empty null = Set.null -- | A 'Maybe' is 'null' when it corresponds to the empty list. instance Null (Maybe a) where empty = Nothing null Nothing = True null (Just a) = False instance Null Doc where empty = mempty null = (== mempty) instance (Null (m a), Monad m) => Null (ReaderT r m a) where empty = lift empty null = __IMPOSSIBLE__ instance (Null (m a), Monad m) => Null (StateT r m a) where empty = lift empty null = __IMPOSSIBLE__ -- * Testing for null. ifNull :: (Null a) => a -> b -> (a -> b) -> b ifNull a b k = if null a then b else k a ifNotNull :: (Null a) => a -> (a -> b) -> b -> b ifNotNull a k b = ifNull a b k ifNullM :: (Monad m, Null a) => m a -> m b -> (a -> m b) -> m b ifNullM ma mb k = ma >>= \ a -> ifNull a mb k ifNotNullM :: (Monad m, Null a) => m a -> (a -> m b) -> m b -> m b ifNotNullM ma k mb = ifNullM ma mb k whenNull :: (Monad m, Null a) => a -> m () -> m () whenNull = when . null unlessNull :: (Monad m, Null a) => a -> (a -> m ()) -> m () unlessNull a k = unless (null a) $ k a whenNullM :: (Monad m, Null a) => m a -> m () -> m () whenNullM ma k = ma >>= (`whenNull` k) unlessNullM :: (Monad m, Null a) => m a -> (a -> m ()) -> m () unlessNullM ma k = ma >>= (`unlessNull` k)
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Utils/Null.hs
haskell
| A 'Maybe' is 'null' when it corresponds to the empty list. * Testing for null.
# OPTIONS_GHC -fno - warn - orphans # | Overloaded @null@ and @empty@ for collections and sequences . module Agda.Utils.Null where import Prelude hiding (null) import Control.Monad import Control.Monad.Reader import Control.Monad.State import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as ByteString import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.HashSet (HashSet) import qualified Data.HashSet as HashSet import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.Set (Set) import qualified Data.Set as Set import Text.PrettyPrint (Doc) import Agda.Utils.Bag (Bag) import qualified Agda.Utils.Bag as Bag import Agda.Utils.Impossible class Null a where empty :: a null :: a -> Bool ^ Satisfying @null empty = = True@. default null :: Eq a => a -> Bool null = (== empty) instance Null () where empty = () null _ = True instance (Null a, Null b) => Null (a,b) where empty = (empty, empty) null (a,b) = null a && null b instance Null ByteString where empty = ByteString.empty null = ByteString.null instance Null [a] where empty = [] null = List.null instance Null (Bag a) where empty = Bag.empty null = Bag.null instance Null (IntMap a) where empty = IntMap.empty null = IntMap.null instance Null IntSet where empty = IntSet.empty null = IntSet.null instance Null (Map k a) where empty = Map.empty null = Map.null instance Null (HashMap k a) where empty = HashMap.empty null = HashMap.null instance Null (HashSet a) where empty = HashSet.empty null = HashSet.null instance Null (Seq a) where empty = Seq.empty null = Seq.null instance Null (Set a) where empty = Set.empty null = Set.null instance Null (Maybe a) where empty = Nothing null Nothing = True null (Just a) = False instance Null Doc where empty = mempty null = (== mempty) instance (Null (m a), Monad m) => Null (ReaderT r m a) where empty = lift empty null = __IMPOSSIBLE__ instance (Null (m a), Monad m) => Null (StateT r m a) where empty = lift empty null = __IMPOSSIBLE__ ifNull :: (Null a) => a -> b -> (a -> b) -> b ifNull a b k = if null a then b else k a ifNotNull :: (Null a) => a -> (a -> b) -> b -> b ifNotNull a k b = ifNull a b k ifNullM :: (Monad m, Null a) => m a -> m b -> (a -> m b) -> m b ifNullM ma mb k = ma >>= \ a -> ifNull a mb k ifNotNullM :: (Monad m, Null a) => m a -> (a -> m b) -> m b -> m b ifNotNullM ma k mb = ifNullM ma mb k whenNull :: (Monad m, Null a) => a -> m () -> m () whenNull = when . null unlessNull :: (Monad m, Null a) => a -> (a -> m ()) -> m () unlessNull a k = unless (null a) $ k a whenNullM :: (Monad m, Null a) => m a -> m () -> m () whenNullM ma k = ma >>= (`whenNull` k) unlessNullM :: (Monad m, Null a) => m a -> (a -> m ()) -> m () unlessNullM ma k = ma >>= (`unlessNull` k)
9cf9ebd3f63b52c487ed82ca7f7e6aaefec823243161bed4c11e722fd916a692
clojure/tools.build
copy.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.tools.build.tasks.copy (:require [clojure.string :as str] [clojure.tools.build.api :as api] [clojure.tools.build.util.file :as file]) (:import [java.io File] [java.nio.file FileSystems FileVisitor FileVisitResult Files Path LinkOption])) (set! *warn-on-reflection* true) ;; copy spec: : from ( coll of dirs ) , default = [ " . " ] ;; ;include (glob), default = "**" ;; :replace (map of replacements) - performed while copying (defn- match-paths "Match glob to paths under root and return a collection of Path objects" [^File root glob] (let [root-path (.toPath root) matcher (.getPathMatcher (FileSystems/getDefault) (str "glob:" glob)) paths (volatile! []) visitor (reify FileVisitor (visitFile [_ path _attrs] (when (.matches matcher (.relativize root-path ^Path path)) (vswap! paths conj path)) FileVisitResult/CONTINUE) (visitFileFailed [_ _path _ex] FileVisitResult/CONTINUE) (preVisitDirectory [_ _ _] FileVisitResult/CONTINUE) (postVisitDirectory [_ _ _] FileVisitResult/CONTINUE))] (Files/walkFileTree root-path visitor) @paths)) (def default-ignores [".*~$" "^#.*#$" "^\\.#.*" "^.DS_Store$"]) (defn ignore? [name ignore-regexes] (boolean (some #(re-matches % name) ignore-regexes))) (def default-non-replaced-exts ["jpg" "jpeg" "png" "gif" "bmp"]) (defn- ends-with-ext? [exts path] (loop [[ext & es] exts] (if ext (if (str/ends-with? path ext) true (recur es)) false))) (defn copy [{:keys [target-dir src-dirs include replace ignores non-replaced-exts] :or {include "**", ignores default-ignores, non-replaced-exts default-non-replaced-exts} :as _params}] (let [to-path (.toPath (file/ensure-dir (api/resolve-path target-dir))) ignore-regexes (map re-pattern ignores) non-replaced (map #(str "." %) default-non-replaced-exts)] (doseq [dir src-dirs] ;(println "from" dir) (let [from-file (api/resolve-path dir) paths (match-paths from-file include)] (doseq [^Path path paths] (let [path-file (.toFile path) path-file-name (.getName path-file) target-file (.toFile (.resolve to-path (.relativize (.toPath from-file) path)))] (when-not (ignore? path-file-name ignore-regexes) ;(println "copying" (.toString path-file) (.toString target-file) (boolean (not (empty? replace)))) (if (or (empty? replace) (ends-with-ext? non-replaced (.getName path-file))) (file/copy-file path-file target-file) (let [contents (slurp path-file) replaced (reduce (fn [s [find replace]] (str/replace s find replace)) contents replace) perms (when (contains? (.supportedFileAttributeViews (FileSystems/getDefault)) "posix") (Files/getPosixFilePermissions (.toPath path-file) (into-array LinkOption [LinkOption/NOFOLLOW_LINKS])))] (file/ensure-file target-file replaced :append false) (when perms (Files/setPosixFilePermissions (.toPath target-file) perms) nil))))))))))
null
https://raw.githubusercontent.com/clojure/tools.build/0563a69670437fb236df9c08d3cb74e1e378aefb/src/main/clojure/clojure/tools/build/tasks/copy.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. copy spec: ;include (glob), default = "**" :replace (map of replacements) - performed while copying (println "from" dir) (println "copying" (.toString path-file) (.toString target-file) (boolean (not (empty? replace))))
Copyright ( c ) . All rights reserved . (ns clojure.tools.build.tasks.copy (:require [clojure.string :as str] [clojure.tools.build.api :as api] [clojure.tools.build.util.file :as file]) (:import [java.io File] [java.nio.file FileSystems FileVisitor FileVisitResult Files Path LinkOption])) (set! *warn-on-reflection* true) : from ( coll of dirs ) , default = [ " . " ] (defn- match-paths "Match glob to paths under root and return a collection of Path objects" [^File root glob] (let [root-path (.toPath root) matcher (.getPathMatcher (FileSystems/getDefault) (str "glob:" glob)) paths (volatile! []) visitor (reify FileVisitor (visitFile [_ path _attrs] (when (.matches matcher (.relativize root-path ^Path path)) (vswap! paths conj path)) FileVisitResult/CONTINUE) (visitFileFailed [_ _path _ex] FileVisitResult/CONTINUE) (preVisitDirectory [_ _ _] FileVisitResult/CONTINUE) (postVisitDirectory [_ _ _] FileVisitResult/CONTINUE))] (Files/walkFileTree root-path visitor) @paths)) (def default-ignores [".*~$" "^#.*#$" "^\\.#.*" "^.DS_Store$"]) (defn ignore? [name ignore-regexes] (boolean (some #(re-matches % name) ignore-regexes))) (def default-non-replaced-exts ["jpg" "jpeg" "png" "gif" "bmp"]) (defn- ends-with-ext? [exts path] (loop [[ext & es] exts] (if ext (if (str/ends-with? path ext) true (recur es)) false))) (defn copy [{:keys [target-dir src-dirs include replace ignores non-replaced-exts] :or {include "**", ignores default-ignores, non-replaced-exts default-non-replaced-exts} :as _params}] (let [to-path (.toPath (file/ensure-dir (api/resolve-path target-dir))) ignore-regexes (map re-pattern ignores) non-replaced (map #(str "." %) default-non-replaced-exts)] (doseq [dir src-dirs] (let [from-file (api/resolve-path dir) paths (match-paths from-file include)] (doseq [^Path path paths] (let [path-file (.toFile path) path-file-name (.getName path-file) target-file (.toFile (.resolve to-path (.relativize (.toPath from-file) path)))] (when-not (ignore? path-file-name ignore-regexes) (if (or (empty? replace) (ends-with-ext? non-replaced (.getName path-file))) (file/copy-file path-file target-file) (let [contents (slurp path-file) replaced (reduce (fn [s [find replace]] (str/replace s find replace)) contents replace) perms (when (contains? (.supportedFileAttributeViews (FileSystems/getDefault)) "posix") (Files/getPosixFilePermissions (.toPath path-file) (into-array LinkOption [LinkOption/NOFOLLOW_LINKS])))] (file/ensure-file target-file replaced :append false) (when perms (Files/setPosixFilePermissions (.toPath target-file) perms) nil))))))))))
a76eb1db5c0f4b5df700f567cf885bb78b34d6ef7fe627e3d54275d48ba034dd
ocaml-multicore/tezos
gas_monad.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs < > Copyright ( c ) 2021 , < > (* *) (* 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 Alpha_context (* The outer option is for gas exhaustion. The inner [result] is for all other errors. *) type ('a, 'trace) t = Local_gas_counter.local_gas_counter -> (('a, 'trace) result * Local_gas_counter.local_gas_counter) option type ('a, 'trace) gas_monad = ('a, 'trace) t let of_result x gas = Some (x, gas) let return x = of_result (ok x) let return_unit = return () (* Inlined [Option.bind] for performance. *) let ( >>?? ) m f = match m with None -> None | Some x -> f x [@@ocaml.inline always] let ( >>$ ) m f gas = m gas >>?? fun (res, gas) -> match res with Ok y -> f y gas | Error _ as err -> of_result err gas let ( >|$ ) m f gas = m gas >>?? fun (x, gas) -> of_result (x >|? f) gas let ( >?$ ) m f = m >>$ fun x -> of_result (f x) let ( >??$ ) m f gas = m gas >>?? fun (x, gas) -> f x gas let consume_gas cost gas = match Local_gas_counter.consume_opt gas cost with | None -> None | Some gas -> Some (ok (), gas) let run ctxt m = let open Local_gas_counter in match Gas.level ctxt with | Gas.Unaccounted -> ( match m (Local_gas_counter (Saturation_repr.saturated :> int)) with | Some (res, _new_gas_counter) -> ok (res, ctxt) | None -> error Gas.Operation_quota_exceeded) | Limited {remaining = _} -> ( let (gas_counter, outdated_ctxt) = local_gas_counter_and_outdated_context ctxt in match m gas_counter with | Some (res, new_gas_counter) -> let ctxt = update_context new_gas_counter outdated_ctxt in ok (res, ctxt) | None -> error Gas.Operation_quota_exceeded) let record_trace_eval : type error_trace. error_details:error_trace Script_tc_errors.error_details -> (unit -> error) -> ('a, error_trace) t -> ('a, error_trace) t = fun ~error_details -> match error_details with | Fast -> fun _f m -> m | Informative -> fun f m gas -> m gas >>?? fun (x, gas) -> of_result (record_trace_eval f x) gas
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/gas_monad.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, 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. 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 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** The outer option is for gas exhaustion. The inner [result] is for all other errors. Inlined [Option.bind] for performance.
Copyright ( c ) 2021 Nomadic Labs < > Copyright ( c ) 2021 , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Alpha_context type ('a, 'trace) t = Local_gas_counter.local_gas_counter -> (('a, 'trace) result * Local_gas_counter.local_gas_counter) option type ('a, 'trace) gas_monad = ('a, 'trace) t let of_result x gas = Some (x, gas) let return x = of_result (ok x) let return_unit = return () let ( >>?? ) m f = match m with None -> None | Some x -> f x [@@ocaml.inline always] let ( >>$ ) m f gas = m gas >>?? fun (res, gas) -> match res with Ok y -> f y gas | Error _ as err -> of_result err gas let ( >|$ ) m f gas = m gas >>?? fun (x, gas) -> of_result (x >|? f) gas let ( >?$ ) m f = m >>$ fun x -> of_result (f x) let ( >??$ ) m f gas = m gas >>?? fun (x, gas) -> f x gas let consume_gas cost gas = match Local_gas_counter.consume_opt gas cost with | None -> None | Some gas -> Some (ok (), gas) let run ctxt m = let open Local_gas_counter in match Gas.level ctxt with | Gas.Unaccounted -> ( match m (Local_gas_counter (Saturation_repr.saturated :> int)) with | Some (res, _new_gas_counter) -> ok (res, ctxt) | None -> error Gas.Operation_quota_exceeded) | Limited {remaining = _} -> ( let (gas_counter, outdated_ctxt) = local_gas_counter_and_outdated_context ctxt in match m gas_counter with | Some (res, new_gas_counter) -> let ctxt = update_context new_gas_counter outdated_ctxt in ok (res, ctxt) | None -> error Gas.Operation_quota_exceeded) let record_trace_eval : type error_trace. error_details:error_trace Script_tc_errors.error_details -> (unit -> error) -> ('a, error_trace) t -> ('a, error_trace) t = fun ~error_details -> match error_details with | Fast -> fun _f m -> m | Informative -> fun f m gas -> m gas >>?? fun (x, gas) -> of_result (record_trace_eval f x) gas
44a631b32e3c852ddfe82c4c498c53200e8fd7ab2f12bfcf3464fd34cfdc4751
deobald/sicp-clojure
ex2_29_group.clj
(ns sec2_2.ex2_29_group (:use clojure.test)) (defn make-mobile [left right] (list left right)) (defn make-branch [length structure] (list length structure)) ; a. Write the corresponding selectors left-branch and right-branch, which return the branches of the mobile, and ; branch-length and branch-structure which return the components of a branch. (defn left-branch [mobile] (first mobile)) (defn right-branch [mobile] (first (rest mobile))) (defn branch-length [branch] (first branch)) (defn branch-structure [branch] (first (rest branch))) ; b. Using those selectors, define a procedure total-weight that returns the total weight of a mobile. (defn total-weight [mobile] (if (seq? (fnext mobile)) (+ (total-weight first) (total-weight fnext)) (fnext mobile))) (deftest should-weigh-an-ultra-simple-mobile (is (= 1 (total-weight '(3 1))))) (deftest should-weigh-a-simple-mobile (let [left (make-branch 2 3) right (make-branch 2 5)] (is (= 8 (total-weight (make-mobile left right)))))) (deftest should-weigh-a-complex-mobile (let [left-1 (make-branch 2 3) left-2 (make-branch 2 5) left-mobile (make-mobile left-1 left-2) left (make-branch 2 left-mobile) right (make-branch 2 9)] (is (= 17 (total-weight (make-mobile left right)))))) ; c. Design a predicate that tests whether a binary mobile is balanced. ;(deftest a-mobile-is-balanced-if-both-branches-have-equal-torque ( let [ left ( make - branch 2 3 ) right ( make - branch 2 3 ) ; mobile (make-mobile left right)] ; (is (balanced? mobile)))) ; ( deftest a - mobile - is - not - balanced - if - one - branch - has - more - torque - than - the - other ( let [ left ( make - branch 2 3 ) right ( make - branch 2 4 ) ; mobile (make-mobile left right)] ; (is (not (balanced? mobile))))) ; d. Suppose we change the constructors to use 'cons' (scheme). How much do you need to change the programs ; to convert to the new representation? answer : only the selectors need to change , given a scheme - style cons . ( car / cdr vs. car ) (run-all-tests #"ex.*")
null
https://raw.githubusercontent.com/deobald/sicp-clojure/fc24e5114604e7a0510dab779bbff962aac7ee7e/src/sec2_2/ex2_29_group.clj
clojure
a. Write the corresponding selectors left-branch and right-branch, which return the branches of the mobile, and branch-length and branch-structure which return the components of a branch. b. Using those selectors, define a procedure total-weight that returns the total weight of a mobile. c. Design a predicate that tests whether a binary mobile is balanced. (deftest a-mobile-is-balanced-if-both-branches-have-equal-torque mobile (make-mobile left right)] (is (balanced? mobile)))) mobile (make-mobile left right)] (is (not (balanced? mobile))))) d. Suppose we change the constructors to use 'cons' (scheme). How much do you need to change the programs to convert to the new representation?
(ns sec2_2.ex2_29_group (:use clojure.test)) (defn make-mobile [left right] (list left right)) (defn make-branch [length structure] (list length structure)) (defn left-branch [mobile] (first mobile)) (defn right-branch [mobile] (first (rest mobile))) (defn branch-length [branch] (first branch)) (defn branch-structure [branch] (first (rest branch))) (defn total-weight [mobile] (if (seq? (fnext mobile)) (+ (total-weight first) (total-weight fnext)) (fnext mobile))) (deftest should-weigh-an-ultra-simple-mobile (is (= 1 (total-weight '(3 1))))) (deftest should-weigh-a-simple-mobile (let [left (make-branch 2 3) right (make-branch 2 5)] (is (= 8 (total-weight (make-mobile left right)))))) (deftest should-weigh-a-complex-mobile (let [left-1 (make-branch 2 3) left-2 (make-branch 2 5) left-mobile (make-mobile left-1 left-2) left (make-branch 2 left-mobile) right (make-branch 2 9)] (is (= 17 (total-weight (make-mobile left right)))))) ( let [ left ( make - branch 2 3 ) right ( make - branch 2 3 ) ( deftest a - mobile - is - not - balanced - if - one - branch - has - more - torque - than - the - other ( let [ left ( make - branch 2 3 ) right ( make - branch 2 4 ) answer : only the selectors need to change , given a scheme - style cons . ( car / cdr vs. car ) (run-all-tests #"ex.*")
95d15c9d7967884f1bc66b726dced738e17697949d449ac459cd0317c308e46d
takikawa/racket-ppa
phase+space.rkt
(module phase+space '#%kernel (#%require "private/qq-and-or.rkt") (#%provide phase? space? phase+space phase+space? phase+space-shift? phase+space-phase phase+space-space phase+space+ phase+space-shift+) (define-values (phase?) (lambda (v) (or (not v) (exact-integer? v)))) (define-values (interned-symbol?) (lambda (v) (and (symbol? v) (symbol-interned? v)))) (define-values (space?) (lambda (v) (or (not v) (interned-symbol? v)))) (define-values (phase+space?) (lambda (v) (or (phase? v) (and (pair? v) (interned-symbol? (cdr v)) (phase? (car v)))))) (define-values (phase+space) (lambda (phase space) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (begin (if (phase? phase) (void) (raise-argument-error 'phase+space "phase?" phase)) (if (space? space) (void) (raise-argument-error 'phase+space "space?" space)))) (if space (cons phase space) phase))) (define-values (phase+space-shift?) (lambda (v) (or (phase? v) (and (pair? v) (or (not (cdr v)) (interned-symbol? (cdr v))) (phase? (car v)))))) (define-values (phase+space-phase) (lambda (p+s) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (if (phase+space? p+s) (void) (raise-argument-error 'phase+space-phase "phase+space?" p+s))) (if (pair? p+s) (car p+s) p+s))) (define-values (phase+space-space) (lambda (p+s) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (if (phase+space? p+s) (void) (raise-argument-error 'phase+space-space "phase+space?" p+s))) (and (pair? p+s) (cdr p+s)))) (define-values (phase+space+) (lambda (p+s s) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (begin (if (phase+space? p+s) (void) (raise-argument-error 'phase+space+ "phase+space?" p+s)) (if (phase+space-shift? s) (void) (raise-argument-error 'phase+space+ "phase+space-shift?" s)))) (let ([p1 (if (pair? p+s) (car p+s) p+s)] [p2 (if (pair? s) (car s) s)] [sp1 (and (pair? p+s) (cdr p+s))]) (let ([p (and p1 p2 (+ p1 p2))] [sp (if (pair? s) (cdr s) sp1)]) (if sp (cons p sp) p))))) (define-values (phase+space-shift+) (lambda (s1 s2) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (begin (if (phase+space-shift? s1) (void) (raise-argument-error 'phase+space+ "phase+space-shift?" s1)) (if (phase+space-shift? s2) (void) (raise-argument-error 'phase+space+ "phase+space-shift?" s2)))) (let ([p1 (if (pair? s1) (car s1) s1)] [p2 (if (pair? s2) (car s2) s2)]) (let ([p (and p1 p2 (+ p1 p2))]) (if (pair? s2) (cons p (cdr s2)) (if (pair? s1) (cons p (cdr s1)) p)))))))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/d336bb10e3e0ec3a20020e9ade9e77d2f6f80b6d/collects/racket/phase%2Bspace.rkt
racket
(module phase+space '#%kernel (#%require "private/qq-and-or.rkt") (#%provide phase? space? phase+space phase+space? phase+space-shift? phase+space-phase phase+space-space phase+space+ phase+space-shift+) (define-values (phase?) (lambda (v) (or (not v) (exact-integer? v)))) (define-values (interned-symbol?) (lambda (v) (and (symbol? v) (symbol-interned? v)))) (define-values (space?) (lambda (v) (or (not v) (interned-symbol? v)))) (define-values (phase+space?) (lambda (v) (or (phase? v) (and (pair? v) (interned-symbol? (cdr v)) (phase? (car v)))))) (define-values (phase+space) (lambda (phase space) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (begin (if (phase? phase) (void) (raise-argument-error 'phase+space "phase?" phase)) (if (space? space) (void) (raise-argument-error 'phase+space "space?" space)))) (if space (cons phase space) phase))) (define-values (phase+space-shift?) (lambda (v) (or (phase? v) (and (pair? v) (or (not (cdr v)) (interned-symbol? (cdr v))) (phase? (car v)))))) (define-values (phase+space-phase) (lambda (p+s) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (if (phase+space? p+s) (void) (raise-argument-error 'phase+space-phase "phase+space?" p+s))) (if (pair? p+s) (car p+s) p+s))) (define-values (phase+space-space) (lambda (p+s) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (if (phase+space? p+s) (void) (raise-argument-error 'phase+space-space "phase+space?" p+s))) (and (pair? p+s) (cdr p+s)))) (define-values (phase+space+) (lambda (p+s s) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (begin (if (phase+space? p+s) (void) (raise-argument-error 'phase+space+ "phase+space?" p+s)) (if (phase+space-shift? s) (void) (raise-argument-error 'phase+space+ "phase+space-shift?" s)))) (let ([p1 (if (pair? p+s) (car p+s) p+s)] [p2 (if (pair? s) (car s) s)] [sp1 (and (pair? p+s) (cdr p+s))]) (let ([p (and p1 p2 (+ p1 p2))] [sp (if (pair? s) (cdr s) sp1)]) (if sp (cons p sp) p))))) (define-values (phase+space-shift+) (lambda (s1 s2) (if (variable-reference-from-unsafe? (#%variable-reference)) (void) (begin (if (phase+space-shift? s1) (void) (raise-argument-error 'phase+space+ "phase+space-shift?" s1)) (if (phase+space-shift? s2) (void) (raise-argument-error 'phase+space+ "phase+space-shift?" s2)))) (let ([p1 (if (pair? s1) (car s1) s1)] [p2 (if (pair? s2) (car s2) s2)]) (let ([p (and p1 p2 (+ p1 p2))]) (if (pair? s2) (cons p (cdr s2)) (if (pair? s1) (cons p (cdr s1)) p)))))))
5634fb939d6c4ee9cf1527b8ad1f35aa8d9307b1a05faf00d2bf97aca478ecb2
robert-strandh/SICL
establish-call-sites.lisp
(cl:in-package #:sicl-compiler) (defun call-site-name (instruction) (typecase instruction (cleavir-ir:named-call-instruction (cleavir-ir:callee-name instruction)) (cleavir-ir:enclose-instruction 'sicl-run-time:enclose) (cleavir-ir:catch-instruction 'sicl-run-time:augment-with-block/tagbody-entry) (cleavir-ir:dynamic-catch-instruction 'sicl-run-time:augment-with-catch-entry) (cleavir-ir:bind-instruction 'sicl-run-time:augment-with-special-variable-entry) (cleavir-ir:unwind-protect-instruction 'sicl-run-time:augment-with-unwind-protect-entry) (cleavir-ir:unwind-instruction 'sicl-run-time:unwind) (cleavir-ir:initialize-values-instruction ;; FIXME: Use a better function. 'error) (cleavir-ir:multiple-value-call-instruction 'sicl-run-time:call-with-values) (cleavir-ir:save-values-instruction 'sicl-run-time:save-values) (cleavir-ir:restore-values-instruction 'sicl-run-time:restore-values) (sicl-ir:patch-literal-instruction 'sicl-run-time:resolve-load-time-value))) (defun establish-call-site (instruction) (change-class instruction 'sicl-ir:named-call-instruction :function-cell-cell (list nil)) (make-instance 'call-site :name (call-site-name instruction) :instruction instruction)) (defun establish-call-sites (ir) (let ((call-sites '())) (cleavir-ir:map-instructions-arbitrary-order (lambda (instruction) (when (typep instruction 'cleavir-ir:named-call-instruction) (push (establish-call-site instruction) call-sites))) ir) call-sites))
null
https://raw.githubusercontent.com/robert-strandh/SICL/4ce7ab169055b55aff760f28f1217ff16d7e81b2/Code/Compiler/AST-compiler/establish-call-sites.lisp
lisp
FIXME: Use a better function.
(cl:in-package #:sicl-compiler) (defun call-site-name (instruction) (typecase instruction (cleavir-ir:named-call-instruction (cleavir-ir:callee-name instruction)) (cleavir-ir:enclose-instruction 'sicl-run-time:enclose) (cleavir-ir:catch-instruction 'sicl-run-time:augment-with-block/tagbody-entry) (cleavir-ir:dynamic-catch-instruction 'sicl-run-time:augment-with-catch-entry) (cleavir-ir:bind-instruction 'sicl-run-time:augment-with-special-variable-entry) (cleavir-ir:unwind-protect-instruction 'sicl-run-time:augment-with-unwind-protect-entry) (cleavir-ir:unwind-instruction 'sicl-run-time:unwind) (cleavir-ir:initialize-values-instruction 'error) (cleavir-ir:multiple-value-call-instruction 'sicl-run-time:call-with-values) (cleavir-ir:save-values-instruction 'sicl-run-time:save-values) (cleavir-ir:restore-values-instruction 'sicl-run-time:restore-values) (sicl-ir:patch-literal-instruction 'sicl-run-time:resolve-load-time-value))) (defun establish-call-site (instruction) (change-class instruction 'sicl-ir:named-call-instruction :function-cell-cell (list nil)) (make-instance 'call-site :name (call-site-name instruction) :instruction instruction)) (defun establish-call-sites (ir) (let ((call-sites '())) (cleavir-ir:map-instructions-arbitrary-order (lambda (instruction) (when (typep instruction 'cleavir-ir:named-call-instruction) (push (establish-call-site instruction) call-sites))) ir) call-sites))
4c63904219009572b76cd2c23bc05a14889d315f5854957766c7c393c5d28ba6
jackfirth/rebellion
binding.rkt
#lang racket/base (require racket/contract/base) (provide record-id (contract-out [record-binding? predicate/c] [record-binding-type (-> record-binding? record-type?)] [record-binding-descriptor (-> record-binding? identifier?)] [record-binding-predicate (-> record-binding? identifier?)] [record-binding-constructor (-> record-binding? identifier?)] [record-binding-accessor (-> record-binding? identifier?)] [record-binding-fields (-> record-binding? (vectorof identifier? #:immutable #t))] [record-binding-field-accessors (-> record-binding? (vectorof identifier? #:immutable #t))])) (module+ private-constructor (provide (contract-out [record-binding (-> #:type record-type? #:descriptor identifier? #:predicate identifier? #:constructor identifier? #:accessor identifier? #:fields (sequence/c identifier?) #:field-accessors (sequence/c identifier?) #:pattern identifier? #:macro (-> syntax? syntax?) record-binding?)]))) (require (for-template racket/base racket/match) racket/sequence racket/syntax rebellion/collection/keyset/low-dependency rebellion/type/record/base syntax/parse) ;@------------------------------------------------------------------------------ (struct record-binding (type descriptor predicate constructor accessor fields field-accessors pattern macro) #:omit-define-syntaxes #:constructor-name constructor:record-binding #:property prop:match-expander (λ (this stx) (define/with-syntax pattern (record-binding-pattern this)) (syntax-parse stx #:track-literals [(_ . body) (quasisyntax/loc stx (pattern . body))])) #:property prop:procedure (λ (this stx) ((record-binding-macro this) stx))) (define (record-binding #:type type #:descriptor descriptor #:predicate predicate #:constructor constructor #:accessor accessor #:fields fields #:field-accessors field-accessors #:pattern pattern #:macro macro) (define field-vector (vector->immutable-vector (for/vector ([field fields]) field))) (define field-accessor-vector (vector->immutable-vector (for/vector ([field-accessor field-accessors]) field-accessor))) (constructor:record-binding type descriptor predicate constructor accessor field-vector field-accessor-vector pattern macro)) (define-syntax-class record-id #:attributes (type binding name descriptor predicate constructor accessor [field 1] [field-name 1] [field-keyword 1] [field-accessor 1]) (pattern binding-id #:declare binding-id (static record-binding? "a static record-binding? value") #:attr binding (attribute binding-id.value) #:attr type (record-binding-type (attribute binding)) #:with name #`'#,(record-type-name (attribute type)) #:with descriptor (record-binding-descriptor (attribute binding)) #:with predicate (record-binding-predicate (attribute binding)) #:with constructor (record-binding-constructor (attribute binding)) #:with accessor (record-binding-accessor (attribute binding)) #:with (field ...) (sequence->list (record-binding-fields (attribute binding))) #:with (field-name ...) (for/list ([field-kw (in-keyset (record-type-fields (attribute type)))]) #`'#,(string->symbol (keyword->string field-kw))) #:with (field-keyword ...) (sequence->list (record-type-fields (attribute type))) #:with (field-accessor ...) (sequence->list (record-binding-field-accessors (attribute binding)))))
null
https://raw.githubusercontent.com/jackfirth/rebellion/64f8f82ac3343fe632388bfcbb9e537759ac1ac2/type/record/binding.rkt
racket
@------------------------------------------------------------------------------
#lang racket/base (require racket/contract/base) (provide record-id (contract-out [record-binding? predicate/c] [record-binding-type (-> record-binding? record-type?)] [record-binding-descriptor (-> record-binding? identifier?)] [record-binding-predicate (-> record-binding? identifier?)] [record-binding-constructor (-> record-binding? identifier?)] [record-binding-accessor (-> record-binding? identifier?)] [record-binding-fields (-> record-binding? (vectorof identifier? #:immutable #t))] [record-binding-field-accessors (-> record-binding? (vectorof identifier? #:immutable #t))])) (module+ private-constructor (provide (contract-out [record-binding (-> #:type record-type? #:descriptor identifier? #:predicate identifier? #:constructor identifier? #:accessor identifier? #:fields (sequence/c identifier?) #:field-accessors (sequence/c identifier?) #:pattern identifier? #:macro (-> syntax? syntax?) record-binding?)]))) (require (for-template racket/base racket/match) racket/sequence racket/syntax rebellion/collection/keyset/low-dependency rebellion/type/record/base syntax/parse) (struct record-binding (type descriptor predicate constructor accessor fields field-accessors pattern macro) #:omit-define-syntaxes #:constructor-name constructor:record-binding #:property prop:match-expander (λ (this stx) (define/with-syntax pattern (record-binding-pattern this)) (syntax-parse stx #:track-literals [(_ . body) (quasisyntax/loc stx (pattern . body))])) #:property prop:procedure (λ (this stx) ((record-binding-macro this) stx))) (define (record-binding #:type type #:descriptor descriptor #:predicate predicate #:constructor constructor #:accessor accessor #:fields fields #:field-accessors field-accessors #:pattern pattern #:macro macro) (define field-vector (vector->immutable-vector (for/vector ([field fields]) field))) (define field-accessor-vector (vector->immutable-vector (for/vector ([field-accessor field-accessors]) field-accessor))) (constructor:record-binding type descriptor predicate constructor accessor field-vector field-accessor-vector pattern macro)) (define-syntax-class record-id #:attributes (type binding name descriptor predicate constructor accessor [field 1] [field-name 1] [field-keyword 1] [field-accessor 1]) (pattern binding-id #:declare binding-id (static record-binding? "a static record-binding? value") #:attr binding (attribute binding-id.value) #:attr type (record-binding-type (attribute binding)) #:with name #`'#,(record-type-name (attribute type)) #:with descriptor (record-binding-descriptor (attribute binding)) #:with predicate (record-binding-predicate (attribute binding)) #:with constructor (record-binding-constructor (attribute binding)) #:with accessor (record-binding-accessor (attribute binding)) #:with (field ...) (sequence->list (record-binding-fields (attribute binding))) #:with (field-name ...) (for/list ([field-kw (in-keyset (record-type-fields (attribute type)))]) #`'#,(string->symbol (keyword->string field-kw))) #:with (field-keyword ...) (sequence->list (record-type-fields (attribute type))) #:with (field-accessor ...) (sequence->list (record-binding-field-accessors (attribute binding)))))
7b68ffdecd6880946a6bf487580b8689bb59fec1a71b9cbc264cf3491361c414
janestreet/bonsai
user_state.ml
open! Core open! Async type t = { user : string ; connection : Rpc.Connection.t }
null
https://raw.githubusercontent.com/janestreet/bonsai/761d04847d5f947318b64c0a46dffa17ad413536/examples/open_source/rpc_chat/server/src/user_state.ml
ocaml
open! Core open! Async type t = { user : string ; connection : Rpc.Connection.t }
367b6fc5eded219b0fa03aafbdc59ec7aa74c6333877281725826b330c62c95b
data61/Mirza
EntityDataAPI.hs
module Main where import qualified Mirza.EntityDataAPI.Main as M main :: IO () main = M.main
null
https://raw.githubusercontent.com/data61/Mirza/24e5ccddfc307cceebcc5ce26d35e91020b8ee10/projects/entity-data-api/app/EntityDataAPI.hs
haskell
module Main where import qualified Mirza.EntityDataAPI.Main as M main :: IO () main = M.main
150708e4c173195b4cc5969b0e03f9fd2dbc873f874712e73b1b39b107d22f82
Dasudian/DSDIN
dsdc_next_nonce_tests.erl
-module(dsdc_next_nonce_tests). -include_lib("eunit/include/eunit.hrl"). -include("blocks.hrl"). -define(TEST_MODULE, dsdc_next_nonce). -define(PUBKEY, <<"BAAggMEhrC3ODBqlYeQ6dk00F87AKMkV6kkyhgfJ/luOzGUC+4APxFkVgAYPai3TjSyLRObv0GeDACg1ZxwnfHY=">>). pick_for_account_test_() -> {foreach, fun() -> meck:new(dsdc_chain), meck:new(dsdc_tx_pool) end, fun(_) -> meck:unload(dsdc_chain), meck:unload(dsdc_tx_pool) end, [{"Return account_not_found when both top block state tree and mempool are empty", fun() -> meck:expect(dsdc_chain, get_account, fun(?PUBKEY) -> none end), meck:expect(dsdc_tx_pool, get_max_nonce, fun(?PUBKEY) -> undefined end), ?assertEqual({error, account_not_found}, ?TEST_MODULE:pick_for_account(?PUBKEY)) end}, {"Return incremented state tree nonce for account existing in state tree and empty mempool", fun() -> Account = dsdc_accounts:set_nonce(dsdc_accounts:new(?PUBKEY, 0), 8), meck:expect(dsdc_chain, get_account, fun(?PUBKEY) -> {value, Account} end), meck:expect(dsdc_tx_pool, get_max_nonce, fun(?PUBKEY) -> undefined end), ?assertEqual({ok, 9}, ?TEST_MODULE:pick_for_account(?PUBKEY)) end}, {"Return [max(mempool account nonce, state tree account nonce) + 1] for account present in state and having txs in mempool", fun() -> Account = dsdc_accounts:set_nonce(dsdc_accounts:new(?PUBKEY, 0), 8), meck:expect(dsdc_chain, get_account, fun(?PUBKEY) -> {value, Account} end), meck:expect(dsdc_tx_pool, get_max_nonce, fun(?PUBKEY) -> {ok, 12} end), ?assertEqual({ok, 13}, ?TEST_MODULE:pick_for_account(?PUBKEY)) end}]}.
null
https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdcore/test/dsdc_next_nonce_tests.erl
erlang
-module(dsdc_next_nonce_tests). -include_lib("eunit/include/eunit.hrl"). -include("blocks.hrl"). -define(TEST_MODULE, dsdc_next_nonce). -define(PUBKEY, <<"BAAggMEhrC3ODBqlYeQ6dk00F87AKMkV6kkyhgfJ/luOzGUC+4APxFkVgAYPai3TjSyLRObv0GeDACg1ZxwnfHY=">>). pick_for_account_test_() -> {foreach, fun() -> meck:new(dsdc_chain), meck:new(dsdc_tx_pool) end, fun(_) -> meck:unload(dsdc_chain), meck:unload(dsdc_tx_pool) end, [{"Return account_not_found when both top block state tree and mempool are empty", fun() -> meck:expect(dsdc_chain, get_account, fun(?PUBKEY) -> none end), meck:expect(dsdc_tx_pool, get_max_nonce, fun(?PUBKEY) -> undefined end), ?assertEqual({error, account_not_found}, ?TEST_MODULE:pick_for_account(?PUBKEY)) end}, {"Return incremented state tree nonce for account existing in state tree and empty mempool", fun() -> Account = dsdc_accounts:set_nonce(dsdc_accounts:new(?PUBKEY, 0), 8), meck:expect(dsdc_chain, get_account, fun(?PUBKEY) -> {value, Account} end), meck:expect(dsdc_tx_pool, get_max_nonce, fun(?PUBKEY) -> undefined end), ?assertEqual({ok, 9}, ?TEST_MODULE:pick_for_account(?PUBKEY)) end}, {"Return [max(mempool account nonce, state tree account nonce) + 1] for account present in state and having txs in mempool", fun() -> Account = dsdc_accounts:set_nonce(dsdc_accounts:new(?PUBKEY, 0), 8), meck:expect(dsdc_chain, get_account, fun(?PUBKEY) -> {value, Account} end), meck:expect(dsdc_tx_pool, get_max_nonce, fun(?PUBKEY) -> {ok, 12} end), ?assertEqual({ok, 13}, ?TEST_MODULE:pick_for_account(?PUBKEY)) end}]}.
2945e9789e70985a195423814e94f428e38978d6427e912a06462e848a1418fb
aeternity/app_ctrl
app_ctrl_server.erl
-*- mode : erlang ; erlang - indent - level : 4 ; indent - tabs - mode : nil -*- %%%------------------------------------------------------------------- ( C ) 2018 - 22 , Aeternity Anstalt %%% @hidden %%%------------------------------------------------------------------- -module(app_ctrl_server). -behaviour(gen_server). -export([ start/0 , start_link/0]). -export([ status/0 , running/2 , stopped/2 , get_mode/0 , set_mode/1 , should_i_run/1 , ok_to_start/1 , ok_to_stop/1 , check_dependencies/1 , is_mode_stable/0 , await_stable_mode/1 , check_for_new_applications/0 ]). -export([whereis/0]). -export([graph/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(st, { controllers = [] , role_apps = [] , allowed_apps = [] , other_apps = [] , live_map = #{} , running_where = #{} , pending_stable = [] , mode , stable = false , graph}). -define(PROTECTED_MODE, app_ctrl_protected). %% hard-coded app list -include_lib("kernel/include/logger.hrl"). %% This is used when the server is bootstrapped from the logger handler, %% since the handler is initialized from a temporary process. start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], []). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). status() -> gen_server:call(?MODULE, status). whereis() -> whereis(?MODULE). running(App, Node) -> gen_server:cast(?MODULE, {app_running, App, Node}). stopped(App, Node) -> gen_server:cast(?MODULE, {app_stopped, App, Node}). get_mode() -> gen_server:call(?MODULE, get_mode). set_mode(Mode) -> case gen_server:call(?MODULE, {set_mode, Mode}) of ok -> app_ctrl_config:set_current_mode(Mode), ok; Error -> Error end. check_dependencies(Deps) -> gen_server:call(?MODULE, {check, Deps}). should_i_run(App) -> gen_server:call(?MODULE, {should_i_run, App}). ok_to_start(App) -> gen_server:call(?MODULE, {ok_to_start, App}). ok_to_stop(App) -> gen_server:call(?MODULE, {ok_to_stop, App}). is_mode_stable() -> gen_server:call(?MODULE, is_mode_stable). await_stable_mode(Timeout) -> %% We don't want the call itself to time out. %% Assume that the server will never get stuck. gen_server:call(?MODULE, {await_stable_mode, Timeout}, infinity). check_for_new_applications() -> gen_server:call(?MODULE, check_for_new_applications). graph() -> gen_server:call(?MODULE, graph). init([]) -> St = init_state(#st{}), {ok, set_current_mode(?PROTECTED_MODE, St)}. init_state(#st{} = St0) -> case St0#st.graph of undefined -> ok; G0 -> digraph:delete(G0) end, #{graph := G, annotated := Deps} = app_ctrl_deps:dependencies(), RoleApps = app_ctrl_deps:role_apps(), %% all apps controlled via roles ?LOG_DEBUG(#{role_apps => RoleApps}), RoleAppDeps = deps_of_apps(RoleApps, G), case [A || A <- RoleAppDeps, not lists:member(A, RoleApps)] of [] -> %% For now, assume that apps are never removed from the system Controllers = start_new_controllers(Deps, St0#st.controllers), ?LOG_DEBUG("Controllers = ~p", [lists:sort(Controllers)]), OtherApps = [A || {A,_} <- Controllers, not lists:member(A, RoleApps)], St0#st{ controllers = Controllers , role_apps = RoleApps , other_apps = OtherApps , graph = G}; Orphans -> ?LOG_ERROR(#{apps_not_found => Orphans}), error({orphans, Orphans}) end. deps_of_apps(As, G) -> lists:foldl( fun(A, Acc) -> lists:foldl(fun ordsets:add_element/2, Acc, app_ctrl_deps:get_dependencies_of_app(G, A)) end, ordsets:new(), As). handle_call({check, Deps}, _From, #st{} = St) -> {reply, check_(Deps, St), St}; handle_call(get_mode, _From, #st{mode = CurMode} = St) -> {reply, CurMode, St}; handle_call({set_mode, Mode}, _From, #st{mode = CurMode} = St) -> ?LOG_DEBUG("set_mode: ~p (CurMode = ~p)", [Mode, CurMode]), case Mode of CurMode -> {reply, ok, St}; _ -> case app_ctrl_deps:valid_mode(Mode) of true -> St1 = set_current_mode(Mode, St), announce_new_mode(Mode, St1), {reply, ok, St1}; false -> {reply, {error, unknown_mode}, St} end end; handle_call({should_i_run, App}, _From, #st{ allowed_apps = Allowed , other_apps = Other } = St) -> {reply, (lists:member(App, Allowed) orelse lists:member(App, Other)), St}; handle_call({ok_to_start, App}, _From, #st{mode = M} = St) -> ?LOG_DEBUG("ok_to_start ~p, mode = ~p", [App, M]), {reply, ok_to_start_(App, St), St}; handle_call({ok_to_stop, App}, _From, #st{graph = G} = St) -> case [A || {_,A,App1,{start_after,App1}} <- in_edges(G, App), App1 =:= App, is_running(A, St)] of [] -> {reply, true, St}; [_|_] = Other -> {reply, {false, [{A, still_running} || A <- Other]}, St} end; handle_call(graph, _From, #st{graph = G} = St) -> {reply, G, St}; handle_call(status, _From, St) -> {reply, status_(St), St}; handle_call(is_mode_stable, _From, St) -> {reply, is_stable(St), St}; handle_call({await_stable_mode, Timeout}, From, #st{pending_stable = Pending} = St) -> case St#st.stable of true -> {reply, {ok, St#st.mode}, St}; false -> TRef = set_timeout(Timeout, {awaiting_stable, From}), {noreply, St#st{pending_stable = [{From, TRef} | Pending]}} end; handle_call(check_for_new_applications, _From, #st{ mode = Mode , allowed_apps = Allowed0} = St0) -> St = init_state(St0), case allowed_apps(St#st.mode, St) of Allowed0 -> {reply, ok, St}; NewAllowedApps -> St1 = St#st{allowed_apps = NewAllowedApps}, case St1#st.stable of false -> {reply, ok, St1}; true -> announce_new_mode(Mode, St1), {reply, ok, St1#st{stable = false}} end end; handle_call(_Req, _From, St) -> {reply, {error, unknown_call}, St}. handle_cast({app_running, App, Node}, #st{mode = Mode} = St0) -> St = note_running({App, Node}, true, St0), tell_controllers(app_running, App, Node, St), publish_event(app_running, {App, Node}, St), case {Mode, App} of {?PROTECTED_MODE, app_ctrl} -> ?LOG_DEBUG("Moving to default mode", []), {noreply, set_next_mode(St)}; _ -> {noreply, check_if_stable(St)} end; handle_cast({app_stopped, App, Node}, #st{} = St0) -> St = note_running({App, Node}, false, St0), tell_controllers(app_stopped, App, Node, St), publish_event(app_stopped, {App, Node}, St), {noreply, check_if_stable(St)}; handle_cast(_Msg, St) -> {noreply, St}. handle_info({timeout, TRef, {awaiting_stable, From}}, #st{pending_stable = Pend} = St) -> case lists:keytake(TRef, 2, Pend) of {value, {From, _}, Pend1} -> case is_stable(St) of true -> {noreply, notify_pending({ok, St#st.mode}, St#st{stable = true})}; {false, Outstanding} -> gen_server:reply(From, {timeout, Outstanding}), {noreply, St#st{pending_stable = Pend1}} end; false -> {noreply, St} end; handle_info(_Msg, St) -> {noreply, St}. terminate(_Reason, _St) -> ok. code_change(_FromVsn, St, _Extra) -> {ok, St}. start_new_controllers(AnnotatedDeps, Controllers) -> [ start_controller(A) || {{A,N} = AppNode, _Deps} <- AnnotatedDeps, N =:= node(), not lists:member(A, [kernel, stdlib]) andalso not lists:keymember(A, 1, Controllers) andalso not load_only(AppNode) ] ++ Controllers. announce_new_mode(Mode, St) -> tell_controllers({new_mode, Mode}, St), publish_event(new_mode, Mode, St). tell_controllers(Event, App, Node, #st{controllers = Cs}) -> ?LOG_DEBUG("tell_controllers(~p, ~p, ~p)", [Event, App, Node]), [gen_server:cast(Pid, {Event, App, Node}) || {_, Pid} <- Cs], ok. tell_controllers(Event, #st{controllers = Cs}) -> ?LOG_DEBUG("tell_controllers(~p)", [Event]), [gen_server:cast(Pid, Event) || {_, Pid} <- Cs], ok. start_controller(A) -> {ok, Pid} = app_ctrl_ctrl:start_link(A), {A, Pid}. note_running(A, Bool, #st{live_map = Map, running_where = Where} = St) when is_boolean(Bool) -> {AppName, Node} = A, Map1 = maps:update_with(A, fun(M0) -> M = maps:without([ongoing], M0), M#{running => Bool} end, #{running => Bool}, Map), Where1 = case Bool of true -> maps:update_with(AppName, fun(Ns) -> ordsets:add_element(Node, Ns) end, ordsets:from_list([Node]), Where); false -> maps:update_with(AppName, fun(Ns) -> ordsets:del_element(Node, Ns) end, ordsets:new(), Where) end, St#st{live_map = Map1, running_where = Where1}. check_(Deps, St) -> case check_(Deps, St, []) of [] -> true; Other -> {false, Other} end. check_([{App, N} = A|Deps], St, Acc) when is_atom(App), N == node() -> case (is_running(A, St) orelse load_only(A)) of true -> check_(Deps, St, Acc); false -> check_(Deps, St, [{App, not_running}|Acc]) end; check_([], _St, Acc) -> Acc. load_only({App, N}) when N == node() -> case application:get_key(App, mod) of {ok, {_, _}} -> false; {ok, []} -> true; undefined -> true end. is_running({_App,N} = A, #st{live_map = Map}) when N == node() -> case maps:find(A, Map) of {ok, #{running := Bool}} -> Bool; error -> false end. set_timeout(infinity, _) -> infinity; set_timeout(T, Msg) when is_integer(T), T >= 0 -> erlang:start_timer(T, self(), Msg). check_if_stable(#st{mode = Mode} = St) -> case is_stable(St) of true -> notify_pending({ok, Mode}, St#st{stable = true}); {false, _Outstanding} -> St end. is_stable(#st{} = St) -> case not_running(St) ++ not_stopped(St) of [] -> true; Other -> {false, Other} end. not_running(#st{allowed_apps = Allowed} = St) -> opt_attr(not_running, [A || A <- Allowed, not is_running({A, node()}, St)]). not_stopped(#st{allowed_apps = Allowed, role_apps = RApps} = St) -> opt_attr(not_stopped, [R || R <- (RApps -- Allowed), is_running({R, node()}, St)]). opt_attr(_ , []) -> []; opt_attr(Key, L) -> [{Key, L}]. notify_pending(Msg, #st{pending_stable = Pend} = St) -> lists:foreach( fun({From, TRef}) -> erlang:cancel_timer(TRef), gen_server:reply(From, Msg) end, Pend), St#st{pending_stable = []}. publish_event(_, _, #st{mode = ?PROTECTED_MODE}) -> ok; publish_event(Event, Info, _St) -> app_ctrl_events:publish(Event, Info). in_edges(G, App) -> [digraph:edge(G, E) || E <- digraph:in_edges(G, App)]. out_edges(G, App) -> [digraph:edge(G, E) || E <- digraph:out_edges(G, App)]. allowed_apps(undefined, #st{controllers = Cs}) -> lists:sort([A || {A, _} <- Cs]); allowed_apps(?PROTECTED_MODE, #st{controllers = Cs} = St) -> any_active(protected_mode_apps(St), Cs); allowed_apps(Mode, #st{role_apps = _RApps, controllers = _Cs}) -> _AppsInMode = lists:sort(app_ctrl_deps:apps_in_mode(Mode)). %% OtherControlled = [A || {A,_} <- Cs, not lists : member(A , RApps ) ] , %% AppsInMode ++ [A || A <- OtherControlled, not lists : member(A , ) ] . set_next_mode(St) -> Mode = app_ctrl_config:current_mode(), St1 = set_current_mode(Mode, St), announce_new_mode(Mode, St1), St1. set_current_mode(Mode, #st{} = St) -> Allowed = allowed_apps(Mode, St), St#st{mode = Mode, allowed_apps = Allowed, stable = false}. any_active(As, Cs) -> intersection(As, [A || {A, _} <- Cs]). protected_mode_apps(#st{graph = G}) -> Res = app_ctrl_config:protected_mode_apps(), ?LOG_DEBUG("protected_mode_apps = ~p", [Res]), Expanded = add_deps(Res, G), ?LOG_DEBUG("Expanded = ~p", [Expanded]), Expanded. add_deps(Apps, G) -> lists:foldr(fun(A, Acc) -> add_deps_(A, G, Acc) end, Apps, Apps). add_deps_(A, G, Acc) -> Deps = app_ctrl_deps:get_app_dependencies(G, A), case Deps -- Acc of [] -> Acc; New -> lists:foldr(fun(A1, Acc1) -> add_deps_(A1, G, Acc1) end, add_to_ordset(New, Acc), New) end. add_to_ordset(Xs, Set) -> lists:foldr(fun ordsets:add_element/2, Set, Xs). intersection(A, B) -> A -- (A -- B). status_(#st{mode = Mode, allowed_apps = AApps, role_apps = RApps} = St) -> Modes = app_ctrl_config:modes(), Roles = app_ctrl_config:roles(), #{ current_mode => Mode , current_roles => proplists:get_value(Mode, app_ctrl_config:modes()) , running_locally => running_locally(St) , running_remotely => running_remotely(St) , allowed_apps => [A1 || {_, Status} = A1 <- [ {A, runnable_app_status(A, St)} || A <- AApps ], Status =/= load_only] , role_apps => [ {A, controlled_app_status(A, Modes, Roles)} || A <- RApps] }. running_locally(#st{running_where = R}) -> maps:filter( fun(_App, Ns) -> ordsets:is_element(node(), Ns) end, R). running_remotely(#st{running_where = R}) -> maps:filter( fun(_App, Ns) -> not ordsets:is_empty( ordsets:del_element(node(), Ns)) end, R). runnable_app_status(A, St) -> ?LOG_DEBUG("runnable_app_status(~p, St)", [A]), TODO : fix this when adding distributed ctrl case is_running(AppNode, St) of true -> running; false -> case load_only(AppNode) of true -> load_only; false -> case ok_to_start_(A, St) of true -> ok_to_start; {false, Why} -> {not_started, Why} end end end. controlled_app_status(A, Modes, Roles) -> InRoles = [R || {R, As} <- Roles, lists:member(A, As)], InModes = [M || {M, Rs} <- Modes, intersection(InRoles, Rs) =/= []], #{ in_roles => InRoles , in_modes => InModes }. ok_to_start_(App, #st{allowed_apps = Allowed, other_apps = Other, graph = G} = St) -> case lists:member(App, Allowed) orelse lists:member(App, Other) of true -> case [A || {_,_,A,{start_after,_}} <- out_edges(G, App), not (is_running(A, St) orelse load_only(A))] of [] -> true; [_|_] = Other -> {false, [{A, not_running} || A <- Other]} end; false -> {false, not_allowed} end.
null
https://raw.githubusercontent.com/aeternity/app_ctrl/c1fb92758ab7add4489837eff3a7d5d44b925dd2/src/app_ctrl_server.erl
erlang
------------------------------------------------------------------- @hidden ------------------------------------------------------------------- hard-coded app list This is used when the server is bootstrapped from the logger handler, since the handler is initialized from a temporary process. We don't want the call itself to time out. Assume that the server will never get stuck. all apps controlled via roles For now, assume that apps are never removed from the system OtherControlled = [A || {A,_} <- Cs, AppsInMode ++ [A || A <- OtherControlled,
-*- mode : erlang ; erlang - indent - level : 4 ; indent - tabs - mode : nil -*- ( C ) 2018 - 22 , Aeternity Anstalt -module(app_ctrl_server). -behaviour(gen_server). -export([ start/0 , start_link/0]). -export([ status/0 , running/2 , stopped/2 , get_mode/0 , set_mode/1 , should_i_run/1 , ok_to_start/1 , ok_to_stop/1 , check_dependencies/1 , is_mode_stable/0 , await_stable_mode/1 , check_for_new_applications/0 ]). -export([whereis/0]). -export([graph/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(st, { controllers = [] , role_apps = [] , allowed_apps = [] , other_apps = [] , live_map = #{} , running_where = #{} , pending_stable = [] , mode , stable = false , graph}). -include_lib("kernel/include/logger.hrl"). start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], []). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). status() -> gen_server:call(?MODULE, status). whereis() -> whereis(?MODULE). running(App, Node) -> gen_server:cast(?MODULE, {app_running, App, Node}). stopped(App, Node) -> gen_server:cast(?MODULE, {app_stopped, App, Node}). get_mode() -> gen_server:call(?MODULE, get_mode). set_mode(Mode) -> case gen_server:call(?MODULE, {set_mode, Mode}) of ok -> app_ctrl_config:set_current_mode(Mode), ok; Error -> Error end. check_dependencies(Deps) -> gen_server:call(?MODULE, {check, Deps}). should_i_run(App) -> gen_server:call(?MODULE, {should_i_run, App}). ok_to_start(App) -> gen_server:call(?MODULE, {ok_to_start, App}). ok_to_stop(App) -> gen_server:call(?MODULE, {ok_to_stop, App}). is_mode_stable() -> gen_server:call(?MODULE, is_mode_stable). await_stable_mode(Timeout) -> gen_server:call(?MODULE, {await_stable_mode, Timeout}, infinity). check_for_new_applications() -> gen_server:call(?MODULE, check_for_new_applications). graph() -> gen_server:call(?MODULE, graph). init([]) -> St = init_state(#st{}), {ok, set_current_mode(?PROTECTED_MODE, St)}. init_state(#st{} = St0) -> case St0#st.graph of undefined -> ok; G0 -> digraph:delete(G0) end, #{graph := G, annotated := Deps} = app_ctrl_deps:dependencies(), ?LOG_DEBUG(#{role_apps => RoleApps}), RoleAppDeps = deps_of_apps(RoleApps, G), case [A || A <- RoleAppDeps, not lists:member(A, RoleApps)] of [] -> Controllers = start_new_controllers(Deps, St0#st.controllers), ?LOG_DEBUG("Controllers = ~p", [lists:sort(Controllers)]), OtherApps = [A || {A,_} <- Controllers, not lists:member(A, RoleApps)], St0#st{ controllers = Controllers , role_apps = RoleApps , other_apps = OtherApps , graph = G}; Orphans -> ?LOG_ERROR(#{apps_not_found => Orphans}), error({orphans, Orphans}) end. deps_of_apps(As, G) -> lists:foldl( fun(A, Acc) -> lists:foldl(fun ordsets:add_element/2, Acc, app_ctrl_deps:get_dependencies_of_app(G, A)) end, ordsets:new(), As). handle_call({check, Deps}, _From, #st{} = St) -> {reply, check_(Deps, St), St}; handle_call(get_mode, _From, #st{mode = CurMode} = St) -> {reply, CurMode, St}; handle_call({set_mode, Mode}, _From, #st{mode = CurMode} = St) -> ?LOG_DEBUG("set_mode: ~p (CurMode = ~p)", [Mode, CurMode]), case Mode of CurMode -> {reply, ok, St}; _ -> case app_ctrl_deps:valid_mode(Mode) of true -> St1 = set_current_mode(Mode, St), announce_new_mode(Mode, St1), {reply, ok, St1}; false -> {reply, {error, unknown_mode}, St} end end; handle_call({should_i_run, App}, _From, #st{ allowed_apps = Allowed , other_apps = Other } = St) -> {reply, (lists:member(App, Allowed) orelse lists:member(App, Other)), St}; handle_call({ok_to_start, App}, _From, #st{mode = M} = St) -> ?LOG_DEBUG("ok_to_start ~p, mode = ~p", [App, M]), {reply, ok_to_start_(App, St), St}; handle_call({ok_to_stop, App}, _From, #st{graph = G} = St) -> case [A || {_,A,App1,{start_after,App1}} <- in_edges(G, App), App1 =:= App, is_running(A, St)] of [] -> {reply, true, St}; [_|_] = Other -> {reply, {false, [{A, still_running} || A <- Other]}, St} end; handle_call(graph, _From, #st{graph = G} = St) -> {reply, G, St}; handle_call(status, _From, St) -> {reply, status_(St), St}; handle_call(is_mode_stable, _From, St) -> {reply, is_stable(St), St}; handle_call({await_stable_mode, Timeout}, From, #st{pending_stable = Pending} = St) -> case St#st.stable of true -> {reply, {ok, St#st.mode}, St}; false -> TRef = set_timeout(Timeout, {awaiting_stable, From}), {noreply, St#st{pending_stable = [{From, TRef} | Pending]}} end; handle_call(check_for_new_applications, _From, #st{ mode = Mode , allowed_apps = Allowed0} = St0) -> St = init_state(St0), case allowed_apps(St#st.mode, St) of Allowed0 -> {reply, ok, St}; NewAllowedApps -> St1 = St#st{allowed_apps = NewAllowedApps}, case St1#st.stable of false -> {reply, ok, St1}; true -> announce_new_mode(Mode, St1), {reply, ok, St1#st{stable = false}} end end; handle_call(_Req, _From, St) -> {reply, {error, unknown_call}, St}. handle_cast({app_running, App, Node}, #st{mode = Mode} = St0) -> St = note_running({App, Node}, true, St0), tell_controllers(app_running, App, Node, St), publish_event(app_running, {App, Node}, St), case {Mode, App} of {?PROTECTED_MODE, app_ctrl} -> ?LOG_DEBUG("Moving to default mode", []), {noreply, set_next_mode(St)}; _ -> {noreply, check_if_stable(St)} end; handle_cast({app_stopped, App, Node}, #st{} = St0) -> St = note_running({App, Node}, false, St0), tell_controllers(app_stopped, App, Node, St), publish_event(app_stopped, {App, Node}, St), {noreply, check_if_stable(St)}; handle_cast(_Msg, St) -> {noreply, St}. handle_info({timeout, TRef, {awaiting_stable, From}}, #st{pending_stable = Pend} = St) -> case lists:keytake(TRef, 2, Pend) of {value, {From, _}, Pend1} -> case is_stable(St) of true -> {noreply, notify_pending({ok, St#st.mode}, St#st{stable = true})}; {false, Outstanding} -> gen_server:reply(From, {timeout, Outstanding}), {noreply, St#st{pending_stable = Pend1}} end; false -> {noreply, St} end; handle_info(_Msg, St) -> {noreply, St}. terminate(_Reason, _St) -> ok. code_change(_FromVsn, St, _Extra) -> {ok, St}. start_new_controllers(AnnotatedDeps, Controllers) -> [ start_controller(A) || {{A,N} = AppNode, _Deps} <- AnnotatedDeps, N =:= node(), not lists:member(A, [kernel, stdlib]) andalso not lists:keymember(A, 1, Controllers) andalso not load_only(AppNode) ] ++ Controllers. announce_new_mode(Mode, St) -> tell_controllers({new_mode, Mode}, St), publish_event(new_mode, Mode, St). tell_controllers(Event, App, Node, #st{controllers = Cs}) -> ?LOG_DEBUG("tell_controllers(~p, ~p, ~p)", [Event, App, Node]), [gen_server:cast(Pid, {Event, App, Node}) || {_, Pid} <- Cs], ok. tell_controllers(Event, #st{controllers = Cs}) -> ?LOG_DEBUG("tell_controllers(~p)", [Event]), [gen_server:cast(Pid, Event) || {_, Pid} <- Cs], ok. start_controller(A) -> {ok, Pid} = app_ctrl_ctrl:start_link(A), {A, Pid}. note_running(A, Bool, #st{live_map = Map, running_where = Where} = St) when is_boolean(Bool) -> {AppName, Node} = A, Map1 = maps:update_with(A, fun(M0) -> M = maps:without([ongoing], M0), M#{running => Bool} end, #{running => Bool}, Map), Where1 = case Bool of true -> maps:update_with(AppName, fun(Ns) -> ordsets:add_element(Node, Ns) end, ordsets:from_list([Node]), Where); false -> maps:update_with(AppName, fun(Ns) -> ordsets:del_element(Node, Ns) end, ordsets:new(), Where) end, St#st{live_map = Map1, running_where = Where1}. check_(Deps, St) -> case check_(Deps, St, []) of [] -> true; Other -> {false, Other} end. check_([{App, N} = A|Deps], St, Acc) when is_atom(App), N == node() -> case (is_running(A, St) orelse load_only(A)) of true -> check_(Deps, St, Acc); false -> check_(Deps, St, [{App, not_running}|Acc]) end; check_([], _St, Acc) -> Acc. load_only({App, N}) when N == node() -> case application:get_key(App, mod) of {ok, {_, _}} -> false; {ok, []} -> true; undefined -> true end. is_running({_App,N} = A, #st{live_map = Map}) when N == node() -> case maps:find(A, Map) of {ok, #{running := Bool}} -> Bool; error -> false end. set_timeout(infinity, _) -> infinity; set_timeout(T, Msg) when is_integer(T), T >= 0 -> erlang:start_timer(T, self(), Msg). check_if_stable(#st{mode = Mode} = St) -> case is_stable(St) of true -> notify_pending({ok, Mode}, St#st{stable = true}); {false, _Outstanding} -> St end. is_stable(#st{} = St) -> case not_running(St) ++ not_stopped(St) of [] -> true; Other -> {false, Other} end. not_running(#st{allowed_apps = Allowed} = St) -> opt_attr(not_running, [A || A <- Allowed, not is_running({A, node()}, St)]). not_stopped(#st{allowed_apps = Allowed, role_apps = RApps} = St) -> opt_attr(not_stopped, [R || R <- (RApps -- Allowed), is_running({R, node()}, St)]). opt_attr(_ , []) -> []; opt_attr(Key, L) -> [{Key, L}]. notify_pending(Msg, #st{pending_stable = Pend} = St) -> lists:foreach( fun({From, TRef}) -> erlang:cancel_timer(TRef), gen_server:reply(From, Msg) end, Pend), St#st{pending_stable = []}. publish_event(_, _, #st{mode = ?PROTECTED_MODE}) -> ok; publish_event(Event, Info, _St) -> app_ctrl_events:publish(Event, Info). in_edges(G, App) -> [digraph:edge(G, E) || E <- digraph:in_edges(G, App)]. out_edges(G, App) -> [digraph:edge(G, E) || E <- digraph:out_edges(G, App)]. allowed_apps(undefined, #st{controllers = Cs}) -> lists:sort([A || {A, _} <- Cs]); allowed_apps(?PROTECTED_MODE, #st{controllers = Cs} = St) -> any_active(protected_mode_apps(St), Cs); allowed_apps(Mode, #st{role_apps = _RApps, controllers = _Cs}) -> _AppsInMode = lists:sort(app_ctrl_deps:apps_in_mode(Mode)). not lists : member(A , RApps ) ] , not lists : member(A , ) ] . set_next_mode(St) -> Mode = app_ctrl_config:current_mode(), St1 = set_current_mode(Mode, St), announce_new_mode(Mode, St1), St1. set_current_mode(Mode, #st{} = St) -> Allowed = allowed_apps(Mode, St), St#st{mode = Mode, allowed_apps = Allowed, stable = false}. any_active(As, Cs) -> intersection(As, [A || {A, _} <- Cs]). protected_mode_apps(#st{graph = G}) -> Res = app_ctrl_config:protected_mode_apps(), ?LOG_DEBUG("protected_mode_apps = ~p", [Res]), Expanded = add_deps(Res, G), ?LOG_DEBUG("Expanded = ~p", [Expanded]), Expanded. add_deps(Apps, G) -> lists:foldr(fun(A, Acc) -> add_deps_(A, G, Acc) end, Apps, Apps). add_deps_(A, G, Acc) -> Deps = app_ctrl_deps:get_app_dependencies(G, A), case Deps -- Acc of [] -> Acc; New -> lists:foldr(fun(A1, Acc1) -> add_deps_(A1, G, Acc1) end, add_to_ordset(New, Acc), New) end. add_to_ordset(Xs, Set) -> lists:foldr(fun ordsets:add_element/2, Set, Xs). intersection(A, B) -> A -- (A -- B). status_(#st{mode = Mode, allowed_apps = AApps, role_apps = RApps} = St) -> Modes = app_ctrl_config:modes(), Roles = app_ctrl_config:roles(), #{ current_mode => Mode , current_roles => proplists:get_value(Mode, app_ctrl_config:modes()) , running_locally => running_locally(St) , running_remotely => running_remotely(St) , allowed_apps => [A1 || {_, Status} = A1 <- [ {A, runnable_app_status(A, St)} || A <- AApps ], Status =/= load_only] , role_apps => [ {A, controlled_app_status(A, Modes, Roles)} || A <- RApps] }. running_locally(#st{running_where = R}) -> maps:filter( fun(_App, Ns) -> ordsets:is_element(node(), Ns) end, R). running_remotely(#st{running_where = R}) -> maps:filter( fun(_App, Ns) -> not ordsets:is_empty( ordsets:del_element(node(), Ns)) end, R). runnable_app_status(A, St) -> ?LOG_DEBUG("runnable_app_status(~p, St)", [A]), TODO : fix this when adding distributed ctrl case is_running(AppNode, St) of true -> running; false -> case load_only(AppNode) of true -> load_only; false -> case ok_to_start_(A, St) of true -> ok_to_start; {false, Why} -> {not_started, Why} end end end. controlled_app_status(A, Modes, Roles) -> InRoles = [R || {R, As} <- Roles, lists:member(A, As)], InModes = [M || {M, Rs} <- Modes, intersection(InRoles, Rs) =/= []], #{ in_roles => InRoles , in_modes => InModes }. ok_to_start_(App, #st{allowed_apps = Allowed, other_apps = Other, graph = G} = St) -> case lists:member(App, Allowed) orelse lists:member(App, Other) of true -> case [A || {_,_,A,{start_after,_}} <- out_edges(G, App), not (is_running(A, St) orelse load_only(A))] of [] -> true; [_|_] = Other -> {false, [{A, not_running} || A <- Other]} end; false -> {false, not_allowed} end.
f61c753a0f17a15136d6fce4218994f45984347727631eb4285a3afc2988969a
skeuchel/needle
WellFormedInversion.hs
{-# LANGUAGE GADTs #-} module KnotCore.Elaboration.Lemma.WellFormedInversion where import Coq.Syntax import Coq.StdLib import KnotCore.Syntax import KnotCore.Elaboration.Core import Control.Applicative import Control.Monad import Data.List (intersect, nub) import Data.Maybe (catMaybes, mapMaybe) import Data.Traversable (for, traverse) lemmas :: Elab m => [SortGroupDecl] -> m [Sentence] lemmas sdgs = concat <$> sequenceA [ sortDecl sd | sdg <- sdgs, sd <- sgSorts sdg ] sortDecl :: Elab m => SortDecl -> m [Sentence] sortDecl (SortDecl _ _ cds) = concat <$> traverse conDecl cds ctorDecl2SymbolicTerm :: CtorDecl -> SymbolicTerm ctorDecl2SymbolicTerm (CtorVar cn rv _) = SymCtorVarFree Nil cn rv ctorDecl2SymbolicTerm (CtorReg cn fds) = SymCtorReg Nil cn [ case fd of TODO TODO TODO | fd <- fds ] ctorDecl2WfPattern :: Elab m => HVarlistVar -> CtorDecl -> m Pattern ctorDecl2WfPattern _ (CtorVar cn rv wf) = do iv <- toIndex rv PatCtorEx <$> (idRelationWellFormedCtor cn >>= toQualId) <*> (sequenceA . concat $ [ pure ] , map (fmap PatQualId) [toQualId iv, toQualId wf] ]) ctorDecl2WfPattern _ (CtorReg cn fds) = PatCtorEx <$> (idRelationWellFormedCtor cn >>= toQualId) <*> (sequenceA . concat $ [ pure ] , map (fmap PatQualId) . concat . catMaybes $ [ case fd of FieldDeclSort _bs sv svWf -> Just [toQualId sv, toQualId svWf] FieldDeclBinding _bs _bv -> Nothing FieldDeclReference fv fvWf -> Just [toIndex fv >>= toQualId, toQualId fvWf] | fd <- fds ] ]) conDecl :: Elab m => CtorDecl -> m [Sentence] conDecl cd = do k <- freshHVarlistVar st <- symbolicTermToSTerm $ ctorDecl2SymbolicTerm cd wfSt <- WellFormedSortHyp <$> freshHypothesis <*> pure (WfSort (HVVar k) st) let stn = typeNameOf st -- The meta-variable representing the symbolic term in the match. stv <- freshSortVariable stn case cd of CtorReg cn fds -> do binders <- sequenceA . concat $ [ [toBinder k] , eFieldDeclBinders fds , [toBinder wfSt] ] sequenceA . catMaybes $ [ case fd of FieldDeclSort bs sv svWf -> Just $ do prop <- toTerm $ WfSort (HVAppend (HVVar k) (evalBindSpec HV0 bs)) (SVar sv) innerMatch <- TermMatch <$> (MatchItem <$> toRef stv <*> pure Nothing <*> pure Nothing ) <*> pure (Just (TermSort Prop)) <*> sequenceA [ Equation <$> ctorDecl2Pattern cd <*> pure prop , Equation <$> pure PatUnderscore <*> pure true ] body <- TermMatch <$> (MatchItem <$> toRef wfSt <*> pure Nothing <*> (Just <$> toMatchItem (WfSort (HVVar k) (SVar stv))) ) <*> pure (Just innerMatch) <*> sequenceA [ Equation <$> ctorDecl2WfPattern k cd <*> toRef svWf , Equation <$> pure PatUnderscore <*> pure (termIdent "I") ] def <- Definition <$> idLemmaWellFormedInversion stn cn i <*> pure binders <*> pure (Just prop) <*> pure body return (SentenceDefinition def) FieldDeclBinding _bs _bv -> Nothing FieldDeclReference _fv _fvWf -> error $ "KnotCore.Elaboration.Lemma.WellFormedInversion." ++ "FieldReference: not implemented" | (i,fd) <- zip [0..] fds ] CtorVar cn rv wf -> do -- TODO: combine with the above iv <- toIndex rv binders <- sequenceA [ toBinder k , toBinder iv , toBinder wfSt ] prop <- toTerm (WfIndex (HVVar k) (IVar iv)) innerMatch <- TermMatch <$> (MatchItem <$> toRef stv <*> pure Nothing <*> pure Nothing ) <*> pure (Just (TermSort Prop)) <*> sequenceA [ Equation <$> ctorDecl2Pattern cd <*> pure prop , Equation <$> pure PatUnderscore <*> pure true ] body <- TermMatch <$> (MatchItem <$> toRef wfSt <*> pure Nothing <*> (Just <$> toMatchItem (WfSort (HVVar k) (SVar stv))) ) <*> pure (Just innerMatch) <*> sequenceA [ Equation <$> ctorDecl2WfPattern k cd <*> toRef wf , Equation <$> pure PatUnderscore <*> pure (termIdent "I") ] def <- Definition <$> idLemmaWellFormedInversion stn cn 1 <*> pure binders <*> pure (Just prop) <*> pure body return [SentenceDefinition def]
null
https://raw.githubusercontent.com/skeuchel/needle/25f46005d37571c1585805487a47950dcd588269/src/KnotCore/Elaboration/Lemma/WellFormedInversion.hs
haskell
# LANGUAGE GADTs # The meta-variable representing the symbolic term in the match. TODO: combine with the above
module KnotCore.Elaboration.Lemma.WellFormedInversion where import Coq.Syntax import Coq.StdLib import KnotCore.Syntax import KnotCore.Elaboration.Core import Control.Applicative import Control.Monad import Data.List (intersect, nub) import Data.Maybe (catMaybes, mapMaybe) import Data.Traversable (for, traverse) lemmas :: Elab m => [SortGroupDecl] -> m [Sentence] lemmas sdgs = concat <$> sequenceA [ sortDecl sd | sdg <- sdgs, sd <- sgSorts sdg ] sortDecl :: Elab m => SortDecl -> m [Sentence] sortDecl (SortDecl _ _ cds) = concat <$> traverse conDecl cds ctorDecl2SymbolicTerm :: CtorDecl -> SymbolicTerm ctorDecl2SymbolicTerm (CtorVar cn rv _) = SymCtorVarFree Nil cn rv ctorDecl2SymbolicTerm (CtorReg cn fds) = SymCtorReg Nil cn [ case fd of TODO TODO TODO | fd <- fds ] ctorDecl2WfPattern :: Elab m => HVarlistVar -> CtorDecl -> m Pattern ctorDecl2WfPattern _ (CtorVar cn rv wf) = do iv <- toIndex rv PatCtorEx <$> (idRelationWellFormedCtor cn >>= toQualId) <*> (sequenceA . concat $ [ pure ] , map (fmap PatQualId) [toQualId iv, toQualId wf] ]) ctorDecl2WfPattern _ (CtorReg cn fds) = PatCtorEx <$> (idRelationWellFormedCtor cn >>= toQualId) <*> (sequenceA . concat $ [ pure ] , map (fmap PatQualId) . concat . catMaybes $ [ case fd of FieldDeclSort _bs sv svWf -> Just [toQualId sv, toQualId svWf] FieldDeclBinding _bs _bv -> Nothing FieldDeclReference fv fvWf -> Just [toIndex fv >>= toQualId, toQualId fvWf] | fd <- fds ] ]) conDecl :: Elab m => CtorDecl -> m [Sentence] conDecl cd = do k <- freshHVarlistVar st <- symbolicTermToSTerm $ ctorDecl2SymbolicTerm cd wfSt <- WellFormedSortHyp <$> freshHypothesis <*> pure (WfSort (HVVar k) st) let stn = typeNameOf st stv <- freshSortVariable stn case cd of CtorReg cn fds -> do binders <- sequenceA . concat $ [ [toBinder k] , eFieldDeclBinders fds , [toBinder wfSt] ] sequenceA . catMaybes $ [ case fd of FieldDeclSort bs sv svWf -> Just $ do prop <- toTerm $ WfSort (HVAppend (HVVar k) (evalBindSpec HV0 bs)) (SVar sv) innerMatch <- TermMatch <$> (MatchItem <$> toRef stv <*> pure Nothing <*> pure Nothing ) <*> pure (Just (TermSort Prop)) <*> sequenceA [ Equation <$> ctorDecl2Pattern cd <*> pure prop , Equation <$> pure PatUnderscore <*> pure true ] body <- TermMatch <$> (MatchItem <$> toRef wfSt <*> pure Nothing <*> (Just <$> toMatchItem (WfSort (HVVar k) (SVar stv))) ) <*> pure (Just innerMatch) <*> sequenceA [ Equation <$> ctorDecl2WfPattern k cd <*> toRef svWf , Equation <$> pure PatUnderscore <*> pure (termIdent "I") ] def <- Definition <$> idLemmaWellFormedInversion stn cn i <*> pure binders <*> pure (Just prop) <*> pure body return (SentenceDefinition def) FieldDeclBinding _bs _bv -> Nothing FieldDeclReference _fv _fvWf -> error $ "KnotCore.Elaboration.Lemma.WellFormedInversion." ++ "FieldReference: not implemented" | (i,fd) <- zip [0..] fds ] CtorVar cn rv wf -> do iv <- toIndex rv binders <- sequenceA [ toBinder k , toBinder iv , toBinder wfSt ] prop <- toTerm (WfIndex (HVVar k) (IVar iv)) innerMatch <- TermMatch <$> (MatchItem <$> toRef stv <*> pure Nothing <*> pure Nothing ) <*> pure (Just (TermSort Prop)) <*> sequenceA [ Equation <$> ctorDecl2Pattern cd <*> pure prop , Equation <$> pure PatUnderscore <*> pure true ] body <- TermMatch <$> (MatchItem <$> toRef wfSt <*> pure Nothing <*> (Just <$> toMatchItem (WfSort (HVVar k) (SVar stv))) ) <*> pure (Just innerMatch) <*> sequenceA [ Equation <$> ctorDecl2WfPattern k cd <*> toRef wf , Equation <$> pure PatUnderscore <*> pure (termIdent "I") ] def <- Definition <$> idLemmaWellFormedInversion stn cn 1 <*> pure binders <*> pure (Just prop) <*> pure body return [SentenceDefinition def]
35fc520446f4a7502099287b424d3ffbe1dbc3978308e8cd492cb47689e02b11
penpot/penpot
guides.cljs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.main.ui.workspace.viewport.guides (:require [app.common.colors :as colors] [app.common.geom.point :as gpt] [app.common.geom.shapes :as gsh] [app.common.math :as mth] [app.common.pages.helpers :as cph] [app.common.types.shape-tree :as ctst] [app.common.uuid :as uuid] [app.main.data.workspace :as dw] [app.main.refs :as refs] [app.main.store :as st] [app.main.streams :as ms] [app.main.ui.cursors :as cur] [app.main.ui.formats :as fmt] [app.main.ui.workspace.viewport.rules :as rules] [app.util.dom :as dom] [rumext.v2 :as mf])) (def guide-width 1) (def guide-opacity 0.7) (def guide-opacity-hover 1) (def guide-color colors/primary) (def guide-pill-width 34) (def guide-pill-height 20) (def guide-pill-corner-radius 4) (def guide-active-area 16) (def guide-creation-margin-left 8) (def guide-creation-margin-top 28) (def guide-creation-width 16) (def guide-creation-height 24) (defn use-guide "Hooks to support drag/drop for existing guides and new guides" [on-guide-change get-hover-frame zoom {:keys [id position axis frame-id]}] (let [dragging-ref (mf/use-ref false) start-ref (mf/use-ref nil) start-pos-ref (mf/use-ref nil) state (mf/use-state {:hover false :new-position nil :new-frame-id frame-id}) frame-id (:new-frame-id @state) frame-ref (mf/use-memo (mf/deps frame-id) #(refs/object-by-id frame-id)) frame (mf/deref frame-ref) snap-pixel? (mf/deref refs/snap-pixel?) on-pointer-enter (mf/use-callback (fn [] (st/emit! (dw/set-hover-guide id true)) (swap! state assoc :hover true))) on-pointer-leave (mf/use-callback (fn [] (st/emit! (dw/set-hover-guide id false)) (swap! state assoc :hover false))) on-pointer-down (mf/use-callback (fn [event] (when (= 0 (.-button event)) (dom/capture-pointer event) (mf/set-ref-val! dragging-ref true) (mf/set-ref-val! start-ref (dom/get-client-position event)) (mf/set-ref-val! start-pos-ref (get @ms/mouse-position axis))))) on-pointer-up (mf/use-callback (mf/deps (select-keys @state [:new-position :new-frame-id]) on-guide-change) (fn [] (when (some? on-guide-change) (when (some? (:new-position @state)) (on-guide-change {:position (:new-position @state) :frame-id (:new-frame-id @state)}))))) on-lost-pointer-capture (mf/use-callback (fn [event] (dom/release-pointer event) (mf/set-ref-val! dragging-ref false) (mf/set-ref-val! start-ref nil) (mf/set-ref-val! start-pos-ref nil) (swap! state assoc :new-position nil))) on-mouse-move (mf/use-callback (mf/deps position zoom snap-pixel?) (fn [event] (when-let [_ (mf/ref-val dragging-ref)] (let [start-pt (mf/ref-val start-ref) start-pos (mf/ref-val start-pos-ref) current-pt (dom/get-client-position event) delta (/ (- (get current-pt axis) (get start-pt axis)) zoom) new-position (if (some? position) (+ position delta) (+ start-pos delta)) new-position (if snap-pixel? (mth/round new-position) new-position) new-frame-id (:id (get-hover-frame))] (swap! state assoc :new-position new-position :new-frame-id new-frame-id)))))] {:on-pointer-enter on-pointer-enter :on-pointer-leave on-pointer-leave :on-pointer-down on-pointer-down :on-pointer-up on-pointer-up :on-lost-pointer-capture on-lost-pointer-capture :on-mouse-move on-mouse-move :state state :frame frame})) ;; This functions are auxiliary to get the coords of components depending on the axis ;; we're handling (defn guide-area-axis [pos vbox zoom frame axis] (let [rules-pos (/ rules/rules-pos zoom) guide-active-area (/ guide-active-area zoom)] (cond (and (some? frame) (= axis :x)) {:x (- pos (/ guide-active-area 2)) :y (:y frame) :width guide-active-area :height (:height frame)} (some? frame) {:x (:x frame) :y (- pos (/ guide-active-area 2)) :width (:width frame) :height guide-active-area} (= axis :x) {:x (- pos (/ guide-active-area 2)) :y (+ (:y vbox) rules-pos) :width guide-active-area :height (:height vbox)} :else {:x (+ (:x vbox) rules-pos) :y (- pos (/ guide-active-area 2)) :width (:width vbox) :height guide-active-area}))) (defn guide-line-axis ([pos vbox axis] (if (= axis :x) {:x1 pos :y1 (:y vbox) :x2 pos :y2 (+ (:y vbox) (:height vbox))} {:x1 (:x vbox) :y1 pos :x2 (+ (:x vbox) (:width vbox)) :y2 pos})) ([pos vbox frame axis] (if (= axis :x) {:l1-x1 pos :l1-y1 (:y vbox) :l1-x2 pos :l1-y2 (:y frame) :l2-x1 pos :l2-y1 (:y frame) :l2-x2 pos :l2-y2 (+ (:y frame) (:height frame)) :l3-x1 pos :l3-y1 (+ (:y frame) (:height frame)) :l3-x2 pos :l3-y2 (+ (:y vbox) (:height vbox))} {:l1-x1 (:x vbox) :l1-y1 pos :l1-x2 (:x frame) :l1-y2 pos :l2-x1 (:x frame) :l2-y1 pos :l2-x2 (+ (:x frame) (:width frame)) :l2-y2 pos :l3-x1 (+ (:x frame) (:width frame)) :l3-y1 pos :l3-x2 (+ (:x vbox) (:width vbox)) :l3-y2 pos}))) (defn guide-pill-axis [pos vbox zoom axis] (let [rules-pos (/ rules/rules-pos zoom) guide-pill-width (/ guide-pill-width zoom) guide-pill-height (/ guide-pill-height zoom)] (if (= axis :x) {:rect-x (- pos (/ guide-pill-width 2)) :rect-y (+ (:y vbox) rules-pos (- (/ guide-pill-width 2)) (/ 3 zoom)) :rect-width guide-pill-width :rect-height guide-pill-height :text-x pos :text-y (+ (:y vbox) rules-pos (- (/ 3 zoom)))} {:rect-x (+ (:x vbox) rules-pos (- (/ guide-pill-height 2)) (- (/ 4 zoom))) :rect-y (- pos (/ guide-pill-width 2)) :rect-width guide-pill-height :rect-height guide-pill-width :text-x (+ (:x vbox) rules-pos (- (/ 3 zoom))) :text-y pos}))) (defn guide-inside-vbox? ([zoom vbox] (partial guide-inside-vbox? zoom vbox)) ([zoom {:keys [x y width height]} {:keys [axis position]}] (let [rule-area-size (/ rules/rule-area-size zoom) x1 x x2 (+ x width) y1 y y2 (+ y height)] (if (= axis :x) (and (>= position (+ x1 rule-area-size)) (<= position x2)) (and (>= position (+ y1 rule-area-size)) (<= position y2)))))) (defn guide-creation-area [vbox zoom axis] (if (= axis :x) {:x (+ (:x vbox) (/ guide-creation-margin-left zoom)) :y (:y vbox) :width (/ guide-creation-width zoom) :height (:height vbox)} {:x (+ (:x vbox) (/ guide-creation-margin-top zoom)) :y (:y vbox) :width (:width vbox) :height (/ guide-creation-height zoom)})) (defn is-guide-inside-frame? [guide frame] (if (= :x (:axis guide)) (and (>= (:position guide) (:x frame) ) (<= (:position guide) (+ (:x frame) (:width frame)) )) (and (>= (:position guide) (:y frame) ) (<= (:position guide) (+ (:y frame) (:height frame)) )))) (mf/defc guide {::mf/wrap [mf/memo]} [{:keys [guide hover? on-guide-change get-hover-frame vbox zoom hover-frame disabled-guides? frame-modifier]}] (let [axis (:axis guide) handle-change-position (mf/use-callback (mf/deps on-guide-change) (fn [changes] (when on-guide-change (on-guide-change (merge guide changes))))) {:keys [on-pointer-enter on-pointer-leave on-pointer-down on-pointer-up on-lost-pointer-capture on-mouse-move state frame]} (use-guide handle-change-position get-hover-frame zoom guide) base-frame (or frame hover-frame) frame (gsh/transform-shape base-frame frame-modifier) move-vec (gpt/to-vec (gpt/point (:x base-frame) (:y base-frame)) (gpt/point (:x frame) (:y frame))) pos (+ (or (:new-position @state) (:position guide)) (get move-vec axis)) guide-width (/ guide-width zoom) guide-pill-corner-radius (/ guide-pill-corner-radius zoom) frame-guide-outside? (and (some? frame) (not (is-guide-inside-frame? (assoc guide :position pos) frame)))] (when (or (nil? frame) (and (cph/root-frame? frame) (not (ctst/rotated-frame? frame)))) [:g.guide-area {:opacity (when frame-guide-outside? 0)} (when-not disabled-guides? (let [{:keys [x y width height]} (guide-area-axis pos vbox zoom frame axis)] [:rect {:x x :y y :width width :height height :style {:fill "none" :pointer-events (if frame-guide-outside? "none" "fill") :cursor (if (= axis :x) (cur/resize-ew 0) (cur/resize-ns 0))} :on-pointer-enter on-pointer-enter :on-pointer-leave on-pointer-leave :on-pointer-down on-pointer-down :on-pointer-up on-pointer-up :on-lost-pointer-capture on-lost-pointer-capture :on-mouse-move on-mouse-move}])) (if (some? frame) (let [{:keys [l1-x1 l1-y1 l1-x2 l1-y2 l2-x1 l2-y1 l2-x2 l2-y2 l3-x1 l3-y1 l3-x2 l3-y2]} (guide-line-axis pos vbox frame axis)] [:g (when (or hover? (:hover @state)) [:line {:x1 l1-x1 :y1 l1-y1 :x2 l1-x2 :y2 l1-y2 :style {:stroke guide-color :stroke-opacity guide-opacity-hover :stroke-dasharray (str "0, " (/ 6 zoom)) :stroke-linecap "round" :stroke-width guide-width}}]) [:line {:x1 l2-x1 :y1 l2-y1 :x2 l2-x2 :y2 l2-y2 :style {:stroke guide-color :stroke-width guide-width :stroke-opacity (if (or hover? (:hover @state)) guide-opacity-hover guide-opacity)}}] (when (or hover? (:hover @state)) [:line {:x1 l3-x1 :y1 l3-y1 :x2 l3-x2 :y2 l3-y2 :style {:stroke guide-color :stroke-opacity guide-opacity-hover :stroke-width guide-width :stroke-dasharray (str "0, " (/ 6 zoom)) :stroke-linecap "round"}}])]) (let [{:keys [x1 y1 x2 y2]} (guide-line-axis pos vbox axis)] [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :style {:stroke guide-color :stroke-width guide-width :stroke-opacity (if (or hover? (:hover @state)) guide-opacity-hover guide-opacity)}}])) (when (or hover? (:hover @state)) (let [{:keys [rect-x rect-y rect-width rect-height text-x text-y]} (guide-pill-axis pos vbox zoom axis)] [:g.guide-pill [:rect {:x rect-x :y rect-y :width rect-width :height rect-height :rx guide-pill-corner-radius :ry guide-pill-corner-radius :style {:fill guide-color}}] [:text {:x text-x :y text-y :text-anchor "middle" :dominant-baseline "middle" :transform (when (= axis :y) (str "rotate(-90 " text-x "," text-y ")")) :style {:font-size (/ rules/font-size zoom) :font-family rules/font-family :fill colors/black}} (fmt/format-number pos)]]))]))) (mf/defc new-guide-area [{:keys [vbox zoom axis get-hover-frame disabled-guides?]}] (let [on-guide-change (mf/use-callback (mf/deps vbox) (fn [guide] (let [guide (-> guide (assoc :id (uuid/next) :axis axis))] (when (guide-inside-vbox? zoom vbox guide) (st/emit! (dw/update-guides guide)))))) {:keys [on-pointer-enter on-pointer-leave on-pointer-down on-pointer-up on-lost-pointer-capture on-mouse-move state frame]} (use-guide on-guide-change get-hover-frame zoom {:axis axis})] [:g.new-guides (when-not disabled-guides? (let [{:keys [x y width height]} (guide-creation-area vbox zoom axis)] [:rect {:x x :y y :width width :height height :on-pointer-enter on-pointer-enter :on-pointer-leave on-pointer-leave :on-pointer-down on-pointer-down :on-pointer-up on-pointer-up :on-lost-pointer-capture on-lost-pointer-capture :on-mouse-move on-mouse-move :style {:fill "none" :pointer-events "fill" :cursor (if (= axis :x) (cur/resize-ew 0) (cur/resize-ns 0))}}])) (when (:new-position @state) [:& guide {:guide {:axis axis :position (:new-position @state)} :get-hover-frame get-hover-frame :vbox vbox :zoom zoom :hover? true :hover-frame frame}])])) (mf/defc viewport-guides {::mf/wrap [mf/memo]} [{:keys [zoom vbox hover-frame disabled-guides? modifiers]}] (let [page (mf/deref refs/workspace-page) guides (mf/use-memo (mf/deps page vbox) #(->> (get-in page [:options :guides] {}) (vals) (filter (guide-inside-vbox? zoom vbox)))) focus (mf/deref refs/workspace-focus-selected) hover-frame-ref (mf/use-ref nil) ;; We use the ref to not redraw every guide everytime the hovering frame change ;; we're only interested to get the frame in the guide we're moving get-hover-frame (mf/use-callback (fn [] (mf/ref-val hover-frame-ref))) on-guide-change (mf/use-callback (mf/deps vbox) (fn [guide] (if (guide-inside-vbox? zoom vbox guide) (st/emit! (dw/update-guides guide)) (st/emit! (dw/remove-guide guide)))))] (mf/use-effect (mf/deps hover-frame) (fn [] (mf/set-ref-val! hover-frame-ref hover-frame))) [:g.guides {:pointer-events "none"} [:& new-guide-area {:vbox vbox :zoom zoom :axis :x :get-hover-frame get-hover-frame :disabled-guides? disabled-guides?}] [:& new-guide-area {:vbox vbox :zoom zoom :axis :y :get-hover-frame get-hover-frame :disabled-guides? disabled-guides?}] (for [current guides] (when (or (nil? (:frame-id current)) (empty? focus) (contains? focus (:frame-id current))) [:& guide {:key (str "guide-" (:id current)) :guide current :vbox vbox :zoom zoom :frame-modifier (get-in modifiers [(:frame-id current) :modifiers]) :get-hover-frame get-hover-frame :on-guide-change on-guide-change :disabled-guides? disabled-guides?}]))]))
null
https://raw.githubusercontent.com/penpot/penpot/cdd268afbc971f04412a9c72f92fad09286a655f/frontend/src/app/main/ui/workspace/viewport/guides.cljs
clojure
Copyright (c) KALEIDOS INC This functions are auxiliary to get the coords of components depending on the axis we're handling We use the ref to not redraw every guide everytime the hovering frame change we're only interested to get the frame in the guide we're moving
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.main.ui.workspace.viewport.guides (:require [app.common.colors :as colors] [app.common.geom.point :as gpt] [app.common.geom.shapes :as gsh] [app.common.math :as mth] [app.common.pages.helpers :as cph] [app.common.types.shape-tree :as ctst] [app.common.uuid :as uuid] [app.main.data.workspace :as dw] [app.main.refs :as refs] [app.main.store :as st] [app.main.streams :as ms] [app.main.ui.cursors :as cur] [app.main.ui.formats :as fmt] [app.main.ui.workspace.viewport.rules :as rules] [app.util.dom :as dom] [rumext.v2 :as mf])) (def guide-width 1) (def guide-opacity 0.7) (def guide-opacity-hover 1) (def guide-color colors/primary) (def guide-pill-width 34) (def guide-pill-height 20) (def guide-pill-corner-radius 4) (def guide-active-area 16) (def guide-creation-margin-left 8) (def guide-creation-margin-top 28) (def guide-creation-width 16) (def guide-creation-height 24) (defn use-guide "Hooks to support drag/drop for existing guides and new guides" [on-guide-change get-hover-frame zoom {:keys [id position axis frame-id]}] (let [dragging-ref (mf/use-ref false) start-ref (mf/use-ref nil) start-pos-ref (mf/use-ref nil) state (mf/use-state {:hover false :new-position nil :new-frame-id frame-id}) frame-id (:new-frame-id @state) frame-ref (mf/use-memo (mf/deps frame-id) #(refs/object-by-id frame-id)) frame (mf/deref frame-ref) snap-pixel? (mf/deref refs/snap-pixel?) on-pointer-enter (mf/use-callback (fn [] (st/emit! (dw/set-hover-guide id true)) (swap! state assoc :hover true))) on-pointer-leave (mf/use-callback (fn [] (st/emit! (dw/set-hover-guide id false)) (swap! state assoc :hover false))) on-pointer-down (mf/use-callback (fn [event] (when (= 0 (.-button event)) (dom/capture-pointer event) (mf/set-ref-val! dragging-ref true) (mf/set-ref-val! start-ref (dom/get-client-position event)) (mf/set-ref-val! start-pos-ref (get @ms/mouse-position axis))))) on-pointer-up (mf/use-callback (mf/deps (select-keys @state [:new-position :new-frame-id]) on-guide-change) (fn [] (when (some? on-guide-change) (when (some? (:new-position @state)) (on-guide-change {:position (:new-position @state) :frame-id (:new-frame-id @state)}))))) on-lost-pointer-capture (mf/use-callback (fn [event] (dom/release-pointer event) (mf/set-ref-val! dragging-ref false) (mf/set-ref-val! start-ref nil) (mf/set-ref-val! start-pos-ref nil) (swap! state assoc :new-position nil))) on-mouse-move (mf/use-callback (mf/deps position zoom snap-pixel?) (fn [event] (when-let [_ (mf/ref-val dragging-ref)] (let [start-pt (mf/ref-val start-ref) start-pos (mf/ref-val start-pos-ref) current-pt (dom/get-client-position event) delta (/ (- (get current-pt axis) (get start-pt axis)) zoom) new-position (if (some? position) (+ position delta) (+ start-pos delta)) new-position (if snap-pixel? (mth/round new-position) new-position) new-frame-id (:id (get-hover-frame))] (swap! state assoc :new-position new-position :new-frame-id new-frame-id)))))] {:on-pointer-enter on-pointer-enter :on-pointer-leave on-pointer-leave :on-pointer-down on-pointer-down :on-pointer-up on-pointer-up :on-lost-pointer-capture on-lost-pointer-capture :on-mouse-move on-mouse-move :state state :frame frame})) (defn guide-area-axis [pos vbox zoom frame axis] (let [rules-pos (/ rules/rules-pos zoom) guide-active-area (/ guide-active-area zoom)] (cond (and (some? frame) (= axis :x)) {:x (- pos (/ guide-active-area 2)) :y (:y frame) :width guide-active-area :height (:height frame)} (some? frame) {:x (:x frame) :y (- pos (/ guide-active-area 2)) :width (:width frame) :height guide-active-area} (= axis :x) {:x (- pos (/ guide-active-area 2)) :y (+ (:y vbox) rules-pos) :width guide-active-area :height (:height vbox)} :else {:x (+ (:x vbox) rules-pos) :y (- pos (/ guide-active-area 2)) :width (:width vbox) :height guide-active-area}))) (defn guide-line-axis ([pos vbox axis] (if (= axis :x) {:x1 pos :y1 (:y vbox) :x2 pos :y2 (+ (:y vbox) (:height vbox))} {:x1 (:x vbox) :y1 pos :x2 (+ (:x vbox) (:width vbox)) :y2 pos})) ([pos vbox frame axis] (if (= axis :x) {:l1-x1 pos :l1-y1 (:y vbox) :l1-x2 pos :l1-y2 (:y frame) :l2-x1 pos :l2-y1 (:y frame) :l2-x2 pos :l2-y2 (+ (:y frame) (:height frame)) :l3-x1 pos :l3-y1 (+ (:y frame) (:height frame)) :l3-x2 pos :l3-y2 (+ (:y vbox) (:height vbox))} {:l1-x1 (:x vbox) :l1-y1 pos :l1-x2 (:x frame) :l1-y2 pos :l2-x1 (:x frame) :l2-y1 pos :l2-x2 (+ (:x frame) (:width frame)) :l2-y2 pos :l3-x1 (+ (:x frame) (:width frame)) :l3-y1 pos :l3-x2 (+ (:x vbox) (:width vbox)) :l3-y2 pos}))) (defn guide-pill-axis [pos vbox zoom axis] (let [rules-pos (/ rules/rules-pos zoom) guide-pill-width (/ guide-pill-width zoom) guide-pill-height (/ guide-pill-height zoom)] (if (= axis :x) {:rect-x (- pos (/ guide-pill-width 2)) :rect-y (+ (:y vbox) rules-pos (- (/ guide-pill-width 2)) (/ 3 zoom)) :rect-width guide-pill-width :rect-height guide-pill-height :text-x pos :text-y (+ (:y vbox) rules-pos (- (/ 3 zoom)))} {:rect-x (+ (:x vbox) rules-pos (- (/ guide-pill-height 2)) (- (/ 4 zoom))) :rect-y (- pos (/ guide-pill-width 2)) :rect-width guide-pill-height :rect-height guide-pill-width :text-x (+ (:x vbox) rules-pos (- (/ 3 zoom))) :text-y pos}))) (defn guide-inside-vbox? ([zoom vbox] (partial guide-inside-vbox? zoom vbox)) ([zoom {:keys [x y width height]} {:keys [axis position]}] (let [rule-area-size (/ rules/rule-area-size zoom) x1 x x2 (+ x width) y1 y y2 (+ y height)] (if (= axis :x) (and (>= position (+ x1 rule-area-size)) (<= position x2)) (and (>= position (+ y1 rule-area-size)) (<= position y2)))))) (defn guide-creation-area [vbox zoom axis] (if (= axis :x) {:x (+ (:x vbox) (/ guide-creation-margin-left zoom)) :y (:y vbox) :width (/ guide-creation-width zoom) :height (:height vbox)} {:x (+ (:x vbox) (/ guide-creation-margin-top zoom)) :y (:y vbox) :width (:width vbox) :height (/ guide-creation-height zoom)})) (defn is-guide-inside-frame? [guide frame] (if (= :x (:axis guide)) (and (>= (:position guide) (:x frame) ) (<= (:position guide) (+ (:x frame) (:width frame)) )) (and (>= (:position guide) (:y frame) ) (<= (:position guide) (+ (:y frame) (:height frame)) )))) (mf/defc guide {::mf/wrap [mf/memo]} [{:keys [guide hover? on-guide-change get-hover-frame vbox zoom hover-frame disabled-guides? frame-modifier]}] (let [axis (:axis guide) handle-change-position (mf/use-callback (mf/deps on-guide-change) (fn [changes] (when on-guide-change (on-guide-change (merge guide changes))))) {:keys [on-pointer-enter on-pointer-leave on-pointer-down on-pointer-up on-lost-pointer-capture on-mouse-move state frame]} (use-guide handle-change-position get-hover-frame zoom guide) base-frame (or frame hover-frame) frame (gsh/transform-shape base-frame frame-modifier) move-vec (gpt/to-vec (gpt/point (:x base-frame) (:y base-frame)) (gpt/point (:x frame) (:y frame))) pos (+ (or (:new-position @state) (:position guide)) (get move-vec axis)) guide-width (/ guide-width zoom) guide-pill-corner-radius (/ guide-pill-corner-radius zoom) frame-guide-outside? (and (some? frame) (not (is-guide-inside-frame? (assoc guide :position pos) frame)))] (when (or (nil? frame) (and (cph/root-frame? frame) (not (ctst/rotated-frame? frame)))) [:g.guide-area {:opacity (when frame-guide-outside? 0)} (when-not disabled-guides? (let [{:keys [x y width height]} (guide-area-axis pos vbox zoom frame axis)] [:rect {:x x :y y :width width :height height :style {:fill "none" :pointer-events (if frame-guide-outside? "none" "fill") :cursor (if (= axis :x) (cur/resize-ew 0) (cur/resize-ns 0))} :on-pointer-enter on-pointer-enter :on-pointer-leave on-pointer-leave :on-pointer-down on-pointer-down :on-pointer-up on-pointer-up :on-lost-pointer-capture on-lost-pointer-capture :on-mouse-move on-mouse-move}])) (if (some? frame) (let [{:keys [l1-x1 l1-y1 l1-x2 l1-y2 l2-x1 l2-y1 l2-x2 l2-y2 l3-x1 l3-y1 l3-x2 l3-y2]} (guide-line-axis pos vbox frame axis)] [:g (when (or hover? (:hover @state)) [:line {:x1 l1-x1 :y1 l1-y1 :x2 l1-x2 :y2 l1-y2 :style {:stroke guide-color :stroke-opacity guide-opacity-hover :stroke-dasharray (str "0, " (/ 6 zoom)) :stroke-linecap "round" :stroke-width guide-width}}]) [:line {:x1 l2-x1 :y1 l2-y1 :x2 l2-x2 :y2 l2-y2 :style {:stroke guide-color :stroke-width guide-width :stroke-opacity (if (or hover? (:hover @state)) guide-opacity-hover guide-opacity)}}] (when (or hover? (:hover @state)) [:line {:x1 l3-x1 :y1 l3-y1 :x2 l3-x2 :y2 l3-y2 :style {:stroke guide-color :stroke-opacity guide-opacity-hover :stroke-width guide-width :stroke-dasharray (str "0, " (/ 6 zoom)) :stroke-linecap "round"}}])]) (let [{:keys [x1 y1 x2 y2]} (guide-line-axis pos vbox axis)] [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :style {:stroke guide-color :stroke-width guide-width :stroke-opacity (if (or hover? (:hover @state)) guide-opacity-hover guide-opacity)}}])) (when (or hover? (:hover @state)) (let [{:keys [rect-x rect-y rect-width rect-height text-x text-y]} (guide-pill-axis pos vbox zoom axis)] [:g.guide-pill [:rect {:x rect-x :y rect-y :width rect-width :height rect-height :rx guide-pill-corner-radius :ry guide-pill-corner-radius :style {:fill guide-color}}] [:text {:x text-x :y text-y :text-anchor "middle" :dominant-baseline "middle" :transform (when (= axis :y) (str "rotate(-90 " text-x "," text-y ")")) :style {:font-size (/ rules/font-size zoom) :font-family rules/font-family :fill colors/black}} (fmt/format-number pos)]]))]))) (mf/defc new-guide-area [{:keys [vbox zoom axis get-hover-frame disabled-guides?]}] (let [on-guide-change (mf/use-callback (mf/deps vbox) (fn [guide] (let [guide (-> guide (assoc :id (uuid/next) :axis axis))] (when (guide-inside-vbox? zoom vbox guide) (st/emit! (dw/update-guides guide)))))) {:keys [on-pointer-enter on-pointer-leave on-pointer-down on-pointer-up on-lost-pointer-capture on-mouse-move state frame]} (use-guide on-guide-change get-hover-frame zoom {:axis axis})] [:g.new-guides (when-not disabled-guides? (let [{:keys [x y width height]} (guide-creation-area vbox zoom axis)] [:rect {:x x :y y :width width :height height :on-pointer-enter on-pointer-enter :on-pointer-leave on-pointer-leave :on-pointer-down on-pointer-down :on-pointer-up on-pointer-up :on-lost-pointer-capture on-lost-pointer-capture :on-mouse-move on-mouse-move :style {:fill "none" :pointer-events "fill" :cursor (if (= axis :x) (cur/resize-ew 0) (cur/resize-ns 0))}}])) (when (:new-position @state) [:& guide {:guide {:axis axis :position (:new-position @state)} :get-hover-frame get-hover-frame :vbox vbox :zoom zoom :hover? true :hover-frame frame}])])) (mf/defc viewport-guides {::mf/wrap [mf/memo]} [{:keys [zoom vbox hover-frame disabled-guides? modifiers]}] (let [page (mf/deref refs/workspace-page) guides (mf/use-memo (mf/deps page vbox) #(->> (get-in page [:options :guides] {}) (vals) (filter (guide-inside-vbox? zoom vbox)))) focus (mf/deref refs/workspace-focus-selected) hover-frame-ref (mf/use-ref nil) get-hover-frame (mf/use-callback (fn [] (mf/ref-val hover-frame-ref))) on-guide-change (mf/use-callback (mf/deps vbox) (fn [guide] (if (guide-inside-vbox? zoom vbox guide) (st/emit! (dw/update-guides guide)) (st/emit! (dw/remove-guide guide)))))] (mf/use-effect (mf/deps hover-frame) (fn [] (mf/set-ref-val! hover-frame-ref hover-frame))) [:g.guides {:pointer-events "none"} [:& new-guide-area {:vbox vbox :zoom zoom :axis :x :get-hover-frame get-hover-frame :disabled-guides? disabled-guides?}] [:& new-guide-area {:vbox vbox :zoom zoom :axis :y :get-hover-frame get-hover-frame :disabled-guides? disabled-guides?}] (for [current guides] (when (or (nil? (:frame-id current)) (empty? focus) (contains? focus (:frame-id current))) [:& guide {:key (str "guide-" (:id current)) :guide current :vbox vbox :zoom zoom :frame-modifier (get-in modifiers [(:frame-id current) :modifiers]) :get-hover-frame get-hover-frame :on-guide-change on-guide-change :disabled-guides? disabled-guides?}]))]))
061af1bb4e13a70424d6abe9f5eab059b5468da604f89267d021ee448c1cd05f
returntocorp/semgrep
AST_to_IL.mli
val function_definition : Lang.t -> AST_generic.function_definition -> IL.name list * IL.stmt list val stmt : Lang.t -> AST_generic.stmt -> IL.stmt list val name_of_entity : AST_generic.entity -> IL.name option val var_of_id_info : AST_generic.ident -> AST_generic.id_info -> IL.name
null
https://raw.githubusercontent.com/returntocorp/semgrep/70af5900482dd15fcce9b8508bd387f7355a531d/src/analyzing/AST_to_IL.mli
ocaml
val function_definition : Lang.t -> AST_generic.function_definition -> IL.name list * IL.stmt list val stmt : Lang.t -> AST_generic.stmt -> IL.stmt list val name_of_entity : AST_generic.entity -> IL.name option val var_of_id_info : AST_generic.ident -> AST_generic.id_info -> IL.name
e5a9f25bfd0d669c6fe6c9a748f699a0549f43571f749fdbcd81fe0f6f199c91
mjsottile/publicstuff
Vec3.hs
module DLA.Vec3 where import DLA.Rmonad data Vec3 = Vec3 Double Double Double deriving Show -- -- for math, see : /~mws/rpos.html -- randVec :: Double -> DLAMonad Vec3 randVec r = do phi ranges from 0.0 to 2.0*pi z <- nextF (2.0 * r) z <- return $ z - r -- z ranges from -r to r theta <- return $ asin (z / r) return $ Vec3 (r*(cos theta)*(cos phi)) (r*(cos theta)*(sin phi)) z randUnitVec :: DLAMonad Vec3 randUnitVec = randVec 1.0 vecAdd :: Vec3 -> Vec3 -> Vec3 vecAdd (Vec3 a b c) (Vec3 x y z) = Vec3 (a+x) (b+y) (c+z) vecSub :: Vec3 -> Vec3 -> Vec3 vecSub (Vec3 a b c) (Vec3 x y z) = Vec3 (a-x) (b-y) (c-z) vecScale :: Vec3 -> Double -> Vec3 vecScale (Vec3 a b c) s = Vec3 (a*s) (b*s) (c*s) vecDot :: Vec3 -> Vec3 -> Double vecDot (Vec3 a b c) (Vec3 x y z) = (a*x)+(b*y)+(c*z) vecNorm :: Vec3 -> Double vecNorm v = sqrt (vecDot v v) vecNormalize :: Vec3 -> Vec3 vecNormalize v = vecScale v (1.0 / (vecNorm v)) vecDimSelect :: Vec3 -> Int -> Double vecDimSelect (Vec3 a b c) n = case (rem n 3) of 0 -> a 1 -> b 2 -> c vecLessThan :: Vec3 -> Vec3 -> Bool vecLessThan (Vec3 a b c) (Vec3 x y z) = (a<x) && (b<y) && (c<z) vecGreaterThan :: Vec3 -> Vec3 -> Bool vecGreaterThan p q = vecLessThan q p
null
https://raw.githubusercontent.com/mjsottile/publicstuff/46fccc93cc62eb9de46186f53012381750fbb17b/dla3d/optimized-haskell2/DLA/Vec3.hs
haskell
for math, see : /~mws/rpos.html z ranges from -r to r
module DLA.Vec3 where import DLA.Rmonad data Vec3 = Vec3 Double Double Double deriving Show randVec :: Double -> DLAMonad Vec3 randVec r = do phi ranges from 0.0 to 2.0*pi z <- nextF (2.0 * r) theta <- return $ asin (z / r) return $ Vec3 (r*(cos theta)*(cos phi)) (r*(cos theta)*(sin phi)) z randUnitVec :: DLAMonad Vec3 randUnitVec = randVec 1.0 vecAdd :: Vec3 -> Vec3 -> Vec3 vecAdd (Vec3 a b c) (Vec3 x y z) = Vec3 (a+x) (b+y) (c+z) vecSub :: Vec3 -> Vec3 -> Vec3 vecSub (Vec3 a b c) (Vec3 x y z) = Vec3 (a-x) (b-y) (c-z) vecScale :: Vec3 -> Double -> Vec3 vecScale (Vec3 a b c) s = Vec3 (a*s) (b*s) (c*s) vecDot :: Vec3 -> Vec3 -> Double vecDot (Vec3 a b c) (Vec3 x y z) = (a*x)+(b*y)+(c*z) vecNorm :: Vec3 -> Double vecNorm v = sqrt (vecDot v v) vecNormalize :: Vec3 -> Vec3 vecNormalize v = vecScale v (1.0 / (vecNorm v)) vecDimSelect :: Vec3 -> Int -> Double vecDimSelect (Vec3 a b c) n = case (rem n 3) of 0 -> a 1 -> b 2 -> c vecLessThan :: Vec3 -> Vec3 -> Bool vecLessThan (Vec3 a b c) (Vec3 x y z) = (a<x) && (b<y) && (c<z) vecGreaterThan :: Vec3 -> Vec3 -> Bool vecGreaterThan p q = vecLessThan q p
d044458ede9af337d65996805608931d564b40362bc7fbb3c021f171475cf29f
bakul/s9fes
find-help.scm
Scheme 9 from Empty Space , Unix Function Library By , 2010 ; Placed in the Public Domain ; ( find - help ) = = > list ( find - help ) = = > list | unspecific ; ; Search the online help database for entries containing the word STRING1 and return a list the names of all pages that contain the word . When STRING2 is passed to FIND - HELP , it ; is interpreted as a string of options. The following options ; will be evaluated: ; ; a Search for substrings instead of full words. ; This options typically yields more results. ; l Return not only the page names but also the context ( up to three lines ) in which the match was found : ( page - name ( ) ) . p Print the results instead of returning them . ; In this case, the result of FIND-HELP is ; unspecific. ; ; Unknown option characters will be ingored. ; ; (Example): (find-help "help") ==> ("help" "locate-file") (require-extension sys-unix) (load-from-library "find-help-path.scm") (load-from-library "read-line.scm") (load-from-library "string-find.scm") (load-from-library "mergesort.scm") (load-from-library "displaystar.scm") (define (search-help-page page what any long prefixlen) (with-input-from-file page (lambda () (let loop ((line (read-line)) (prev '())) (cond ((eof-object? line) '()) (((if any string-ci-find string-ci-find-word) what line) (if long `(,(list (substring page prefixlen (string-length page))) (append prev (list line) (let ((next (read-line))) (if (eof-object? next) '() (list next)))))) `(,(substring page prefixlen (string-length page)))) (else (loop (read-line) (list line)))))))) (define (print-results pages) (for-each (lambda (match) (cond ((pair? match) (display* (car match) #\newline) (for-each (lambda (desc) (if (not (string=? "" desc)) (display* " " desc #\newline))) (cadr match)) (newline)) (else (display* match #\newline)))) pages)) (define (scan-help-pages path) (let scan ((pages (sys:readdir path)) (exts (map symbol->string *extensions*))) (if (null? exts) pages (let* ((dir (string-append path "/" (car exts))) (new (if (sys:access dir sys:access-f-ok) (sys:readdir dir) '())) (new (map (lambda (x) (string-append (car exts) "/" x)) new))) (scan (append pages new) (cdr exts)))))) (define find-help (let ((find-help-path find-help-path) (search-help-page search-help-page) (scan-help-pages scan-help-pages) (print-results print-results)) (lambda (what . opts) (let ((help-path (find-help-path)) (opts (if (null? opts) '() (string->list (car opts))))) (if (not help-path) (error "help pages not found in *library-path*")) (let loop ((pages (scan-help-pages help-path)) (found '())) (let ((page (if (null? pages) "" (string-append help-path "/" (car pages))))) (cond ((null? pages) (let ((result (apply append (map (lambda (page) (search-help-page page what (memv #\a opts) (memv #\l opts) (+ 1 (string-length help-path)))) (mergesort string<? found))))) (if (memv #\p opts) (print-results result) result))) ((sys:lstat-regular? page) (loop (cdr pages) (cons page found))) (else (loop (cdr pages) found)))))))))
null
https://raw.githubusercontent.com/bakul/s9fes/74c14c0db5f07f5bc6d94131e9e4ee15a29275aa/attic/find-help.scm
scheme
Placed in the Public Domain Search the online help database for entries containing the is interpreted as a string of options. The following options will be evaluated: a Search for substrings instead of full words. This options typically yields more results. l Return not only the page names but also the In this case, the result of FIND-HELP is unspecific. Unknown option characters will be ingored. (Example): (find-help "help") ==> ("help" "locate-file")
Scheme 9 from Empty Space , Unix Function Library By , 2010 ( find - help ) = = > list ( find - help ) = = > list | unspecific word STRING1 and return a list the names of all pages that contain the word . When STRING2 is passed to FIND - HELP , it context ( up to three lines ) in which the match was found : ( page - name ( ) ) . p Print the results instead of returning them . (require-extension sys-unix) (load-from-library "find-help-path.scm") (load-from-library "read-line.scm") (load-from-library "string-find.scm") (load-from-library "mergesort.scm") (load-from-library "displaystar.scm") (define (search-help-page page what any long prefixlen) (with-input-from-file page (lambda () (let loop ((line (read-line)) (prev '())) (cond ((eof-object? line) '()) (((if any string-ci-find string-ci-find-word) what line) (if long `(,(list (substring page prefixlen (string-length page))) (append prev (list line) (let ((next (read-line))) (if (eof-object? next) '() (list next)))))) `(,(substring page prefixlen (string-length page)))) (else (loop (read-line) (list line)))))))) (define (print-results pages) (for-each (lambda (match) (cond ((pair? match) (display* (car match) #\newline) (for-each (lambda (desc) (if (not (string=? "" desc)) (display* " " desc #\newline))) (cadr match)) (newline)) (else (display* match #\newline)))) pages)) (define (scan-help-pages path) (let scan ((pages (sys:readdir path)) (exts (map symbol->string *extensions*))) (if (null? exts) pages (let* ((dir (string-append path "/" (car exts))) (new (if (sys:access dir sys:access-f-ok) (sys:readdir dir) '())) (new (map (lambda (x) (string-append (car exts) "/" x)) new))) (scan (append pages new) (cdr exts)))))) (define find-help (let ((find-help-path find-help-path) (search-help-page search-help-page) (scan-help-pages scan-help-pages) (print-results print-results)) (lambda (what . opts) (let ((help-path (find-help-path)) (opts (if (null? opts) '() (string->list (car opts))))) (if (not help-path) (error "help pages not found in *library-path*")) (let loop ((pages (scan-help-pages help-path)) (found '())) (let ((page (if (null? pages) "" (string-append help-path "/" (car pages))))) (cond ((null? pages) (let ((result (apply append (map (lambda (page) (search-help-page page what (memv #\a opts) (memv #\l opts) (+ 1 (string-length help-path)))) (mergesort string<? found))))) (if (memv #\p opts) (print-results result) result))) ((sys:lstat-regular? page) (loop (cdr pages) (cons page found))) (else (loop (cdr pages) found)))))))))
dc07169eb8d631e9b2647ca81f034645b13252627381fc79a7f833fd1712e503
vision-05/betterCode
css.clj
(ns bettercode.css (:require [cljfx.css :as css] [clojure.edn :as edn] [bettercode.meta])) (def colors (edn/read-string (slurp (bettercode.meta/conf-info :theme-path)))) (defn background-radius [radius] {:-fx-background-radius radius}) (defn background ([color] {:-fx-background-color color}) ([color radius] (conj (background color) (background-radius radius)))) (defn inner-background ([color] {:-fx-control-inner-background color}) ([color _] (conj (inner-background color) {:-fx-background color}))) (defn back-and-inner [color] (conj (background color) (inner-background color ""))) (defn text ([color] {:-fx-text-fill color}) ([color size] (conj (text color) {:-fx-font-size size}))) (defn border-radius [radius] {:-fx-border-radius radius}) (defn border ([color] {:-fx-border-color color}) ([color radius] (conj (border color) (border-radius radius)))) (defn highlight [color] {:-fx-highlight-fill color}) (defn root [{:keys [background-color text-color]}] {".root" (conj (background background-color) (text text-color))}) (defn color-picker [{:keys [background-color border-color text-color highlight-color]}] (conj (background background-color 5) (border border-color 5) (text text-color) (background-radius 5) {":hover" (background highlight-color)})) (defn color-picker-label [{:keys [text-color]}] (text text-color)) (defn color-picker-combo-popup [{:keys [background-color]}] (back-and-inner background-color)) (defn menu-bar [{:keys [background-color text-color]}] (conj (back-and-inner background-color) (text text-color))) (defn menu-bar-label [{:keys [text-color]}] (text text-color 12)) (defn menu-bar-item [{:keys [background-color text-color border-color]}] (conj (back-and-inner background-color) (border border-color) (text text-color))) (defn menu-bar-item-label [{:keys [text-color]}] (text text-color 10)) (defn menu-bar-sub-item [{:keys [background-color text-color button-hover-color]}] (conj (back-and-inner background-color) (border background-color 5) (text text-color) {:-fx-padding [4 4 4 4] ":hover" (background button-hover-color 5)})) (defn fsview [{:keys [background-color text-color]}] (conj (inner-background background-color) (text text-color))) (defn fsview-button [{:keys [background-color border-color text-color button-hover-color]}] (conj (background background-color) (border border-color 5) (text text-color) {:-fx-padding [4 4 4 4] ":hover" (background button-hover-color 5)})) (defn fsview-filename-input [{:keys [background-color border-color text-color]}] (conj (background background-color) (border border-color 5) (text text-color) {:-fx-padding [4 4 4 4]})) (defn fsview-vflow [_] {:-fx-background-color "#00000000" :-fx-hbar-policy :as-needed :-fx-vbar-policy :as-needed}) (defn fsview-vflow-corner [_] (background "#00000000")) (defn fsview-vflow-scroll-bar [{:keys [scroll-color]}] {":horizontal" (conj (background "#00000000") {" .thumb" (background scroll-color)}) ":vertical" (conj (background "#00000000") {" .thumb" (background scroll-color)})}) (defn text-area-status [{:keys [background-color border-color text-color highlight-color]}] (conj (background background-color) (border border-color) (text text-color) (highlight highlight-color) {:-fx-border-style [:hidden :hidden :solid :hidden]})) (defn text-area-editor [{:keys [background-color text-color highlight-color]}] (conj (background background-color) (text text-color) (highlight highlight-color))) (defn text-area-editor-content [{:keys [background-color]}] (background background-color)) (defn text-area-editor-scroll-pane [_] (conj (background "#00000000") {:-fx-hbar-policy :as-needed :-fx-vbar-policy :as-needed})) (defn text-area-editor-scroll-pane-corner [_] (background "#00000000")) (defn text-area-editor-scroll-pane-scroll-bar [{:keys [scroll-color]}] {" .decrement-button" {:-fx-opacity 0} " .increment-button" {:-fx-opacity 0} ":horizontal" (conj (background "#00000000") {" .track" {:-fx-opacity 0} " .track-background" {:-fx-opacity 0} " .thumb" (background scroll-color)}) ":vertical" (conj (background "#00000000") {" .track" {:-fx-opacity 0} " .track-background" {:-fx-opacity 0} " .thumb" (background scroll-color)})}) (defn text-area-numbers [{:keys [background-color line-no-color]}] (conj (background background-color) (highlight background-color) (text line-no-color))) (defn text-area-numbers-text [_] {:-fx-text-alignment :right}) (defn text-area-numbers-content [{:keys [background-color]}] (background background-color)) (defn text-area-numbers-scroll-pane [{:keys [background-color]}] (conj (background background-color) {:-fx-hbar-policy :never :-fx-vbar-policy :never})) (defn compose-style-map [color-map] ;this function should also be able to partially reconstruct a map (-> (root color-map) (assoc-in [".root" "-color-picker"] (color-picker color-map)) (assoc-in [".root" "-color-picker" " .color-picker-label"] (color-picker-label color-map)) (assoc-in [".root" "-color-picker" " .combo-box-popup"] (color-picker-combo-popup color-map)) (assoc-in [".root" "-menu-bar"] (menu-bar color-map)) (assoc-in [".root" "-menu-bar" " .label"] (menu-bar-label color-map)) (assoc-in [".root" "-menu-bar" "-item"] (menu-bar-item color-map)) (assoc-in [".root" "-menu-bar" "-item" " .label"] (menu-bar-item-label color-map)) (assoc-in [".root" "-menu-bar" "-item" "-sub-item"] (menu-bar-sub-item color-map)) (assoc-in [".root" "-fsview"] (fsview color-map)) (assoc-in [".root" "-fsview" "-button"] (fsview-button color-map)) (assoc-in [".root" "-fsview" "-filename-input"] (fsview-filename-input color-map)) (assoc-in [".root" "-fsview" "> .virtual-flow"] (fsview-vflow color-map)) (assoc-in [".root" "-fsview" "> .virtual-flow" "> .corner"] (fsview-vflow-corner color-map)) (assoc-in [".root" "-fsview" "> .virtual-flow" "> .scroll-bar"] (fsview-vflow-scroll-bar color-map)) (assoc-in [".root" "-text-area" "-status"] (text-area-status color-map)) (assoc-in [".root" "-text-area" "-editor"] (text-area-editor color-map)) (assoc-in [".root" "-text-area" "-editor" " .content"] (text-area-editor-content color-map)) (assoc-in [".root" "-text-area" "-editor" " .scroll-pane"] (text-area-editor-scroll-pane color-map)) (assoc-in [".root" "-text-area" "-editor" " .scroll-pane" "> .corner"] (text-area-editor-scroll-pane-corner color-map)) (assoc-in [".root" "-text-area" "-editor" " .scroll-pane" " .scroll-bar"] (text-area-editor-scroll-pane-scroll-bar color-map)) (assoc-in [".root" "-text-area" "-numbers"] (text-area-numbers color-map)) (assoc-in [".root" "-text-area" "-numbers" " *.text"] (text-area-numbers-text color-map)) (assoc-in [".root" "-text-area" "-numbers" " .content"] (text-area-numbers-content color-map)) (assoc-in [".root" "-text-area" "-numbers" " .scroll-pane"] (text-area-numbers-scroll-pane color-map)))) (defn make-style-sheet [color-map] (css/register ::style (compose-style-map color-map))) (def style (make-style-sheet colors))
null
https://raw.githubusercontent.com/vision-05/betterCode/0cd88cdd1f0a968c36ecb41d92ba24137abf2891/bettercode/src/bettercode/css.clj
clojure
this function should also be able to partially reconstruct a map
(ns bettercode.css (:require [cljfx.css :as css] [clojure.edn :as edn] [bettercode.meta])) (def colors (edn/read-string (slurp (bettercode.meta/conf-info :theme-path)))) (defn background-radius [radius] {:-fx-background-radius radius}) (defn background ([color] {:-fx-background-color color}) ([color radius] (conj (background color) (background-radius radius)))) (defn inner-background ([color] {:-fx-control-inner-background color}) ([color _] (conj (inner-background color) {:-fx-background color}))) (defn back-and-inner [color] (conj (background color) (inner-background color ""))) (defn text ([color] {:-fx-text-fill color}) ([color size] (conj (text color) {:-fx-font-size size}))) (defn border-radius [radius] {:-fx-border-radius radius}) (defn border ([color] {:-fx-border-color color}) ([color radius] (conj (border color) (border-radius radius)))) (defn highlight [color] {:-fx-highlight-fill color}) (defn root [{:keys [background-color text-color]}] {".root" (conj (background background-color) (text text-color))}) (defn color-picker [{:keys [background-color border-color text-color highlight-color]}] (conj (background background-color 5) (border border-color 5) (text text-color) (background-radius 5) {":hover" (background highlight-color)})) (defn color-picker-label [{:keys [text-color]}] (text text-color)) (defn color-picker-combo-popup [{:keys [background-color]}] (back-and-inner background-color)) (defn menu-bar [{:keys [background-color text-color]}] (conj (back-and-inner background-color) (text text-color))) (defn menu-bar-label [{:keys [text-color]}] (text text-color 12)) (defn menu-bar-item [{:keys [background-color text-color border-color]}] (conj (back-and-inner background-color) (border border-color) (text text-color))) (defn menu-bar-item-label [{:keys [text-color]}] (text text-color 10)) (defn menu-bar-sub-item [{:keys [background-color text-color button-hover-color]}] (conj (back-and-inner background-color) (border background-color 5) (text text-color) {:-fx-padding [4 4 4 4] ":hover" (background button-hover-color 5)})) (defn fsview [{:keys [background-color text-color]}] (conj (inner-background background-color) (text text-color))) (defn fsview-button [{:keys [background-color border-color text-color button-hover-color]}] (conj (background background-color) (border border-color 5) (text text-color) {:-fx-padding [4 4 4 4] ":hover" (background button-hover-color 5)})) (defn fsview-filename-input [{:keys [background-color border-color text-color]}] (conj (background background-color) (border border-color 5) (text text-color) {:-fx-padding [4 4 4 4]})) (defn fsview-vflow [_] {:-fx-background-color "#00000000" :-fx-hbar-policy :as-needed :-fx-vbar-policy :as-needed}) (defn fsview-vflow-corner [_] (background "#00000000")) (defn fsview-vflow-scroll-bar [{:keys [scroll-color]}] {":horizontal" (conj (background "#00000000") {" .thumb" (background scroll-color)}) ":vertical" (conj (background "#00000000") {" .thumb" (background scroll-color)})}) (defn text-area-status [{:keys [background-color border-color text-color highlight-color]}] (conj (background background-color) (border border-color) (text text-color) (highlight highlight-color) {:-fx-border-style [:hidden :hidden :solid :hidden]})) (defn text-area-editor [{:keys [background-color text-color highlight-color]}] (conj (background background-color) (text text-color) (highlight highlight-color))) (defn text-area-editor-content [{:keys [background-color]}] (background background-color)) (defn text-area-editor-scroll-pane [_] (conj (background "#00000000") {:-fx-hbar-policy :as-needed :-fx-vbar-policy :as-needed})) (defn text-area-editor-scroll-pane-corner [_] (background "#00000000")) (defn text-area-editor-scroll-pane-scroll-bar [{:keys [scroll-color]}] {" .decrement-button" {:-fx-opacity 0} " .increment-button" {:-fx-opacity 0} ":horizontal" (conj (background "#00000000") {" .track" {:-fx-opacity 0} " .track-background" {:-fx-opacity 0} " .thumb" (background scroll-color)}) ":vertical" (conj (background "#00000000") {" .track" {:-fx-opacity 0} " .track-background" {:-fx-opacity 0} " .thumb" (background scroll-color)})}) (defn text-area-numbers [{:keys [background-color line-no-color]}] (conj (background background-color) (highlight background-color) (text line-no-color))) (defn text-area-numbers-text [_] {:-fx-text-alignment :right}) (defn text-area-numbers-content [{:keys [background-color]}] (background background-color)) (defn text-area-numbers-scroll-pane [{:keys [background-color]}] (conj (background background-color) {:-fx-hbar-policy :never :-fx-vbar-policy :never})) (-> (root color-map) (assoc-in [".root" "-color-picker"] (color-picker color-map)) (assoc-in [".root" "-color-picker" " .color-picker-label"] (color-picker-label color-map)) (assoc-in [".root" "-color-picker" " .combo-box-popup"] (color-picker-combo-popup color-map)) (assoc-in [".root" "-menu-bar"] (menu-bar color-map)) (assoc-in [".root" "-menu-bar" " .label"] (menu-bar-label color-map)) (assoc-in [".root" "-menu-bar" "-item"] (menu-bar-item color-map)) (assoc-in [".root" "-menu-bar" "-item" " .label"] (menu-bar-item-label color-map)) (assoc-in [".root" "-menu-bar" "-item" "-sub-item"] (menu-bar-sub-item color-map)) (assoc-in [".root" "-fsview"] (fsview color-map)) (assoc-in [".root" "-fsview" "-button"] (fsview-button color-map)) (assoc-in [".root" "-fsview" "-filename-input"] (fsview-filename-input color-map)) (assoc-in [".root" "-fsview" "> .virtual-flow"] (fsview-vflow color-map)) (assoc-in [".root" "-fsview" "> .virtual-flow" "> .corner"] (fsview-vflow-corner color-map)) (assoc-in [".root" "-fsview" "> .virtual-flow" "> .scroll-bar"] (fsview-vflow-scroll-bar color-map)) (assoc-in [".root" "-text-area" "-status"] (text-area-status color-map)) (assoc-in [".root" "-text-area" "-editor"] (text-area-editor color-map)) (assoc-in [".root" "-text-area" "-editor" " .content"] (text-area-editor-content color-map)) (assoc-in [".root" "-text-area" "-editor" " .scroll-pane"] (text-area-editor-scroll-pane color-map)) (assoc-in [".root" "-text-area" "-editor" " .scroll-pane" "> .corner"] (text-area-editor-scroll-pane-corner color-map)) (assoc-in [".root" "-text-area" "-editor" " .scroll-pane" " .scroll-bar"] (text-area-editor-scroll-pane-scroll-bar color-map)) (assoc-in [".root" "-text-area" "-numbers"] (text-area-numbers color-map)) (assoc-in [".root" "-text-area" "-numbers" " *.text"] (text-area-numbers-text color-map)) (assoc-in [".root" "-text-area" "-numbers" " .content"] (text-area-numbers-content color-map)) (assoc-in [".root" "-text-area" "-numbers" " .scroll-pane"] (text-area-numbers-scroll-pane color-map)))) (defn make-style-sheet [color-map] (css/register ::style (compose-style-map color-map))) (def style (make-style-sheet colors))
b54d462c03e85de932d3fe926eb0610668be9304823b1422fd3956c73f61cfea
corecursive/sicp-study-group
operation-test.scm
(load "vector.scm") (load "rectangle.scm") (load "graphics.scm") (load "picture.scm") (load "operation.scm") (load "escher.scm") Based on Functional Geometry by ;; -systems.co.uk/phAcademic/papers/funcgeo.pdf (define (draw pict name) (define rectangle (make-rect (make-vect 0 0) (make-vect 1000 0) (make-vect 0 1000))) (make-viewport name 1000 1000) (pict rectangle)) (define E (make-picture '())) (define P (make-picture p)) (define Q (make-picture q)) (define R (make-picture r)) (define S (make-picture s)) (define T (quartet P Q R S)) (define U (cycle (rotate Q))) (define S1 (quartet E E (rotate T) T)) (define S2 (quartet S1 S1 (rotate T) T)) (define C1 (quartet E E E U)) (define C2 (quartet C1 S1 (rotate S1) U)) (define C3 (quartet C2 S2 (rotate S2) U)) (define PC (quartet C2 S2 (rotate S2) (rotate T))) (define PL (cycle PC)) (define C (nonet C2 S2 S2 (rotate S2) U (rotate T) (rotate S2) (rotate T) (rotate Q))) (define SL (cycle C)) (draw PL "pseudo limit") (draw SL "square limit")
null
https://raw.githubusercontent.com/corecursive/sicp-study-group/578ebfc3d85f13a4b00cc2e49219906eba5b539d/wulab/lecture-3a/picture-language/operation-test.scm
scheme
-systems.co.uk/phAcademic/papers/funcgeo.pdf
(load "vector.scm") (load "rectangle.scm") (load "graphics.scm") (load "picture.scm") (load "operation.scm") (load "escher.scm") Based on Functional Geometry by (define (draw pict name) (define rectangle (make-rect (make-vect 0 0) (make-vect 1000 0) (make-vect 0 1000))) (make-viewport name 1000 1000) (pict rectangle)) (define E (make-picture '())) (define P (make-picture p)) (define Q (make-picture q)) (define R (make-picture r)) (define S (make-picture s)) (define T (quartet P Q R S)) (define U (cycle (rotate Q))) (define S1 (quartet E E (rotate T) T)) (define S2 (quartet S1 S1 (rotate T) T)) (define C1 (quartet E E E U)) (define C2 (quartet C1 S1 (rotate S1) U)) (define C3 (quartet C2 S2 (rotate S2) U)) (define PC (quartet C2 S2 (rotate S2) (rotate T))) (define PL (cycle PC)) (define C (nonet C2 S2 S2 (rotate S2) U (rotate T) (rotate S2) (rotate T) (rotate Q))) (define SL (cycle C)) (draw PL "pseudo limit") (draw SL "square limit")
f74ed6f7d287bdb98271c360d9960a8c538b56ccd2a5768e45557df91b547052
ijvcms/chuanqi_dev
player_shop_once_cache.erl
%%%------------------------------------------------------------------- %%% @author qhb ( C ) 2016 , < COMPANY > %%% @doc %%% %%% @end Created : 23 . 九月 2016 上午11:43 %%%------------------------------------------------------------------- -module(player_shop_once_cache). -include("common.hrl"). -include("cache.hrl"). %% API -export([ insert/1, update/2, delete/1, select_row/1, select_all/1 ]). insert(Info) -> PlayerId = Info#db_player_shop_once.player_id, Lv = Info#db_player_shop_once.lv, Pos = Info#db_player_shop_once.pos, db_cache_lib:insert(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}, Info). update({PlayerId, Lv, Pos}, Info) -> db_cache_lib:update(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}, Info). delete({PlayerId, Lv, Pos}) -> db_cache_lib:delete(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}). select_row({PlayerId, Lv, Pos}) -> db_cache_lib:select_row(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}). select_all({PlayerId, Lv, '_'}) -> db_cache_lib:select_all(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, '_'}).
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/shop/player_shop_once_cache.erl
erlang
------------------------------------------------------------------- @author qhb @doc @end ------------------------------------------------------------------- API
( C ) 2016 , < COMPANY > Created : 23 . 九月 2016 上午11:43 -module(player_shop_once_cache). -include("common.hrl"). -include("cache.hrl"). -export([ insert/1, update/2, delete/1, select_row/1, select_all/1 ]). insert(Info) -> PlayerId = Info#db_player_shop_once.player_id, Lv = Info#db_player_shop_once.lv, Pos = Info#db_player_shop_once.pos, db_cache_lib:insert(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}, Info). update({PlayerId, Lv, Pos}, Info) -> db_cache_lib:update(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}, Info). delete({PlayerId, Lv, Pos}) -> db_cache_lib:delete(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}). select_row({PlayerId, Lv, Pos}) -> db_cache_lib:select_row(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, Pos}). select_all({PlayerId, Lv, '_'}) -> db_cache_lib:select_all(?DB_PLAYER_SHOP_ONCE, {PlayerId, Lv, '_'}).
c50046099e5fc916385c042862c02f913a93dfb4d49d2b76028ebe9fb6c10c2c
iskandr/parakeet-retired
MutableSet.mli
type 'a t val create : int -> 'a t val mem : 'a t -> 'a -> bool val add : 'a t -> 'a -> unit val remove : 'a t -> 'a -> unit val enum : 'a t -> 'a Enum.t val iter : ('a -> unit) -> 'a t -> unit val fold : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b val copy : 'a t -> 'a t val is_empty : 'a t -> bool
null
https://raw.githubusercontent.com/iskandr/parakeet-retired/3d7e6e5b699f83ce8a1c01290beed0b78c0d0945/Base/MutableSet.mli
ocaml
type 'a t val create : int -> 'a t val mem : 'a t -> 'a -> bool val add : 'a t -> 'a -> unit val remove : 'a t -> 'a -> unit val enum : 'a t -> 'a Enum.t val iter : ('a -> unit) -> 'a t -> unit val fold : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b val copy : 'a t -> 'a t val is_empty : 'a t -> bool
6dc7551c9d4461cfe393c80e344716763c1f3035267a8fdc99ad2a4bf68aabde
fabianbergmark/ECMA-262
JSON.hs
module Language.JavaScript.JSON where import Control.Applicative ((<$>), (<*)) import Text.Parsec ((<|>), char, choice, notFollowedBy, optionMaybe, satisfy) import Text.ParserCombinators.Parsec.Prim (GenParser) import Language.JavaScript.Lexer type JSONParser a = GenParser Char () a jsonWhiteSpace :: JSONParser Char jsonWhiteSpace = choice $ char <$> [ '\t', '\r', '\n', ' ' ] jsonString = do { char '"'; ms <- optionMaybe jsonStringCharacters; char '"' } jsonStringCharacters = do { c <- jsonStringCharacter; ms <- optionMaybe jsonStringCharacters; return () } jsonStringCharacter = do { notFollowedBy $ satisfy $ \c -> c == '"' || c == '\\' || c <= '\x001F'; sourceCharacter } <|> do { char '\\'; jsonEscapeSequence } jsonEscapeSequence = jsonEscapeCharacter <|> unicodeEscapeSequence jsonEscapeCharacter = choice $ char <$> [ '"', '/', '\\', 'b', 'f', 'n', 'r', 't' ] jsonNumber = do { optionMaybe $ char '-'; decimalIntegerLiteral; mfv <- jsonFraction; mev <- optionMaybe exponentPart; return () } jsonFraction = do { char '.'; decimalDigits } jsonNullLiteral = do { nullLiteral } jsonBooleanLiteral = do { booleanLiteral } jsonText = do { jsonValue } jsonValue = jsonNullLiteral <|> jsonBooleanLiteral <|> jsonObject <|> jsonArray <|> jsonString <|> jsonNumber jsonObject = do { char '{'; mml <- optionMaybe jsonMemberList; char '}' } jsonMember = do { jsonString; char ':'; jsonValue } jsonMemberList = do { m <- jsonMember; applyRest jsonMemberListRest } jsonMemberListRest = do { char ','; m <- jsonMember; applyRest jsonMemberListRest } jsonArray = do { char '['; mel <- optionMaybe jsonElementList; char ']' } jsonElementList = do { v <- jsonValue; applyRest jsonElementListRest } jsonElementListRest = do { char ','; v <- jsonValue; applyRest jsonElementListRest }
null
https://raw.githubusercontent.com/fabianbergmark/ECMA-262/ff1d8c347514625595f34b48e95a594c35b052ea/src/Language/JavaScript/JSON.hs
haskell
module Language.JavaScript.JSON where import Control.Applicative ((<$>), (<*)) import Text.Parsec ((<|>), char, choice, notFollowedBy, optionMaybe, satisfy) import Text.ParserCombinators.Parsec.Prim (GenParser) import Language.JavaScript.Lexer type JSONParser a = GenParser Char () a jsonWhiteSpace :: JSONParser Char jsonWhiteSpace = choice $ char <$> [ '\t', '\r', '\n', ' ' ] jsonString = do { char '"'; ms <- optionMaybe jsonStringCharacters; char '"' } jsonStringCharacters = do { c <- jsonStringCharacter; ms <- optionMaybe jsonStringCharacters; return () } jsonStringCharacter = do { notFollowedBy $ satisfy $ \c -> c == '"' || c == '\\' || c <= '\x001F'; sourceCharacter } <|> do { char '\\'; jsonEscapeSequence } jsonEscapeSequence = jsonEscapeCharacter <|> unicodeEscapeSequence jsonEscapeCharacter = choice $ char <$> [ '"', '/', '\\', 'b', 'f', 'n', 'r', 't' ] jsonNumber = do { optionMaybe $ char '-'; decimalIntegerLiteral; mfv <- jsonFraction; mev <- optionMaybe exponentPart; return () } jsonFraction = do { char '.'; decimalDigits } jsonNullLiteral = do { nullLiteral } jsonBooleanLiteral = do { booleanLiteral } jsonText = do { jsonValue } jsonValue = jsonNullLiteral <|> jsonBooleanLiteral <|> jsonObject <|> jsonArray <|> jsonString <|> jsonNumber jsonObject = do { char '{'; mml <- optionMaybe jsonMemberList; char '}' } jsonMember = do { jsonString; char ':'; jsonValue } jsonMemberList = do { m <- jsonMember; applyRest jsonMemberListRest } jsonMemberListRest = do { char ','; m <- jsonMember; applyRest jsonMemberListRest } jsonArray = do { char '['; mel <- optionMaybe jsonElementList; char ']' } jsonElementList = do { v <- jsonValue; applyRest jsonElementListRest } jsonElementListRest = do { char ','; v <- jsonValue; applyRest jsonElementListRest }
fbef3cd52ce0db5e68c23303d019799db222f6a23b0d155776e558fd94e9cbe3
seantempesta/cljs-react-navigation
core.cljs
(ns uiexplorer.core (:require [reagent.core :as r :refer [atom]] [re-frame.core :refer [subscribe dispatch dispatch-sync]] [uiexplorer.react-requires :refer [Expo]] [uiexplorer.routing :as routing] [uiexplorer.events] [uiexplorer.subs])) (def app-root routing/app-root) (defn init [] (aset js/console "disableYellowBox" true) (dispatch-sync [:initialize-db]) (.registerRootComponent Expo (r/reactify-component routing/app-root)) ( UIExplorer " # ( r / reactify - component routing / app - root ) ) )
null
https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/uiexplorer/src/uiexplorer/core.cljs
clojure
(ns uiexplorer.core (:require [reagent.core :as r :refer [atom]] [re-frame.core :refer [subscribe dispatch dispatch-sync]] [uiexplorer.react-requires :refer [Expo]] [uiexplorer.routing :as routing] [uiexplorer.events] [uiexplorer.subs])) (def app-root routing/app-root) (defn init [] (aset js/console "disableYellowBox" true) (dispatch-sync [:initialize-db]) (.registerRootComponent Expo (r/reactify-component routing/app-root)) ( UIExplorer " # ( r / reactify - component routing / app - root ) ) )
04dabb8d8b56430576ab4d091c09ff2f4cbff39ed0e177d0727d987045f47591
nasser/magic
run_test.clj
(assembly-load-from "clojure.tools.namespace.dll") (assembly-load-from "clojure.data.generators.dll") (assembly-load-from "clojure.test.generative.dll") (assembly-load-from "clojure.test.check.dll") ( System / setProperty " java.awt.headless " " true " ) (require '[clojure.test :as test] '[clojure.tools.namespace.find :as ns]) System / getProperty (ns/find-namespaces-in-dir (System.IO.DirectoryInfo. "clojure/test_clojure")))) ;;; (java.io.File. "test") (doseq [ns namespaces] (require ns)) (let [summary (apply test/run-tests namespaces)] (Environment/Exit (if (test/successful? summary) 0 -1))) ;;; System/exit
null
https://raw.githubusercontent.com/nasser/magic/7a46f773bc7785c82d9527d52c1a8c28ac16e195/tests/clojure/run_test.clj
clojure
(java.io.File. "test") System/exit
(assembly-load-from "clojure.tools.namespace.dll") (assembly-load-from "clojure.data.generators.dll") (assembly-load-from "clojure.test.generative.dll") (assembly-load-from "clojure.test.check.dll") ( System / setProperty " java.awt.headless " " true " ) (require '[clojure.test :as test] '[clojure.tools.namespace.find :as ns]) System / getProperty (doseq [ns namespaces] (require ns)) (let [summary (apply test/run-tests namespaces)]
a9f0aa7920892dc1068a9b86d7d8e80ac6761c5c9459711b7d13efd3cd8d34f7
phoityne/haskell-debug-adapter
Watch.hs
# LANGUAGE LambdaCase # module Haskell.Debug.Adapter.Watch where import Control.Monad.IO.Class import qualified System.FSNotify as S import Control.Lens import Control.Concurrent (threadDelay) import Control.Concurrent.MVar import Control.Monad.State.Lazy import qualified System.Log.Logger as L import Control.Monad.Except import qualified Data.List as L import Haskell.Debug.Adapter.Type import Haskell.Debug.Adapter.Utility import Haskell.Debug.Adapter.Constant -- | -- run :: AppStores -> IO () run appData = do L.debugM _LOG_WATCH "start watch app" _ <- runApp appData app L.debugM _LOG_WATCH "end watch app" -- | -- app :: AppContext () app = flip catchError errHdl $ do liftIO $ L.infoM _LOG_WATCH "wait getting workspace path." ws <- getWS liftIO $ L.infoM _LOG_WATCH $ "start watching " ++ ws reqStore <- view reqStoreAppStores <$> get let conf = S.defaultConfig liftIO $ S.withManagerConf conf $ goIO ws reqStore where -- | -- errHdl msg = do criticalEV _LOG_REQUEST msg addEvent CriticalExitEvent -- | -- goIO ws reqStore mgr = do S.watchTree mgr ws hsFilter (action reqStore) forever $ threadDelay _1_SEC -- | -- hsFilter ev = L.isSuffixOf _HS_FILE_EXT $ S.eventPath ev -- | -- action mvar ev@(S.Added{}) = sendRequest mvar ev action mvar ev@(S.Modified{}) = sendRequest mvar ev action _ _ = return () -- | -- sendRequest mvar ev = do L.debugM _LOG_WATCH $ "detect. " ++ show ev let req = WrapRequest $ InternalLoadRequest $ HdaInternalLoadRequest $ S.eventPath ev reqs <- takeMVar mvar putMVar mvar (req : reqs) -- | -- getWS :: AppContext FilePath getWS = do wsMVar <- view workspaceAppStores <$> get ws <- liftIO $ readMVar wsMVar if not (null ws) then return ws else do liftIO $ threadDelay _1_SEC getWS
null
https://raw.githubusercontent.com/phoityne/haskell-debug-adapter/a8914e7768302b38a3d644906d27b530d1c8782d/src/Haskell/Debug/Adapter/Watch.hs
haskell
| | | | | | | |
# LANGUAGE LambdaCase # module Haskell.Debug.Adapter.Watch where import Control.Monad.IO.Class import qualified System.FSNotify as S import Control.Lens import Control.Concurrent (threadDelay) import Control.Concurrent.MVar import Control.Monad.State.Lazy import qualified System.Log.Logger as L import Control.Monad.Except import qualified Data.List as L import Haskell.Debug.Adapter.Type import Haskell.Debug.Adapter.Utility import Haskell.Debug.Adapter.Constant run :: AppStores -> IO () run appData = do L.debugM _LOG_WATCH "start watch app" _ <- runApp appData app L.debugM _LOG_WATCH "end watch app" app :: AppContext () app = flip catchError errHdl $ do liftIO $ L.infoM _LOG_WATCH "wait getting workspace path." ws <- getWS liftIO $ L.infoM _LOG_WATCH $ "start watching " ++ ws reqStore <- view reqStoreAppStores <$> get let conf = S.defaultConfig liftIO $ S.withManagerConf conf $ goIO ws reqStore where errHdl msg = do criticalEV _LOG_REQUEST msg addEvent CriticalExitEvent goIO ws reqStore mgr = do S.watchTree mgr ws hsFilter (action reqStore) forever $ threadDelay _1_SEC hsFilter ev = L.isSuffixOf _HS_FILE_EXT $ S.eventPath ev action mvar ev@(S.Added{}) = sendRequest mvar ev action mvar ev@(S.Modified{}) = sendRequest mvar ev action _ _ = return () sendRequest mvar ev = do L.debugM _LOG_WATCH $ "detect. " ++ show ev let req = WrapRequest $ InternalLoadRequest $ HdaInternalLoadRequest $ S.eventPath ev reqs <- takeMVar mvar putMVar mvar (req : reqs) getWS :: AppContext FilePath getWS = do wsMVar <- view workspaceAppStores <$> get ws <- liftIO $ readMVar wsMVar if not (null ws) then return ws else do liftIO $ threadDelay _1_SEC getWS
e7dc8b962dc6a27e9ba51a49ccc41f75061edb26e8e376fbed5a60ac82b64299
paurkedal/ocaml-caqti
caqti_dynload.ml
Copyright ( C ) 2017 - -2018 Petter A. Urkedal < > * * 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 LGPL-3.0 Linking 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 * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * 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 LGPL-3.0 Linking 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 * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) let debug = try bool_of_string (Sys.getenv "CAQTI_DEBUG_DYNLOAD") with Not_found -> false let backend_predicates () = (match Sys.backend_type with | Sys.Native -> ["native"] | Sys.Bytecode -> ["byte"] | Sys.Other _ -> []) let init = lazy begin let predicates = backend_predicates () in Findlib.init (); Findlib.record_package_predicates predicates; List.iter (Findlib.record_package Record_core) (Findlib.package_deep_ancestors predicates ["caqti"]); if debug then Printf.eprintf "\ [DEBUG] Caqti_dynload: recorded_predicates = %s\n\ [DEBUG] Caqti_dynload: recorded_packages.core = %s\n\ [DEBUG] Caqti_dynload: recorded_packages.load = %s\n%!" (String.concat " " (Findlib.recorded_predicates ())) (String.concat " " (Findlib.recorded_packages Record_core)) (String.concat " " (Findlib.recorded_packages Record_load)) end let () = Caqti_platform.Connector.define_loader @@ fun pkg -> Lazy.force init; if debug then Printf.eprintf "[DEBUG] Caqti_dynload: requested package: %s\n" pkg; (try Ok (Fl_dynload.load_packages ~debug [pkg]) with | Dynlink.Error err -> Error (Dynlink.error_message err) | Findlib.No_such_package (_pkg, info) -> Error info) module Weak_ = struct include Weak end (* for caqti-driver-mariadb *)
null
https://raw.githubusercontent.com/paurkedal/ocaml-caqti/f8b7a1c2bde2013d24ffc0b104f4af6e5f01480b/caqti-dynload/lib/caqti_dynload.ml
ocaml
for caqti-driver-mariadb
Copyright ( C ) 2017 - -2018 Petter A. Urkedal < > * * 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 LGPL-3.0 Linking 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 * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * 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 LGPL-3.0 Linking 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 * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) let debug = try bool_of_string (Sys.getenv "CAQTI_DEBUG_DYNLOAD") with Not_found -> false let backend_predicates () = (match Sys.backend_type with | Sys.Native -> ["native"] | Sys.Bytecode -> ["byte"] | Sys.Other _ -> []) let init = lazy begin let predicates = backend_predicates () in Findlib.init (); Findlib.record_package_predicates predicates; List.iter (Findlib.record_package Record_core) (Findlib.package_deep_ancestors predicates ["caqti"]); if debug then Printf.eprintf "\ [DEBUG] Caqti_dynload: recorded_predicates = %s\n\ [DEBUG] Caqti_dynload: recorded_packages.core = %s\n\ [DEBUG] Caqti_dynload: recorded_packages.load = %s\n%!" (String.concat " " (Findlib.recorded_predicates ())) (String.concat " " (Findlib.recorded_packages Record_core)) (String.concat " " (Findlib.recorded_packages Record_load)) end let () = Caqti_platform.Connector.define_loader @@ fun pkg -> Lazy.force init; if debug then Printf.eprintf "[DEBUG] Caqti_dynload: requested package: %s\n" pkg; (try Ok (Fl_dynload.load_packages ~debug [pkg]) with | Dynlink.Error err -> Error (Dynlink.error_message err) | Findlib.No_such_package (_pkg, info) -> Error info)
a2fa4fb7327deac55cb0c39af0897ca9173a57050e62178b48cf7ed4af155b32
camilodoa/deig
fitness.clj
(ns deig.fitness (:require [libpython-clj.require :refer [require-python]] [libpython-clj.python :as py :refer [call-attr]] [quil.core :as q])) (require-python '[numpy :as np] '[keras_preprocessing.image :as image-processing] '[tensorflow.keras.models :as models]) ;; Load default Keras MNIST classifier (def model (models/load_model "mnist.h5")) (defn fitness [img] "Evaluate an image based on its best categorical score" (let [x-array (image-processing/img_to_array img) x (np/expand_dims (np/array x-array) 0) probabilities (first (call-attr model "predict_proba" x)) fitness (* (apply max probabilities) 100)] fitness)) (defn predict-class [img] "Evaluate an image based on its best categorical score" (let [x-array (image-processing/img_to_array img) x (np/expand_dims (np/array x-array) 0) class (first (call-attr model "predict_classes" x))] class)) (defn save-image [genome generation class] "Save individual's genome to file" (call-attr (image-processing/array_to_img genome) "save" (str "./individuals/gen" generation "predicted" class ".png"))) ;; Example code (defn grayscale-genome [dimension] "Returns random grayscale genome of dimensions dimension*dimension" (vec (repeatedly dimension #(vec (repeatedly dimension (fn [] (vector (* (rand) 256)))))))) (defn line-genome [] "Returns a genome with a centered vertical white line." (let [genome (grayscale-genome 28)] (vec (map-indexed (fn [i col] (map-indexed (fn [j pixel] (if (and (< j 16) (> j 13) (> i 4) (< i 26)) [255] [0])) col)) genome)))) (defn trial "Run a practice fitness run" [] (fitness (line-genome))) : Should return 100 . #_ (trial)
null
https://raw.githubusercontent.com/camilodoa/deig/1133f2e07d1fa25d1db5c0586ebe4b82e1562c9c/src/deig/fitness.clj
clojure
Load default Keras MNIST classifier Example code
(ns deig.fitness (:require [libpython-clj.require :refer [require-python]] [libpython-clj.python :as py :refer [call-attr]] [quil.core :as q])) (require-python '[numpy :as np] '[keras_preprocessing.image :as image-processing] '[tensorflow.keras.models :as models]) (def model (models/load_model "mnist.h5")) (defn fitness [img] "Evaluate an image based on its best categorical score" (let [x-array (image-processing/img_to_array img) x (np/expand_dims (np/array x-array) 0) probabilities (first (call-attr model "predict_proba" x)) fitness (* (apply max probabilities) 100)] fitness)) (defn predict-class [img] "Evaluate an image based on its best categorical score" (let [x-array (image-processing/img_to_array img) x (np/expand_dims (np/array x-array) 0) class (first (call-attr model "predict_classes" x))] class)) (defn save-image [genome generation class] "Save individual's genome to file" (call-attr (image-processing/array_to_img genome) "save" (str "./individuals/gen" generation "predicted" class ".png"))) (defn grayscale-genome [dimension] "Returns random grayscale genome of dimensions dimension*dimension" (vec (repeatedly dimension #(vec (repeatedly dimension (fn [] (vector (* (rand) 256)))))))) (defn line-genome [] "Returns a genome with a centered vertical white line." (let [genome (grayscale-genome 28)] (vec (map-indexed (fn [i col] (map-indexed (fn [j pixel] (if (and (< j 16) (> j 13) (> i 4) (< i 26)) [255] [0])) col)) genome)))) (defn trial "Run a practice fitness run" [] (fitness (line-genome))) : Should return 100 . #_ (trial)
b713ebd3fd100f067786e4a26b80aa1b90ae68da0fa63b63759816e955ed1d7a
archimag/cl-mssql
mssql.lisp
;;;; mssql.lisp ;;;; ;;;; This file is part of the cl-mssql library, released under Lisp-LGPL. ;;;; See file COPYING for details. ;;;; Author : < > (in-package :mssql) (define-foreign-library sybdb (:darwin "libsybdb.dylib") (:linux (:or "libsybdb.so" "libsybdb.so.5")) (:unix "libsybdb.so") (t (:default "sybdb"))) (with-simple-restart (skip "Skip loading foreign library tds.") (use-foreign-library sybdb)) (defctype %DBPROCESS :pointer) (defctype %CHARPTR :pointer) (defctype %LOGINREC :pointer) (defctype %RETCODE :int) (defctype %BYTE :uchar) (defctype %DBINT :int32) (defctype %DBSMALLINT :int16) (defconstant +FAIL+ 0) (defconstant +INT_CANCEL+ 2) (define-condition mssql-error (error) ((messages :initarg :messages :initform nil))) (defmethod print-object ((err mssql-error) stream) (format stream "~{~A~^~%~}" (slot-value err 'messages))) ;; error-handler (defcfun ("dberrhandle" %dberrhandle) :pointer (handler :pointer)) (defvar *error-message-list*) (defcallback %error-handler :int ((%dbproc %DBPROCESS) (%severity :int) (%dberr :int) (%oserr :int) (%dberrstr :pointer) (%oserrstr :pointer)) (declare (ignore %dbproc %severity %dberr %oserr)) (if (boundp '*error-message-list*) (progn (unless (null-pointer-p %dberrstr) (push (foreign-string-to-lisp %dberrstr) *error-message-list*)) (unless (null-pointer-p %oserrstr) (push (foreign-string-to-lisp %oserrstr) *error-message-list*))) (progn (unless (null-pointer-p %dberrstr) (warn (foreign-string-to-lisp %dberrstr))) (unless (null-pointer-p %oserrstr) (warn (foreign-string-to-lisp %oserrstr))))) +INT_CANCEL+) (%dberrhandle (callback %error-handler)) ;;; message-handler (defcfun ("dbmsghandle" %dbmsghandle) :pointer (handler :pointer)) (defcallback %message-handler :int ((%dbproc %DBPROCESS) (%msgno :int) (%msgstate :int) (%severity :int) (%msgtext :pointer) (%svrname :pointer) (%proc :pointer) (%line :int)) (declare (ignore %dbproc %severity %msgno %msgstate %svrname %proc %line)) (unless (null-pointer-p %msgtext) (if (boundp '*error-message-list*) (push (foreign-string-to-lisp %msgtext) *error-message-list*) (warn (foreign-string-to-lisp %msgtext)))) 0) (%dbmsghandle (callback %message-handler)) ;; define-sybdb-function (defmacro define-sybdb-function ((foreign-name lisp-name &optional check-mode error-message) return-type &body args) (if check-mode (let ((impl-name (intern (format nil "%~A" (symbol-name lisp-name)))) (simplify-args (map 'list #'car args)) (error-msg (or error-message (format nil "~(~A fail~)" lisp-name))) (check-fun (case check-mode (:check-retcode '(lambda (val) (= val +FAIL+))) (:check-null-pointer '(lambda (val) (null-pointer-p val)))))) `(progn (defcfun (,foreign-name ,impl-name) ,return-type ,@args) (defun ,lisp-name ,simplify-args (let ((*error-message-list* nil)) (let ((result (,impl-name ,@simplify-args))) (if (funcall ,check-fun result) (progn (push ,error-msg *error-message-list*) (error 'mssql-error :messages (reverse *error-message-list*))) (progn (when *error-message-list* (format t "~{~A~^~%~}~%" *error-message-list*)) result))))))) `(defcfun (,foreign-name ,lisp-name) ,return-type ,@args))) ;;; utility (defun cffi-string (str &optional (pool garbage-pools::*pool*)) (if str (garbage-pools:cleanup-register (foreign-string-alloc str) #'foreign-string-free pool) (null-pointer)))
null
https://raw.githubusercontent.com/archimag/cl-mssql/045602a19a32254108f2b75871049293f49731eb/src/mssql.lisp
lisp
mssql.lisp This file is part of the cl-mssql library, released under Lisp-LGPL. See file COPYING for details. error-handler message-handler define-sybdb-function utility
Author : < > (in-package :mssql) (define-foreign-library sybdb (:darwin "libsybdb.dylib") (:linux (:or "libsybdb.so" "libsybdb.so.5")) (:unix "libsybdb.so") (t (:default "sybdb"))) (with-simple-restart (skip "Skip loading foreign library tds.") (use-foreign-library sybdb)) (defctype %DBPROCESS :pointer) (defctype %CHARPTR :pointer) (defctype %LOGINREC :pointer) (defctype %RETCODE :int) (defctype %BYTE :uchar) (defctype %DBINT :int32) (defctype %DBSMALLINT :int16) (defconstant +FAIL+ 0) (defconstant +INT_CANCEL+ 2) (define-condition mssql-error (error) ((messages :initarg :messages :initform nil))) (defmethod print-object ((err mssql-error) stream) (format stream "~{~A~^~%~}" (slot-value err 'messages))) (defcfun ("dberrhandle" %dberrhandle) :pointer (handler :pointer)) (defvar *error-message-list*) (defcallback %error-handler :int ((%dbproc %DBPROCESS) (%severity :int) (%dberr :int) (%oserr :int) (%dberrstr :pointer) (%oserrstr :pointer)) (declare (ignore %dbproc %severity %dberr %oserr)) (if (boundp '*error-message-list*) (progn (unless (null-pointer-p %dberrstr) (push (foreign-string-to-lisp %dberrstr) *error-message-list*)) (unless (null-pointer-p %oserrstr) (push (foreign-string-to-lisp %oserrstr) *error-message-list*))) (progn (unless (null-pointer-p %dberrstr) (warn (foreign-string-to-lisp %dberrstr))) (unless (null-pointer-p %oserrstr) (warn (foreign-string-to-lisp %oserrstr))))) +INT_CANCEL+) (%dberrhandle (callback %error-handler)) (defcfun ("dbmsghandle" %dbmsghandle) :pointer (handler :pointer)) (defcallback %message-handler :int ((%dbproc %DBPROCESS) (%msgno :int) (%msgstate :int) (%severity :int) (%msgtext :pointer) (%svrname :pointer) (%proc :pointer) (%line :int)) (declare (ignore %dbproc %severity %msgno %msgstate %svrname %proc %line)) (unless (null-pointer-p %msgtext) (if (boundp '*error-message-list*) (push (foreign-string-to-lisp %msgtext) *error-message-list*) (warn (foreign-string-to-lisp %msgtext)))) 0) (%dbmsghandle (callback %message-handler)) (defmacro define-sybdb-function ((foreign-name lisp-name &optional check-mode error-message) return-type &body args) (if check-mode (let ((impl-name (intern (format nil "%~A" (symbol-name lisp-name)))) (simplify-args (map 'list #'car args)) (error-msg (or error-message (format nil "~(~A fail~)" lisp-name))) (check-fun (case check-mode (:check-retcode '(lambda (val) (= val +FAIL+))) (:check-null-pointer '(lambda (val) (null-pointer-p val)))))) `(progn (defcfun (,foreign-name ,impl-name) ,return-type ,@args) (defun ,lisp-name ,simplify-args (let ((*error-message-list* nil)) (let ((result (,impl-name ,@simplify-args))) (if (funcall ,check-fun result) (progn (push ,error-msg *error-message-list*) (error 'mssql-error :messages (reverse *error-message-list*))) (progn (when *error-message-list* (format t "~{~A~^~%~}~%" *error-message-list*)) result))))))) `(defcfun (,foreign-name ,lisp-name) ,return-type ,@args))) (defun cffi-string (str &optional (pool garbage-pools::*pool*)) (if str (garbage-pools:cleanup-register (foreign-string-alloc str) #'foreign-string-free pool) (null-pointer)))
8c3b0f3f1553f4efba56e2a7bde96b26b2935b60d1650b700f19b55f44085933
ryanpbrewster/haskell
monad_exploration_1.hs
-- monad_exploration.hs import Control.Monad {- Minimal definition of a monadic Wrapper -} data Wrapper a = Wrapper a deriving (Show, Eq, Ord) instance Monad Wrapper where return x = Wrapper x Wrapper x >>= f = f x To add two wrappers , we need to ` ` lift '' the ( + ) function main = do print $ liftM2 (+) (Wrapper 1) (Wrapper 2) print $ foldl1 (liftM2 (+)) [Wrapper i | i <- [1..10]]
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/hello-world/monad_exploration_1.hs
haskell
monad_exploration.hs Minimal definition of a monadic Wrapper
import Control.Monad data Wrapper a = Wrapper a deriving (Show, Eq, Ord) instance Monad Wrapper where return x = Wrapper x Wrapper x >>= f = f x To add two wrappers , we need to ` ` lift '' the ( + ) function main = do print $ liftM2 (+) (Wrapper 1) (Wrapper 2) print $ foldl1 (liftM2 (+)) [Wrapper i | i <- [1..10]]
3f0f1f86241be66fa6cb0d5ae6a45e452c705189590f0eec7b625a9e02c39784
yogthos/pg-feed-demo
handler.clj
(ns pg-feed-demo.test.handler (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [pg-feed-demo.handler :refer :all])) (deftest test-app (testing "main route" (let [response ((app) (request :get "/"))] (is (= 200 (:status response))))) (testing "not-found route" (let [response ((app) (request :get "/invalid"))] (is (= 404 (:status response))))))
null
https://raw.githubusercontent.com/yogthos/pg-feed-demo/4b6e0cb7903182a9211c62ef85d36a2b7d78405f/test/clj/pg_feed_demo/test/handler.clj
clojure
(ns pg-feed-demo.test.handler (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [pg-feed-demo.handler :refer :all])) (deftest test-app (testing "main route" (let [response ((app) (request :get "/"))] (is (= 200 (:status response))))) (testing "not-found route" (let [response ((app) (request :get "/invalid"))] (is (= 404 (:status response))))))
c82311129253fa9d5ca302ba25e9cee347110ebce2e5ded6bac5477bb06d5043
uswitch/bifrost
s3.clj
(ns uswitch.bifrost.s3 (:require [com.stuartsierra.component :refer (Lifecycle system-map using start stop)] [clojure.tools.logging :refer (info warn error debug)] [clojure.core.async :refer (<! >! go-loop thread chan close! alts! timeout >!! <!!)] [clojure.java.io :refer (file)] [aws.sdk.s3 :refer (put-object bucket-exists? create-bucket)] [metrics.timers :refer (time! timer)] [clj-kafka.zk :refer (committed-offset set-offset!)] [uswitch.bifrost.util :refer (close-channels)] [uswitch.bifrost.async :refer (observable-chan map->Spawner)] [uswitch.bifrost.telemetry :refer (rate-gauge reset-gauge! stop-gauge! update-gauge!)])) (def buffer-size 100) (defn generate-key [consumer-group-id topic partition first-offset] (format "%s/%s/partition=%s/%s.baldr.gz" consumer-group-id topic partition (format "%010d" first-offset))) (def caching-rate-gauge (memoize rate-gauge)) (defn upload-to-s3 [credentials bucket consumer-group-id topic partition first-offset file-path] (let [f (file file-path)] (if (.exists f) (let [g (caching-rate-gauge (str topic "-" partition "-uploadBytes")) key (generate-key consumer-group-id topic partition first-offset) dest-url (str "s3n://" bucket "/" key)] (info "Uploading" file-path "to" dest-url) (time! (timer (str topic "-s3-upload-time")) (do (reset-gauge! g) (put-object credentials bucket key f {:progress-listener (fn [{:keys [bytes-transferred event]}] (when (= :transferring event) (update-gauge! g bytes-transferred)))}) (stop-gauge! g))) (info "Finished uploading" dest-url)) (warn "Unable to find file" file-path)))) (defn progress-s3-upload "Performs a step through uploading a file to S3. Returns {:goto :pause}" [state credentials bucket consumer-properties topic partition first-offset last-offset file-path] (debug "Asked to step" {:state state :file-path file-path}) (case state nil {:goto :upload-file} :upload-file (try (info "Starting S3 upload for" {:topic topic :partition partition :first-offset first-offset :last-offset last-offset}) (upload-to-s3 credentials bucket (consumer-properties "group.id") topic partition first-offset file-path) {:goto :commit} (catch Exception e (error e "Error whilst uploading to S3. Retrying in 15s.") {:goto :upload-file :pause (* 15 1000)})) :commit (try (let [commit-offset (inc last-offset)] (set-offset! consumer-properties (consumer-properties "group.id") topic partition commit-offset) (info "Committed offset information to ZooKeeper" {:topic topic :partition partition :offset commit-offset})) {:goto :delete} (catch Exception e (error e "Unable to commit offset to ZooKeeper. Retrying in 15s.") {:goto :commit :pause (* 15 1000)})) :delete (try (info "Deleting file" file-path) (if (.delete (file file-path)) (info "Deleted" file-path) (info "Unable to delete" file-path)) {:goto :done} (catch Exception e (error e "Error while deleting file" file-path) {:goto :done})))) (defn spawn-s3-upload [credentials bucket consumer-properties semaphore [partition topic]] (let [rotated-event-ch (observable-chan (str partition "-" topic "-rotation-event-ch") 100)] (info "Starting S3Upload component.") (when-not (bucket-exists? credentials bucket) (info "Creating" bucket "bucket") (create-bucket credentials bucket)) (thread (loop [] (let [msg (<!! rotated-event-ch)] (if (nil? msg) (debug "Terminating S3 uploader") (let [{:keys [topic partition file-path first-offset last-offset]} msg] (debug "Attempting to acquire semaphore to begin upload" {:file-path file-path}) (>!! semaphore :token) (info "Starting S3 upload of" file-path) (loop [state nil] (let [{:keys [goto pause]} (progress-s3-upload state credentials bucket consumer-properties topic partition first-offset last-offset file-path)] (<!! (timeout (or pause 0))) (if (= :done goto) (info "Terminating stepping S3 upload machine.") (recur goto)))) (info "Done uploading to S3:" file-path) (<!! semaphore) (recur)))))) rotated-event-ch)) (defn s3-upload-spawner [{:keys [cloud-storage consumer-properties uploaders-n]}] (let [credentials (:credentials cloud-storage) bucket (:bucket cloud-storage) semaphore (observable-chan "semaphore" uploaders-n)] (map->Spawner {:key-fn (juxt :partition :topic) :spawn (partial spawn-s3-upload credentials bucket consumer-properties semaphore)}))) (defn s3-system [config] (system-map :uploader (using (s3-upload-spawner config) {:ch :rotated-event-ch})))
null
https://raw.githubusercontent.com/uswitch/bifrost/40a2bbb8af5c3b6d65930511c141c777a9585942/src/uswitch/bifrost/s3.clj
clojure
(ns uswitch.bifrost.s3 (:require [com.stuartsierra.component :refer (Lifecycle system-map using start stop)] [clojure.tools.logging :refer (info warn error debug)] [clojure.core.async :refer (<! >! go-loop thread chan close! alts! timeout >!! <!!)] [clojure.java.io :refer (file)] [aws.sdk.s3 :refer (put-object bucket-exists? create-bucket)] [metrics.timers :refer (time! timer)] [clj-kafka.zk :refer (committed-offset set-offset!)] [uswitch.bifrost.util :refer (close-channels)] [uswitch.bifrost.async :refer (observable-chan map->Spawner)] [uswitch.bifrost.telemetry :refer (rate-gauge reset-gauge! stop-gauge! update-gauge!)])) (def buffer-size 100) (defn generate-key [consumer-group-id topic partition first-offset] (format "%s/%s/partition=%s/%s.baldr.gz" consumer-group-id topic partition (format "%010d" first-offset))) (def caching-rate-gauge (memoize rate-gauge)) (defn upload-to-s3 [credentials bucket consumer-group-id topic partition first-offset file-path] (let [f (file file-path)] (if (.exists f) (let [g (caching-rate-gauge (str topic "-" partition "-uploadBytes")) key (generate-key consumer-group-id topic partition first-offset) dest-url (str "s3n://" bucket "/" key)] (info "Uploading" file-path "to" dest-url) (time! (timer (str topic "-s3-upload-time")) (do (reset-gauge! g) (put-object credentials bucket key f {:progress-listener (fn [{:keys [bytes-transferred event]}] (when (= :transferring event) (update-gauge! g bytes-transferred)))}) (stop-gauge! g))) (info "Finished uploading" dest-url)) (warn "Unable to find file" file-path)))) (defn progress-s3-upload "Performs a step through uploading a file to S3. Returns {:goto :pause}" [state credentials bucket consumer-properties topic partition first-offset last-offset file-path] (debug "Asked to step" {:state state :file-path file-path}) (case state nil {:goto :upload-file} :upload-file (try (info "Starting S3 upload for" {:topic topic :partition partition :first-offset first-offset :last-offset last-offset}) (upload-to-s3 credentials bucket (consumer-properties "group.id") topic partition first-offset file-path) {:goto :commit} (catch Exception e (error e "Error whilst uploading to S3. Retrying in 15s.") {:goto :upload-file :pause (* 15 1000)})) :commit (try (let [commit-offset (inc last-offset)] (set-offset! consumer-properties (consumer-properties "group.id") topic partition commit-offset) (info "Committed offset information to ZooKeeper" {:topic topic :partition partition :offset commit-offset})) {:goto :delete} (catch Exception e (error e "Unable to commit offset to ZooKeeper. Retrying in 15s.") {:goto :commit :pause (* 15 1000)})) :delete (try (info "Deleting file" file-path) (if (.delete (file file-path)) (info "Deleted" file-path) (info "Unable to delete" file-path)) {:goto :done} (catch Exception e (error e "Error while deleting file" file-path) {:goto :done})))) (defn spawn-s3-upload [credentials bucket consumer-properties semaphore [partition topic]] (let [rotated-event-ch (observable-chan (str partition "-" topic "-rotation-event-ch") 100)] (info "Starting S3Upload component.") (when-not (bucket-exists? credentials bucket) (info "Creating" bucket "bucket") (create-bucket credentials bucket)) (thread (loop [] (let [msg (<!! rotated-event-ch)] (if (nil? msg) (debug "Terminating S3 uploader") (let [{:keys [topic partition file-path first-offset last-offset]} msg] (debug "Attempting to acquire semaphore to begin upload" {:file-path file-path}) (>!! semaphore :token) (info "Starting S3 upload of" file-path) (loop [state nil] (let [{:keys [goto pause]} (progress-s3-upload state credentials bucket consumer-properties topic partition first-offset last-offset file-path)] (<!! (timeout (or pause 0))) (if (= :done goto) (info "Terminating stepping S3 upload machine.") (recur goto)))) (info "Done uploading to S3:" file-path) (<!! semaphore) (recur)))))) rotated-event-ch)) (defn s3-upload-spawner [{:keys [cloud-storage consumer-properties uploaders-n]}] (let [credentials (:credentials cloud-storage) bucket (:bucket cloud-storage) semaphore (observable-chan "semaphore" uploaders-n)] (map->Spawner {:key-fn (juxt :partition :topic) :spawn (partial spawn-s3-upload credentials bucket consumer-properties semaphore)}))) (defn s3-system [config] (system-map :uploader (using (s3-upload-spawner config) {:ch :rotated-event-ch})))
536e895f49abb3d45f0c85b2ff3d138f5355d3ffd3f4d6954625f4294a450137
ssadler/zeno
Aeson.hs
{-# LANGUAGE OverloadedStrings #-} module Zeno.Data.Aeson ( module DA , SerializeAeson(..) , StrictObject , withStrictObject , (.:-) , (.:-?) ) where import qualified Data.Aeson as Aeson import Data.Aeson as DA hiding (encode, decode) import Data.Aeson.Types as DA import Data.Aeson.Quick as DA (build, (.?), (.!), (.%)) import Data.Aeson.Encode.Pretty as Pretty import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Base16 as B16 import Data.IORef import Data.HashMap.Strict import qualified Data.Serialize as S import qualified Data.Set as Set import Data.Text import Data.Text.Encoding import qualified Data.Serialize as S import Data.VarInt import System.IO.Unsafe -------------------------------------------------------------------------------- SerializeAeson - A wrapper to provide Serialize via Aeson -------------------------------------------------------------------------------- newtype SerializeAeson a = SerializeAeson { unSerializeAeson :: a } instance (ToJSON a, FromJSON a) => S.Serialize (SerializeAeson a) where put (SerializeAeson a) = S.put $ VarPrefixedLazyByteString $ encodeStable a get = do VarPrefixedLazyByteString bs <- S.get either fail (pure . SerializeAeson) $ Aeson.eitherDecode bs encodeStable :: ToJSON a => a -> BSL.ByteString encodeStable = Pretty.encodePretty' conf where conf = Pretty.Config (Pretty.Spaces 0) compare Pretty.Generic False -------------------------------------------------------------------------------- -- Strict Object - An object where the parse operation must consume all keys -------------------------------------------------------------------------------- data StrictObject = StrictObject Object (IORef (Set.Set Text)) instance Show StrictObject where show (StrictObject o r) = show (o, unsafePerformIO $ readIORef r) (.:-) :: FromJSON v => StrictObject -> Text -> Parser v (.:-) so key = addKeyLookup (.:) key so (.:-?) :: FromJSON v => StrictObject -> Text -> Parser (Maybe v) (.:-?) so key = addKeyLookup (.:?) key so addKeyLookup :: (Object -> Text -> Parser v) -> Text -> StrictObject -> Parser v addKeyLookup op key (StrictObject obj ref) = let p = unsafePerformIO $ modifyIORef' ref $ Set.insert key in seq p $ op obj key withStrictObject :: String -> (StrictObject -> Parser a) -> Value -> Parser a withStrictObject label act = withObject label $ \obj -> do let ref = unsafeDepend act $ newIORef Set.empty r <- act $ StrictObject obj ref let keysRead = unsafeDepend r $ readIORef ref :: Set.Set Text objKeys = Set.fromList $ keys obj extraKeys = Set.difference objKeys keysRead if extraKeys /= mempty then let shown = setToString extraKeys in fail (label ++ ": extra keys: " ++ shown) else pure r where -- Slightly dodgy function here. It's neccesary to manually add edges -- to sequence pure and impure computations in this case. unsafeDepend a = unsafePerformIO . seq a setToString = unpack . intercalate "," . Set.toList
null
https://raw.githubusercontent.com/ssadler/zeno/9f715d7104a7b7b00dee9fe35275fb217532fdb6/src/Zeno/Data/Aeson.hs
haskell
# LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Strict Object - An object where the parse operation must consume all keys ------------------------------------------------------------------------------ Slightly dodgy function here. It's neccesary to manually add edges to sequence pure and impure computations in this case.
module Zeno.Data.Aeson ( module DA , SerializeAeson(..) , StrictObject , withStrictObject , (.:-) , (.:-?) ) where import qualified Data.Aeson as Aeson import Data.Aeson as DA hiding (encode, decode) import Data.Aeson.Types as DA import Data.Aeson.Quick as DA (build, (.?), (.!), (.%)) import Data.Aeson.Encode.Pretty as Pretty import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Base16 as B16 import Data.IORef import Data.HashMap.Strict import qualified Data.Serialize as S import qualified Data.Set as Set import Data.Text import Data.Text.Encoding import qualified Data.Serialize as S import Data.VarInt import System.IO.Unsafe SerializeAeson - A wrapper to provide Serialize via Aeson newtype SerializeAeson a = SerializeAeson { unSerializeAeson :: a } instance (ToJSON a, FromJSON a) => S.Serialize (SerializeAeson a) where put (SerializeAeson a) = S.put $ VarPrefixedLazyByteString $ encodeStable a get = do VarPrefixedLazyByteString bs <- S.get either fail (pure . SerializeAeson) $ Aeson.eitherDecode bs encodeStable :: ToJSON a => a -> BSL.ByteString encodeStable = Pretty.encodePretty' conf where conf = Pretty.Config (Pretty.Spaces 0) compare Pretty.Generic False data StrictObject = StrictObject Object (IORef (Set.Set Text)) instance Show StrictObject where show (StrictObject o r) = show (o, unsafePerformIO $ readIORef r) (.:-) :: FromJSON v => StrictObject -> Text -> Parser v (.:-) so key = addKeyLookup (.:) key so (.:-?) :: FromJSON v => StrictObject -> Text -> Parser (Maybe v) (.:-?) so key = addKeyLookup (.:?) key so addKeyLookup :: (Object -> Text -> Parser v) -> Text -> StrictObject -> Parser v addKeyLookup op key (StrictObject obj ref) = let p = unsafePerformIO $ modifyIORef' ref $ Set.insert key in seq p $ op obj key withStrictObject :: String -> (StrictObject -> Parser a) -> Value -> Parser a withStrictObject label act = withObject label $ \obj -> do let ref = unsafeDepend act $ newIORef Set.empty r <- act $ StrictObject obj ref let keysRead = unsafeDepend r $ readIORef ref :: Set.Set Text objKeys = Set.fromList $ keys obj extraKeys = Set.difference objKeys keysRead if extraKeys /= mempty then let shown = setToString extraKeys in fail (label ++ ": extra keys: " ++ shown) else pure r where unsafeDepend a = unsafePerformIO . seq a setToString = unpack . intercalate "," . Set.toList
d79daddd956a3cb652f0ef381c0338ce7768358fe4c9b574b35ba3b2d3435268
remixlabs/wasicaml
wc_emit.ml
Copyright ( C ) 2021 by Figly , Inc. This code is free software , see the file LICENSE for details . This code is free software, see the file LICENSE for details. *) open Printf open Bigarray open Wc_types open Wc_number open Wc_sexp open Wc_instruct OCaml functions are translated to Wasm functions with parameters : param 1 : envptr param 2 : extra_args param 3 : code pointer ( overriding the one in the closure ) param 4 : fp So far , the function args are passed via the bytecode stack . The envptr is a pointer to the stack location of the environment ( env ) . This pointer is created when a function is called - the bytecode interpreter reserves 3 stack locations for PC , saved env , and extra_args . We also reserve stack locations upon function call but differently : - need only one location and not three - the one location stores the env of the called function , not the env of the calling function There are also two ways of invoking functions . If there are up to 3 args , the bytecode only includes the instructions to push the args onto the stack , followed by Kapply . It is then the task of Kapply to make room for the saved values ( as explained ) . If , however , there are more than 3 args , the bytecode includes a Kpush_retaddr instruction which reserves 3 positions on the stack in advance . Although we only need one of these , there is no fixup that would eliminate the other two . param 1: envptr param 2: extra_args param 3: code pointer (overriding the one in the closure) param 4: fp So far, the function args are passed via the bytecode stack. The envptr is a pointer to the stack location of the environment (env). This pointer is created when a function is called - the bytecode interpreter reserves 3 stack locations for PC, saved env, and extra_args. We also reserve stack locations upon function call but differently: - need only one location and not three - the one location stores the env of the called function, not the env of the calling function There are also two ways of invoking functions. If there are up to 3 args, the bytecode only includes the instructions to push the args onto the stack, followed by Kapply. It is then the task of Kapply to make room for the saved values (as explained). If, however, there are more than 3 args, the bytecode includes a Kpush_retaddr instruction which reserves 3 positions on the stack in advance. Although we only need one of these, there is no fixup that would eliminate the other two. *) type wasm_value_type = | TI32 | TI64 | TF64 let string_of_vtype = function | TI32 -> "i32" | TI64 -> "i64" | TF64 -> "f64" let zero_expr_of_vtype = function | TI32 -> [ L [ K "i32.const"; N (I32 0l) ] ] | TI64 -> [ L [ K "i64.const"; N (I64 0L) ] ] | TF64 -> [ L [ K "f64.const"; N (F64 0.0) ] ] type letrec_label = | Func of int | Main of int type gpad = (* global pad *) { letrec_name : (letrec_label, string) Hashtbl.t; (* maps letrec label to name *) primitives : (string, sexp list) Hashtbl.t; (* maps name to type *) funcmapping : (int, letrec_label * int) Hashtbl.t; (* maps function label to (letrec_label, subfunction_id) *) subfunctions : (letrec_label, int list) Hashtbl.t; (* maps letrec_label to list of subfunction labels *) wasmindex : (letrec_label, int) Hashtbl.t; (* maps letrec label to the (relative) index in the table of functions *) mutable need_reinit_frame : bool; mutable need_reinit_frame_k : ISet.t; mutable need_mlookup : bool; mutable globals_table : (int, Wc_traceglobals.initvalue) Hashtbl.t; (* knowledge about the globals *) mutable glbfun_table : (int, int * Wc_traceglobals.initvalue array) Hashtbl.t; (* for each letrec function: knowledge about its environment *) } type fpad = (* function pad *) { lpad : Wc_unstack.lpad; fpad_letrec_label : letrec_label; mutable fpad_scope : Wc_control.cfg_scope; mutable maxdepth : int; mutable need_appterm_common : bool; mutable need_startover : bool; (* back to subfunction selection *) mutable need_selfrecurse : bool; (* self-recursion - only when tailcalls are enabled! *) mutable need_return : bool; mutable need_panic : bool; mutable need_tmp1_i32 : bool; mutable need_tmp2_i32 : bool; mutable need_tmp1_f64 : bool; mutable need_xalloc : bool; Wgrab is only allowed at the beginning } Stack layout of a function with N arguments : fp is the stack pointer at the time the function starts executing . POSITION USED FOR -------------------------------------------------------- - fp+N-1 : argN - fp+1 to fp+N-2 : ... - fp : arg1 - fp-1 : bottom of local stack - fp - camldepth+1 to fp-2 : ... - fp - camldepth : top of local stack - fp - camldepth-1 etc : free fp is the stack pointer at the time the function starts executing. POSITION USED FOR -------------------------------------------------------- - fp+N-1: argN - fp+1 to fp+N-2: ... - fp: arg1 - fp-1: bottom of local stack - fp-camldepth+1 to fp-2: ... - fp-camldepth: top of local stack - fp-camldepth-1 etc: free *) let enable_multireturn = ref false whether Wasm code can use multivalue returns NB . This seems to be broken in llvm-11 let enable_returncall = ref false (* whether Wasm code can use the return_call instruction (tail calls) *) let enable_deadbeef_check = ref false (* debugging: check that there is no uninitialized memory on the stack *) let code_pointer_shift = 12 OCaml code pointers : - Bit 0 : always 1 - Bit 1 : whether to run RESTART - Bit 2 - code_pointer_shift-1 : subfunction of the letrec - Bit code_pointer_shift-31 : the Wasm function index See also ocaml / runtime / callback.c - Bit 0: always 1 - Bit 1: whether to run RESTART - Bit 2 - code_pointer_shift-1: subfunction of the letrec - Bit code_pointer_shift-31: the Wasm function index See also ocaml/runtime/callback.c *) let code_pointer_subfunc_mask = 0xffcl let code_pointer_letrec_mask = 0xffff_f000l let code_pointer_restart_mask = 2l (* TODO: grab the following values from C: *) Note that the domain fields are 8 - aligned , even on 32 bit systems let max_young_wosize = 256 let domain_field_young_ptr = 0 let domain_field_young_limit = 1 let domain_field_stack_low = 17 let domain_field_stack_high = 18 let domain_field_stack_threshold = 19 let domain_field_extern_sp = 20 let domain_field_trapsp = 21 let domain_field_trap_barrier = 22 let domain_field_external_raise = 23 let domain_field_exn_bucket = 24 let domain_field_local_roots = 36 let double_size = 2 let double_tag = 253 let double_array_tag = 254 let closure_tag = 247 let infix_tag = 249 let caml_from_c = 0 let make_header size tag = (* color=white *) (size lsl 10) lor tag let vtype repr = match repr with | RValue | RInt | RIntUnclean | RIntVal | RNatInt | RInt32 -> TI32 | RInt64 -> TI64 | RFloat -> TF64 let empty_fpad() = { lpad = Wc_unstack.empty_lpad ~enable_returncall:!enable_returncall (); fpad_letrec_label = Main 0; fpad_scope = { cfg_letrec_label = None; cfg_func_label = 0; cfg_try_labels = []; cfg_main = false }; maxdepth = 0; need_appterm_common = false; need_startover = false; need_selfrecurse = false; need_return = false; need_panic = false; need_tmp1_i32 = false; need_tmp2_i32 = false; need_tmp1_f64 = false; need_xalloc = false; disallow_grab = false; } let returncall name = if !enable_returncall then [ L [ K "return_call"; ID name ] ] else [ L [ K "call"; ID name ]; L [ K "return" ] ] let new_local fpad repr = Wc_unstack.new_local fpad.lpad repr let req_tmp1_i32 fpad = if fpad.lpad.avoid_locals then ( fpad.need_tmp1_i32 <- true; "tmp1_i32" ) else new_local fpad RInt let req_tmp2_i32 fpad = if fpad.lpad.avoid_locals then ( fpad.need_tmp2_i32 <- true; "tmp2_i32" ) else new_local fpad RInt let req_tmp1_f64 fpad = if fpad.lpad.avoid_locals then ( fpad.need_tmp1_f64 <- true; "tmp1_f64" ) else new_local fpad RFloat let set_bp_1 fpad = [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * fpad.maxdepth))) ]; L [ K "i32.sub" ]; L [ K "local.tee"; ID "bp" ]; L [ K "global.get"; ID "wasicaml_stack_threshold" ]; L [ K "i32.lt_u" ]; L [ K "if"; L [ K "then"; L [ K "call"; ID "caml_raise_stack_overflow" ]; ] ] ] let set_bp fpad = if fpad.maxdepth = 0 then [] else [ L [ K "local.get"; ID "fp" ] ] @ set_bp_1 fpad let push_const n = [ L [ K "i32.const"; N (I32 n) ]] let push_local var = [ L [ K "local.get"; ID var ]] let pop_to_local var = [ L [ K "local.set"; ID var ]] let pop_to_fp fpad = if fpad.maxdepth = 0 then pop_to_local "fp" else [ L [ K "local.tee"; ID "fp" ]] @ set_bp_1 fpad let load_offset offset = if offset >= 0 then [ L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int offset)); K "align=2"; ] ] else [ L [ K "i32.const"; N (I32 (Int32.of_int (-offset))) ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ] ] let add_offset offset = if offset <> 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int offset)) ]; L [ K "i32.add" ] ] else [] let push_env = [ L [ K "local.get"; ID "envptr" ]; L [ K "i32.load"; K "align=2" ] ] let push_field var_base field = [ L [ K "local.get"; ID var_base; ] ] @ load_offset (4 * field) let push_global_field var_base field = [ L [ K "global.get"; ID var_base; ] ] @ load_offset (4 * field) let push_field_addr var_base field = [ L [ K "local.get"; ID var_base ] ] @ if field <> 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * field))); ]; L [ K "i32.add" ] ] else [] let push_global_field_addr var_base field = [ L [ K "global.get"; ID var_base; ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * field))); ]; L [ K "i32.add" ] ] let push_stack fpad pos = if pos >= 0 then push_field "fp" pos else push_field "bp" (pos + fpad.maxdepth) let push_domain_field field = [ L [ K "global.get"; ID "wasicaml_domain_state" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * field))); K "align=2"; ]; ] let store_offset addr offset code_value = if offset >= 0 then [ L [ K "local.get"; ID addr ] ] @ code_value @ [ L [ K "i32.store"; K (sprintf "offset=0x%lx" (Int32.of_int offset)); K "align=2"; ] ] else [ L [ K "local.get"; ID addr ]; L [ K "i32.const"; N (I32 (Int32.of_int (-offset))) ]; L [ K "i32.sub" ] ] @ code_value @ [ L [ K "i32.store"; K "align=2" ] ] let pop_to_field var_base field code_value = store_offset var_base (4*field) code_value let pop_to_double_field var_base field code_value = [ L [ K "local.get"; ID var_base ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * double_size * field))); ]; L [ K "i32.add" ] ] @ code_value @ [ L [ K "f64.store"; K "align=2" ]] let pop_to_domain_field field code_value = [ L [ K "global.get"; ID "wasicaml_domain_state" ]] @ code_value @ [ L [ K "i32.store"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * field))); K "align=2"; ]; ] let pop_to_stack fpad pos code_value = if pos >= 0 then pop_to_field "fp" pos code_value else pop_to_field "bp" (pos + fpad.maxdepth) code_value let load_double = [ L [ K "f64.load"; K "align=2" ] ] let debug2 x0 x1 = [ L [ K "i32.const"; N (I32 (Int32.of_int x0)) ]; L [ K "i32.const"; N (I32 (Int32.of_int x1)) ]; L [ K "call"; ID "debug2" ] ] let debug2_var x0 var = [ L [ K "i32.const"; N (I32 (Int32.of_int x0)) ]; L [ K "local.get"; ID var ]; L [ K "call"; ID "debug2" ] ] let deadbeef_init = IBM mainframes used to initialize fresh memory with 0xdeadbeef [ L ( [ [ K "func"; ID "deadbeef_init"; L [ K "param"; ID "bp"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; ]; (* loop *) [ L [ K "block"; ID "loop_exit"; BR; L [ K "loop"; ID "loop"; BR; (* if (bp >= fp) break *) L [ K "local.get"; ID "bp" ]; L [ K "local.get"; ID "fp" ]; L [ K "i32.ge_u" ]; L [ K "br_if"; ID "loop_exit" ]; (* *bp = 0xdeadbeef *) L [ K "local.get"; ID "bp" ]; L [ K "i32.const"; N (I32 0xdeadbeefl) ]; L [ K "i32.store" ]; (* bp++ *) L [ K "local.get"; ID "bp" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.add" ]; L [ K "local.set"; ID "bp" ]; L [ K "br"; ID "loop" ] ] ] ] ] |> List.flatten ) ] let deadbeef_check = (* now check that there's no dead beef on the stack! *) [ L ( [ [ K "func"; ID "deadbeef_check"; L [ K "param"; ID "ptr"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; ]; (* assert (ptr <= fp) *) push_local "ptr"; push_local "fp"; [ L [ K "i32.gt_u" ]; L [ K "if"; L [ K "then"; L [ K "unreachable" ] ] ] ]; (* loop *) [ L [ K "block"; ID "loop_exit"; BR; L [ K "loop"; ID "loop"; BR; (* if (ptr >= fp) break *) L [ K "local.get"; ID "ptr" ]; L [ K "local.get"; ID "fp" ]; L [ K "i32.ge_u" ]; L [ K "br_if"; ID "loop_exit" ]; (* assert( *bp != 0xdeadbeef) *) L [ K "local.get"; ID "ptr" ]; L [ K "i32.load" ]; L [ K "i32.const"; N (I32 0xdeadbeefl) ]; L [ K "i32.eq" ]; L [ K "if"; L [ K "then"; L [ K "unreachable" ] ] ]; (* ptr++ *) L [ K "local.get"; ID "ptr" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.add" ]; L [ K "local.set"; ID "ptr" ]; L [ K "br"; ID "loop" ] ] ] ] ] |> List.flatten ) ] let stack_init fpad descr = put zeros into the uninitialized stack positions List.map (fun pos -> pop_to_stack fpad pos (push_const 1l) ) descr.stack_uninit |> List.flatten let setup_for_gc fpad descr = let sp_decr = if descr.stack_save_accu then 1 else 0 in let sexpl_stack = stack_init fpad descr in let sexpl_accu = if descr.stack_save_accu then push_local "accu" |> pop_to_stack fpad (-descr.stack_depth-1) else [] in let sexpl_extern_sp = ( [ L [ K "local.get"; ID "fp"; ] ] @ (if descr.stack_depth + sp_decr > 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int ( 4 * (descr.stack_depth + sp_decr)))); ]; L [ K "i32.sub" ]; ] else [] ) ) |> pop_to_domain_field domain_field_extern_sp in let sexpl_check = ( if !enable_deadbeef_check then push_domain_field domain_field_extern_sp @ [ L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ) in sexpl_stack @ sexpl_accu @ sexpl_extern_sp @ sexpl_check let restore_after_gc fpad descr = if descr.stack_save_accu then push_stack fpad (-descr.stack_depth-1) @ pop_to_local "accu" else [] let alloc_atom fpad tag = [ L [ K "global.get"; ID "wasicaml_atom_table"; ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * tag))); ]; L [ K "i32.add" ]; ] let alloc_fast = [ L ( [ [ K "func"; ID "alloc_fast"; L [ K "param"; ID "bhsize"; K "i32" ]; L [ K "param"; ID "header"; K "i32" ]; BR; L [ K "result"; C "ptr"; K "i32" ]; L [ K "local"; ID "ptr"; K "i32" ]; ]; ptr = ) - Whsize_wosize ( wosize ) push_domain_field domain_field_young_ptr; push_local "bhsize"; [ L [ K "i32.sub" ]; L [ K "local.tee"; ID "ptr" ]; ]; (* Caml_state_field(young_ptr) = ptr *) ( push_local "ptr" |> pop_to_domain_field domain_field_young_ptr ); if ( ptr < Caml_state_field(young_limit ) ) return 0 push_domain_field domain_field_young_limit; [ L [ K "i32.lt_u" ] ]; [ L [ K "if"; L [ K "then"; L [ K "i32.const"; N (I32 0l) ]; L [ K "return" ] ] ] ]; (* *ptr = header *) ( push_local "header" |> pop_to_field "ptr" 0 ); (* return ptr+1 *) push_local "ptr"; push_const 4l; [ L [ K "i32.add" ]; L [ K "return" ] ] ] |> List.flatten ) ] let alloc_slow() = [ L ( [ [ K "func"; ID "alloc_slow"; L [ K "param"; ID "wosize"; K "i32" ]; L [ K "param"; ID "header"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "stackdepth"; K "i32" ]; L [ K "param"; ID "accu"; K "i32" ]; BR; L [ K "result"; C "ptr"; K "i32" ]; ]; if !enable_multireturn then [ L [ K "result"; C "out_accu"; K "i32" ]; ] else []; [ L [ K "local"; ID "ptr"; K "i32" ]; L [ K "local"; ID "sp"; K "i32" ] ]; ( [ L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "stackdepth" ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 4l) ]; (* for the accu *) L [ K "i32.sub" ]; L [ K "local.tee"; ID "sp" ]; ] |> pop_to_domain_field domain_field_extern_sp ) @ (push_local "accu" |> pop_to_field "sp" 0); ( if !enable_deadbeef_check then push_domain_field domain_field_extern_sp @ [ L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ); caml_alloc_small_dispatch(wosize , CAML_FROM_C , 1 , NULL ) push_local "wosize"; push_const (Int32.of_int caml_from_c); push_const 1l; push_const 0l; [ L [ K "call"; ID "caml_alloc_small_dispatch" ]]; push_domain_field domain_field_young_ptr; pop_to_local "ptr"; (* *ptr = header *) ( push_local "header" |> pop_to_field "ptr" 0 ); (* return ptr+1 *) push_local "ptr"; push_const 4l; [ L [ K "i32.add" ] ]; (* return saved accu *) push_field "sp" 0; if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ]; ]; [ L [ K "return" ]] ] |> List.flatten ) ] let call_alloc_slow() = [ L [ K "call"; ID "alloc_slow" ]] @ if !enable_multireturn then [] else [ L [ K "global.get"; ID "retval2" ] ] let alloc_non_atom fpad descr size tag = fpad.need_xalloc <- true; let ptr = "xalloc" (* new_local fpad RValue *) in let young = size <= max_young_wosize in let code = if young then [ push_const (Int32.of_int (4 * (size+1))); push_const (Int32.of_int (make_header size tag)); [ L [ K "call"; ID "alloc_fast" ]; L [ K "local.tee"; ID ptr ]; ]; (* if (ptr == NULL) *) [ L [ K "i32.eqz" ]]; [ L [ K "if"; L ( [ [ K "then"; ]; stack_init fpad descr; push_const (Int32.of_int size); push_const (Int32.of_int (make_header size tag)); push_local "fp"; push_const (Int32.of_int (4 * descr.stack_depth)); push_local "accu"; call_alloc_slow(); pop_to_local "accu"; pop_to_local ptr; ] |> List.flatten ) ]; ]; ] |> List.flatten else [ L [ K "i32.const"; N (I32 (Int32.of_int size)) ]; L [ K "i32.const"; N (I32 (Int32.of_int tag)) ]; L [ K "call"; ID "caml_alloc_shr" ]; L [ K "local.set"; ID ptr ]; ] in (code, ptr, young) let alloc fpad descr size tag = if size = 0 then alloc_atom fpad tag else let (code, ptr, _) = alloc_non_atom fpad descr size tag in code @ push_local ptr let alloc_set fpad descr size tag = if size = 0 then ( fpad.need_xalloc <- true; let ptr = "xalloc" (* new_local fpad RValue *) in let young = false in (alloc_atom fpad tag @ push_local ptr, ptr, young) ) else alloc_non_atom fpad descr size tag let grab_helper gpad = generates a helper function : $ grab_helper(extra_args , , fp ) $grab_helper(extra_args, codeptr, fp) *) let fpad = empty_fpad() in let descr = empty_descr in assert(descr.stack_save_accu = false); [ L ( [ [ K "func"; ID "grab_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "codeptr"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; BR; L [ K "result"; K "i32" ]; L [ K "local"; ID "accu"; K "i32" ]; L [ K "local"; ID "i"; K "i32" ]; ]; setup_for_gc fpad descr; [ L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 (Int32.of_int closure_tag))]; L [ K "call"; ID "caml_alloc_small" ]; L [ K "local.set"; ID "accu" ]; ]; restore_after_gc fpad descr; (* won't overwrite accu *) (push_env |> pop_to_field "accu" 2); push_const 0l; pop_to_local "i"; [ L [ K "loop"; ID "fields"; BR; (* Field(accu, i+3) = ... *) L [ K "local.get"; ID "accu" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; (* fp[i] *) L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; (* assign *) L [ K "i32.store"; K "align=2" ]; (* i++, and jump back if i <= extra_args *) L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.add" ]; L [ K "local.tee"; ID "i" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.le_u" ]; L [ K "br_if"; ID "fields" ]; ] ]; ( (push_local "codeptr" @ [ L [ K "i32.const"; N (I32 code_pointer_restart_mask) ]; (* restart flag *) L [ K "i32.or" ] ] ) |> pop_to_field "accu" 0 ); (push_const 5l |> pop_to_field "accu" 1); push_local "accu"; [ L [ K "return" ] ] ] |> List.flatten ) ] let restart_helper gpad = [ L ( [ [ K "func"; ID "restart_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; BR; L [ K "result"; C "out_extra_args"; K "i32" ]; ]; if !enable_multireturn then [ L [ K "result"; C "out_fp"; K "i32" ]; ] else []; [ L [ K "local"; ID "i"; K "i32" ]; L [ K "local"; ID "num_args"; K "i32" ]; ]; num_args = Wosize_val(env ) - 3 push_env; [ L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.const"; N (I32 10l) ]; L [ K "i32.shr_u" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "num_args" ]; ]; [ (* fp -= num_args *) L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "num_args" ]; L [ K "i32.const"; N (I32 2l)]; L [ K "i32.shl" ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "fp" ]; ]; [ L [ K "i32.const"; N (I32 0l)]; L [ K "local.set"; ID "i" ]; L ( [ [ K "loop"; ID "args"; BR; (* fp[i[ = ... *) L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ] ]; (* Field(env, i+3) *) push_env; [ L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; ]; (* assign *) [ L [ K "i32.store"; K "align=2" ] ]; (* i++, and jump back if i < num_args *) [ L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.add" ]; L [ K "local.tee"; ID "i" ]; L [ K "local.get"; ID "num_args" ]; L [ K "i32.lt_u" ]; L [ K "br_if"; ID "args" ]; ] ] |> List.flatten ) ]; env = Field(env , 2 ) [ L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "envptr" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.load"; K "offset=8"; K "align=2" ]; L [ K "i32.store"; K "align=2" ] ]; (* extra_args += num_args *) [ L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "num_args" ]; L [ K "i32.add" ]; L [ K "local.set"; ID "extra_args" ]; ]; (* return *) push_local "extra_args"; push_local "fp"; if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ] ]; [ L [ K "return" ] ]; ] |> List.flatten ) ] let call_restart_helper() = [ L [ K "call"; ID "restart_helper" ]] @ if !enable_multireturn then [] else [ L [ K "global.get"; ID "retval2" ]] let reinit_frame = [ L [ K "func"; ID "reinit_frame"; L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "depth"; K "i32" ]; > = 1 > = 1 BR; L [ K "result"; C "out_fp"; K "i32" ]; L [ K "local"; ID "i"; K "i32" ]; L [ K "local"; ID "new_fp"; K "i32" ]; new_fp = fp + old_num_args - new_num_args L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "old_num_args" ]; L [ K "local.get"; ID "new_num_args" ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "local.set"; ID "new_fp" ]; L [ K "local.get"; ID "new_num_args" ]; L [ K "local.set"; ID "i" ]; L [ K "loop"; ID "args"; BR; (* i-- *) L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "i" ]; (* new_fp[i] = ... *) L [ K "local.get"; ID "new_fp" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; (* fp[-(depth-i)] *) L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "depth" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ]; (* assign *) L [ K "i32.store"; K "align=2" ]; loop if i > 0 L [ K "local.get"; ID "i" ]; L [ K "br_if"; ID "args" ]; ]; L [ K "local.get"; ID "new_fp" ]; L [ K "return" ] ]; ] let reinit_frame_k new_num_args = [ L ( [ K "func"; ID (sprintf "reinit_frame_%d" new_num_args); L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "depth"; K "i32" ]; > = 1 BR; L [ K "result"; C "out_fp"; K "i32" ]; L [ K "local"; ID "i"; K "i32" ]; L [ K "local"; ID "bp"; K "i32" ]; L [ K "local"; ID "new_fp"; K "i32" ]; new_fp = fp + old_num_args - new_num_args L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "old_num_args" ]; L [ K "i32.const"; N (I32 (Int32.of_int new_num_args)) ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "local.set"; ID "new_fp" ]; (* bp = fp - depth *) L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "depth" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "bp" ]; ] @ ( Wc_util.enum 0 new_num_args |> List.map (fun j -> let i = new_num_args - 1 - j in [ (* new_fp[i] = ... *) L [ K "local.get"; ID "new_fp" ]; (* bp[i)] *) L [ K "local.get"; ID "bp" ]; L [ K "i32.load"; K (sprintf "offset=0x%x" (4 * i)); K "align=2" ]; (* assign *) L [ K "i32.store"; K (sprintf "offset=0x%x" (4 * i)); K "align=2" ]; ] ) |> List.flatten ) @ [ L [ K "local.get"; ID "new_fp" ]; L [ K "return" ] ] ) ] let return_helper() = [ L ( [ [ K "func"; ID "return_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "accu"; K "i32" ]; BR; L [ K "result"; K "i32" ]; L [ K "local"; ID "codeptr"; K "i32" ]; ]; ( push_local "accu" |> pop_to_field "envptr" 0 ); [ L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ]; ]; push_field "accu" 0; [ L [ K "local.tee"; ID "codeptr" ] ]; [ L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shr_u" ]; ]; if !enable_returncall then [ L [ K "return_call_indirect"; N (I32 0l); (* table *) L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ] ] else [ L [ K "call_indirect"; N (I32 0l); (* table *) L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ]; L [ K "return" ] ] ] |> List.flatten ) ] let appterm_helper() = if !enable_returncall then [] else [ L ( [ [ K "func"; ID "appterm_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "codeptr"; K "i32" ]; L [ K "param"; ID "accu"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "new_num_args"; K "i32" ]; BR; L [ K "result"; C "out_codeptr"; K "i32" ]; ]; if !enable_multireturn then [L [ K "result"; C "out_extra_args"; K "i32" ]] else []; [ L [ K "local"; ID "out_codeptr"; K "i32" ]]; push_local "extra_args"; push_local "new_num_args"; [ L [ K "i32.add" ]]; pop_to_local "extra_args"; (push_local "accu" |> pop_to_field "envptr" 0); push_field "accu" 0; pop_to_local "out_codeptr"; [ L [ K "local.get"; ID "out_codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_letrec_mask) ]; L [ K "i32.and" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_letrec_mask) ]; L [ K "i32.and" ]; L [ K "i32.eq" ]; L [ K "if"; L ( [ K "then" ; (* same letrec: we can jump! *) L [ K "local.get"; ID "out_codeptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ] ] @ (if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ] ] ) @ [ L [ K "return" ] ] ); L ( [ K "else"; (* different letrec: call + return. *) L [ K "i32.const"; N (I32 0l) ]; L [ K "local.get"; ID "extra_args" ] ] @ (if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ] ] ) @ [ L [ K "return" ]] ) ]; L [ K "unreachable" ] ] ] |> List.flatten ) ] let call_appterm_helper() = assert(not !enable_returncall); [ L [ K "call"; ID "appterm_helper" ]] @ if !enable_multireturn then [] else [ L [ K "global.get"; ID "retval2" ]] let mlookup = [ L ( [ [ K "func"; ID "mlookup"; L [ K "param"; ID "obj"; K "i32" ]; L [ K "param"; ID "tag"; K "i32" ]; L [ K "param"; ID "cache"; K "i32" ]; BR; L [ K "result"; C "method"; K "i32" ]; L [ K "local"; ID "meths"; K "i32" ]; L [ K "local"; ID "ofs"; K "i32" ]; L [ K "local"; ID "li"; K "i32" ]; L [ K "local"; ID "hi"; K "i32" ]; L [ K "local"; ID "mi"; K "i32" ]; ]; get the descriptor : meths = obj[0 ] [ L [ K "local.get"; ID "obj" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.set"; ID "meths" ]; ]; (* test the cache first, if any: *) [ L [ K "local.get"; ID "cache" ]; L [ K "if"; L [ K "then"; (* ofs = *cache & meths[1] *) L [ K "local.get"; ID "cache" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.get"; ID "meths" ]; L [ K "i32.load"; K "offset=0x4"; K "align=2" ]; L [ K "i32.and" ]; L [ K "local.tee"; ID "ofs" ]; (* get &meths[3] + ofs *) L [ K "local.get"; ID "meths" ]; L [ K "i32.const"; N (I32 12l) ]; L [ K "i32.add" ]; L [ K "i32.add" ]; (* load the tag there, and compare with [tag] *) L [ K "i32.load"; K "align=2" ]; L [ K "local.get"; ID "tag" ]; L [ K "i32.eq" ]; (* if equal, found something *) L [ K "if"; L [ K "then"; get & meths[2 ] + ofs L [ K "local.get"; ID "meths" ]; L [ K "i32.const"; N (I32 8l) ]; L [ K "i32.add" ]; L [ K "local.get"; ID "ofs" ]; L [ K "i32.add" ]; (* load it *) L [ K "i32.load"; K "align=2" ]; L [ K "return" ]; ] ] ] ] ]; (* li=3 *) [ L [ K "i32.const"; N (I32 3l) ]; L [ K "local.set"; ID "li" ]; ]; (* hi=meths[0] *) [ L [ K "local.get"; ID "meths" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.set"; ID "hi" ]; ]; (* loop *) [ L [ K "block"; ID "loop_exit"; BR; L [ K "loop"; ID "loop"; BR; (* if (li >= hi) break *) L [ K "local.get"; ID "li" ]; L [ K "local.get"; ID "hi" ]; L [ K "i32.ge_u" ]; L [ K "br_if"; ID "loop_exit" ]; (* mi = (li+hi) >> 1 | 1 *) L [ K "local.get"; ID "li" ]; L [ K "local.get"; ID "hi" ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ]; L [ K "local.set"; ID "mi" ]; (* if (tag < meths[mi]) *) L [ K "local.get"; ID "tag" ]; L [ K "local.get"; ID "meths" ]; L [ K "local.get"; ID "mi" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.lt_s" ]; L [ K "if"; L [ K "then"; (* hi = mi-2 *) L [ K "local.get"; ID "mi" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "hi" ]; ]; L [ K "else"; (* li = mi *) L [ K "local.get"; ID "mi" ]; L [ K "local.set"; ID "li" ]; ] ]; L [ K "br"; ID "loop" ]; ] ] ]; (* set cache *) [ L [ K "local.get"; ID "cache" ]; L [ K "if"; L [ K "then"; * cache = ( li-3 ) * 4 L [ K "local.get"; ID "cache" ]; L [ K "local.get"; ID "li" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.mul" ]; L [ K "i32.store"; K "align=2" ]; ] ] ]; (* return meths[li-1] *) [ L [ K "local.get"; ID "meths" ]; L [ K "local.get"; ID "li" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "return" ]; ] ] |> List.flatten ) ] let wasicaml_get_data = [ L [ K "func"; ID "wasicaml_get_data"; (* L [ K "export"; S "wasicaml_get_data" ]; *) L [ K "result"; K "i32" ]; BR; (* PIC: L [ K "global.get"; ID "wc__memory_base" ]; *) (* Extension: *) L [ K "i32.const"; ID "data" ]; L [ K "return" ] ] ] let wasicaml_get_data_size size = [ L [ K "func"; ID "wasicaml_get_data_size"; (* L [ K "export"; S "wasicaml_get_data_size" ]; *) L [ K "result"; K "i32" ]; BR; L [ K "i32.const"; N (I32 (Int32.of_int size)) ]; L [ K "return" ] ] ] let wasicaml_init = [ L [ K "func"; ID "wasicaml_init"; (* L [ K "export"; S "wasicaml_init" ]; *) BR; L [ K "call"; ID "wasicaml_get_global_data" ]; L [ K "global.set"; ID "wasicaml_global_data" ]; L [ K "call"; ID "wasicaml_get_domain_state" ]; L [ K "global.set"; ID "wasicaml_domain_state" ]; L [ K "call"; ID "wasicaml_get_atom_table" ]; L [ K "global.set"; ID "wasicaml_atom_table" ]; L [ K "global.get"; ID "wasicaml_domain_state" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * domain_field_stack_threshold))); K "align=2"; ]; L [ K "global.set"; ID "wasicaml_stack_threshold" ]; L [ K "return" ] ] ] let tovalue_alloc fpad repr descr_opt = (* transform the value of the Wasm stack to a proper OCaml value, and put that back on the Wasm stack *) match repr with | RValue | RIntVal -> [] | RInt | RIntUnclean -> [ L [ K "i32.const"; N (I32 1l); ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 1l); ]; L [ K "i32.or" ]; ] | RFloat -> ( match descr_opt with | None -> failwith "cannot convert to double w/o stack descr" | Some descr -> let (instrs_alloc, ptr, _) = alloc_set fpad descr double_size double_tag in let local = req_tmp1_f64 fpad in let instrs = [ L [ K "local.set"; ID local ] ] @ instrs_alloc @ [ L [ K "local.get"; ID ptr ]; L [ K "local.get"; ID local ]; L [ K "f64.store"; K "align=2" ]; L [ K "local.get"; ID ptr ]; ] in instrs ) | _ -> (* TODO: need to allocate the block *) Careful : when allocating a block and initializing it , we can not allocate in the middle ( e.g. makeblock ) . If allocations are generated by tovalue , we need to insert more code to set the block early to 0 . Probably the way out is a function straighten_if_alloc_needed that only straightens the stack positions that are neither RValue nor RInt . we cannot allocate in the middle (e.g. makeblock). If allocations are generated by tovalue, we need to insert more code to set the block early to 0. Probably the way out is a function straighten_if_alloc_needed that only straightens the stack positions that are neither RValue nor RInt. *) assert false let tovalue fpad repr = tovalue_alloc fpad repr None let toint repr = match repr with | RInt -> [] | RIntUnclean -> [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; ] | RValue | RIntVal -> [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; ] | _ -> assert false let tointunclean repr = match repr with | RIntUnclean -> [] | _ -> toint repr let tofloat repr = match repr with | RValue -> load_double | _ -> assert false let convert fpad repr_from repr_to descr_opt = convert the value on the wasm stack , from repr_from to match repr_to with | RValue | RIntVal -> tovalue_alloc fpad repr_from descr_opt | RInt -> toint repr_from | RIntUnclean -> tointunclean repr_from | RFloat -> tofloat repr_from | _ -> TODO let push_global offset = [ L [ K "global.get"; ID "wasicaml_global_data"; ]; L [ K "i32.load" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * offset))); K "align=2"; ] ] let follow_path path = List.map (fun field -> L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * field))); K "align=2"; ] ) path let push fpad store = put the value in store onto the wasm stack match store with | RealAccu _ -> push_local "accu" | Local(repr, name) -> push_local name | Const x -> push_const (Int32.of_int x) | RealStack pos -> push_stack fpad pos | Atom tag -> alloc_atom fpad tag | TracedGlobal(Glb glb_offset, path, _) -> push_global glb_offset @ follow_path path | TracedGlobal(Env env_offset, path, _) -> push_env @ add_offset (4 * env_offset) @ follow_path path | Invalid -> assert false let push_alloc_as fpad store req_repr descr_opt = match store, req_repr with | Const x, (RValue | RIntVal) -> push_const (Int32.logor (Int32.shift_left (Int32.of_int x) 1) 1l) | Local(RInt, name), (RValue | RIntVal) -> saves one instr push_local name @ push_local name @ [ L [ K "i32.add" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ] ] | _ -> let sexpl_push = push fpad store in let repr = repr_of_store store in sexpl_push @ convert fpad repr req_repr descr_opt let push_as fpad store req_repr = push_alloc_as fpad store req_repr None let pop_to fpad store repr descr_opt code_value = match store with | RealAccu _ -> code_value @ tovalue_alloc fpad repr descr_opt @ pop_to_local "accu" | Local(lrepr, name) -> code_value @ convert fpad repr lrepr descr_opt @ pop_to_local name | RealStack pos -> (code_value @ tovalue_alloc fpad repr descr_opt) |> pop_to_stack fpad pos | _ -> assert false let copy fpad src dest descr_opt = match dest with | RealAccu _ -> push_alloc_as fpad src RValue descr_opt @ pop_to_local "accu" | Local(repr, name) -> push_as fpad src repr @ pop_to_local name | RealStack pos -> push_alloc_as fpad src RValue descr_opt |> pop_to_stack fpad pos | _ -> assert false let rec drop n l = if n > 0 then match l with | _ :: l -> drop (n-1) l | [] -> [] else l let emit_unary gpad fpad op src1 dest = match op with | Pnegint -> ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 (0xffff_fffel)); ]; L [ K "i32.xor" ]; L [ K "i32.const"; N (I32 2l); ]; L [ K "i32.add" ]; ] ) |> pop_to fpad dest RIntVal None | Pboolnot -> ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 2l); ]; L [ K "i32.xor" ] ] ) |> pop_to fpad dest RIntVal None | Poffsetint offset -> ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 (Int32.shift_left (Int32.of_int offset) 1)); ]; L [ K "i32.add" ] ] ) |> pop_to fpad dest RIntVal None | Pisint -> ( push_as fpad src1 RValue @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.and" ]; ] ) |> pop_to fpad dest RInt None | Pgetfield field -> assert(field >= 0); ( push_as fpad src1 RValue @ [ L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * field))); K "align=2"; ]; ] ) |> pop_to fpad dest RValue None | Pgetfloatfield field -> (* dest is here a Local(RFloat,_), so no allocation needed *) ( match dest with | Local(RFloat, name) -> push_as fpad src1 RValue @ [ L [ K "f64.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * double_size * field))); K "align=2"; ]; L [ K "local.set"; ID name ] ] | _ -> assert false ) | Pvectlength -> (* CHECK: this is long enough for a helper function *) let local = req_tmp1_i32 fpad in ( push_as fpad src1 RValue @ [ L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.sub" ]; L [ K "i32.load" ]; L [ K "local.tee"; ID local ]; L [ K "local.get"; ID local ]; L [ K "i32.const"; N (I32 0xffl) ]; L [ K "i32.and" ]; L [ K "i32.const"; N (I32 (Int32.of_int double_array_tag)); ]; 1 if double array , else 0 L [ K "i32.const"; N (I32 9l) ]; L [ K "i32.add" ]; L [ K "i32.shr_u" ]; shift by 10 for double array , else by 9 L [ K "i32.const"; N (I32 1l); ]; L [ K "i32.or" ]; ] ) |> pop_to fpad dest RIntVal None | Pgetpubmet tag -> TODO : enable the cache : pass a unique pointer to a 4 byte mem block instead of NULL ( initialized to 0 ) instead of NULL (initialized to 0) *) gpad.need_mlookup <- true; ( (* mlookup(src1, tag, NULL) *) push_as fpad src1 RValue @ push_const (Int32.succ (Int32.shift_left (Int32.of_int tag) 1)) @ push_const 0l @ [ L [ K "call"; ID "mlookup" ] ] ) |> pop_to fpad dest RValue None let emit_unaryeffect fpad op src1 = match op with | Poffsetref offset -> let local = req_tmp1_i32 fpad in push_as fpad src1 RIntVal @ [ L [ K "local.tee"; ID local ]; L [ K "local.get"; ID local ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.const"; N (I32 (Int32.shift_left (Int32.of_int offset) 1)); ]; L [ K "i32.add" ]; L [ K "i32.store"; K "align=2" ]; ] | Psetglobal (Global index) -> (* let local = new_local fpad RValue in *) [ L [ K "global.get"; ID "wasicaml_global_data"; ]; L [ K "i32.load" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * index))); ]; L [ K "i32.add" ] ] @ debug2 150 index @ [ L [ K " local.tee " ; ID local ] ] @ debug2_var 151 local @ [ L [ K " local.get " ; ID local ] ] @ debug2 150 index @ [ L [ K "local.tee"; ID local ]] @ debug2_var 151 local @ [ L [ K "local.get"; ID local ]] *) @ push_as fpad src1 RValue @ [ L [ K "call"; ID "caml_modify"; ] ] let emit_int_binary fpad src1 src2 dest instrs_repr instrs_int = ( push_as fpad src1 RInt @ push_as fpad src2 RInt @ instrs_int ) |> pop_to fpad dest instrs_repr None let emit_int_binary_unclean_ok fpad src1 src2 dest instrs_int = ( push_as fpad src1 RIntUnclean @ push_as fpad src2 RIntUnclean @ instrs_int ) |> pop_to fpad dest RIntUnclean None let emit_intval_binary fpad src1 src2 dest instrs_int instrs_intval = if repr_of_store src1 = RInt && repr_of_store src2 = RInt then ( push_as fpad src1 RInt @ push_as fpad src2 RInt @ instrs_int @ tovalue fpad RIntUnclean ) |> pop_to fpad dest RIntVal None else ( push_as fpad src1 RIntVal @ push_as fpad src2 RIntVal @ instrs_intval ) |> pop_to fpad dest RIntVal None let emit_intval_binary_unclean_ok fpad src1 src2 dest instrs_int instrs_intval = let is_ok st = let repr = repr_of_store st in repr = RInt || repr = RIntUnclean in if is_ok src1 && is_ok src2 then ( push_as fpad src1 RIntUnclean @ push_as fpad src2 RIntUnclean @ instrs_int @ tovalue fpad RIntUnclean ) |> pop_to fpad dest RIntVal None else emit_intval_binary fpad src1 src2 dest instrs_int instrs_intval let emit_intval_int_binary fpad src1 src2 dest instrs_int instrs_intval = src2 is always an RInt if repr_of_store src1 = RInt then ( push_as fpad src1 RInt @ push_as fpad src2 RInt @ instrs_int @ tovalue fpad RIntUnclean ) |> pop_to fpad dest RIntVal None else ( push_as fpad src1 RIntVal @ push_as fpad src2 RInt @ instrs_intval ) |> pop_to fpad dest RIntVal None let emit_binary gpad fpad op src1 src2 dest = match op with | Paddint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.add" ] ] [ L [ K "i32.add" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.sub" ] ] | Psubint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.sub" ] ] [ L [ K "i32.sub" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.add" ] ] | Pmulint -> emit_int_binary fpad src1 src2 dest RIntUnclean [ L [ K "i32.mul" ] ] | Pdivint -> ( match src2 with | Const n when n <> 0 -> emit_int_binary fpad src1 src2 dest RInt [ L [ K "i32.div_s" ]] | _ -> let local = req_tmp1_i32 fpad in emit_int_binary fpad src1 src2 dest RInt [ L [ K "local.tee"; ID local ]; L [ K "i32.eqz" ]; L [ K "if"; L [ K "then"; L [ K "call"; ID "caml_raise_zero_divide" ] ] ]; L [ K "local.get"; ID local ]; L [ K "i32.div_s" ] ] ) | Pmodint -> ( match src2 with | Const n when n <> 0 -> emit_int_binary fpad src1 src2 dest RInt [ L [ K "i32.rem_s" ]] | _ -> let local = req_tmp1_i32 fpad in emit_int_binary fpad src1 src2 dest RInt [ L [ K "local.tee"; ID local ]; L [ K "i32.eqz" ]; L [ K "if"; L [ K "then"; L [ K "call"; ID "caml_raise_zero_divide" ] ] ]; L [ K "local.get"; ID local ]; L [ K "i32.rem_s" ] ] ) | Pandint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.and" ] ] [ L [ K "i32.and" ] ] | Porint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.or" ] ] [ L [ K "i32.or" ] ] | Pxorint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.xor" ] ] [ L [ K "i32.xor" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ]; ] | Plslint -> let r1 = repr_of_store src1 in if r1 = RInt || r1 = RIntUnclean then emit_int_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.shl" ]] else ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 0xffff_fffel) ]; L [ K "i32.and" ] ] @ push_as fpad src2 RIntUnclean @ [ L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ] ] ) |> pop_to fpad dest RIntVal None | Plsrint -> emit_intval_int_binary fpad src1 src2 dest [ L [ K "i32.shr_u" ]; L [ K "i32.const"; N (I32 0x3fff_ffffl) ]; L [ K "i32.and" ] ] [ L [ K "i32.shr_u" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.or" ] ] | Pasrint -> emit_intval_int_binary fpad src1 src2 dest [ L [ K "i32.shr_s" ]] [ L [ K "i32.shr_s" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.or" ] ] | (Pintcomp cmp | Puintcomp cmp) -> let wasm_op = match op with | Pintcomp Ceq | Puintcomp Ceq -> "i32.eq" | Pintcomp Cne | Puintcomp Cne -> "i32.ne" | Pintcomp Clt -> "i32.lt_s" | Pintcomp Cle -> "i32.le_s" | Pintcomp Cgt -> "i32.gt_s" | Pintcomp Cge -> "i32.ge_s" | Puintcomp Clt -> "i32.lt_u" | Puintcomp Cle -> "i32.le_u" | Puintcomp Cgt -> "i32.gt_u" | Puintcomp Cge -> "i32.ge_u" | _ -> assert false in TODO : we miss some optimizations when one of the operands is a constant constant *) if repr_comparable_as_i32 (repr_of_store src1) (repr_of_store src2) then (* repr doesn't matter *) ( push fpad src1 @ push fpad src2 @ [ L [ K wasm_op ]] ) |> pop_to fpad dest RInt None else emit_int_binary fpad src1 src2 dest RInt [ L [ K wasm_op ]] | Pgetvectitem -> ( push_as fpad src1 RValue @ ( match src2, repr_of_store src2 with | Const c, _ -> [ L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.shift_left (Int32.of_int c) 2)); K "align=2" ] ] | _, (RInt | RIntUnclean) -> push_as fpad src2 RInt @ [ L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ] ] | _ -> push_as fpad src2 RIntVal @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 0xffff_fffcl) ]; L [ K "i32.and" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ] ] ) ) |> pop_to fpad dest RValue None | Pgetstringchar | Pgetbyteschar -> ( push_as fpad src1 RValue @ ( match src2 with | Const c -> [ L [ K "i32.load8_u"; K (sprintf "offset=0x%x" c) ] ] | _ -> push_as fpad src2 RIntUnclean @ [ L [ K "i32.add" ]; L [ K "i32.load8_u" ] ] ) ) |> pop_to fpad dest RInt None | Pgetmethod -> gpad.need_mlookup <- true; ( (* src2[0][src1] *) push_as fpad src2 RValue @ [ L [ K "i32.load"; K "align=2" ]] @ push_as fpad src1 RInt @ [ L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ] ] ) |> pop_to fpad dest RValue None | Pgetdynmet -> gpad.need_mlookup <- true; ( (* mlookup(src2, arc1, NULL) *) push_as fpad src2 RValue @ push_as fpad src1 RValue @ push_const 0l @ [ L [ K "call"; ID "mlookup" ] ] ) |> pop_to fpad dest RValue None let emit_binaryeffect fpad op src1 src2 = match op with | Psetfield field -> push_as fpad src1 RValue @ ( if field <> 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * field))); ]; L [ K "i32.add" ] ] else [] ) @ push_as fpad src2 RValue @ [ L [ K "call"; ID "caml_modify" ]] | Psetfloatfield field -> push_as fpad src1 RValue @ push_as fpad src2 RFloat @ [ L [ K "f64.store"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * field))); K "align=2"; ] ] let emit_ternaryeffect fpad op src1 src2 src3 = match op with | Psetvectitem -> push_as fpad src1 RValue @ ( match src2, repr_of_store src2 with | Const c, _ -> [ L [ K "i32.const"; N (I32 (Int32.shift_left (Int32.of_int c) 2)) ]; L [ K "i32.add" ] ] | _, (RInt | RIntUnclean) -> push_as fpad src2 RIntUnclean @ [ L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; ] | _ -> push_as fpad src2 RIntVal @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 0xffff_fffcl) ]; L [ K "i32.and" ]; L [ K "i32.add" ]; ] ) @ push_as fpad src3 RValue @ [ L [ K "call"; ID "caml_modify" ]] | Psetbyteschar -> push_as fpad src1 RValue @ ( match src2 with | Const c -> push_as fpad src3 RInt @ [ L [ K "i32.store8"; K (sprintf "offset=0x%x" c) ] ] | _ -> push_as fpad src2 RIntUnclean @ [ L [ K "i32.add" ] ] @ push_as fpad src3 RIntUnclean @ [ L [ K "i32.store8" ]] ) type mb_elem = | MB_store of store | MB_const of int32 | MB_code of sexp list let push_mb_elem fpad = function | MB_store src -> push_as fpad src RValue | MB_const n -> push_const n | MB_code code -> code let makeblock fpad descr src_list tag = let size = List.length src_list in let sexpl_alloc, ptr, young = alloc_set fpad descr size tag in let sexpl_init = if young then List.mapi (fun field src -> push_mb_elem fpad src |> pop_to_field ptr field ) src_list else List.mapi (fun field src -> push_field_addr ptr field @ push_mb_elem fpad src @ [ L [ K "call"; ID "caml_initialize" ]] ) src_list in let c1 = [ C "<makeblock>" ] in let c2 = [ C "</makeblock>" ] in (ptr, c1 @ sexpl_alloc @ List.flatten sexpl_init @ c2) let makefloatblock fpad descr src_list = let size = List.length src_list in let wosize = size * double_size in let sexpl_alloc, ptr, _ = alloc_set fpad descr wosize double_array_tag in let sexpl_init = List.mapi (fun field src -> ( push_as fpad src RValue @ load_double ) |> pop_to_double_field ptr field ) src_list in (ptr, sexpl_alloc @ List.flatten sexpl_init) let lookup_label gpad lab = let letrec_label, subfunc = try Hashtbl.find gpad.funcmapping lab with Not_found -> assert false in let wasmindex = try Hashtbl.find gpad.wasmindex letrec_label with Not_found -> assert false in (wasmindex, letrec_label, subfunc) let push_wasmptr gpad lab = (* For PIC: *) let wasmindex , subfunc = lookup_label gpad lab in [ L [ K " global.get " ; ID " _ _ table_base " ] ; L [ K " i32.const " ; N ( I32 ( Int32.of_int wasmindex ) ) ] ; L [ K " i32.add " ] ; ] let wasmindex, subfunc = lookup_label gpad lab in [ L [ K "global.get"; ID "__table_base" ]; L [ K "i32.const"; N (I32 (Int32.of_int wasmindex)) ]; L [ K "i32.add" ]; ] *) For statically linked WASM . Note that this way of taking the address of a function is not officially supported in the wat file format . address of a function is not officially supported in the wat file format. *) let wasmindex, letrec_label, subfunc = lookup_label gpad lab in [ L [ K "i32.const"; ID (Hashtbl.find gpad.letrec_name letrec_label) ]] let push_codeptr gpad lab = let wasmindex, letrec_label, subfunc = lookup_label gpad lab in push_wasmptr gpad lab @ [ L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 (Int32.of_int ((subfunc lsl 2)+1))) ]; L [ K "i32.or" ]; ] let closurerec gpad fpad descr src_list dest_list = let nfuncs = List.length dest_list in let envofs = nfuncs * 3 - 1 in let mb_src_list = ( List.mapi (fun i (_, label) -> ( if i > 0 then [ MB_const (Int32.of_int (make_header (3*i) infix_tag)) ] else [] ) @ [ MB_code (push_codeptr gpad label) ] @ [ MB_const (Int32.of_int (((envofs - 3*i) lsl 1) + 1)) ] ) dest_list |> List.flatten ) @ List.map (fun src -> MB_store src) src_list in let ptr, sexpl_mb = makeblock fpad descr mb_src_list closure_tag in let sexpl_dest = List.mapi (fun i (dest, _) -> ( [ L [ K "local.get"; ID ptr ] ] @ (if i > 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int (12*i))) ]; L [ K "i32.add" ] ] else [] ) descr is not up to date ) dest_list |> List.flatten in sexpl_mb @ sexpl_dest let c_call gpad fpad descr src_list name = let descr = { descr with stack_save_accu = false } in (* it is overwritten *) let sexpl_setup = setup_for_gc fpad descr in let sexpl_restore = restore_after_gc fpad descr in let sexpl_debug_args = List.map ( fun src - > push_const 21l @ push_as fpad src RValue @ [ L [ K " call " ; ID " debug2 " ] ] ) src_list | > List.flatten in let sexpl_debug_args = List.map (fun src -> push_const 21l @ push_as fpad src RValue @ [ L [ K "call"; ID "debug2" ]]) src_list |> List.flatten in *) let sexpl_args = List.map (fun src -> push_as fpad src RValue) src_list in let sexpl_call = [ L [ K "call"; ID name ]] @ pop_to_local "accu" in let p_i32 = L [ K "param"; K "i32" ] in let r_i32 = L [ K "result"; K "i32" ] in let ty = (src_list |> List.map (fun _ -> p_i32)) @ [ r_i32 ] in Hashtbl.replace gpad.primitives name ty; debug2 20 0 (* @ sexpl_debug_args *) sexpl_setup @ List.flatten sexpl_args @ sexpl_call @ sexpl_restore @ debug2 20 1 let c_call_vector gpad fpad descr numargs depth name = let descr = { descr with stack_save_accu = false } in (* it is overwritten *) let sexpl_setup = setup_for_gc fpad descr in let sexpl_restore = restore_after_gc fpad descr in let sexpl_call = push_field_addr "fp" (-depth) @ push_const (Int32.of_int numargs) @ [ L [ K "call"; ID name ]] @ pop_to_local "accu" in let ty = [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ] in Hashtbl.replace gpad.primitives name ty; debug2 20 0 sexpl_setup @ sexpl_call @ sexpl_restore let string_label = function | Label k -> sprintf "label%d" k | Loop k -> sprintf "loop%d" k let switch fpad src labls_ints labls_blocks = fpad.need_panic <- true; let value = req_tmp1_i32 fpad in push_as fpad src RValue @ pop_to_local value if ( ! Is_block(value ) ) L [ K "local.get"; ID value ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.and" ]; L [ K "if"; L [ K "then"; L [ K "local.get"; ID value ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; L ( [ K "br_table" ] @ ( Array.map (fun lab -> ID (string_label lab)) labls_ints |> Array.to_list ) @ [ ID "panic" ] ); ]; L [ K "else"; L [ K "local.get"; ID value ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.const"; N (I32 0xffl) ]; L [ K "i32.and" ]; L ( [ K "br_table" ] @ ( Array.map (fun lab -> ID (string_label lab)) labls_blocks |> Array.to_list ) @ [ ID "panic" ] ); ]; ] ] let grab fpad num = let sexpl = if ( codeptr & 1 ) L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_restart_mask) ]; L [ K "i32.and" ]; L [ K "if"; L ( [ K "then"; RESTART (* (extra_args, fp) = restart_helper(envptr, extra_args, fp) *) L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "fp" ]; ] @ call_restart_helper() @ pop_to_fp fpad @ [ L [ K "local.set"; ID "extra_args" ]; codeptr & = ~1 - I think this is not needed L [ K " local.get " ; ID " codeptr " ] ; L [ K " i32.const " ; N ( ) ] ; L [ K " i32.and " ] ; L [ K " local.set " ; ID " codeptr " ] ; L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 0xffff_fffel) ]; L [ K "i32.and" ]; L [ K "local.set"; ID "codeptr" ]; *) ] ) ]; (* regular GRAB *) L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 (Int32.of_int num)) ]; L [ K "i32.ge_u" ]; L [ K "if"; L [ K "then"; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 (Int32.of_int num)) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "extra_args" ]; ]; L ( [ [ K "else"; L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "local.get"; ID "fp" ]; ]; returncall "grab_helper" ] |> List.flatten ) ]; ] in sexpl let return() = NB . do n't use bp here . codeptr is already destroyed when coming from appterm_common codeptr is already destroyed when coming from appterm_common *) [ C "$return"; L [ K "local.get"; ID "extra_args" ]; L [ K "if"; L ( [ [ K "then"; L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "accu" ]; ]; returncall "return_helper" ] |> List.flatten ) ]; L [ K "local.get"; ID "accu" ]; L [ K "return" ]; ] let throw fpad = (* the exception value must be in domain_field_exn_bucket *) if fpad.fpad_scope.cfg_main && fpad.fpad_scope.cfg_try_labels = [] then (* in outermost scope there is no caller - prefer to throw a real exception *) [ L [ K "call"; ID "wasicaml_throw" ]; L [ K "unreachable" ] ] else if fpad.fpad_scope.cfg_try_labels = [] then (* a normal function, but outside a "try" block *) [ L [ K "i32.const"; N (I32 0l) ]; L [ K "return" ] ] else (* inside a "try" block: the result is returned via exn_result *) [ L [ K "i32.const"; N (I32 0l) ]; L [ K "global.set"; ID "exn_result" ]; L [ K "i32.const"; N (I32 0l) ]; L [ K "return" ] ] let apply_direct gpad fpad funlabel numargs depth = let _, letrec_label, _ = lookup_label gpad funlabel in let letrec_name = Hashtbl.find gpad.letrec_name letrec_label in let env_pos = (-depth + numargs) in ( push_local "accu" |> pop_to_stack fpad env_pos ) @ push_field_addr "fp" env_pos (* new envptr *) @ [ L [ K "i32.const"; N (I32 (Int32.of_int (numargs-1))) ]; ] @ push_field "accu" 0 @ push_local "fp" @ [L [ K "i32.const"; N (I32 (Int32.of_int (4 * depth))) ]; L [ K "i32.sub" ]; L [ K "call"; ID letrec_name ]; L [ K "local.tee"; ID "accu" ]; L [ K "i32.eqz" ]; (* check for exceptions *) L [ K "if"; L ([ K "then"] @ throw fpad) ]; ] let apply fpad numargs depth = let env_pos = (-depth + numargs) in let codeptr = req_tmp1_i32 fpad in ( push_local "accu" |> pop_to_stack fpad env_pos ) @ push_field_addr "fp" env_pos (* new envptr *) @ [ L [ K "i32.const"; N (I32 (Int32.of_int (numargs-1))) ]; ] @ push_field "accu" 0 @ (if !enable_deadbeef_check then [ L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * depth))) ]; L [ K "i32.sub" ]; L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ) @ [ L [ K "local.tee"; ID codeptr ]; (* L [ K "i32.const"; N (I32 3l) ]; L [ K "local.get"; ID codeptr ]; L [ K "call"; ID "debug2" ]; *) L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * depth))) ]; L [ K "i32.sub" ]; L [ K "local.get"; ID codeptr ]; L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shr_u" ]; L [ K " local.set " ; ID " h.i32 " ] ; L [ K " i32.const " ; N ( I32 2l ) ] ; L [ K " local.get " ; ID " h.i32 " ] ; L [ K " call " ; ID " debug2 " ] ; L [ K " local.get " ; ID " h.i32 " ] ; L [ K "local.set"; ID "h.i32" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "local.get"; ID "h.i32" ]; L [ K "call"; ID "debug2" ]; L [ K "local.get"; ID "h.i32" ]; *) L [ K "call_indirect"; N (I32 0l); (* table index *) L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ]; L [ K "local.tee"; ID "accu" ]; L [ K "i32.eqz" ]; (* check for exceptions *) L [ K "if"; L ([ K "then"] @ throw fpad) ]; ] let appterm_common fpad () = NB . do n't use bp here [ C "$appterm_common"; L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "local.get"; ID "accu" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "appterm_new_num_args" ]; ] @ call_appterm_helper() @ [ L [ K "local.set"; ID "extra_args" ]; L [ K "local.tee"; ID "codeptr" ]; L [ K "if"; L [ K "then"; (* same letrec: we can jump! *) L [ K "br"; ID "startover" ] ]; L [ K "else"; (* different letrec: call + return *) (* we can jump to $return *) L [ K "br"; ID "return" ] ] ] ] let call_reinit_frame gpad fpad numargs oldnumargs depth = if numargs <= 10 then ( gpad.need_reinit_frame_k <- ISet.add numargs gpad.need_reinit_frame_k; push_local "fp" @ push_const (Int32.of_int depth) @ push_const (Int32.of_int oldnumargs) @ [ L [ K "call"; ID (sprintf "reinit_frame_%d" numargs) ] ] ) else ( gpad.need_reinit_frame <- true; push_local "fp" @ push_const (Int32.of_int depth) @ push_const (Int32.of_int oldnumargs) @ push_const (Int32.of_int numargs) @ [ L [ K "call"; ID "reinit_frame" ] ] ) let appterm_push_params numargs = first arg of call ] second arg of call ] @ (if numargs >= 2 then [ L [ K "i32.const"; N (I32 (Int32.of_int (numargs - 1))) ]; L [ K "i32.add" ]; ] else [] ) third arg of call : code pointer fourth arg of call ] let appterm_with_returncall gpad fpad numargs oldnumargs depth = let sexpl = call_reinit_frame gpad fpad numargs oldnumargs depth @ pop_to_local "fp" (* no need to set bp here *) @ (push_local "accu" |> pop_to_field "envptr" 0) @ appterm_push_params numargs @ push_field "accu" 0 @ [ L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shr_u" ]; (* which function to call *) ] @ [ L [ K "return_call_indirect"; N (I32 0l); (* table *) L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ] ] in sexpl let appterm_without_returncall gpad fpad numargs oldnumargs depth = let sexpl = call_reinit_frame gpad fpad numargs oldnumargs depth @ pop_to_local "fp" (* no need to set bp here *) @ push_const (Int32.of_int numargs) @ pop_to_local "appterm_new_num_args" @ [ L [ K "br"; ID "appterm_common" ] ] in fpad.need_appterm_common <- true; fpad.need_return <- true; if not !enable_returncall then fpad.need_startover <- true; sexpl let appterm_direct gpad fpad funlabel numargs oldnumargs depth = (* Wc_unstack must not emit Wappterm_direct when tail calls are unavailable *) assert(!enable_returncall); let _, letrec_label, _ = lookup_label gpad funlabel in let letrec_name = Hashtbl.find gpad.letrec_name letrec_label in let goto_selfrecurse = letrec_label = fpad.fpad_letrec_label && numargs = oldnumargs in let sexpl = call_reinit_frame gpad fpad numargs oldnumargs depth @ pop_to_local "fp" (* no need to set bp here *) @ (push_local "accu" |> pop_to_field "envptr" 0) @ (if goto_selfrecurse then [ L [ K "br"; ID "selfrecurse" ] ] else appterm_push_params numargs @ [ L [ K "return_call"; ID letrec_name ] ] ) in if goto_selfrecurse then fpad.need_selfrecurse <- true; sexpl let appterm gpad fpad funlabel_opt numargs oldnumargs depth = if !enable_returncall then match funlabel_opt with | Some funlabel -> appterm_direct gpad fpad funlabel numargs oldnumargs depth | None -> appterm_with_returncall gpad fpad numargs oldnumargs depth else appterm_without_returncall gpad fpad numargs oldnumargs depth let appterm_args gpad fpad funlabel_opt funsrc argsrc oldnumargs depth = (* Wc_unstack must not emit Wappterm_args when tail calls are unavailable *) assert(!enable_returncall); let newnumargs = List.length argsrc in (* save argsrc in local variables *) let arg_locals = List.map (fun src -> new_local fpad (repr_of_store src)) argsrc in let arg_instrs1 = List.map2 (fun src localname -> let dest = Local(repr_of_store src, localname) in copy fpad src dest None ) argsrc arg_locals |> List.flatten in (* set "accu" to the function pointer: *) let accu_instrs = copy fpad funsrc (RealAccu { no_function = false }) None in (* fp = fp + old_num_args - new_num_args *) let fp_delta = oldnumargs - newnumargs in let fp_instrs = if fp_delta = 0 then [] else [ L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * fp_delta))) ]; L [ K "i32.add" ]; L [ K "local.set"; ID "fp" ]; ] in let arg_instrs2 = List.map2 (fun src (localname, i) -> let src = Local(repr_of_store src, localname) in let dest = RealStack i in copy fpad src dest None ) argsrc (List.mapi (fun i localname -> (localname, i)) arg_locals) |> List.flatten in let envptr_instrs = (push_local "accu" |> pop_to_field "envptr" 0) in let call_instrs = match funlabel_opt with | Some funlabel -> let _, letrec_label, _ = lookup_label gpad funlabel in let letrec_name = Hashtbl.find gpad.letrec_name letrec_label in let goto_selfrecurse = letrec_label = fpad.fpad_letrec_label && newnumargs = oldnumargs in if goto_selfrecurse then ( fpad.need_selfrecurse <- true; [ L [ K "br"; ID "selfrecurse" ] ] ) else appterm_push_params newnumargs @ [ L [ K "return_call"; ID letrec_name ] ] | None -> appterm_push_params newnumargs @ push_field "accu" 0 @ [ L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shr_u" ]; (* which function to call *) ] @ [ L [ K "return_call_indirect"; N (I32 0l); (* table *) L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ] ] in arg_instrs1 @ accu_instrs @ fp_instrs @ arg_instrs2 @ envptr_instrs @ call_instrs let trap gpad fpad trylabel catchlabel depth = push 4 values onto stack : 0 , 0 , 0 , extra_args get function pointer and caught = wasicaml_wraptry4(f , env , extra_args , , fp - depth ) (* if (caught): accu = Caml_state->exn_bucket; jump lab *) (* else: accu = global "exn_result" *) (* at end of try function: global "exn_result" = accu *) let local1 = req_tmp1_i32 fpad in let local2 = req_tmp2_i32 fpad in let sexpl_stack = (push_const 0l |> pop_to_stack fpad (-depth-1)) @ (push_const 0l |> pop_to_stack fpad (-depth-2)) @ (push_const 0l |> pop_to_stack fpad (-depth-3)) @ (push_local "extra_args" |> pop_to_stack fpad (-depth-4)) @ (if !enable_deadbeef_check then [ L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * (depth + 4)))) ]; L [ K "i32.sub" ]; L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ) in let sexpl_try = push_domain_field domain_field_local_roots @ pop_to_local local2 @ push_wasmptr gpad trylabel @ push_local "envptr" @ push_local "extra_args" @ push_codeptr gpad trylabel @ push_local "fp" @ [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * (depth + 4))))]; L [ K "i32.sub" ] ] @ debug2 30 0 @ [ L [ K "call"; ID "wasicaml_wraptry4" ]; L [ K "local.set"; ID local1 ]; ] @ debug2 30 1 @ ( push_local local2 |> pop_to_domain_field domain_field_local_roots ) @ [ L [ K "local.get"; ID local1 ]; L [ K "global.get"; ID "exn_result" ]; L [ K "i32.eqz" ]; L [ K "i32.or" ]; L [ K "if"; L [ K "then"; L [ K "global.get"; ID "wasicaml_domain_state" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * domain_field_exn_bucket))); K "align=2" ]; L [ K "local.set"; ID "accu" ]; L [ K "br"; ID (sprintf "label%d" catchlabel) ] ] ]; L [ K "global.get"; ID "exn_result" ]; L [ K "local.set"; ID "accu" ] ] in sexpl_stack @ sexpl_try let rec emit_instr gpad fpad instr = match instr with | Wcomment s -> [] | Wblock arg -> ( match arg.label with | Label lab -> [ L ( [ K "block"; ID (sprintf "label%d" lab); BR ] @ emit_instrs gpad fpad arg.body ) ] @ debug2 100 lab | Loop lab -> [ L ( [ K "loop"; ID (sprintf "loop%d" lab); BR ] @ emit_instrs gpad fpad arg.body ) ] ) | Wcond { cond; ontrue; onfalse } -> emit_instr gpad fpad (if !cond then ontrue else onfalse) | Wcopy arg -> copy fpad arg.src arg.dest None | Walloc arg -> copy fpad arg.src arg.dest (Some arg.descr) | Wenv arg -> push_env @ load_offset (4 * arg.field) @ pop_to_local "accu" | Wcopyenv arg -> push_env @ add_offset (4 * arg.offset) @ pop_to_local "accu" | Wgetglobal arg -> let Global offset = arg.src in debug2 160 offset @ push_const 161l @ [ L [ K " global.get " ; ID " wasicaml_global_data " ; ] ; L [ K " i32.load " ] ; L [ K " i32.const " ; N ( I32 ( Int32.of_int ( 4 * offset ) ) ) ; ] ; L [ K " i32.add " ] ; L [ K " call " ; ID " debug2 " ] ] debug2 160 offset @ push_const 161l @ [ L [ K "global.get"; ID "wasicaml_global_data"; ]; L [ K "i32.load" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * offset))); ]; L [ K "i32.add" ]; L [ K "call"; ID "debug2" ] ] *) push_global offset @ pop_to_local "accu" | Wunary arg -> emit_unary gpad fpad arg.op arg.src1 arg.dest | Wunaryeffect arg -> emit_unaryeffect fpad arg.op arg.src1 | Wbinary arg -> emit_binary gpad fpad arg.op arg.src1 arg.src2 arg.dest | Wbinaryeffect arg -> emit_binaryeffect fpad arg.op arg.src1 arg.src2 | Wternaryeffect arg -> emit_ternaryeffect fpad arg.op arg.src1 arg.src2 arg.src3 | Wmakeblock arg -> let src = List.map (fun s -> MB_store s) arg.src in let ptr, sexpl = makeblock fpad arg.descr src arg.tag in sexpl @ push_local ptr @ pop_to_local "accu" | Wmakefloatblock arg -> let ptr, sexpl = makefloatblock fpad arg.descr arg.src in sexpl @ push_local ptr @ pop_to_local "accu" | Wccall arg -> (* TODO: maintain a list of noalloc primitives *) (* TODO: maintain a list of unit primitives (set accu=Const 0 instead), or more generally, primitives that never return functions *) c_call gpad fpad arg.descr arg.src arg.name | Wccall_vector arg -> c_call_vector gpad fpad arg.descr arg.numargs arg.depth arg.name | Wbranch arg -> [ L [ K "br"; ID (string_label arg.label) ]] | Wif arg -> ( match repr_of_store arg.src with | RInt -> push_as fpad arg.src RInt @ (if arg.neg then [ L [ K "i32.eqz" ]] else []) | RIntUnclean -> push_as fpad arg.src RIntUnclean @ [ L [ K "i32.const"; N (I32 0x7fff_ffffl) ]; L [ K "i32.and" ] ] @ (if arg.neg then [ L [ K "i32.eqz" ]] else []) | _ -> push_as fpad arg.src RIntVal @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K (if arg.neg then "i32.le_u" else "i32.gt_u") ] ] ) @ [ L [ K "if"; L ( K "then" :: ( List.map (emit_instr gpad fpad) arg.body |> List.flatten ) ) ] ] | Wswitch arg -> switch fpad arg.src arg.labels_int arg.labels_blk | Wapply arg -> apply fpad arg.numargs arg.depth | Wapply_direct arg -> (* TODO: the copy is only needed for calling functions that actually access the environment. Note that, however, functions not accessing the environment at all seem to be relatively rare. *) let fn = Wc_traceglobals.Unknown in (* this arg is ignored by [copy] *) let src = TracedGlobal(arg.global, arg.path, fn) in copy fpad src Wc_unstack.real_accu None @ apply_direct gpad fpad arg.funlabel arg.numargs arg.depth | Wappterm arg -> appterm gpad fpad None arg.numargs arg.oldnumargs arg.depth | Wappterm_direct arg -> (* TODO: the copy is only needed for calling functions that actually access the environment. Note that, however, functions not accessing the environment at all seem to be relatively rare. *) let fn = Wc_traceglobals.Unknown in (* this arg is ignored by [copy] *) let src = TracedGlobal(arg.global, arg.path, fn) in copy fpad src Wc_unstack.real_accu None @ appterm gpad fpad (Some arg.funlabel) arg.numargs arg.oldnumargs arg.depth | Wappterm_args arg -> appterm_args gpad fpad None arg.funsrc arg.argsrc arg.oldnumargs arg.depth | Wappterm_direct_args arg -> appterm_args gpad fpad (Some arg.funlabel) arg.funsrc arg.argsrc arg.oldnumargs arg.depth | Wreturn arg -> let no_function = match arg.src with | RealAccu { no_function } -> no_function | _ -> repr_of_store arg.src <> RValue in if no_function then push_as fpad arg.src RValue @ [ L [ K "return" ]] else ( (* return value could be another closure *) fpad.need_return <- true; push_as fpad arg.src RValue @ pop_to_local "accu" @ push_field_addr "fp" arg.arity @ pop_to_local "fp" @ [ L [ K "br"; ID "return" ]] ) | Wgrab arg -> if fpad.disallow_grab then ( (* disallow_grab is set when there shouldn't be (another) Wgrab after some structural analysis/transform *) let letrec_name = Hashtbl.find gpad.letrec_name fpad.fpad_letrec_label in eprintf "[DEBUG] function: %s\n%!" letrec_name; assert false; ); grab fpad arg.numargs | Wclosurerec arg -> closurerec gpad fpad arg.descr arg.src arg.dest | Wraise arg -> ( push_as fpad arg.src RValue |> pop_to_domain_field domain_field_exn_bucket ) @ ( push_local "fp" |> pop_to_domain_field domain_field_extern_sp ) @ throw fpad | Wtrap arg -> trap gpad fpad arg.trylabel arg.catchlabel arg.depth | Wtryreturn arg -> push_as fpad arg.src RValue @ [ L [ K "global.set"; ID "exn_result" ]; L [ K "i32.const"; N (I32 0l) ]; L ( K " block " : : debug2 1 3 ) ; L [ K "return" ] ] | Wnextmain { label } -> push_local "accu" (* sic! *) @ push_local "extra_args" @ push_local "codeptr" @ push_local "fp" @ returncall (sprintf "letrec_main%d" label) | Wstop -> [ L [ K "i32.const"; N (I32 0l) ]; L ( K " block " : : debug2 1 2 ) ; L [ K "return" ] ] | Wnop -> [] | Wunreachable -> [ L [ K "unreachable" ]] and emit_instrs gpad fpad instrs = List.fold_left (fun acc instr -> let comment = string_of_winstruction instr in List.rev_append (emit_instr gpad fpad instr) (List.rev_append [C comment] acc) ) [] instrs |> List.rev let rec extract_grab instrs = Extract the first Wgrab , optionally wrapped in a cascade of Wblock match instrs with | Wgrab _ as grab :: rest -> (rest, Some grab) | Wcomment _ as i :: rest -> let rest_after_extract, grab_opt = extract_grab rest in (i :: rest_after_extract, grab_opt) | Wblock arg :: rest -> ( match arg.label with | Label _ -> let body_after_extract, grab_opt = extract_grab arg.body in (Wblock { arg with body = body_after_extract } :: rest, grab_opt ) | Loop _ -> (instrs, None) ) | _ -> (instrs, None) let emit_fblock_instrs gpad fpad instrs = fpad.disallow_grab <- false; let rest, grab_opt = extract_grab instrs in match grab_opt with | Some grab -> let code_grab = emit_instrs gpad fpad [ grab ] in fpad.disallow_grab <- true; let code_rest = emit_instrs gpad fpad rest in if fpad.need_selfrecurse then ( assert(!enable_returncall); code_grab @ [ L ( [ K "loop"; ID "selfrecurse"; BR ] @ code_rest) ] ) else code_grab @ code_rest | None -> fpad.disallow_grab <- true; let code = emit_instrs gpad fpad instrs in if fpad.need_selfrecurse then ( assert(!enable_returncall); [ L ( [ K "loop"; ID "selfrecurse"; BR ] @ code) ] ) else code let emit_fblock gpad fpad fblock = let maxdepth = Wc_tracestack.max_stack_depth_of_fblock fblock in (* make maxdepth a bit larger than stricly necessary to completely avoid bp[k] with k<0 *) fpad.maxdepth <- if maxdepth > 0 then maxdepth + 2 else 0; let instrs = Wc_unstack.transl_fblock fpad.lpad fblock |> emit_fblock_instrs gpad fpad in set_bp fpad @ (if !enable_deadbeef_check && fpad.maxdepth > 0 then [ L [ K "local.get"; ID "bp" ]; L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_init" ] ] else [] ) @ instrs let get_funcmapping_without_tailcalls scode = let open Wc_control in let funcmapping = Hashtbl.create 7 in let subfunction_num = Hashtbl.create 7 in let subfunctions = Hashtbl.create 7 in IMap.iter (fun func_label fblock -> let letrec_func_label = match fblock.scope.cfg_letrec_label with | None -> 0 | Some label -> label in let letrec_label = if fblock.scope.cfg_main then Main letrec_func_label else Func letrec_func_label in let subfunc_num = try Hashtbl.find subfunction_num letrec_label with Not_found -> 0 in Hashtbl.replace subfunction_num letrec_label (subfunc_num+1); Hashtbl.add funcmapping func_label (letrec_label, subfunc_num); let subfunc_list = try Hashtbl.find subfunctions letrec_label with Not_found -> [] in Hashtbl.replace subfunctions letrec_label (func_label :: subfunc_list) ) scode.functions; let subfunctions_rev = Hashtbl.create 7 in Hashtbl.iter (fun letrec_label subfunc_labels -> Hashtbl.add subfunctions_rev letrec_label (List.rev subfunc_labels) ) subfunctions; ( funcmapping, subfunctions_rev ) let get_funcmapping_with_tailcalls scode = (* simplified: do not generate subfunctions *) let open Wc_control in let funcmapping = Hashtbl.create 7 in let subfunctions = Hashtbl.create 7 in IMap.iter (fun func_label fblock -> let letrec_label = if fblock.scope.cfg_main then Main func_label else Func func_label in Hashtbl.add funcmapping func_label (letrec_label, 0); Hashtbl.replace subfunctions letrec_label [func_label] ) scode.functions; let subfunctions_rev = Hashtbl.create 7 in Hashtbl.iter (fun letrec_label subfunc_labels -> Hashtbl.add subfunctions_rev letrec_label (List.rev subfunc_labels) ) subfunctions; ( funcmapping, subfunctions_rev ) let get_funcmapping scode = if !enable_returncall then get_funcmapping_with_tailcalls scode else get_funcmapping_without_tailcalls scode let block_cascade start_sexpl label_sexpl_pairs = let rec shift prev_sexpl pairs = match pairs with | (label, lsexpl) :: pairs' -> (prev_sexpl, Some label) :: shift lsexpl pairs' | [] -> [ prev_sexpl, None ] in let rec arrange inner_sexpl shifted = match shifted with | (sexpl, label_opt) :: shifted' -> let body = inner_sexpl @ sexpl @ [ L [ K "unreachable" ]] in let inner_sexpl' = match label_opt with | None -> body | Some lab -> [ L ( [ K "block"; ID lab; BR; ] @ body ) ] in arrange inner_sexpl' shifted' | [] -> inner_sexpl in arrange [] (shift start_sexpl label_sexpl_pairs) let cond_section_lz cond label sexpl_section sexpl_users = if cond then [ L ( [ K "block"; ID label; BR ] @ sexpl_users ) ] @ sexpl_section() else sexpl_users let cond_section cond label sexpl_section sexpl_users = cond_section_lz cond label (fun () -> sexpl_section) sexpl_users let cond_loop cond label sexpl = if cond then [ L ( [ K "loop"; ID label; BR ] @ sexpl ) ] else sexpl let eff_label = function | Func l -> l | Main l -> l let init_lpad_for_subfunc gpad fpad func_label = let func_offset, environment = ( try Hashtbl.find gpad.glbfun_table func_label with Not_found -> 0, [| |] ) in fpad.lpad.environment <- environment; fpad.lpad.func_offset <- func_offset let generate_function scode gpad letrec_label func_name subfunc_labels export_flag = let fpad = { (empty_fpad()) with fpad_letrec_label = letrec_label } in Hashtbl.add fpad.lpad.locals "accu" RValue; Hashtbl.add fpad.lpad.locals "bp" RValue; fpad.lpad.avoid_locals <- export_flag; (* avoid local vars in the long main function *) fpad.lpad.globals_table <- gpad.globals_table; let subfunc_pairs = List.map (fun func_label -> let fblock = IMap.find func_label Wc_control.(scode.functions) in fpad.fpad_scope <- fblock.scope; let label = sprintf "func%d" func_label in init_lpad_for_subfunc gpad fpad func_label; let sexpl = emit_fblock gpad fpad fblock in (label, sexpl) ) subfunc_labels in let subfunc_pairs_with_panic = subfunc_pairs @ [ "panic", [] ] in let subfunc_sexpl = match subfunc_pairs with | [] -> assert false | [ label, sexpl ] -> cond_section fpad.need_panic "panic" [ L [ K "unreachable" ]] sexpl | _ -> let labels = List.map (fun (label, _) -> ID label) subfunc_pairs_with_panic in let body = [ L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_subfunc_mask) ]; L [ K "i32.and" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shr_u" ]; L ( [ K "br_table" ] @ labels ) ] in block_cascade body subfunc_pairs_with_panic in let sexpl = ( match letrec_label with | Main 0 | Func _ -> [ L [ K "i32.const"; N (I32 1l) ]; L [ K "local.set"; ID "accu" ] ] | Main _ -> envptr is abused to pass on the accu from one main function to the next to the next *) [ L [ K "local.get"; ID "envptr" ]; L [ K "local.set"; ID "accu" ]; L [ K "i32.const"; N (I32 0xffff_fffcl) ]; L [ K "local.set"; ID "envptr" ] ] ) @ (subfunc_sexpl |> cond_section_lz fpad.need_appterm_common "appterm_common" (appterm_common fpad) |> cond_loop fpad.need_startover "startover" |> cond_section_lz fpad.need_return "return" return ) in if fpad.need_appterm_common then ( Hashtbl.add fpad.lpad.locals "appterm_new_num_args" RInt; ); if fpad.need_xalloc then Hashtbl.add fpad.lpad.locals "xalloc" RValue; if fpad.need_tmp1_i32 then Hashtbl.add fpad.lpad.locals "tmp1_i32" RValue; if fpad.need_tmp2_i32 then Hashtbl.add fpad.lpad.locals "tmp2_i32" RValue; if fpad.need_tmp1_f64 then Hashtbl.add fpad.lpad.locals "tmp1_f64" RValue; let locals = Hashtbl.fold (fun name vtype acc -> (name,vtype) :: acc) fpad.lpad.locals [] in let letrec = [ L ( [ K "func"; ID func_name; ] @ (if export_flag then [ L [ K "export"; S func_name ]] else []) @ [ L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "codeptr"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; BR; L [ K "result"; K "i32" ]; ] @ (List.map (fun (name,repr) -> L [ K "local"; ID name; K (string_of_vtype (vtype repr)) ]; ) locals ) @ debug2 0 ( eff_label letrec_label ) @ debug2_var 10 " fp " @ debug2_var 11 " envptr " @ debug2_var 12 " " @ debug2_var 13 " extra_args " @ [ L [ K " local.get " ; ID " envptr " ] ; ( * print 14 : env , if possible @ debug2 0 (eff_label letrec_label) @ debug2_var 10 "fp" @ debug2_var 11 "envptr" @ debug2_var 12 "codeptr" @ debug2_var 13 "extra_args" @ [ L [ K "local.get"; ID "envptr" ]; (* print 14: env, if possible *) L [ K "i32.const"; N (I32 (-1l)) ]; L [ K "i32.ne" ]; L [ K "if"; L ( [ K "then"; L [ K "i32.const"; N (I32 14l) ]] @ push_env @ [ L [ K "call"; ID "debug2" ]] ) ] ] *) @ sexpl @ [ L [ K "unreachable" ]] ) ] in letrec let generate_letrec scode gpad letrec_label = let subfunc_labels = try Hashtbl.find gpad.subfunctions letrec_label with Not_found -> assert false in assert(subfunc_labels <> []); let func_name = Hashtbl.find gpad.letrec_name letrec_label in let export = (letrec_label = Main 0) in generate_function scode gpad letrec_label func_name subfunc_labels export let globals() = [ "wasicaml_global_data", true, TI32; "wasicaml_domain_state", true, TI32; "wasicaml_atom_table", true, TI32; "wasicaml_stack_threshold", true, TI32; "exn_result", true, TI32; ] @ if !enable_multireturn then [] else [ "retval2", true, TI32; "retval3", true, TI32; ] let imp_functions = [ "env", "caml_alloc_small_dispatch", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "env", "caml_alloc_small", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ]; "env", "caml_alloc_shr", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ]; "env", "caml_initialize", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "env", "caml_modify", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "env", "caml_raise_zero_divide", []; "env", "caml_raise_stack_overflow", []; "env", "wasicaml_wraptry4", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ]; "env", "wasicaml_get_global_data", [ L [ K "result"; K "i32" ]]; "env", "wasicaml_get_domain_state", [ L [ K "result"; K "i32" ]]; "env", "wasicaml_get_atom_table", [ L [ K "result"; K "i32" ]]; "env", "debug2", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "wasicaml", "wasicaml_throw", []; ] let sanitize = String.map (fun c -> match c with | 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '.' -> c | _ -> '?' ) let bigarray_to_string_list limit ba = let n = Array1.dim ba in let l = ref [] in let p = ref 0 in while !p < n do let q = min (n - !p) limit in let by = Bytes.create q in for i = 0 to q-1 do Bytes.set by i ba.{!p + i} done; l := Bytes.to_string by :: !l; p := !p + q done; List.rev !l let generate scode exe get_defname globals_table = let (funcmapping, subfunctions) = get_funcmapping scode in let letrec_name = Hashtbl.create 7 in Hashtbl.iter (fun _ (letrec_label, _) -> match letrec_label with | Main 0 -> Hashtbl.add letrec_name letrec_label "letrec_main" | Main lab -> Hashtbl.add letrec_name letrec_label (sprintf "letrec_main%d" lab) | Func lab -> let suffix = try let defname = get_defname lab in "_" ^ sanitize defname with | Not_found -> "" in Hashtbl.add letrec_name letrec_label (sprintf "letrec%d%s" lab suffix) ) funcmapping; let wasmindex = Hashtbl.create 7 in (* Need 'elements' this only for PIC: *) let nextindex = ref 0 in let _elements = Hashtbl.fold (fun _ (letrec_label, _) acc -> Hashtbl.add wasmindex letrec_label !nextindex; incr nextindex; let name = Hashtbl.find letrec_name letrec_label in (ID name) :: acc ) funcmapping [] in let data = bigarray_to_string_list 4096 Wc_reader.(exe.data) |> List.map (fun s -> S s) in let gpad = { funcmapping; subfunctions; primitives = Hashtbl.create 7; wasmindex; letrec_name; need_reinit_frame = false; need_reinit_frame_k = ISet.empty; need_mlookup = false; globals_table; glbfun_table = Wc_traceglobals.derive_glbfun_table globals_table; } in let sexpl_code = Hashtbl.fold (fun letrec_label _ acc -> let sexpl = generate_letrec scode gpad letrec_label in sexpl @ acc ) gpad.subfunctions [] in let sexpl_memory = [ L [ K "import"; S "env"; S "memory"; L [ K "memory"; ID "memory"; N (I32 65536l); ] ] ] in let sexpl_table = [ L [ K "import"; S "env"; S "table"; L [ K "table"; (* ID "table"; *) N (I32 (Int32.of_int (Hashtbl.length subfunctions))); K "funcref" ] ] ] in let sexpl_functions = List.map (fun (modname, name, typeuse) -> L [ K "import"; S modname; S name; L ( [ K "func"; ID name; ] @ typeuse ) ] ) imp_functions @ Hashtbl.fold (fun name typeuse acc -> ( L [ K "import"; S "env"; S name; L ( [ K "func"; ID name; ] @ typeuse ) ] ) :: acc ) gpad.primitives [] in let sexpl_globals = List.map (fun (name, mut, vtype) -> L ( [ K "global"; ID name; ( if mut then L [ K "mut"; K (string_of_vtype vtype) ] else K (string_of_vtype vtype) ); ] @ zero_expr_of_vtype vtype ) ) (globals()) in sexpl_memory @ sexpl_functions @ sexpl_table @ sexpl_globals @ wasicaml_init @ wasicaml_get_data @ wasicaml_get_data_size Wc_reader.(Array1.dim exe.data) @ alloc_fast @ alloc_slow() @ grab_helper gpad @ return_helper() @ appterm_helper() @ restart_helper gpad @ (if gpad.need_reinit_frame then reinit_frame else [] ) @ (if gpad.need_mlookup then mlookup else [] ) @ (if !enable_deadbeef_check then deadbeef_init @ deadbeef_check else [] ) @ (ISet.elements gpad.need_reinit_frame_k |> List.map reinit_frame_k |> List.flatten ) @ sexpl_code (* Only PIC: @ [ L ( [ K "elem"; L [ K "global.get"; ID "__table_base" ]; K "func"; ] @ elements ) ] *) @ [ L ( [ K "data"; L [ K "memory"; N (I32 0l) ]; (* PIC: L [ K "offset"; K "global.get"; ID "__memory_base" ]; *) WAT extension : ID "data"; ] @ data ) ] Notes : ~/.wasicaml / bin / wasi_ld --relocatable / initruntime.o lib / prims.o ~/.wasicaml / lib / ocaml / libcamlrun.a ~/.wasicaml / bin / wasi_ld -o final.wasm caml.wasm src / wasicaml / t.wasm wat syntax : deficiencies of wat2wasm : Static linking : -conventions/blob/master/Linking.md some toolchain tricks : -to-webassembly/ wasm - ld : : -to-llvm-mc-project.html LLVM wasm assembly parser : LLVM wasm assembly tests : -project/tree/main/llvm/test/MC/WebAssembly Notes: ~/.wasicaml/bin/wasi_ld --relocatable -o caml.wasm lib/initruntime.o lib/prims.o ~/.wasicaml/lib/ocaml/libcamlrun.a ~/.wasicaml/bin/wasi_ld -o final.wasm caml.wasm src/wasicaml/t.wasm wat syntax: deficiencies of wat2wasm: Static linking: -conventions/blob/master/Linking.md some llvm toolchain tricks: -to-webassembly/ wasm-ld: LLVM MC: -to-llvm-mc-project.html LLVM wasm assembly parser: LLVM wasm assembly tests: -project/tree/main/llvm/test/MC/WebAssembly *)
null
https://raw.githubusercontent.com/remixlabs/wasicaml/1c048a373b90c50ef4cabb25ec47517b8a076ef8/src/wasicaml/wc_emit.ml
ocaml
global pad maps letrec label to name maps name to type maps function label to (letrec_label, subfunction_id) maps letrec_label to list of subfunction labels maps letrec label to the (relative) index in the table of functions knowledge about the globals for each letrec function: knowledge about its environment function pad back to subfunction selection self-recursion - only when tailcalls are enabled! whether Wasm code can use the return_call instruction (tail calls) debugging: check that there is no uninitialized memory on the stack TODO: grab the following values from C: color=white loop if (bp >= fp) break *bp = 0xdeadbeef bp++ now check that there's no dead beef on the stack! assert (ptr <= fp) loop if (ptr >= fp) break assert( *bp != 0xdeadbeef) ptr++ Caml_state_field(young_ptr) = ptr *ptr = header return ptr+1 for the accu *ptr = header return ptr+1 return saved accu new_local fpad RValue if (ptr == NULL) new_local fpad RValue won't overwrite accu Field(accu, i+3) = ... fp[i] assign i++, and jump back if i <= extra_args restart flag fp -= num_args fp[i[ = ... Field(env, i+3) assign i++, and jump back if i < num_args extra_args += num_args return i-- new_fp[i] = ... fp[-(depth-i)] assign bp = fp - depth new_fp[i] = ... bp[i)] assign table table same letrec: we can jump! different letrec: call + return. test the cache first, if any: ofs = *cache & meths[1] get &meths[3] + ofs load the tag there, and compare with [tag] if equal, found something load it li=3 hi=meths[0] loop if (li >= hi) break mi = (li+hi) >> 1 | 1 if (tag < meths[mi]) hi = mi-2 li = mi set cache return meths[li-1] L [ K "export"; S "wasicaml_get_data" ]; PIC: L [ K "global.get"; ID "wc__memory_base" ]; Extension: L [ K "export"; S "wasicaml_get_data_size" ]; L [ K "export"; S "wasicaml_init" ]; transform the value of the Wasm stack to a proper OCaml value, and put that back on the Wasm stack TODO: need to allocate the block dest is here a Local(RFloat,_), so no allocation needed CHECK: this is long enough for a helper function mlookup(src1, tag, NULL) let local = new_local fpad RValue in repr doesn't matter src2[0][src1] mlookup(src2, arc1, NULL) For PIC: it is overwritten @ sexpl_debug_args it is overwritten (extra_args, fp) = restart_helper(envptr, extra_args, fp) regular GRAB the exception value must be in domain_field_exn_bucket in outermost scope there is no caller - prefer to throw a real exception a normal function, but outside a "try" block inside a "try" block: the result is returned via exn_result new envptr check for exceptions new envptr L [ K "i32.const"; N (I32 3l) ]; L [ K "local.get"; ID codeptr ]; L [ K "call"; ID "debug2" ]; table index check for exceptions same letrec: we can jump! different letrec: call + return we can jump to $return no need to set bp here which function to call table no need to set bp here Wc_unstack must not emit Wappterm_direct when tail calls are unavailable no need to set bp here Wc_unstack must not emit Wappterm_args when tail calls are unavailable save argsrc in local variables set "accu" to the function pointer: fp = fp + old_num_args - new_num_args which function to call table if (caught): accu = Caml_state->exn_bucket; jump lab else: accu = global "exn_result" at end of try function: global "exn_result" = accu TODO: maintain a list of noalloc primitives TODO: maintain a list of unit primitives (set accu=Const 0 instead), or more generally, primitives that never return functions TODO: the copy is only needed for calling functions that actually access the environment. Note that, however, functions not accessing the environment at all seem to be relatively rare. this arg is ignored by [copy] TODO: the copy is only needed for calling functions that actually access the environment. Note that, however, functions not accessing the environment at all seem to be relatively rare. this arg is ignored by [copy] return value could be another closure disallow_grab is set when there shouldn't be (another) Wgrab after some structural analysis/transform sic! make maxdepth a bit larger than stricly necessary to completely avoid bp[k] with k<0 simplified: do not generate subfunctions avoid local vars in the long main function print 14: env, if possible Need 'elements' this only for PIC: ID "table"; Only PIC: @ [ L ( [ K "elem"; L [ K "global.get"; ID "__table_base" ]; K "func"; ] @ elements ) ] PIC: L [ K "offset"; K "global.get"; ID "__memory_base" ];
Copyright ( C ) 2021 by Figly , Inc. This code is free software , see the file LICENSE for details . This code is free software, see the file LICENSE for details. *) open Printf open Bigarray open Wc_types open Wc_number open Wc_sexp open Wc_instruct OCaml functions are translated to Wasm functions with parameters : param 1 : envptr param 2 : extra_args param 3 : code pointer ( overriding the one in the closure ) param 4 : fp So far , the function args are passed via the bytecode stack . The envptr is a pointer to the stack location of the environment ( env ) . This pointer is created when a function is called - the bytecode interpreter reserves 3 stack locations for PC , saved env , and extra_args . We also reserve stack locations upon function call but differently : - need only one location and not three - the one location stores the env of the called function , not the env of the calling function There are also two ways of invoking functions . If there are up to 3 args , the bytecode only includes the instructions to push the args onto the stack , followed by Kapply . It is then the task of Kapply to make room for the saved values ( as explained ) . If , however , there are more than 3 args , the bytecode includes a Kpush_retaddr instruction which reserves 3 positions on the stack in advance . Although we only need one of these , there is no fixup that would eliminate the other two . param 1: envptr param 2: extra_args param 3: code pointer (overriding the one in the closure) param 4: fp So far, the function args are passed via the bytecode stack. The envptr is a pointer to the stack location of the environment (env). This pointer is created when a function is called - the bytecode interpreter reserves 3 stack locations for PC, saved env, and extra_args. We also reserve stack locations upon function call but differently: - need only one location and not three - the one location stores the env of the called function, not the env of the calling function There are also two ways of invoking functions. If there are up to 3 args, the bytecode only includes the instructions to push the args onto the stack, followed by Kapply. It is then the task of Kapply to make room for the saved values (as explained). If, however, there are more than 3 args, the bytecode includes a Kpush_retaddr instruction which reserves 3 positions on the stack in advance. Although we only need one of these, there is no fixup that would eliminate the other two. *) type wasm_value_type = | TI32 | TI64 | TF64 let string_of_vtype = function | TI32 -> "i32" | TI64 -> "i64" | TF64 -> "f64" let zero_expr_of_vtype = function | TI32 -> [ L [ K "i32.const"; N (I32 0l) ] ] | TI64 -> [ L [ K "i64.const"; N (I64 0L) ] ] | TF64 -> [ L [ K "f64.const"; N (F64 0.0) ] ] type letrec_label = | Func of int | Main of int { letrec_name : (letrec_label, string) Hashtbl.t; primitives : (string, sexp list) Hashtbl.t; funcmapping : (int, letrec_label * int) Hashtbl.t; subfunctions : (letrec_label, int list) Hashtbl.t; wasmindex : (letrec_label, int) Hashtbl.t; mutable need_reinit_frame : bool; mutable need_reinit_frame_k : ISet.t; mutable need_mlookup : bool; mutable globals_table : (int, Wc_traceglobals.initvalue) Hashtbl.t; mutable glbfun_table : (int, int * Wc_traceglobals.initvalue array) Hashtbl.t; } { lpad : Wc_unstack.lpad; fpad_letrec_label : letrec_label; mutable fpad_scope : Wc_control.cfg_scope; mutable maxdepth : int; mutable need_appterm_common : bool; mutable need_return : bool; mutable need_panic : bool; mutable need_tmp1_i32 : bool; mutable need_tmp2_i32 : bool; mutable need_tmp1_f64 : bool; mutable need_xalloc : bool; Wgrab is only allowed at the beginning } Stack layout of a function with N arguments : fp is the stack pointer at the time the function starts executing . POSITION USED FOR -------------------------------------------------------- - fp+N-1 : argN - fp+1 to fp+N-2 : ... - fp : arg1 - fp-1 : bottom of local stack - fp - camldepth+1 to fp-2 : ... - fp - camldepth : top of local stack - fp - camldepth-1 etc : free fp is the stack pointer at the time the function starts executing. POSITION USED FOR -------------------------------------------------------- - fp+N-1: argN - fp+1 to fp+N-2: ... - fp: arg1 - fp-1: bottom of local stack - fp-camldepth+1 to fp-2: ... - fp-camldepth: top of local stack - fp-camldepth-1 etc: free *) let enable_multireturn = ref false whether Wasm code can use multivalue returns NB . This seems to be broken in llvm-11 let enable_returncall = ref false let enable_deadbeef_check = ref false let code_pointer_shift = 12 OCaml code pointers : - Bit 0 : always 1 - Bit 1 : whether to run RESTART - Bit 2 - code_pointer_shift-1 : subfunction of the letrec - Bit code_pointer_shift-31 : the Wasm function index See also ocaml / runtime / callback.c - Bit 0: always 1 - Bit 1: whether to run RESTART - Bit 2 - code_pointer_shift-1: subfunction of the letrec - Bit code_pointer_shift-31: the Wasm function index See also ocaml/runtime/callback.c *) let code_pointer_subfunc_mask = 0xffcl let code_pointer_letrec_mask = 0xffff_f000l let code_pointer_restart_mask = 2l Note that the domain fields are 8 - aligned , even on 32 bit systems let max_young_wosize = 256 let domain_field_young_ptr = 0 let domain_field_young_limit = 1 let domain_field_stack_low = 17 let domain_field_stack_high = 18 let domain_field_stack_threshold = 19 let domain_field_extern_sp = 20 let domain_field_trapsp = 21 let domain_field_trap_barrier = 22 let domain_field_external_raise = 23 let domain_field_exn_bucket = 24 let domain_field_local_roots = 36 let double_size = 2 let double_tag = 253 let double_array_tag = 254 let closure_tag = 247 let infix_tag = 249 let caml_from_c = 0 let make_header size tag = (size lsl 10) lor tag let vtype repr = match repr with | RValue | RInt | RIntUnclean | RIntVal | RNatInt | RInt32 -> TI32 | RInt64 -> TI64 | RFloat -> TF64 let empty_fpad() = { lpad = Wc_unstack.empty_lpad ~enable_returncall:!enable_returncall (); fpad_letrec_label = Main 0; fpad_scope = { cfg_letrec_label = None; cfg_func_label = 0; cfg_try_labels = []; cfg_main = false }; maxdepth = 0; need_appterm_common = false; need_startover = false; need_selfrecurse = false; need_return = false; need_panic = false; need_tmp1_i32 = false; need_tmp2_i32 = false; need_tmp1_f64 = false; need_xalloc = false; disallow_grab = false; } let returncall name = if !enable_returncall then [ L [ K "return_call"; ID name ] ] else [ L [ K "call"; ID name ]; L [ K "return" ] ] let new_local fpad repr = Wc_unstack.new_local fpad.lpad repr let req_tmp1_i32 fpad = if fpad.lpad.avoid_locals then ( fpad.need_tmp1_i32 <- true; "tmp1_i32" ) else new_local fpad RInt let req_tmp2_i32 fpad = if fpad.lpad.avoid_locals then ( fpad.need_tmp2_i32 <- true; "tmp2_i32" ) else new_local fpad RInt let req_tmp1_f64 fpad = if fpad.lpad.avoid_locals then ( fpad.need_tmp1_f64 <- true; "tmp1_f64" ) else new_local fpad RFloat let set_bp_1 fpad = [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * fpad.maxdepth))) ]; L [ K "i32.sub" ]; L [ K "local.tee"; ID "bp" ]; L [ K "global.get"; ID "wasicaml_stack_threshold" ]; L [ K "i32.lt_u" ]; L [ K "if"; L [ K "then"; L [ K "call"; ID "caml_raise_stack_overflow" ]; ] ] ] let set_bp fpad = if fpad.maxdepth = 0 then [] else [ L [ K "local.get"; ID "fp" ] ] @ set_bp_1 fpad let push_const n = [ L [ K "i32.const"; N (I32 n) ]] let push_local var = [ L [ K "local.get"; ID var ]] let pop_to_local var = [ L [ K "local.set"; ID var ]] let pop_to_fp fpad = if fpad.maxdepth = 0 then pop_to_local "fp" else [ L [ K "local.tee"; ID "fp" ]] @ set_bp_1 fpad let load_offset offset = if offset >= 0 then [ L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int offset)); K "align=2"; ] ] else [ L [ K "i32.const"; N (I32 (Int32.of_int (-offset))) ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ] ] let add_offset offset = if offset <> 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int offset)) ]; L [ K "i32.add" ] ] else [] let push_env = [ L [ K "local.get"; ID "envptr" ]; L [ K "i32.load"; K "align=2" ] ] let push_field var_base field = [ L [ K "local.get"; ID var_base; ] ] @ load_offset (4 * field) let push_global_field var_base field = [ L [ K "global.get"; ID var_base; ] ] @ load_offset (4 * field) let push_field_addr var_base field = [ L [ K "local.get"; ID var_base ] ] @ if field <> 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * field))); ]; L [ K "i32.add" ] ] else [] let push_global_field_addr var_base field = [ L [ K "global.get"; ID var_base; ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * field))); ]; L [ K "i32.add" ] ] let push_stack fpad pos = if pos >= 0 then push_field "fp" pos else push_field "bp" (pos + fpad.maxdepth) let push_domain_field field = [ L [ K "global.get"; ID "wasicaml_domain_state" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * field))); K "align=2"; ]; ] let store_offset addr offset code_value = if offset >= 0 then [ L [ K "local.get"; ID addr ] ] @ code_value @ [ L [ K "i32.store"; K (sprintf "offset=0x%lx" (Int32.of_int offset)); K "align=2"; ] ] else [ L [ K "local.get"; ID addr ]; L [ K "i32.const"; N (I32 (Int32.of_int (-offset))) ]; L [ K "i32.sub" ] ] @ code_value @ [ L [ K "i32.store"; K "align=2" ] ] let pop_to_field var_base field code_value = store_offset var_base (4*field) code_value let pop_to_double_field var_base field code_value = [ L [ K "local.get"; ID var_base ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * double_size * field))); ]; L [ K "i32.add" ] ] @ code_value @ [ L [ K "f64.store"; K "align=2" ]] let pop_to_domain_field field code_value = [ L [ K "global.get"; ID "wasicaml_domain_state" ]] @ code_value @ [ L [ K "i32.store"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * field))); K "align=2"; ]; ] let pop_to_stack fpad pos code_value = if pos >= 0 then pop_to_field "fp" pos code_value else pop_to_field "bp" (pos + fpad.maxdepth) code_value let load_double = [ L [ K "f64.load"; K "align=2" ] ] let debug2 x0 x1 = [ L [ K "i32.const"; N (I32 (Int32.of_int x0)) ]; L [ K "i32.const"; N (I32 (Int32.of_int x1)) ]; L [ K "call"; ID "debug2" ] ] let debug2_var x0 var = [ L [ K "i32.const"; N (I32 (Int32.of_int x0)) ]; L [ K "local.get"; ID var ]; L [ K "call"; ID "debug2" ] ] let deadbeef_init = IBM mainframes used to initialize fresh memory with 0xdeadbeef [ L ( [ [ K "func"; ID "deadbeef_init"; L [ K "param"; ID "bp"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; ]; [ L [ K "block"; ID "loop_exit"; BR; L [ K "loop"; ID "loop"; BR; L [ K "local.get"; ID "bp" ]; L [ K "local.get"; ID "fp" ]; L [ K "i32.ge_u" ]; L [ K "br_if"; ID "loop_exit" ]; L [ K "local.get"; ID "bp" ]; L [ K "i32.const"; N (I32 0xdeadbeefl) ]; L [ K "i32.store" ]; L [ K "local.get"; ID "bp" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.add" ]; L [ K "local.set"; ID "bp" ]; L [ K "br"; ID "loop" ] ] ] ] ] |> List.flatten ) ] let deadbeef_check = [ L ( [ [ K "func"; ID "deadbeef_check"; L [ K "param"; ID "ptr"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; ]; push_local "ptr"; push_local "fp"; [ L [ K "i32.gt_u" ]; L [ K "if"; L [ K "then"; L [ K "unreachable" ] ] ] ]; [ L [ K "block"; ID "loop_exit"; BR; L [ K "loop"; ID "loop"; BR; L [ K "local.get"; ID "ptr" ]; L [ K "local.get"; ID "fp" ]; L [ K "i32.ge_u" ]; L [ K "br_if"; ID "loop_exit" ]; L [ K "local.get"; ID "ptr" ]; L [ K "i32.load" ]; L [ K "i32.const"; N (I32 0xdeadbeefl) ]; L [ K "i32.eq" ]; L [ K "if"; L [ K "then"; L [ K "unreachable" ] ] ]; L [ K "local.get"; ID "ptr" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.add" ]; L [ K "local.set"; ID "ptr" ]; L [ K "br"; ID "loop" ] ] ] ] ] |> List.flatten ) ] let stack_init fpad descr = put zeros into the uninitialized stack positions List.map (fun pos -> pop_to_stack fpad pos (push_const 1l) ) descr.stack_uninit |> List.flatten let setup_for_gc fpad descr = let sp_decr = if descr.stack_save_accu then 1 else 0 in let sexpl_stack = stack_init fpad descr in let sexpl_accu = if descr.stack_save_accu then push_local "accu" |> pop_to_stack fpad (-descr.stack_depth-1) else [] in let sexpl_extern_sp = ( [ L [ K "local.get"; ID "fp"; ] ] @ (if descr.stack_depth + sp_decr > 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int ( 4 * (descr.stack_depth + sp_decr)))); ]; L [ K "i32.sub" ]; ] else [] ) ) |> pop_to_domain_field domain_field_extern_sp in let sexpl_check = ( if !enable_deadbeef_check then push_domain_field domain_field_extern_sp @ [ L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ) in sexpl_stack @ sexpl_accu @ sexpl_extern_sp @ sexpl_check let restore_after_gc fpad descr = if descr.stack_save_accu then push_stack fpad (-descr.stack_depth-1) @ pop_to_local "accu" else [] let alloc_atom fpad tag = [ L [ K "global.get"; ID "wasicaml_atom_table"; ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * tag))); ]; L [ K "i32.add" ]; ] let alloc_fast = [ L ( [ [ K "func"; ID "alloc_fast"; L [ K "param"; ID "bhsize"; K "i32" ]; L [ K "param"; ID "header"; K "i32" ]; BR; L [ K "result"; C "ptr"; K "i32" ]; L [ K "local"; ID "ptr"; K "i32" ]; ]; ptr = ) - Whsize_wosize ( wosize ) push_domain_field domain_field_young_ptr; push_local "bhsize"; [ L [ K "i32.sub" ]; L [ K "local.tee"; ID "ptr" ]; ]; ( push_local "ptr" |> pop_to_domain_field domain_field_young_ptr ); if ( ptr < Caml_state_field(young_limit ) ) return 0 push_domain_field domain_field_young_limit; [ L [ K "i32.lt_u" ] ]; [ L [ K "if"; L [ K "then"; L [ K "i32.const"; N (I32 0l) ]; L [ K "return" ] ] ] ]; ( push_local "header" |> pop_to_field "ptr" 0 ); push_local "ptr"; push_const 4l; [ L [ K "i32.add" ]; L [ K "return" ] ] ] |> List.flatten ) ] let alloc_slow() = [ L ( [ [ K "func"; ID "alloc_slow"; L [ K "param"; ID "wosize"; K "i32" ]; L [ K "param"; ID "header"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "stackdepth"; K "i32" ]; L [ K "param"; ID "accu"; K "i32" ]; BR; L [ K "result"; C "ptr"; K "i32" ]; ]; if !enable_multireturn then [ L [ K "result"; C "out_accu"; K "i32" ]; ] else []; [ L [ K "local"; ID "ptr"; K "i32" ]; L [ K "local"; ID "sp"; K "i32" ] ]; ( [ L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "stackdepth" ]; L [ K "i32.sub" ]; L [ K "i32.sub" ]; L [ K "local.tee"; ID "sp" ]; ] |> pop_to_domain_field domain_field_extern_sp ) @ (push_local "accu" |> pop_to_field "sp" 0); ( if !enable_deadbeef_check then push_domain_field domain_field_extern_sp @ [ L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ); caml_alloc_small_dispatch(wosize , CAML_FROM_C , 1 , NULL ) push_local "wosize"; push_const (Int32.of_int caml_from_c); push_const 1l; push_const 0l; [ L [ K "call"; ID "caml_alloc_small_dispatch" ]]; push_domain_field domain_field_young_ptr; pop_to_local "ptr"; ( push_local "header" |> pop_to_field "ptr" 0 ); push_local "ptr"; push_const 4l; [ L [ K "i32.add" ] ]; push_field "sp" 0; if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ]; ]; [ L [ K "return" ]] ] |> List.flatten ) ] let call_alloc_slow() = [ L [ K "call"; ID "alloc_slow" ]] @ if !enable_multireturn then [] else [ L [ K "global.get"; ID "retval2" ] ] let alloc_non_atom fpad descr size tag = fpad.need_xalloc <- true; let young = size <= max_young_wosize in let code = if young then [ push_const (Int32.of_int (4 * (size+1))); push_const (Int32.of_int (make_header size tag)); [ L [ K "call"; ID "alloc_fast" ]; L [ K "local.tee"; ID ptr ]; ]; [ L [ K "i32.eqz" ]]; [ L [ K "if"; L ( [ [ K "then"; ]; stack_init fpad descr; push_const (Int32.of_int size); push_const (Int32.of_int (make_header size tag)); push_local "fp"; push_const (Int32.of_int (4 * descr.stack_depth)); push_local "accu"; call_alloc_slow(); pop_to_local "accu"; pop_to_local ptr; ] |> List.flatten ) ]; ]; ] |> List.flatten else [ L [ K "i32.const"; N (I32 (Int32.of_int size)) ]; L [ K "i32.const"; N (I32 (Int32.of_int tag)) ]; L [ K "call"; ID "caml_alloc_shr" ]; L [ K "local.set"; ID ptr ]; ] in (code, ptr, young) let alloc fpad descr size tag = if size = 0 then alloc_atom fpad tag else let (code, ptr, _) = alloc_non_atom fpad descr size tag in code @ push_local ptr let alloc_set fpad descr size tag = if size = 0 then ( fpad.need_xalloc <- true; let young = false in (alloc_atom fpad tag @ push_local ptr, ptr, young) ) else alloc_non_atom fpad descr size tag let grab_helper gpad = generates a helper function : $ grab_helper(extra_args , , fp ) $grab_helper(extra_args, codeptr, fp) *) let fpad = empty_fpad() in let descr = empty_descr in assert(descr.stack_save_accu = false); [ L ( [ [ K "func"; ID "grab_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "codeptr"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; BR; L [ K "result"; K "i32" ]; L [ K "local"; ID "accu"; K "i32" ]; L [ K "local"; ID "i"; K "i32" ]; ]; setup_for_gc fpad descr; [ L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 (Int32.of_int closure_tag))]; L [ K "call"; ID "caml_alloc_small" ]; L [ K "local.set"; ID "accu" ]; ]; (push_env |> pop_to_field "accu" 2); push_const 0l; pop_to_local "i"; [ L [ K "loop"; ID "fields"; BR; L [ K "local.get"; ID "accu" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.store"; K "align=2" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.add" ]; L [ K "local.tee"; ID "i" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.le_u" ]; L [ K "br_if"; ID "fields" ]; ] ]; ( (push_local "codeptr" @ [ L [ K "i32.const"; N (I32 code_pointer_restart_mask) ]; L [ K "i32.or" ] ] ) |> pop_to_field "accu" 0 ); (push_const 5l |> pop_to_field "accu" 1); push_local "accu"; [ L [ K "return" ] ] ] |> List.flatten ) ] let restart_helper gpad = [ L ( [ [ K "func"; ID "restart_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; BR; L [ K "result"; C "out_extra_args"; K "i32" ]; ]; if !enable_multireturn then [ L [ K "result"; C "out_fp"; K "i32" ]; ] else []; [ L [ K "local"; ID "i"; K "i32" ]; L [ K "local"; ID "num_args"; K "i32" ]; ]; num_args = Wosize_val(env ) - 3 push_env; [ L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.const"; N (I32 10l) ]; L [ K "i32.shr_u" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "num_args" ]; ]; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "num_args" ]; L [ K "i32.const"; N (I32 2l)]; L [ K "i32.shl" ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "fp" ]; ]; [ L [ K "i32.const"; N (I32 0l)]; L [ K "local.set"; ID "i" ]; L ( [ [ K "loop"; ID "args"; BR; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ] ]; push_env; [ L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; ]; [ L [ K "i32.store"; K "align=2" ] ]; [ L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.add" ]; L [ K "local.tee"; ID "i" ]; L [ K "local.get"; ID "num_args" ]; L [ K "i32.lt_u" ]; L [ K "br_if"; ID "args" ]; ] ] |> List.flatten ) ]; env = Field(env , 2 ) [ L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "envptr" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.load"; K "offset=8"; K "align=2" ]; L [ K "i32.store"; K "align=2" ] ]; [ L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "num_args" ]; L [ K "i32.add" ]; L [ K "local.set"; ID "extra_args" ]; ]; push_local "extra_args"; push_local "fp"; if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ] ]; [ L [ K "return" ] ]; ] |> List.flatten ) ] let call_restart_helper() = [ L [ K "call"; ID "restart_helper" ]] @ if !enable_multireturn then [] else [ L [ K "global.get"; ID "retval2" ]] let reinit_frame = [ L [ K "func"; ID "reinit_frame"; L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "depth"; K "i32" ]; > = 1 > = 1 BR; L [ K "result"; C "out_fp"; K "i32" ]; L [ K "local"; ID "i"; K "i32" ]; L [ K "local"; ID "new_fp"; K "i32" ]; new_fp = fp + old_num_args - new_num_args L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "old_num_args" ]; L [ K "local.get"; ID "new_num_args" ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "local.set"; ID "new_fp" ]; L [ K "local.get"; ID "new_num_args" ]; L [ K "local.set"; ID "i" ]; L [ K "loop"; ID "args"; BR; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "i" ]; L [ K "local.get"; ID "new_fp" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "depth" ]; L [ K "local.get"; ID "i" ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.store"; K "align=2" ]; loop if i > 0 L [ K "local.get"; ID "i" ]; L [ K "br_if"; ID "args" ]; ]; L [ K "local.get"; ID "new_fp" ]; L [ K "return" ] ]; ] let reinit_frame_k new_num_args = [ L ( [ K "func"; ID (sprintf "reinit_frame_%d" new_num_args); L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "depth"; K "i32" ]; > = 1 BR; L [ K "result"; C "out_fp"; K "i32" ]; L [ K "local"; ID "i"; K "i32" ]; L [ K "local"; ID "bp"; K "i32" ]; L [ K "local"; ID "new_fp"; K "i32" ]; new_fp = fp + old_num_args - new_num_args L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "old_num_args" ]; L [ K "i32.const"; N (I32 (Int32.of_int new_num_args)) ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "local.set"; ID "new_fp" ]; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "depth" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "bp" ]; ] @ ( Wc_util.enum 0 new_num_args |> List.map (fun j -> let i = new_num_args - 1 - j in L [ K "local.get"; ID "new_fp" ]; L [ K "local.get"; ID "bp" ]; L [ K "i32.load"; K (sprintf "offset=0x%x" (4 * i)); K "align=2" ]; L [ K "i32.store"; K (sprintf "offset=0x%x" (4 * i)); K "align=2" ]; ] ) |> List.flatten ) @ [ L [ K "local.get"; ID "new_fp" ]; L [ K "return" ] ] ) ] let return_helper() = [ L ( [ [ K "func"; ID "return_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; L [ K "param"; ID "accu"; K "i32" ]; BR; L [ K "result"; K "i32" ]; L [ K "local"; ID "codeptr"; K "i32" ]; ]; ( push_local "accu" |> pop_to_field "envptr" 0 ); [ L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ]; ]; push_field "accu" 0; [ L [ K "local.tee"; ID "codeptr" ] ]; [ L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shr_u" ]; ]; if !enable_returncall then [ L [ K "return_call_indirect"; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ] ] else [ L [ K "call_indirect"; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ]; L [ K "return" ] ] ] |> List.flatten ) ] let appterm_helper() = if !enable_returncall then [] else [ L ( [ [ K "func"; ID "appterm_helper"; L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "codeptr"; K "i32" ]; L [ K "param"; ID "accu"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "new_num_args"; K "i32" ]; BR; L [ K "result"; C "out_codeptr"; K "i32" ]; ]; if !enable_multireturn then [L [ K "result"; C "out_extra_args"; K "i32" ]] else []; [ L [ K "local"; ID "out_codeptr"; K "i32" ]]; push_local "extra_args"; push_local "new_num_args"; [ L [ K "i32.add" ]]; pop_to_local "extra_args"; (push_local "accu" |> pop_to_field "envptr" 0); push_field "accu" 0; pop_to_local "out_codeptr"; [ L [ K "local.get"; ID "out_codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_letrec_mask) ]; L [ K "i32.and" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_letrec_mask) ]; L [ K "i32.and" ]; L [ K "i32.eq" ]; L [ K "if"; L ( [ K "then" ; L [ K "local.get"; ID "out_codeptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ] ] @ (if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ] ] ) @ [ L [ K "return" ] ] ); L ( [ K "else"; L [ K "i32.const"; N (I32 0l) ]; L [ K "local.get"; ID "extra_args" ] ] @ (if !enable_multireturn then [] else [ L [ K "global.set"; ID "retval2" ] ] ) @ [ L [ K "return" ]] ) ]; L [ K "unreachable" ] ] ] |> List.flatten ) ] let call_appterm_helper() = assert(not !enable_returncall); [ L [ K "call"; ID "appterm_helper" ]] @ if !enable_multireturn then [] else [ L [ K "global.get"; ID "retval2" ]] let mlookup = [ L ( [ [ K "func"; ID "mlookup"; L [ K "param"; ID "obj"; K "i32" ]; L [ K "param"; ID "tag"; K "i32" ]; L [ K "param"; ID "cache"; K "i32" ]; BR; L [ K "result"; C "method"; K "i32" ]; L [ K "local"; ID "meths"; K "i32" ]; L [ K "local"; ID "ofs"; K "i32" ]; L [ K "local"; ID "li"; K "i32" ]; L [ K "local"; ID "hi"; K "i32" ]; L [ K "local"; ID "mi"; K "i32" ]; ]; get the descriptor : meths = obj[0 ] [ L [ K "local.get"; ID "obj" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.set"; ID "meths" ]; ]; [ L [ K "local.get"; ID "cache" ]; L [ K "if"; L [ K "then"; L [ K "local.get"; ID "cache" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.get"; ID "meths" ]; L [ K "i32.load"; K "offset=0x4"; K "align=2" ]; L [ K "i32.and" ]; L [ K "local.tee"; ID "ofs" ]; L [ K "local.get"; ID "meths" ]; L [ K "i32.const"; N (I32 12l) ]; L [ K "i32.add" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.get"; ID "tag" ]; L [ K "i32.eq" ]; L [ K "if"; L [ K "then"; get & meths[2 ] + ofs L [ K "local.get"; ID "meths" ]; L [ K "i32.const"; N (I32 8l) ]; L [ K "i32.add" ]; L [ K "local.get"; ID "ofs" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "return" ]; ] ] ] ] ]; [ L [ K "i32.const"; N (I32 3l) ]; L [ K "local.set"; ID "li" ]; ]; [ L [ K "local.get"; ID "meths" ]; L [ K "i32.load"; K "align=2" ]; L [ K "local.set"; ID "hi" ]; ]; [ L [ K "block"; ID "loop_exit"; BR; L [ K "loop"; ID "loop"; BR; L [ K "local.get"; ID "li" ]; L [ K "local.get"; ID "hi" ]; L [ K "i32.ge_u" ]; L [ K "br_if"; ID "loop_exit" ]; L [ K "local.get"; ID "li" ]; L [ K "local.get"; ID "hi" ]; L [ K "i32.add" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ]; L [ K "local.set"; ID "mi" ]; L [ K "local.get"; ID "tag" ]; L [ K "local.get"; ID "meths" ]; L [ K "local.get"; ID "mi" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.lt_s" ]; L [ K "if"; L [ K "then"; L [ K "local.get"; ID "mi" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "hi" ]; ]; L [ K "else"; L [ K "local.get"; ID "mi" ]; L [ K "local.set"; ID "li" ]; ] ]; L [ K "br"; ID "loop" ]; ] ] ]; [ L [ K "local.get"; ID "cache" ]; L [ K "if"; L [ K "then"; * cache = ( li-3 ) * 4 L [ K "local.get"; ID "cache" ]; L [ K "local.get"; ID "li" ]; L [ K "i32.const"; N (I32 3l) ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.mul" ]; L [ K "i32.store"; K "align=2" ]; ] ] ]; [ L [ K "local.get"; ID "meths" ]; L [ K "local.get"; ID "li" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.sub" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ]; L [ K "return" ]; ] ] |> List.flatten ) ] let wasicaml_get_data = [ L [ K "func"; ID "wasicaml_get_data"; L [ K "result"; K "i32" ]; BR; L [ K "i32.const"; ID "data" ]; L [ K "return" ] ] ] let wasicaml_get_data_size size = [ L [ K "func"; ID "wasicaml_get_data_size"; L [ K "result"; K "i32" ]; BR; L [ K "i32.const"; N (I32 (Int32.of_int size)) ]; L [ K "return" ] ] ] let wasicaml_init = [ L [ K "func"; ID "wasicaml_init"; BR; L [ K "call"; ID "wasicaml_get_global_data" ]; L [ K "global.set"; ID "wasicaml_global_data" ]; L [ K "call"; ID "wasicaml_get_domain_state" ]; L [ K "global.set"; ID "wasicaml_domain_state" ]; L [ K "call"; ID "wasicaml_get_atom_table" ]; L [ K "global.set"; ID "wasicaml_atom_table" ]; L [ K "global.get"; ID "wasicaml_domain_state" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * domain_field_stack_threshold))); K "align=2"; ]; L [ K "global.set"; ID "wasicaml_stack_threshold" ]; L [ K "return" ] ] ] let tovalue_alloc fpad repr descr_opt = match repr with | RValue | RIntVal -> [] | RInt | RIntUnclean -> [ L [ K "i32.const"; N (I32 1l); ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 1l); ]; L [ K "i32.or" ]; ] | RFloat -> ( match descr_opt with | None -> failwith "cannot convert to double w/o stack descr" | Some descr -> let (instrs_alloc, ptr, _) = alloc_set fpad descr double_size double_tag in let local = req_tmp1_f64 fpad in let instrs = [ L [ K "local.set"; ID local ] ] @ instrs_alloc @ [ L [ K "local.get"; ID ptr ]; L [ K "local.get"; ID local ]; L [ K "f64.store"; K "align=2" ]; L [ K "local.get"; ID ptr ]; ] in instrs ) | _ -> Careful : when allocating a block and initializing it , we can not allocate in the middle ( e.g. makeblock ) . If allocations are generated by tovalue , we need to insert more code to set the block early to 0 . Probably the way out is a function straighten_if_alloc_needed that only straightens the stack positions that are neither RValue nor RInt . we cannot allocate in the middle (e.g. makeblock). If allocations are generated by tovalue, we need to insert more code to set the block early to 0. Probably the way out is a function straighten_if_alloc_needed that only straightens the stack positions that are neither RValue nor RInt. *) assert false let tovalue fpad repr = tovalue_alloc fpad repr None let toint repr = match repr with | RInt -> [] | RIntUnclean -> [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; ] | RValue | RIntVal -> [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; ] | _ -> assert false let tointunclean repr = match repr with | RIntUnclean -> [] | _ -> toint repr let tofloat repr = match repr with | RValue -> load_double | _ -> assert false let convert fpad repr_from repr_to descr_opt = convert the value on the wasm stack , from repr_from to match repr_to with | RValue | RIntVal -> tovalue_alloc fpad repr_from descr_opt | RInt -> toint repr_from | RIntUnclean -> tointunclean repr_from | RFloat -> tofloat repr_from | _ -> TODO let push_global offset = [ L [ K "global.get"; ID "wasicaml_global_data"; ]; L [ K "i32.load" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * offset))); K "align=2"; ] ] let follow_path path = List.map (fun field -> L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * field))); K "align=2"; ] ) path let push fpad store = put the value in store onto the wasm stack match store with | RealAccu _ -> push_local "accu" | Local(repr, name) -> push_local name | Const x -> push_const (Int32.of_int x) | RealStack pos -> push_stack fpad pos | Atom tag -> alloc_atom fpad tag | TracedGlobal(Glb glb_offset, path, _) -> push_global glb_offset @ follow_path path | TracedGlobal(Env env_offset, path, _) -> push_env @ add_offset (4 * env_offset) @ follow_path path | Invalid -> assert false let push_alloc_as fpad store req_repr descr_opt = match store, req_repr with | Const x, (RValue | RIntVal) -> push_const (Int32.logor (Int32.shift_left (Int32.of_int x) 1) 1l) | Local(RInt, name), (RValue | RIntVal) -> saves one instr push_local name @ push_local name @ [ L [ K "i32.add" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ] ] | _ -> let sexpl_push = push fpad store in let repr = repr_of_store store in sexpl_push @ convert fpad repr req_repr descr_opt let push_as fpad store req_repr = push_alloc_as fpad store req_repr None let pop_to fpad store repr descr_opt code_value = match store with | RealAccu _ -> code_value @ tovalue_alloc fpad repr descr_opt @ pop_to_local "accu" | Local(lrepr, name) -> code_value @ convert fpad repr lrepr descr_opt @ pop_to_local name | RealStack pos -> (code_value @ tovalue_alloc fpad repr descr_opt) |> pop_to_stack fpad pos | _ -> assert false let copy fpad src dest descr_opt = match dest with | RealAccu _ -> push_alloc_as fpad src RValue descr_opt @ pop_to_local "accu" | Local(repr, name) -> push_as fpad src repr @ pop_to_local name | RealStack pos -> push_alloc_as fpad src RValue descr_opt |> pop_to_stack fpad pos | _ -> assert false let rec drop n l = if n > 0 then match l with | _ :: l -> drop (n-1) l | [] -> [] else l let emit_unary gpad fpad op src1 dest = match op with | Pnegint -> ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 (0xffff_fffel)); ]; L [ K "i32.xor" ]; L [ K "i32.const"; N (I32 2l); ]; L [ K "i32.add" ]; ] ) |> pop_to fpad dest RIntVal None | Pboolnot -> ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 2l); ]; L [ K "i32.xor" ] ] ) |> pop_to fpad dest RIntVal None | Poffsetint offset -> ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 (Int32.shift_left (Int32.of_int offset) 1)); ]; L [ K "i32.add" ] ] ) |> pop_to fpad dest RIntVal None | Pisint -> ( push_as fpad src1 RValue @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.and" ]; ] ) |> pop_to fpad dest RInt None | Pgetfield field -> assert(field >= 0); ( push_as fpad src1 RValue @ [ L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * field))); K "align=2"; ]; ] ) |> pop_to fpad dest RValue None | Pgetfloatfield field -> ( match dest with | Local(RFloat, name) -> push_as fpad src1 RValue @ [ L [ K "f64.load"; K (sprintf "offset=0x%lx" (Int32.of_int (4 * double_size * field))); K "align=2"; ]; L [ K "local.set"; ID name ] ] | _ -> assert false ) | Pvectlength -> let local = req_tmp1_i32 fpad in ( push_as fpad src1 RValue @ [ L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.sub" ]; L [ K "i32.load" ]; L [ K "local.tee"; ID local ]; L [ K "local.get"; ID local ]; L [ K "i32.const"; N (I32 0xffl) ]; L [ K "i32.and" ]; L [ K "i32.const"; N (I32 (Int32.of_int double_array_tag)); ]; 1 if double array , else 0 L [ K "i32.const"; N (I32 9l) ]; L [ K "i32.add" ]; L [ K "i32.shr_u" ]; shift by 10 for double array , else by 9 L [ K "i32.const"; N (I32 1l); ]; L [ K "i32.or" ]; ] ) |> pop_to fpad dest RIntVal None | Pgetpubmet tag -> TODO : enable the cache : pass a unique pointer to a 4 byte mem block instead of NULL ( initialized to 0 ) instead of NULL (initialized to 0) *) gpad.need_mlookup <- true; push_as fpad src1 RValue @ push_const (Int32.succ (Int32.shift_left (Int32.of_int tag) 1)) @ push_const 0l @ [ L [ K "call"; ID "mlookup" ] ] ) |> pop_to fpad dest RValue None let emit_unaryeffect fpad op src1 = match op with | Poffsetref offset -> let local = req_tmp1_i32 fpad in push_as fpad src1 RIntVal @ [ L [ K "local.tee"; ID local ]; L [ K "local.get"; ID local ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.const"; N (I32 (Int32.shift_left (Int32.of_int offset) 1)); ]; L [ K "i32.add" ]; L [ K "i32.store"; K "align=2" ]; ] | Psetglobal (Global index) -> [ L [ K "global.get"; ID "wasicaml_global_data"; ]; L [ K "i32.load" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * index))); ]; L [ K "i32.add" ] ] @ debug2 150 index @ [ L [ K " local.tee " ; ID local ] ] @ debug2_var 151 local @ [ L [ K " local.get " ; ID local ] ] @ debug2 150 index @ [ L [ K "local.tee"; ID local ]] @ debug2_var 151 local @ [ L [ K "local.get"; ID local ]] *) @ push_as fpad src1 RValue @ [ L [ K "call"; ID "caml_modify"; ] ] let emit_int_binary fpad src1 src2 dest instrs_repr instrs_int = ( push_as fpad src1 RInt @ push_as fpad src2 RInt @ instrs_int ) |> pop_to fpad dest instrs_repr None let emit_int_binary_unclean_ok fpad src1 src2 dest instrs_int = ( push_as fpad src1 RIntUnclean @ push_as fpad src2 RIntUnclean @ instrs_int ) |> pop_to fpad dest RIntUnclean None let emit_intval_binary fpad src1 src2 dest instrs_int instrs_intval = if repr_of_store src1 = RInt && repr_of_store src2 = RInt then ( push_as fpad src1 RInt @ push_as fpad src2 RInt @ instrs_int @ tovalue fpad RIntUnclean ) |> pop_to fpad dest RIntVal None else ( push_as fpad src1 RIntVal @ push_as fpad src2 RIntVal @ instrs_intval ) |> pop_to fpad dest RIntVal None let emit_intval_binary_unclean_ok fpad src1 src2 dest instrs_int instrs_intval = let is_ok st = let repr = repr_of_store st in repr = RInt || repr = RIntUnclean in if is_ok src1 && is_ok src2 then ( push_as fpad src1 RIntUnclean @ push_as fpad src2 RIntUnclean @ instrs_int @ tovalue fpad RIntUnclean ) |> pop_to fpad dest RIntVal None else emit_intval_binary fpad src1 src2 dest instrs_int instrs_intval let emit_intval_int_binary fpad src1 src2 dest instrs_int instrs_intval = src2 is always an RInt if repr_of_store src1 = RInt then ( push_as fpad src1 RInt @ push_as fpad src2 RInt @ instrs_int @ tovalue fpad RIntUnclean ) |> pop_to fpad dest RIntVal None else ( push_as fpad src1 RIntVal @ push_as fpad src2 RInt @ instrs_intval ) |> pop_to fpad dest RIntVal None let emit_binary gpad fpad op src1 src2 dest = match op with | Paddint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.add" ] ] [ L [ K "i32.add" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.sub" ] ] | Psubint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.sub" ] ] [ L [ K "i32.sub" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.add" ] ] | Pmulint -> emit_int_binary fpad src1 src2 dest RIntUnclean [ L [ K "i32.mul" ] ] | Pdivint -> ( match src2 with | Const n when n <> 0 -> emit_int_binary fpad src1 src2 dest RInt [ L [ K "i32.div_s" ]] | _ -> let local = req_tmp1_i32 fpad in emit_int_binary fpad src1 src2 dest RInt [ L [ K "local.tee"; ID local ]; L [ K "i32.eqz" ]; L [ K "if"; L [ K "then"; L [ K "call"; ID "caml_raise_zero_divide" ] ] ]; L [ K "local.get"; ID local ]; L [ K "i32.div_s" ] ] ) | Pmodint -> ( match src2 with | Const n when n <> 0 -> emit_int_binary fpad src1 src2 dest RInt [ L [ K "i32.rem_s" ]] | _ -> let local = req_tmp1_i32 fpad in emit_int_binary fpad src1 src2 dest RInt [ L [ K "local.tee"; ID local ]; L [ K "i32.eqz" ]; L [ K "if"; L [ K "then"; L [ K "call"; ID "caml_raise_zero_divide" ] ] ]; L [ K "local.get"; ID local ]; L [ K "i32.rem_s" ] ] ) | Pandint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.and" ] ] [ L [ K "i32.and" ] ] | Porint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.or" ] ] [ L [ K "i32.or" ] ] | Pxorint -> emit_intval_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.xor" ] ] [ L [ K "i32.xor" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ]; ] | Plslint -> let r1 = repr_of_store src1 in if r1 = RInt || r1 = RIntUnclean then emit_int_binary_unclean_ok fpad src1 src2 dest [ L [ K "i32.shl" ]] else ( push_as fpad src1 RIntVal @ [ L [ K "i32.const"; N (I32 0xffff_fffel) ]; L [ K "i32.and" ] ] @ push_as fpad src2 RIntUnclean @ [ L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.or" ] ] ) |> pop_to fpad dest RIntVal None | Plsrint -> emit_intval_int_binary fpad src1 src2 dest [ L [ K "i32.shr_u" ]; L [ K "i32.const"; N (I32 0x3fff_ffffl) ]; L [ K "i32.and" ] ] [ L [ K "i32.shr_u" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.or" ] ] | Pasrint -> emit_intval_int_binary fpad src1 src2 dest [ L [ K "i32.shr_s" ]] [ L [ K "i32.shr_s" ]; L [ K "i32.const"; N(I32 1l) ]; L [ K "i32.or" ] ] | (Pintcomp cmp | Puintcomp cmp) -> let wasm_op = match op with | Pintcomp Ceq | Puintcomp Ceq -> "i32.eq" | Pintcomp Cne | Puintcomp Cne -> "i32.ne" | Pintcomp Clt -> "i32.lt_s" | Pintcomp Cle -> "i32.le_s" | Pintcomp Cgt -> "i32.gt_s" | Pintcomp Cge -> "i32.ge_s" | Puintcomp Clt -> "i32.lt_u" | Puintcomp Cle -> "i32.le_u" | Puintcomp Cgt -> "i32.gt_u" | Puintcomp Cge -> "i32.ge_u" | _ -> assert false in TODO : we miss some optimizations when one of the operands is a constant constant *) if repr_comparable_as_i32 (repr_of_store src1) (repr_of_store src2) then ( push fpad src1 @ push fpad src2 @ [ L [ K wasm_op ]] ) |> pop_to fpad dest RInt None else emit_int_binary fpad src1 src2 dest RInt [ L [ K wasm_op ]] | Pgetvectitem -> ( push_as fpad src1 RValue @ ( match src2, repr_of_store src2 with | Const c, _ -> [ L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.shift_left (Int32.of_int c) 2)); K "align=2" ] ] | _, (RInt | RIntUnclean) -> push_as fpad src2 RInt @ [ L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ] ] | _ -> push_as fpad src2 RIntVal @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 0xffff_fffcl) ]; L [ K "i32.and" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ] ] ) ) |> pop_to fpad dest RValue None | Pgetstringchar | Pgetbyteschar -> ( push_as fpad src1 RValue @ ( match src2 with | Const c -> [ L [ K "i32.load8_u"; K (sprintf "offset=0x%x" c) ] ] | _ -> push_as fpad src2 RIntUnclean @ [ L [ K "i32.add" ]; L [ K "i32.load8_u" ] ] ) ) |> pop_to fpad dest RInt None | Pgetmethod -> gpad.need_mlookup <- true; push_as fpad src2 RValue @ [ L [ K "i32.load"; K "align=2" ]] @ push_as fpad src1 RInt @ [ L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; L [ K "i32.load"; K "align=2" ] ] ) |> pop_to fpad dest RValue None | Pgetdynmet -> gpad.need_mlookup <- true; push_as fpad src2 RValue @ push_as fpad src1 RValue @ push_const 0l @ [ L [ K "call"; ID "mlookup" ] ] ) |> pop_to fpad dest RValue None let emit_binaryeffect fpad op src1 src2 = match op with | Psetfield field -> push_as fpad src1 RValue @ ( if field <> 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * field))); ]; L [ K "i32.add" ] ] else [] ) @ push_as fpad src2 RValue @ [ L [ K "call"; ID "caml_modify" ]] | Psetfloatfield field -> push_as fpad src1 RValue @ push_as fpad src2 RFloat @ [ L [ K "f64.store"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * field))); K "align=2"; ] ] let emit_ternaryeffect fpad op src1 src2 src3 = match op with | Psetvectitem -> push_as fpad src1 RValue @ ( match src2, repr_of_store src2 with | Const c, _ -> [ L [ K "i32.const"; N (I32 (Int32.shift_left (Int32.of_int c) 2)) ]; L [ K "i32.add" ] ] | _, (RInt | RIntUnclean) -> push_as fpad src2 RIntUnclean @ [ L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shl" ]; L [ K "i32.add" ]; ] | _ -> push_as fpad src2 RIntVal @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 0xffff_fffcl) ]; L [ K "i32.and" ]; L [ K "i32.add" ]; ] ) @ push_as fpad src3 RValue @ [ L [ K "call"; ID "caml_modify" ]] | Psetbyteschar -> push_as fpad src1 RValue @ ( match src2 with | Const c -> push_as fpad src3 RInt @ [ L [ K "i32.store8"; K (sprintf "offset=0x%x" c) ] ] | _ -> push_as fpad src2 RIntUnclean @ [ L [ K "i32.add" ] ] @ push_as fpad src3 RIntUnclean @ [ L [ K "i32.store8" ]] ) type mb_elem = | MB_store of store | MB_const of int32 | MB_code of sexp list let push_mb_elem fpad = function | MB_store src -> push_as fpad src RValue | MB_const n -> push_const n | MB_code code -> code let makeblock fpad descr src_list tag = let size = List.length src_list in let sexpl_alloc, ptr, young = alloc_set fpad descr size tag in let sexpl_init = if young then List.mapi (fun field src -> push_mb_elem fpad src |> pop_to_field ptr field ) src_list else List.mapi (fun field src -> push_field_addr ptr field @ push_mb_elem fpad src @ [ L [ K "call"; ID "caml_initialize" ]] ) src_list in let c1 = [ C "<makeblock>" ] in let c2 = [ C "</makeblock>" ] in (ptr, c1 @ sexpl_alloc @ List.flatten sexpl_init @ c2) let makefloatblock fpad descr src_list = let size = List.length src_list in let wosize = size * double_size in let sexpl_alloc, ptr, _ = alloc_set fpad descr wosize double_array_tag in let sexpl_init = List.mapi (fun field src -> ( push_as fpad src RValue @ load_double ) |> pop_to_double_field ptr field ) src_list in (ptr, sexpl_alloc @ List.flatten sexpl_init) let lookup_label gpad lab = let letrec_label, subfunc = try Hashtbl.find gpad.funcmapping lab with Not_found -> assert false in let wasmindex = try Hashtbl.find gpad.wasmindex letrec_label with Not_found -> assert false in (wasmindex, letrec_label, subfunc) let push_wasmptr gpad lab = let wasmindex , subfunc = lookup_label gpad lab in [ L [ K " global.get " ; ID " _ _ table_base " ] ; L [ K " i32.const " ; N ( I32 ( Int32.of_int wasmindex ) ) ] ; L [ K " i32.add " ] ; ] let wasmindex, subfunc = lookup_label gpad lab in [ L [ K "global.get"; ID "__table_base" ]; L [ K "i32.const"; N (I32 (Int32.of_int wasmindex)) ]; L [ K "i32.add" ]; ] *) For statically linked WASM . Note that this way of taking the address of a function is not officially supported in the wat file format . address of a function is not officially supported in the wat file format. *) let wasmindex, letrec_label, subfunc = lookup_label gpad lab in [ L [ K "i32.const"; ID (Hashtbl.find gpad.letrec_name letrec_label) ]] let push_codeptr gpad lab = let wasmindex, letrec_label, subfunc = lookup_label gpad lab in push_wasmptr gpad lab @ [ L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shl" ]; L [ K "i32.const"; N (I32 (Int32.of_int ((subfunc lsl 2)+1))) ]; L [ K "i32.or" ]; ] let closurerec gpad fpad descr src_list dest_list = let nfuncs = List.length dest_list in let envofs = nfuncs * 3 - 1 in let mb_src_list = ( List.mapi (fun i (_, label) -> ( if i > 0 then [ MB_const (Int32.of_int (make_header (3*i) infix_tag)) ] else [] ) @ [ MB_code (push_codeptr gpad label) ] @ [ MB_const (Int32.of_int (((envofs - 3*i) lsl 1) + 1)) ] ) dest_list |> List.flatten ) @ List.map (fun src -> MB_store src) src_list in let ptr, sexpl_mb = makeblock fpad descr mb_src_list closure_tag in let sexpl_dest = List.mapi (fun i (dest, _) -> ( [ L [ K "local.get"; ID ptr ] ] @ (if i > 0 then [ L [ K "i32.const"; N (I32 (Int32.of_int (12*i))) ]; L [ K "i32.add" ] ] else [] ) descr is not up to date ) dest_list |> List.flatten in sexpl_mb @ sexpl_dest let c_call gpad fpad descr src_list name = let sexpl_setup = setup_for_gc fpad descr in let sexpl_restore = restore_after_gc fpad descr in let sexpl_debug_args = List.map ( fun src - > push_const 21l @ push_as fpad src RValue @ [ L [ K " call " ; ID " debug2 " ] ] ) src_list | > List.flatten in let sexpl_debug_args = List.map (fun src -> push_const 21l @ push_as fpad src RValue @ [ L [ K "call"; ID "debug2" ]]) src_list |> List.flatten in *) let sexpl_args = List.map (fun src -> push_as fpad src RValue) src_list in let sexpl_call = [ L [ K "call"; ID name ]] @ pop_to_local "accu" in let p_i32 = L [ K "param"; K "i32" ] in let r_i32 = L [ K "result"; K "i32" ] in let ty = (src_list |> List.map (fun _ -> p_i32)) @ [ r_i32 ] in Hashtbl.replace gpad.primitives name ty; debug2 20 0 sexpl_setup @ List.flatten sexpl_args @ sexpl_call @ sexpl_restore @ debug2 20 1 let c_call_vector gpad fpad descr numargs depth name = let sexpl_setup = setup_for_gc fpad descr in let sexpl_restore = restore_after_gc fpad descr in let sexpl_call = push_field_addr "fp" (-depth) @ push_const (Int32.of_int numargs) @ [ L [ K "call"; ID name ]] @ pop_to_local "accu" in let ty = [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ] in Hashtbl.replace gpad.primitives name ty; debug2 20 0 sexpl_setup @ sexpl_call @ sexpl_restore let string_label = function | Label k -> sprintf "label%d" k | Loop k -> sprintf "loop%d" k let switch fpad src labls_ints labls_blocks = fpad.need_panic <- true; let value = req_tmp1_i32 fpad in push_as fpad src RValue @ pop_to_local value if ( ! Is_block(value ) ) L [ K "local.get"; ID value ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.and" ]; L [ K "if"; L [ K "then"; L [ K "local.get"; ID value ]; L [ K "i32.const"; N (I32 1l) ]; L [ K "i32.shr_s" ]; L ( [ K "br_table" ] @ ( Array.map (fun lab -> ID (string_label lab)) labls_ints |> Array.to_list ) @ [ ID "panic" ] ); ]; L [ K "else"; L [ K "local.get"; ID value ]; L [ K "i32.const"; N (I32 4l) ]; L [ K "i32.sub" ]; L [ K "i32.load"; K "align=2" ]; L [ K "i32.const"; N (I32 0xffl) ]; L [ K "i32.and" ]; L ( [ K "br_table" ] @ ( Array.map (fun lab -> ID (string_label lab)) labls_blocks |> Array.to_list ) @ [ ID "panic" ] ); ]; ] ] let grab fpad num = let sexpl = if ( codeptr & 1 ) L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_restart_mask) ]; L [ K "i32.and" ]; L [ K "if"; L ( [ K "then"; RESTART L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "fp" ]; ] @ call_restart_helper() @ pop_to_fp fpad @ [ L [ K "local.set"; ID "extra_args" ]; codeptr & = ~1 - I think this is not needed L [ K " local.get " ; ID " codeptr " ] ; L [ K " i32.const " ; N ( ) ] ; L [ K " i32.and " ] ; L [ K " local.set " ; ID " codeptr " ] ; L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 0xffff_fffel) ]; L [ K "i32.and" ]; L [ K "local.set"; ID "codeptr" ]; *) ] ) ]; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 (Int32.of_int num)) ]; L [ K "i32.ge_u" ]; L [ K "if"; L [ K "then"; L [ K "local.get"; ID "extra_args" ]; L [ K "i32.const"; N (I32 (Int32.of_int num)) ]; L [ K "i32.sub" ]; L [ K "local.set"; ID "extra_args" ]; ]; L ( [ [ K "else"; L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "local.get"; ID "fp" ]; ]; returncall "grab_helper" ] |> List.flatten ) ]; ] in sexpl let return() = NB . do n't use bp here . codeptr is already destroyed when coming from appterm_common codeptr is already destroyed when coming from appterm_common *) [ C "$return"; L [ K "local.get"; ID "extra_args" ]; L [ K "if"; L ( [ [ K "then"; L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "fp" ]; L [ K "local.get"; ID "accu" ]; ]; returncall "return_helper" ] |> List.flatten ) ]; L [ K "local.get"; ID "accu" ]; L [ K "return" ]; ] let throw fpad = if fpad.fpad_scope.cfg_main && fpad.fpad_scope.cfg_try_labels = [] then [ L [ K "call"; ID "wasicaml_throw" ]; L [ K "unreachable" ] ] else if fpad.fpad_scope.cfg_try_labels = [] then [ L [ K "i32.const"; N (I32 0l) ]; L [ K "return" ] ] else [ L [ K "i32.const"; N (I32 0l) ]; L [ K "global.set"; ID "exn_result" ]; L [ K "i32.const"; N (I32 0l) ]; L [ K "return" ] ] let apply_direct gpad fpad funlabel numargs depth = let _, letrec_label, _ = lookup_label gpad funlabel in let letrec_name = Hashtbl.find gpad.letrec_name letrec_label in let env_pos = (-depth + numargs) in ( push_local "accu" |> pop_to_stack fpad env_pos ) @ [ L [ K "i32.const"; N (I32 (Int32.of_int (numargs-1))) ]; ] @ push_field "accu" 0 @ push_local "fp" @ [L [ K "i32.const"; N (I32 (Int32.of_int (4 * depth))) ]; L [ K "i32.sub" ]; L [ K "call"; ID letrec_name ]; L [ K "local.tee"; ID "accu" ]; L [ K "if"; L ([ K "then"] @ throw fpad) ]; ] let apply fpad numargs depth = let env_pos = (-depth + numargs) in let codeptr = req_tmp1_i32 fpad in ( push_local "accu" |> pop_to_stack fpad env_pos ) @ [ L [ K "i32.const"; N (I32 (Int32.of_int (numargs-1))) ]; ] @ push_field "accu" 0 @ (if !enable_deadbeef_check then [ L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * depth))) ]; L [ K "i32.sub" ]; L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ) @ [ L [ K "local.tee"; ID codeptr ]; L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * depth))) ]; L [ K "i32.sub" ]; L [ K "local.get"; ID codeptr ]; L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; L [ K "i32.shr_u" ]; L [ K " local.set " ; ID " h.i32 " ] ; L [ K " i32.const " ; N ( I32 2l ) ] ; L [ K " local.get " ; ID " h.i32 " ] ; L [ K " call " ; ID " debug2 " ] ; L [ K " local.get " ; ID " h.i32 " ] ; L [ K "local.set"; ID "h.i32" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "local.get"; ID "h.i32" ]; L [ K "call"; ID "debug2" ]; L [ K "local.get"; ID "h.i32" ]; *) L [ K "call_indirect"; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ]; L [ K "local.tee"; ID "accu" ]; L [ K "if"; L ([ K "then"] @ throw fpad) ]; ] let appterm_common fpad () = NB . do n't use bp here [ C "$appterm_common"; L [ K "local.get"; ID "envptr" ]; L [ K "local.get"; ID "codeptr" ]; L [ K "local.get"; ID "accu" ]; L [ K "local.get"; ID "extra_args" ]; L [ K "local.get"; ID "appterm_new_num_args" ]; ] @ call_appterm_helper() @ [ L [ K "local.set"; ID "extra_args" ]; L [ K "local.tee"; ID "codeptr" ]; L [ K "if"; L [ K "then"; L [ K "br"; ID "startover" ] ]; L [ K "else"; L [ K "br"; ID "return" ] ] ] ] let call_reinit_frame gpad fpad numargs oldnumargs depth = if numargs <= 10 then ( gpad.need_reinit_frame_k <- ISet.add numargs gpad.need_reinit_frame_k; push_local "fp" @ push_const (Int32.of_int depth) @ push_const (Int32.of_int oldnumargs) @ [ L [ K "call"; ID (sprintf "reinit_frame_%d" numargs) ] ] ) else ( gpad.need_reinit_frame <- true; push_local "fp" @ push_const (Int32.of_int depth) @ push_const (Int32.of_int oldnumargs) @ push_const (Int32.of_int numargs) @ [ L [ K "call"; ID "reinit_frame" ] ] ) let appterm_push_params numargs = first arg of call ] second arg of call ] @ (if numargs >= 2 then [ L [ K "i32.const"; N (I32 (Int32.of_int (numargs - 1))) ]; L [ K "i32.add" ]; ] else [] ) third arg of call : code pointer fourth arg of call ] let appterm_with_returncall gpad fpad numargs oldnumargs depth = let sexpl = call_reinit_frame gpad fpad numargs oldnumargs depth @ (push_local "accu" |> pop_to_field "envptr" 0) @ appterm_push_params numargs @ push_field "accu" 0 @ [ L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; ] @ [ L [ K "return_call_indirect"; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ] ] in sexpl let appterm_without_returncall gpad fpad numargs oldnumargs depth = let sexpl = call_reinit_frame gpad fpad numargs oldnumargs depth @ push_const (Int32.of_int numargs) @ pop_to_local "appterm_new_num_args" @ [ L [ K "br"; ID "appterm_common" ] ] in fpad.need_appterm_common <- true; fpad.need_return <- true; if not !enable_returncall then fpad.need_startover <- true; sexpl let appterm_direct gpad fpad funlabel numargs oldnumargs depth = assert(!enable_returncall); let _, letrec_label, _ = lookup_label gpad funlabel in let letrec_name = Hashtbl.find gpad.letrec_name letrec_label in let goto_selfrecurse = letrec_label = fpad.fpad_letrec_label && numargs = oldnumargs in let sexpl = call_reinit_frame gpad fpad numargs oldnumargs depth @ (push_local "accu" |> pop_to_field "envptr" 0) @ (if goto_selfrecurse then [ L [ K "br"; ID "selfrecurse" ] ] else appterm_push_params numargs @ [ L [ K "return_call"; ID letrec_name ] ] ) in if goto_selfrecurse then fpad.need_selfrecurse <- true; sexpl let appterm gpad fpad funlabel_opt numargs oldnumargs depth = if !enable_returncall then match funlabel_opt with | Some funlabel -> appterm_direct gpad fpad funlabel numargs oldnumargs depth | None -> appterm_with_returncall gpad fpad numargs oldnumargs depth else appterm_without_returncall gpad fpad numargs oldnumargs depth let appterm_args gpad fpad funlabel_opt funsrc argsrc oldnumargs depth = assert(!enable_returncall); let newnumargs = List.length argsrc in let arg_locals = List.map (fun src -> new_local fpad (repr_of_store src)) argsrc in let arg_instrs1 = List.map2 (fun src localname -> let dest = Local(repr_of_store src, localname) in copy fpad src dest None ) argsrc arg_locals |> List.flatten in let accu_instrs = copy fpad funsrc (RealAccu { no_function = false }) None in let fp_delta = oldnumargs - newnumargs in let fp_instrs = if fp_delta = 0 then [] else [ L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * fp_delta))) ]; L [ K "i32.add" ]; L [ K "local.set"; ID "fp" ]; ] in let arg_instrs2 = List.map2 (fun src (localname, i) -> let src = Local(repr_of_store src, localname) in let dest = RealStack i in copy fpad src dest None ) argsrc (List.mapi (fun i localname -> (localname, i)) arg_locals) |> List.flatten in let envptr_instrs = (push_local "accu" |> pop_to_field "envptr" 0) in let call_instrs = match funlabel_opt with | Some funlabel -> let _, letrec_label, _ = lookup_label gpad funlabel in let letrec_name = Hashtbl.find gpad.letrec_name letrec_label in let goto_selfrecurse = letrec_label = fpad.fpad_letrec_label && newnumargs = oldnumargs in if goto_selfrecurse then ( fpad.need_selfrecurse <- true; [ L [ K "br"; ID "selfrecurse" ] ] ) else appterm_push_params newnumargs @ [ L [ K "return_call"; ID letrec_name ] ] | None -> appterm_push_params newnumargs @ push_field "accu" 0 @ [ L [ K "i32.const"; N (I32 (Int32.of_int code_pointer_shift)) ]; ] @ [ L [ K "return_call_indirect"; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ]; ] ] in arg_instrs1 @ accu_instrs @ fp_instrs @ arg_instrs2 @ envptr_instrs @ call_instrs let trap gpad fpad trylabel catchlabel depth = push 4 values onto stack : 0 , 0 , 0 , extra_args get function pointer and caught = wasicaml_wraptry4(f , env , extra_args , , fp - depth ) let local1 = req_tmp1_i32 fpad in let local2 = req_tmp2_i32 fpad in let sexpl_stack = (push_const 0l |> pop_to_stack fpad (-depth-1)) @ (push_const 0l |> pop_to_stack fpad (-depth-2)) @ (push_const 0l |> pop_to_stack fpad (-depth-3)) @ (push_local "extra_args" |> pop_to_stack fpad (-depth-4)) @ (if !enable_deadbeef_check then [ L [ K "local.get"; ID "fp" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * (depth + 4)))) ]; L [ K "i32.sub" ]; L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_check" ] ] else [] ) in let sexpl_try = push_domain_field domain_field_local_roots @ pop_to_local local2 @ push_wasmptr gpad trylabel @ push_local "envptr" @ push_local "extra_args" @ push_codeptr gpad trylabel @ push_local "fp" @ [ L [ K "i32.const"; N (I32 (Int32.of_int (4 * (depth + 4))))]; L [ K "i32.sub" ] ] @ debug2 30 0 @ [ L [ K "call"; ID "wasicaml_wraptry4" ]; L [ K "local.set"; ID local1 ]; ] @ debug2 30 1 @ ( push_local local2 |> pop_to_domain_field domain_field_local_roots ) @ [ L [ K "local.get"; ID local1 ]; L [ K "global.get"; ID "exn_result" ]; L [ K "i32.eqz" ]; L [ K "i32.or" ]; L [ K "if"; L [ K "then"; L [ K "global.get"; ID "wasicaml_domain_state" ]; L [ K "i32.load"; K (sprintf "offset=0x%lx" (Int32.of_int (8 * domain_field_exn_bucket))); K "align=2" ]; L [ K "local.set"; ID "accu" ]; L [ K "br"; ID (sprintf "label%d" catchlabel) ] ] ]; L [ K "global.get"; ID "exn_result" ]; L [ K "local.set"; ID "accu" ] ] in sexpl_stack @ sexpl_try let rec emit_instr gpad fpad instr = match instr with | Wcomment s -> [] | Wblock arg -> ( match arg.label with | Label lab -> [ L ( [ K "block"; ID (sprintf "label%d" lab); BR ] @ emit_instrs gpad fpad arg.body ) ] @ debug2 100 lab | Loop lab -> [ L ( [ K "loop"; ID (sprintf "loop%d" lab); BR ] @ emit_instrs gpad fpad arg.body ) ] ) | Wcond { cond; ontrue; onfalse } -> emit_instr gpad fpad (if !cond then ontrue else onfalse) | Wcopy arg -> copy fpad arg.src arg.dest None | Walloc arg -> copy fpad arg.src arg.dest (Some arg.descr) | Wenv arg -> push_env @ load_offset (4 * arg.field) @ pop_to_local "accu" | Wcopyenv arg -> push_env @ add_offset (4 * arg.offset) @ pop_to_local "accu" | Wgetglobal arg -> let Global offset = arg.src in debug2 160 offset @ push_const 161l @ [ L [ K " global.get " ; ID " wasicaml_global_data " ; ] ; L [ K " i32.load " ] ; L [ K " i32.const " ; N ( I32 ( Int32.of_int ( 4 * offset ) ) ) ; ] ; L [ K " i32.add " ] ; L [ K " call " ; ID " debug2 " ] ] debug2 160 offset @ push_const 161l @ [ L [ K "global.get"; ID "wasicaml_global_data"; ]; L [ K "i32.load" ]; L [ K "i32.const"; N (I32 (Int32.of_int (4 * offset))); ]; L [ K "i32.add" ]; L [ K "call"; ID "debug2" ] ] *) push_global offset @ pop_to_local "accu" | Wunary arg -> emit_unary gpad fpad arg.op arg.src1 arg.dest | Wunaryeffect arg -> emit_unaryeffect fpad arg.op arg.src1 | Wbinary arg -> emit_binary gpad fpad arg.op arg.src1 arg.src2 arg.dest | Wbinaryeffect arg -> emit_binaryeffect fpad arg.op arg.src1 arg.src2 | Wternaryeffect arg -> emit_ternaryeffect fpad arg.op arg.src1 arg.src2 arg.src3 | Wmakeblock arg -> let src = List.map (fun s -> MB_store s) arg.src in let ptr, sexpl = makeblock fpad arg.descr src arg.tag in sexpl @ push_local ptr @ pop_to_local "accu" | Wmakefloatblock arg -> let ptr, sexpl = makefloatblock fpad arg.descr arg.src in sexpl @ push_local ptr @ pop_to_local "accu" | Wccall arg -> c_call gpad fpad arg.descr arg.src arg.name | Wccall_vector arg -> c_call_vector gpad fpad arg.descr arg.numargs arg.depth arg.name | Wbranch arg -> [ L [ K "br"; ID (string_label arg.label) ]] | Wif arg -> ( match repr_of_store arg.src with | RInt -> push_as fpad arg.src RInt @ (if arg.neg then [ L [ K "i32.eqz" ]] else []) | RIntUnclean -> push_as fpad arg.src RIntUnclean @ [ L [ K "i32.const"; N (I32 0x7fff_ffffl) ]; L [ K "i32.and" ] ] @ (if arg.neg then [ L [ K "i32.eqz" ]] else []) | _ -> push_as fpad arg.src RIntVal @ [ L [ K "i32.const"; N (I32 1l) ]; L [ K (if arg.neg then "i32.le_u" else "i32.gt_u") ] ] ) @ [ L [ K "if"; L ( K "then" :: ( List.map (emit_instr gpad fpad) arg.body |> List.flatten ) ) ] ] | Wswitch arg -> switch fpad arg.src arg.labels_int arg.labels_blk | Wapply arg -> apply fpad arg.numargs arg.depth | Wapply_direct arg -> let src = TracedGlobal(arg.global, arg.path, fn) in copy fpad src Wc_unstack.real_accu None @ apply_direct gpad fpad arg.funlabel arg.numargs arg.depth | Wappterm arg -> appterm gpad fpad None arg.numargs arg.oldnumargs arg.depth | Wappterm_direct arg -> let src = TracedGlobal(arg.global, arg.path, fn) in copy fpad src Wc_unstack.real_accu None @ appterm gpad fpad (Some arg.funlabel) arg.numargs arg.oldnumargs arg.depth | Wappterm_args arg -> appterm_args gpad fpad None arg.funsrc arg.argsrc arg.oldnumargs arg.depth | Wappterm_direct_args arg -> appterm_args gpad fpad (Some arg.funlabel) arg.funsrc arg.argsrc arg.oldnumargs arg.depth | Wreturn arg -> let no_function = match arg.src with | RealAccu { no_function } -> no_function | _ -> repr_of_store arg.src <> RValue in if no_function then push_as fpad arg.src RValue @ [ L [ K "return" ]] else ( fpad.need_return <- true; push_as fpad arg.src RValue @ pop_to_local "accu" @ push_field_addr "fp" arg.arity @ pop_to_local "fp" @ [ L [ K "br"; ID "return" ]] ) | Wgrab arg -> if fpad.disallow_grab then ( let letrec_name = Hashtbl.find gpad.letrec_name fpad.fpad_letrec_label in eprintf "[DEBUG] function: %s\n%!" letrec_name; assert false; ); grab fpad arg.numargs | Wclosurerec arg -> closurerec gpad fpad arg.descr arg.src arg.dest | Wraise arg -> ( push_as fpad arg.src RValue |> pop_to_domain_field domain_field_exn_bucket ) @ ( push_local "fp" |> pop_to_domain_field domain_field_extern_sp ) @ throw fpad | Wtrap arg -> trap gpad fpad arg.trylabel arg.catchlabel arg.depth | Wtryreturn arg -> push_as fpad arg.src RValue @ [ L [ K "global.set"; ID "exn_result" ]; L [ K "i32.const"; N (I32 0l) ]; L ( K " block " : : debug2 1 3 ) ; L [ K "return" ] ] | Wnextmain { label } -> @ push_local "extra_args" @ push_local "codeptr" @ push_local "fp" @ returncall (sprintf "letrec_main%d" label) | Wstop -> [ L [ K "i32.const"; N (I32 0l) ]; L ( K " block " : : debug2 1 2 ) ; L [ K "return" ] ] | Wnop -> [] | Wunreachable -> [ L [ K "unreachable" ]] and emit_instrs gpad fpad instrs = List.fold_left (fun acc instr -> let comment = string_of_winstruction instr in List.rev_append (emit_instr gpad fpad instr) (List.rev_append [C comment] acc) ) [] instrs |> List.rev let rec extract_grab instrs = Extract the first Wgrab , optionally wrapped in a cascade of Wblock match instrs with | Wgrab _ as grab :: rest -> (rest, Some grab) | Wcomment _ as i :: rest -> let rest_after_extract, grab_opt = extract_grab rest in (i :: rest_after_extract, grab_opt) | Wblock arg :: rest -> ( match arg.label with | Label _ -> let body_after_extract, grab_opt = extract_grab arg.body in (Wblock { arg with body = body_after_extract } :: rest, grab_opt ) | Loop _ -> (instrs, None) ) | _ -> (instrs, None) let emit_fblock_instrs gpad fpad instrs = fpad.disallow_grab <- false; let rest, grab_opt = extract_grab instrs in match grab_opt with | Some grab -> let code_grab = emit_instrs gpad fpad [ grab ] in fpad.disallow_grab <- true; let code_rest = emit_instrs gpad fpad rest in if fpad.need_selfrecurse then ( assert(!enable_returncall); code_grab @ [ L ( [ K "loop"; ID "selfrecurse"; BR ] @ code_rest) ] ) else code_grab @ code_rest | None -> fpad.disallow_grab <- true; let code = emit_instrs gpad fpad instrs in if fpad.need_selfrecurse then ( assert(!enable_returncall); [ L ( [ K "loop"; ID "selfrecurse"; BR ] @ code) ] ) else code let emit_fblock gpad fpad fblock = let maxdepth = Wc_tracestack.max_stack_depth_of_fblock fblock in fpad.maxdepth <- if maxdepth > 0 then maxdepth + 2 else 0; let instrs = Wc_unstack.transl_fblock fpad.lpad fblock |> emit_fblock_instrs gpad fpad in set_bp fpad @ (if !enable_deadbeef_check && fpad.maxdepth > 0 then [ L [ K "local.get"; ID "bp" ]; L [ K "local.get"; ID "fp" ]; L [ K "call"; ID "deadbeef_init" ] ] else [] ) @ instrs let get_funcmapping_without_tailcalls scode = let open Wc_control in let funcmapping = Hashtbl.create 7 in let subfunction_num = Hashtbl.create 7 in let subfunctions = Hashtbl.create 7 in IMap.iter (fun func_label fblock -> let letrec_func_label = match fblock.scope.cfg_letrec_label with | None -> 0 | Some label -> label in let letrec_label = if fblock.scope.cfg_main then Main letrec_func_label else Func letrec_func_label in let subfunc_num = try Hashtbl.find subfunction_num letrec_label with Not_found -> 0 in Hashtbl.replace subfunction_num letrec_label (subfunc_num+1); Hashtbl.add funcmapping func_label (letrec_label, subfunc_num); let subfunc_list = try Hashtbl.find subfunctions letrec_label with Not_found -> [] in Hashtbl.replace subfunctions letrec_label (func_label :: subfunc_list) ) scode.functions; let subfunctions_rev = Hashtbl.create 7 in Hashtbl.iter (fun letrec_label subfunc_labels -> Hashtbl.add subfunctions_rev letrec_label (List.rev subfunc_labels) ) subfunctions; ( funcmapping, subfunctions_rev ) let get_funcmapping_with_tailcalls scode = let open Wc_control in let funcmapping = Hashtbl.create 7 in let subfunctions = Hashtbl.create 7 in IMap.iter (fun func_label fblock -> let letrec_label = if fblock.scope.cfg_main then Main func_label else Func func_label in Hashtbl.add funcmapping func_label (letrec_label, 0); Hashtbl.replace subfunctions letrec_label [func_label] ) scode.functions; let subfunctions_rev = Hashtbl.create 7 in Hashtbl.iter (fun letrec_label subfunc_labels -> Hashtbl.add subfunctions_rev letrec_label (List.rev subfunc_labels) ) subfunctions; ( funcmapping, subfunctions_rev ) let get_funcmapping scode = if !enable_returncall then get_funcmapping_with_tailcalls scode else get_funcmapping_without_tailcalls scode let block_cascade start_sexpl label_sexpl_pairs = let rec shift prev_sexpl pairs = match pairs with | (label, lsexpl) :: pairs' -> (prev_sexpl, Some label) :: shift lsexpl pairs' | [] -> [ prev_sexpl, None ] in let rec arrange inner_sexpl shifted = match shifted with | (sexpl, label_opt) :: shifted' -> let body = inner_sexpl @ sexpl @ [ L [ K "unreachable" ]] in let inner_sexpl' = match label_opt with | None -> body | Some lab -> [ L ( [ K "block"; ID lab; BR; ] @ body ) ] in arrange inner_sexpl' shifted' | [] -> inner_sexpl in arrange [] (shift start_sexpl label_sexpl_pairs) let cond_section_lz cond label sexpl_section sexpl_users = if cond then [ L ( [ K "block"; ID label; BR ] @ sexpl_users ) ] @ sexpl_section() else sexpl_users let cond_section cond label sexpl_section sexpl_users = cond_section_lz cond label (fun () -> sexpl_section) sexpl_users let cond_loop cond label sexpl = if cond then [ L ( [ K "loop"; ID label; BR ] @ sexpl ) ] else sexpl let eff_label = function | Func l -> l | Main l -> l let init_lpad_for_subfunc gpad fpad func_label = let func_offset, environment = ( try Hashtbl.find gpad.glbfun_table func_label with Not_found -> 0, [| |] ) in fpad.lpad.environment <- environment; fpad.lpad.func_offset <- func_offset let generate_function scode gpad letrec_label func_name subfunc_labels export_flag = let fpad = { (empty_fpad()) with fpad_letrec_label = letrec_label } in Hashtbl.add fpad.lpad.locals "accu" RValue; Hashtbl.add fpad.lpad.locals "bp" RValue; fpad.lpad.globals_table <- gpad.globals_table; let subfunc_pairs = List.map (fun func_label -> let fblock = IMap.find func_label Wc_control.(scode.functions) in fpad.fpad_scope <- fblock.scope; let label = sprintf "func%d" func_label in init_lpad_for_subfunc gpad fpad func_label; let sexpl = emit_fblock gpad fpad fblock in (label, sexpl) ) subfunc_labels in let subfunc_pairs_with_panic = subfunc_pairs @ [ "panic", [] ] in let subfunc_sexpl = match subfunc_pairs with | [] -> assert false | [ label, sexpl ] -> cond_section fpad.need_panic "panic" [ L [ K "unreachable" ]] sexpl | _ -> let labels = List.map (fun (label, _) -> ID label) subfunc_pairs_with_panic in let body = [ L [ K "local.get"; ID "codeptr" ]; L [ K "i32.const"; N (I32 code_pointer_subfunc_mask) ]; L [ K "i32.and" ]; L [ K "i32.const"; N (I32 2l) ]; L [ K "i32.shr_u" ]; L ( [ K "br_table" ] @ labels ) ] in block_cascade body subfunc_pairs_with_panic in let sexpl = ( match letrec_label with | Main 0 | Func _ -> [ L [ K "i32.const"; N (I32 1l) ]; L [ K "local.set"; ID "accu" ] ] | Main _ -> envptr is abused to pass on the accu from one main function to the next to the next *) [ L [ K "local.get"; ID "envptr" ]; L [ K "local.set"; ID "accu" ]; L [ K "i32.const"; N (I32 0xffff_fffcl) ]; L [ K "local.set"; ID "envptr" ] ] ) @ (subfunc_sexpl |> cond_section_lz fpad.need_appterm_common "appterm_common" (appterm_common fpad) |> cond_loop fpad.need_startover "startover" |> cond_section_lz fpad.need_return "return" return ) in if fpad.need_appterm_common then ( Hashtbl.add fpad.lpad.locals "appterm_new_num_args" RInt; ); if fpad.need_xalloc then Hashtbl.add fpad.lpad.locals "xalloc" RValue; if fpad.need_tmp1_i32 then Hashtbl.add fpad.lpad.locals "tmp1_i32" RValue; if fpad.need_tmp2_i32 then Hashtbl.add fpad.lpad.locals "tmp2_i32" RValue; if fpad.need_tmp1_f64 then Hashtbl.add fpad.lpad.locals "tmp1_f64" RValue; let locals = Hashtbl.fold (fun name vtype acc -> (name,vtype) :: acc) fpad.lpad.locals [] in let letrec = [ L ( [ K "func"; ID func_name; ] @ (if export_flag then [ L [ K "export"; S func_name ]] else []) @ [ L [ K "param"; ID "envptr"; K "i32" ]; L [ K "param"; ID "extra_args"; K "i32" ]; L [ K "param"; ID "codeptr"; K "i32" ]; L [ K "param"; ID "fp"; K "i32" ]; BR; L [ K "result"; K "i32" ]; ] @ (List.map (fun (name,repr) -> L [ K "local"; ID name; K (string_of_vtype (vtype repr)) ]; ) locals ) @ debug2 0 ( eff_label letrec_label ) @ debug2_var 10 " fp " @ debug2_var 11 " envptr " @ debug2_var 12 " " @ debug2_var 13 " extra_args " @ [ L [ K " local.get " ; ID " envptr " ] ; ( * print 14 : env , if possible @ debug2 0 (eff_label letrec_label) @ debug2_var 10 "fp" @ debug2_var 11 "envptr" @ debug2_var 12 "codeptr" @ debug2_var 13 "extra_args" L [ K "i32.const"; N (I32 (-1l)) ]; L [ K "i32.ne" ]; L [ K "if"; L ( [ K "then"; L [ K "i32.const"; N (I32 14l) ]] @ push_env @ [ L [ K "call"; ID "debug2" ]] ) ] ] *) @ sexpl @ [ L [ K "unreachable" ]] ) ] in letrec let generate_letrec scode gpad letrec_label = let subfunc_labels = try Hashtbl.find gpad.subfunctions letrec_label with Not_found -> assert false in assert(subfunc_labels <> []); let func_name = Hashtbl.find gpad.letrec_name letrec_label in let export = (letrec_label = Main 0) in generate_function scode gpad letrec_label func_name subfunc_labels export let globals() = [ "wasicaml_global_data", true, TI32; "wasicaml_domain_state", true, TI32; "wasicaml_atom_table", true, TI32; "wasicaml_stack_threshold", true, TI32; "exn_result", true, TI32; ] @ if !enable_multireturn then [] else [ "retval2", true, TI32; "retval3", true, TI32; ] let imp_functions = [ "env", "caml_alloc_small_dispatch", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "env", "caml_alloc_small", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ]; "env", "caml_alloc_shr", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ]; "env", "caml_initialize", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "env", "caml_modify", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "env", "caml_raise_zero_divide", []; "env", "caml_raise_stack_overflow", []; "env", "wasicaml_wraptry4", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; L [ K "result"; K "i32" ] ]; "env", "wasicaml_get_global_data", [ L [ K "result"; K "i32" ]]; "env", "wasicaml_get_domain_state", [ L [ K "result"; K "i32" ]]; "env", "wasicaml_get_atom_table", [ L [ K "result"; K "i32" ]]; "env", "debug2", [ L [ K "param"; K "i32" ]; L [ K "param"; K "i32" ]; ]; "wasicaml", "wasicaml_throw", []; ] let sanitize = String.map (fun c -> match c with | 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '.' -> c | _ -> '?' ) let bigarray_to_string_list limit ba = let n = Array1.dim ba in let l = ref [] in let p = ref 0 in while !p < n do let q = min (n - !p) limit in let by = Bytes.create q in for i = 0 to q-1 do Bytes.set by i ba.{!p + i} done; l := Bytes.to_string by :: !l; p := !p + q done; List.rev !l let generate scode exe get_defname globals_table = let (funcmapping, subfunctions) = get_funcmapping scode in let letrec_name = Hashtbl.create 7 in Hashtbl.iter (fun _ (letrec_label, _) -> match letrec_label with | Main 0 -> Hashtbl.add letrec_name letrec_label "letrec_main" | Main lab -> Hashtbl.add letrec_name letrec_label (sprintf "letrec_main%d" lab) | Func lab -> let suffix = try let defname = get_defname lab in "_" ^ sanitize defname with | Not_found -> "" in Hashtbl.add letrec_name letrec_label (sprintf "letrec%d%s" lab suffix) ) funcmapping; let wasmindex = Hashtbl.create 7 in let nextindex = ref 0 in let _elements = Hashtbl.fold (fun _ (letrec_label, _) acc -> Hashtbl.add wasmindex letrec_label !nextindex; incr nextindex; let name = Hashtbl.find letrec_name letrec_label in (ID name) :: acc ) funcmapping [] in let data = bigarray_to_string_list 4096 Wc_reader.(exe.data) |> List.map (fun s -> S s) in let gpad = { funcmapping; subfunctions; primitives = Hashtbl.create 7; wasmindex; letrec_name; need_reinit_frame = false; need_reinit_frame_k = ISet.empty; need_mlookup = false; globals_table; glbfun_table = Wc_traceglobals.derive_glbfun_table globals_table; } in let sexpl_code = Hashtbl.fold (fun letrec_label _ acc -> let sexpl = generate_letrec scode gpad letrec_label in sexpl @ acc ) gpad.subfunctions [] in let sexpl_memory = [ L [ K "import"; S "env"; S "memory"; L [ K "memory"; ID "memory"; N (I32 65536l); ] ] ] in let sexpl_table = [ L [ K "import"; S "env"; S "table"; L [ K "table"; N (I32 (Int32.of_int (Hashtbl.length subfunctions))); K "funcref" ] ] ] in let sexpl_functions = List.map (fun (modname, name, typeuse) -> L [ K "import"; S modname; S name; L ( [ K "func"; ID name; ] @ typeuse ) ] ) imp_functions @ Hashtbl.fold (fun name typeuse acc -> ( L [ K "import"; S "env"; S name; L ( [ K "func"; ID name; ] @ typeuse ) ] ) :: acc ) gpad.primitives [] in let sexpl_globals = List.map (fun (name, mut, vtype) -> L ( [ K "global"; ID name; ( if mut then L [ K "mut"; K (string_of_vtype vtype) ] else K (string_of_vtype vtype) ); ] @ zero_expr_of_vtype vtype ) ) (globals()) in sexpl_memory @ sexpl_functions @ sexpl_table @ sexpl_globals @ wasicaml_init @ wasicaml_get_data @ wasicaml_get_data_size Wc_reader.(Array1.dim exe.data) @ alloc_fast @ alloc_slow() @ grab_helper gpad @ return_helper() @ appterm_helper() @ restart_helper gpad @ (if gpad.need_reinit_frame then reinit_frame else [] ) @ (if gpad.need_mlookup then mlookup else [] ) @ (if !enable_deadbeef_check then deadbeef_init @ deadbeef_check else [] ) @ (ISet.elements gpad.need_reinit_frame_k |> List.map reinit_frame_k |> List.flatten ) @ sexpl_code @ [ L ( [ K "data"; L [ K "memory"; N (I32 0l) ]; WAT extension : ID "data"; ] @ data ) ] Notes : ~/.wasicaml / bin / wasi_ld --relocatable / initruntime.o lib / prims.o ~/.wasicaml / lib / ocaml / libcamlrun.a ~/.wasicaml / bin / wasi_ld -o final.wasm caml.wasm src / wasicaml / t.wasm wat syntax : deficiencies of wat2wasm : Static linking : -conventions/blob/master/Linking.md some toolchain tricks : -to-webassembly/ wasm - ld : : -to-llvm-mc-project.html LLVM wasm assembly parser : LLVM wasm assembly tests : -project/tree/main/llvm/test/MC/WebAssembly Notes: ~/.wasicaml/bin/wasi_ld --relocatable -o caml.wasm lib/initruntime.o lib/prims.o ~/.wasicaml/lib/ocaml/libcamlrun.a ~/.wasicaml/bin/wasi_ld -o final.wasm caml.wasm src/wasicaml/t.wasm wat syntax: deficiencies of wat2wasm: Static linking: -conventions/blob/master/Linking.md some llvm toolchain tricks: -to-webassembly/ wasm-ld: LLVM MC: -to-llvm-mc-project.html LLVM wasm assembly parser: LLVM wasm assembly tests: -project/tree/main/llvm/test/MC/WebAssembly *)
69555ca4c8e01a62576cf993239e033fab3cdcda0484775fde09feea96d91b80
joachimdb/dl4clj
word2vec_raw_text_example.clj
(ns ^{:doc ""} dl4clj.examples.word2vec.word2vec-raw-text-example (:import [org.deeplearning4j.models.word2vec Word2Vec Word2Vec$Builder] [org.deeplearning4j.models.word2vec.wordstore.inmemory InMemoryLookupCache] [org.deeplearning4j.models.embeddings.loader WordVectorSerializer] [org.deeplearning4j.text.sentenceiterator BasicLineIterator] [org.deeplearning4j.text.sentenceiterator SentenceIterator] [org.deeplearning4j.text.sentenceiterator UimaSentenceIterator] [org.deeplearning4j.text.tokenization.tokenizer.preprocessor CommonPreprocessor] [org.deeplearning4j.text.tokenization.tokenizerfactory DefaultTokenizerFactory] [org.deeplearning4j.text.tokenization.tokenizerfactory TokenizerFactory] [org.deeplearning4j.ui UiServer])) (defn ^Word2Vec vec-from-file [^String path {:keys [min-word-frequency iterations layer-size seed window-size] :or {min-word-frequency 5 iterations 1 layer-size 100 seed 42 window-size 5}}] (let [iter (BasicLineIterator. path) ;; Strip white space before and after for each line tf (doto (DefaultTokenizerFactory.) ;; Split on white spaces in the line to get words (.setTokenPreProcessor (CommonPreprocessor.)))] (-> (Word2Vec$Builder.) (.iterations iterations) (.minWordFrequency min-word-frequency) (.layerSize layer-size) (.seed seed) (.windowSize window-size) (.iterate iter) (.tokenizerFactory tf) (.build) (.fit)))) (defn save [^Word2Vec model path] (WordVectorSerializer/writeWordVectors model path)) (defn n-closest [n ^Word2Vec model ^String target n] (seq (.wordsNearest model target (int n)))) (defn ui-server [] (UiServer/getInstance)) (comment ;; Example usage: (def vec (vec-from-file "/tmp/ (.getPort ui-server) )
null
https://raw.githubusercontent.com/joachimdb/dl4clj/fe9af7c886b80df5e18cd79923fbc6955ddc2694/src/dl4clj/examples/word2vec/word2vec_raw_text_example.clj
clojure
Strip white space before and after for each line Split on white spaces in the line to get words Example usage:
(ns ^{:doc ""} dl4clj.examples.word2vec.word2vec-raw-text-example (:import [org.deeplearning4j.models.word2vec Word2Vec Word2Vec$Builder] [org.deeplearning4j.models.word2vec.wordstore.inmemory InMemoryLookupCache] [org.deeplearning4j.models.embeddings.loader WordVectorSerializer] [org.deeplearning4j.text.sentenceiterator BasicLineIterator] [org.deeplearning4j.text.sentenceiterator SentenceIterator] [org.deeplearning4j.text.sentenceiterator UimaSentenceIterator] [org.deeplearning4j.text.tokenization.tokenizer.preprocessor CommonPreprocessor] [org.deeplearning4j.text.tokenization.tokenizerfactory DefaultTokenizerFactory] [org.deeplearning4j.text.tokenization.tokenizerfactory TokenizerFactory] [org.deeplearning4j.ui UiServer])) (defn ^Word2Vec vec-from-file [^String path {:keys [min-word-frequency iterations layer-size seed window-size] :or {min-word-frequency 5 iterations 1 layer-size 100 seed 42 window-size 5}}] (.setTokenPreProcessor (CommonPreprocessor.)))] (-> (Word2Vec$Builder.) (.iterations iterations) (.minWordFrequency min-word-frequency) (.layerSize layer-size) (.seed seed) (.windowSize window-size) (.iterate iter) (.tokenizerFactory tf) (.build) (.fit)))) (defn save [^Word2Vec model path] (WordVectorSerializer/writeWordVectors model path)) (defn n-closest [n ^Word2Vec model ^String target n] (seq (.wordsNearest model target (int n)))) (defn ui-server [] (UiServer/getInstance)) (comment (def vec (vec-from-file "/tmp/ (.getPort ui-server) )
45e4392cf733f4345987bb2b154d4310910735966e3797adb117369929c3970e
bobbae/gosling-emacs
scribe.ml
(defun (apply-look go-forward (save-excursion c (if (! (eolp)) (forward-character)) (setq go-forward -1) (backward-word) (setq c (get-tty-character)) (if (> c ' ') (progn (insert-character '@') (insert-character c) (insert-character '[') (forward-word) (setq go-forward (dot)) (insert-character ']') ) ) ) (if (= go-forward (dot)) (forward-character)) ) ) (defun (scribe-mode (remove-all-local-bindings) (if (! buffer-is-modified) (save-excursion (error-occured (goto-character 2000) (search-reverse "LastEditDate=""") (search-forward """") (set-mark) (search-forward """") (backward-character) (delete-to-killbuffer) (insert-string (current-time)) (setq buffer-is-modified 0) ) ) ) (local-bind-to-key "justify-paragraph" (+ 128 'j')) (local-bind-to-key "apply-look" (+ 128 'l')) (setq right-margin 77) (setq mode-string "Scribe") (setq case-fold-search 1) (use-syntax-table "text-mode") (modify-syntax-entry "w -'") (use-abbrev-table "text-mode") (setq left-margin 1) (novalue) ) ) (scribe-mode) (novalue)
null
https://raw.githubusercontent.com/bobbae/gosling-emacs/8fdda532abbffb0c952251a0b5a4857e0f27495a/lib/maclib/scribe.ml
ocaml
(defun (apply-look go-forward (save-excursion c (if (! (eolp)) (forward-character)) (setq go-forward -1) (backward-word) (setq c (get-tty-character)) (if (> c ' ') (progn (insert-character '@') (insert-character c) (insert-character '[') (forward-word) (setq go-forward (dot)) (insert-character ']') ) ) ) (if (= go-forward (dot)) (forward-character)) ) ) (defun (scribe-mode (remove-all-local-bindings) (if (! buffer-is-modified) (save-excursion (error-occured (goto-character 2000) (search-reverse "LastEditDate=""") (search-forward """") (set-mark) (search-forward """") (backward-character) (delete-to-killbuffer) (insert-string (current-time)) (setq buffer-is-modified 0) ) ) ) (local-bind-to-key "justify-paragraph" (+ 128 'j')) (local-bind-to-key "apply-look" (+ 128 'l')) (setq right-margin 77) (setq mode-string "Scribe") (setq case-fold-search 1) (use-syntax-table "text-mode") (modify-syntax-entry "w -'") (use-abbrev-table "text-mode") (setq left-margin 1) (novalue) ) ) (scribe-mode) (novalue)
2393a282e0067eea7f26d53b684038a09023e68a130de7162fbd5d7ffa3bf0fd
ocaml-ppx/ocamlformat
nesting.ml
module M = struct let a = (((((( ) ) ) ) ) ) let a = (ff(ff(ff(ff(ff(ff( ) ) ) ) ) ) ) let a = [[[[[[ ] ] ] ] ] ] let a = [ff[ff[ff[ff[ff[ff[ ] ] ] ] ] ] ]
null
https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/3d1c992240f7d30bcb8151285274f44619dae197/test/failing/tests/nesting.ml
ocaml
module M = struct let a = (((((( ) ) ) ) ) ) let a = (ff(ff(ff(ff(ff(ff( ) ) ) ) ) ) ) let a = [[[[[[ ] ] ] ] ] ] let a = [ff[ff[ff[ff[ff[ff[ ] ] ] ] ] ] ]
b38274f7fce21f26bdcb59167caa1a49886228491c9cedccece92d1e64876bf4
mirage/irmin
hash.ml
* Copyright ( c ) 2013 - 2022 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2022 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) include Hash_intf module Make (H : Digestif.S) = struct type t = H.t external get_64 : string -> int -> int64 = "%caml_string_get64u" external swap64 : int64 -> int64 = "%bswap_int64" let get_64_little_endian str idx = if Sys.big_endian then swap64 (get_64 str idx) else get_64 str idx let short_hash c = Int64.to_int (get_64_little_endian (H.to_raw_string c) 0) let short_hash_substring bigstring ~off = Int64.to_int (Bigstringaf.get_int64_le bigstring off) let hash_size = H.digest_size let of_hex s = match H.consistent_of_hex s with | x -> Ok x | exception Invalid_argument e -> Error (`Msg e) let pp_hex ppf x = Fmt.string ppf (H.to_hex x) let t = Type.map ~pp:pp_hex ~of_string:of_hex Type.(string_of (`Fixed hash_size)) H.of_raw_string H.to_raw_string let hash s = H.digesti_string s let to_raw_string s = H.to_raw_string s let unsafe_of_raw_string s = H.of_raw_string s end module Make_BLAKE2B (D : sig val digest_size : int end) = Make (Digestif.Make_BLAKE2B (D)) module Make_BLAKE2S (D : sig val digest_size : int end) = Make (Digestif.Make_BLAKE2S (D)) module SHA1 = Make (Digestif.SHA1) module RMD160 = Make (Digestif.RMD160) module SHA224 = Make (Digestif.SHA224) module SHA256 = Make (Digestif.SHA256) module SHA384 = Make (Digestif.SHA384) module SHA512 = Make (Digestif.SHA512) module BLAKE2B = Make (Digestif.BLAKE2B) module BLAKE2S = Make (Digestif.BLAKE2S) module Typed (K : S) (V : Type.S) = struct include K type value = V.t [@@deriving irmin ~pre_hash] let hash v = K.hash (pre_hash_value v) end module V1 (K : S) : S with type t = K.t = struct type t = K.t [@@deriving irmin ~encode_bin ~decode_bin] let hash = K.hash let short_hash = K.short_hash let short_hash_substring = K.short_hash_substring let hash_size = K.hash_size let int64_to_bin_string = Type.(unstage (to_bin_string int64)) let hash_size_str = int64_to_bin_string (Int64.of_int K.hash_size) let to_raw_string = K.to_raw_string let unsafe_of_raw_string = K.unsafe_of_raw_string let encode_bin e f = f hash_size_str; encode_bin e f let decode_bin buf pos_ref = pos_ref := !pos_ref + 8; decode_bin buf pos_ref let size_of = Type.Size.custom_static (8 + hash_size) let t = Type.like K.t ~bin:(encode_bin, decode_bin, size_of) end module Set = struct module Make (Hash : S) = struct include Irmin_data.Fixed_size_string_set let create ?(initial_slots = 0) () = let elt_length = Hash.hash_size and hash s = Hash.(short_hash (unsafe_of_raw_string s)) and hash_substring t ~off ~len:_ = Hash.short_hash_substring t ~off in create ~elt_length ~initial_slots ~hash ~hash_substring () let add t h = add t (Hash.to_raw_string h) let mem t h = mem t (Hash.to_raw_string h) end module type S = Set end
null
https://raw.githubusercontent.com/mirage/irmin/b5d5e3f98eeb5095bcb9cd097e61b724eb66aef9/src/irmin/hash.ml
ocaml
* Copyright ( c ) 2013 - 2022 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2022 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) include Hash_intf module Make (H : Digestif.S) = struct type t = H.t external get_64 : string -> int -> int64 = "%caml_string_get64u" external swap64 : int64 -> int64 = "%bswap_int64" let get_64_little_endian str idx = if Sys.big_endian then swap64 (get_64 str idx) else get_64 str idx let short_hash c = Int64.to_int (get_64_little_endian (H.to_raw_string c) 0) let short_hash_substring bigstring ~off = Int64.to_int (Bigstringaf.get_int64_le bigstring off) let hash_size = H.digest_size let of_hex s = match H.consistent_of_hex s with | x -> Ok x | exception Invalid_argument e -> Error (`Msg e) let pp_hex ppf x = Fmt.string ppf (H.to_hex x) let t = Type.map ~pp:pp_hex ~of_string:of_hex Type.(string_of (`Fixed hash_size)) H.of_raw_string H.to_raw_string let hash s = H.digesti_string s let to_raw_string s = H.to_raw_string s let unsafe_of_raw_string s = H.of_raw_string s end module Make_BLAKE2B (D : sig val digest_size : int end) = Make (Digestif.Make_BLAKE2B (D)) module Make_BLAKE2S (D : sig val digest_size : int end) = Make (Digestif.Make_BLAKE2S (D)) module SHA1 = Make (Digestif.SHA1) module RMD160 = Make (Digestif.RMD160) module SHA224 = Make (Digestif.SHA224) module SHA256 = Make (Digestif.SHA256) module SHA384 = Make (Digestif.SHA384) module SHA512 = Make (Digestif.SHA512) module BLAKE2B = Make (Digestif.BLAKE2B) module BLAKE2S = Make (Digestif.BLAKE2S) module Typed (K : S) (V : Type.S) = struct include K type value = V.t [@@deriving irmin ~pre_hash] let hash v = K.hash (pre_hash_value v) end module V1 (K : S) : S with type t = K.t = struct type t = K.t [@@deriving irmin ~encode_bin ~decode_bin] let hash = K.hash let short_hash = K.short_hash let short_hash_substring = K.short_hash_substring let hash_size = K.hash_size let int64_to_bin_string = Type.(unstage (to_bin_string int64)) let hash_size_str = int64_to_bin_string (Int64.of_int K.hash_size) let to_raw_string = K.to_raw_string let unsafe_of_raw_string = K.unsafe_of_raw_string let encode_bin e f = f hash_size_str; encode_bin e f let decode_bin buf pos_ref = pos_ref := !pos_ref + 8; decode_bin buf pos_ref let size_of = Type.Size.custom_static (8 + hash_size) let t = Type.like K.t ~bin:(encode_bin, decode_bin, size_of) end module Set = struct module Make (Hash : S) = struct include Irmin_data.Fixed_size_string_set let create ?(initial_slots = 0) () = let elt_length = Hash.hash_size and hash s = Hash.(short_hash (unsafe_of_raw_string s)) and hash_substring t ~off ~len:_ = Hash.short_hash_substring t ~off in create ~elt_length ~initial_slots ~hash ~hash_substring () let add t h = add t (Hash.to_raw_string h) let mem t h = mem t (Hash.to_raw_string h) end module type S = Set end
a1ce47ea17a246cc4cae657ec6a1c22d176490eba480de1226fb715d57b70fe3
facebookarchive/duckling_old
finance.clj
( {} "$10" "10$" "ten dollars" (money 10 "$") ;"under $15" ;"no more than 15$" ;"no greater than 15$" " less than fifteen dollars " ( money 15 " $ " " < " ) "ten cents" (money 10 "cent") "$10,000" "10K$" "$10k" (money 10000 "$") "USD1.23" (money 1.23 "USD") "2 dollar and 23 cents" "two dollar 23 cents" "2 dollar 23" "two dollar and 23" (money 2.23 "$") "20€" "20 euros" "20 Euro" "20 Euros" "EUR 20" (money 20 "EUR") "EUR29.99" (money 29.99 "EUR") Indian Currency "Rs. 20" "Rs 20" "20 Rupees" "20Rs" "Rs20" (money 20 "INR") "20 Rupees 43" "twenty rupees 43" (money 20.43 "INR") "INR33" (money 33 "INR") "3 bucks" (money 3) ; unknown unit "£9" "nine pounds" (money 9 "£") "GBP3.01" "GBP 3.01" (money 3.01 "GBP") ) around $ 200 between $ 200 and $ 300 around 200 - 500 dollars up to 1000 ~50 - 100
null
https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/en/corpus/finance.clj
clojure
"under $15" "no more than 15$" "no greater than 15$" unknown unit
( {} "$10" "10$" "ten dollars" (money 10 "$") " less than fifteen dollars " ( money 15 " $ " " < " ) "ten cents" (money 10 "cent") "$10,000" "10K$" "$10k" (money 10000 "$") "USD1.23" (money 1.23 "USD") "2 dollar and 23 cents" "two dollar 23 cents" "2 dollar 23" "two dollar and 23" (money 2.23 "$") "20€" "20 euros" "20 Euro" "20 Euros" "EUR 20" (money 20 "EUR") "EUR29.99" (money 29.99 "EUR") Indian Currency "Rs. 20" "Rs 20" "20 Rupees" "20Rs" "Rs20" (money 20 "INR") "20 Rupees 43" "twenty rupees 43" (money 20.43 "INR") "INR33" (money 33 "INR") "3 bucks" "£9" "nine pounds" (money 9 "£") "GBP3.01" "GBP 3.01" (money 3.01 "GBP") ) around $ 200 between $ 200 and $ 300 around 200 - 500 dollars up to 1000 ~50 - 100
30ba2811f528f1e782b076bbff98f4c2ee33c0b673b60c87ac2b90a55818788e
hanshuebner/bknr-web
smtp-commands.lisp
(in-package :bknr.smtp-server.commands) (enable-interpol-syntax) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; smtp commands ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod helo ((client smtp-client) args) (unless args (reply client 501 "missing parameter")) (when (smtp-client-peer-id client) (error (make-smtp-error 502 "HELO/EHLO command already seen"))) (setf (smtp-client-peer-id client) args) (reply client 250 "hello ~a and welcome aboard!" args)) (defmethod noop ((client smtp-client) args) (when args (reply client 501 "bad parameter")) (reply client 250 "ok")) (defmethod rset ((client smtp-client) args) (when args (reply client 501 "bad parameter")) (reset client) (reply client 250 "okay, transaction reset")) (defmethod mail-from ((client smtp-client) args) (let ((from (parse-smtp-address-arg args))) (unless from (error (make-smtp-error 501 "missing parameter to MAIL FROM command"))) (when (smtp-client-from client) (error (make-smtp-error 502 "MAIL FROM command already issued"))) (setf (smtp-client-from client) from) (reply client 250 "sender accepted"))) (defmethod rcpt-to ((client smtp-client) args) (unless (smtp-client-from client) (error (make-smtp-error 502 "expecting MAIL FROM command"))) (let ((to (parse-smtp-address-arg args))) (unless to (error (make-smtp-error 501 "bad parameter to RCPT TO command"))) (if (mailinglist-with-email to) (progn (push to (smtp-client-to client)) (reply client 250 "recipient accepted")) (reply client 550 "recipient ~a not known" to)))) (defmethod data ((client smtp-client) args) (when args (error (make-smtp-error 501 "bad argument(s) to DATA command"))) (unless (and (smtp-client-from client) (smtp-client-to client)) (error (make-smtp-error 502 "can't handle DATA before both MAIL FROM and RCPT TO have been issued"))) (reply client 250 "okay, give me the mail") (loop for line = (read-line-from-client client t) until (equal line ".") when (equal line "..") do (setf line ".") do (push (format nil "~a~%" line) (smtp-client-message-lines client))) (setf (smtp-client-message-lines client) (nreverse (smtp-client-message-lines client))) (handler-case (let ((mail (with-input-from-string (s (apply #'concatenate 'string (nreverse (smtp-client-message-lines client)))) (parse-mail s)))) (handle-mail (mailinglist-with-email (smtp-client-to client)) mail) (reply client 250 "your mail has been processed")) (mail-parser-error (e) (reply client 451 "problem ~a delivering your email, can't deliver message" e))) (reset client)) (defmethod quit ((client smtp-client) args) (when args (error (make-smtp-error 501 "bad argument(s) to QUIT command"))) (error (make-condition 'end-of-smtp-session)))
null
https://raw.githubusercontent.com/hanshuebner/bknr-web/5c30b61818a2f02f6f2e5dc69fd77396ec3afc51/modules/mail/smtp-commands.lisp
lisp
smtp commands
(in-package :bknr.smtp-server.commands) (enable-interpol-syntax) (defmethod helo ((client smtp-client) args) (unless args (reply client 501 "missing parameter")) (when (smtp-client-peer-id client) (error (make-smtp-error 502 "HELO/EHLO command already seen"))) (setf (smtp-client-peer-id client) args) (reply client 250 "hello ~a and welcome aboard!" args)) (defmethod noop ((client smtp-client) args) (when args (reply client 501 "bad parameter")) (reply client 250 "ok")) (defmethod rset ((client smtp-client) args) (when args (reply client 501 "bad parameter")) (reset client) (reply client 250 "okay, transaction reset")) (defmethod mail-from ((client smtp-client) args) (let ((from (parse-smtp-address-arg args))) (unless from (error (make-smtp-error 501 "missing parameter to MAIL FROM command"))) (when (smtp-client-from client) (error (make-smtp-error 502 "MAIL FROM command already issued"))) (setf (smtp-client-from client) from) (reply client 250 "sender accepted"))) (defmethod rcpt-to ((client smtp-client) args) (unless (smtp-client-from client) (error (make-smtp-error 502 "expecting MAIL FROM command"))) (let ((to (parse-smtp-address-arg args))) (unless to (error (make-smtp-error 501 "bad parameter to RCPT TO command"))) (if (mailinglist-with-email to) (progn (push to (smtp-client-to client)) (reply client 250 "recipient accepted")) (reply client 550 "recipient ~a not known" to)))) (defmethod data ((client smtp-client) args) (when args (error (make-smtp-error 501 "bad argument(s) to DATA command"))) (unless (and (smtp-client-from client) (smtp-client-to client)) (error (make-smtp-error 502 "can't handle DATA before both MAIL FROM and RCPT TO have been issued"))) (reply client 250 "okay, give me the mail") (loop for line = (read-line-from-client client t) until (equal line ".") when (equal line "..") do (setf line ".") do (push (format nil "~a~%" line) (smtp-client-message-lines client))) (setf (smtp-client-message-lines client) (nreverse (smtp-client-message-lines client))) (handler-case (let ((mail (with-input-from-string (s (apply #'concatenate 'string (nreverse (smtp-client-message-lines client)))) (parse-mail s)))) (handle-mail (mailinglist-with-email (smtp-client-to client)) mail) (reply client 250 "your mail has been processed")) (mail-parser-error (e) (reply client 451 "problem ~a delivering your email, can't deliver message" e))) (reset client)) (defmethod quit ((client smtp-client) args) (when args (error (make-smtp-error 501 "bad argument(s) to QUIT command"))) (error (make-condition 'end-of-smtp-session)))
e84f0a3f2f3d6f6de0ba62d6874ecc2c95fc3120f93668a2e7137f7304fd7f79
theodormoroianu/SecondYearCourses
LambdaChurch_20210415164649.hs
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) -- alpha-equivalence aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) -- subst u x t defines [u/x]t, i.e., substituting u for x in t for example [ 3 / x](x + x ) = = 3 + 3 -- This substitution avoids variable captures so it is safe to be used when -- reducing terms with free variables (e.g., if evaluating inside lambda abstractions) subst :: Term -- ^ substitution term -> Variable -- ^ variable to be substitutes -> Term -- ^ term in which the substitution occurs -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV -- Normal order reduction -- - like call by name -- - but also reduce under lambda abstractions if no application is possible -- - guarantees reaching a normal form if it exists normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce -- alpha-beta equivalence (for strongly normalizing terms) is obtained by -- fully evaluating the terms using beta-reduction, then checking their -- alpha-equivalence. abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s -- Church Encodings in Lambda -- BOOLEANS A boolean is any way to choose between two alternatives ( ) churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat = undefined churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) churchNil :: Term churchNil = lams ["agg", "init"] (v "init") churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ))
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164649.hs
haskell
alpha-equivalence subst u x t defines [u/x]t, i.e., substituting u for x in t This substitution avoids variable captures so it is safe to be used when reducing terms with free variables (e.g., if evaluating inside lambda abstractions) ^ substitution term ^ variable to be substitutes ^ term in which the substitution occurs Normal order reduction - like call by name - but also reduce under lambda abstractions if no application is possible - guarantees reaching a normal form if it exists alpha-beta equivalence (for strongly normalizing terms) is obtained by fully evaluating the terms using beta-reduction, then checking their alpha-equivalence. Church Encodings in Lambda BOOLEANS note that it's the same as churchFalse
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) for example [ 3 / x](x + x ) = = 3 + 3 subst -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s A boolean is any way to choose between two alternatives ( ) churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat = undefined churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) churchNil :: Term churchNil = lams ["agg", "init"] (v "init") churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ))
49b0d99bec0e3c1b1612681dcb1994f3e3ab1ae0dd8e8b8f8668b4162cf07173
CzesiaLa/RoadToHaskell
Kmean.hs
module Kmean ( Cluster , kmean ) where import Data.List import Piksel data Cluster = Cluster Color [Piksel] instance Show Cluster where show (Cluster col pixels) = "--\n" ++ show col ++ "\n-\n" ++ intercalate "\n" (map show pixels) type SelectedColors = [Color] getClusterColor :: Cluster -> Color getClusterColor (Cluster col pixels) = col setClusterColor :: Cluster -> Color -> Cluster setClusterColor (Cluster col pixels) col' = Cluster col' pixels getClusterPixels :: Cluster -> [Piksel] getClusterPixels (Cluster col pixels) = pixels setClusterPixels :: Cluster -> [Piksel] -> Cluster setClusterPixels (Cluster col pixels) pixels' = Cluster col pixels' showClusters :: [Cluster] -> IO () showClusters [] = return () showClusters (x:xs) = do print x showClusters xs isColorDifferent :: Color -> [Color] -> Bool isColorDifferent _ [] = True isColorDifferent c (x:xs) | c == x = False | otherwise = isColorDifferent c xs selectColors :: Int -> [Piksel] -> [Color] selectColors n pixels = select n (map getColor pixels) [] where select n (x:xs) selectedColors | n == 0 = selectedColors | null selectedColors = select (n - 1) xs (x : selectedColors) | isColorDifferent x selectedColors = select (n - 1) xs (x : selectedColors) | otherwise = select n xs selectedColors isNearestPixelToColor :: Color -> SelectedColors -> Piksel -> Bool isNearestPixelToColor col [] pixel = True isNearestPixelToColor col (x:xs) pixel | col == x = isNearestPixelToColor col xs pixel | distColor col (getColor pixel) <= distColor x (getColor pixel) = isNearestPixelToColor col xs pixel | otherwise = False regroupPixelsToColor :: Color -> SelectedColors -> [Piksel] -> [Piksel] regroupPixelsToColor col sc pixels = filter (isNearestPixelToColor col sc) pixels isKmeanDone :: Double -> [Cluster] -> [Cluster] -> Bool isKmeanDone _ [] [] = True isKmeanDone e (x:xs) (y:ys) | eDistColor (getClusterColor x) (getClusterColor y) > e = False | otherwise = isKmeanDone e xs ys replaceCentroids :: [Piksel] -> [Cluster] -> [Cluster] replaceCentroids pixels clusters = newClusters clusters [] [] where newClusters [] _ nc = reverse nc newClusters (x:xs) usedPixels nc = newClusters xs (newPixelGroup x usedPixels ++ usedPixels) (Cluster (newColor x) (newPixelGroup x usedPixels) : nc) newColor cluster = colorAverage (getClusterPixels cluster) newPixelGroup cluster usedPixels = regroupPixelsToColor (newColor cluster) (map (colorAverage . getClusterPixels) clusters) (groupUnusedPixels pixels usedPixels) defineKCentroids :: Int -> [Piksel] -> [Cluster] defineKCentroids k pixels = createCluster selectedColors [] [] where createCluster [] _ c = c createCluster (x:xs) usedPixels c = createCluster xs (regroupPixels x usedPixels ++ usedPixels) (Cluster x (regroupPixels x usedPixels) : c) selectedColors = selectColors k pixels regroupPixels x usedPixels = regroupPixelsToColor x selectedColors (groupUnusedPixels pixels usedPixels) kmean :: Int -> Double -> FilePath -> IO () kmean k e infile = do text <- fmap lines (readFile infile) let pixels = inputToPixels text doKmean pixels (defineKCentroids k pixels) (replaceCentroids pixels (defineKCentroids k pixels)) where doKmean pixels cx cy | isKmeanDone e cx cy = showClusters cy | otherwise = doKmean pixels cy (replaceCentroids pixels cy)
null
https://raw.githubusercontent.com/CzesiaLa/RoadToHaskell/9cb87a211f5441670328e7dfcc9facf2e33a00a9/04-image_compressor/image-compressor/src/Kmean.hs
haskell
module Kmean ( Cluster , kmean ) where import Data.List import Piksel data Cluster = Cluster Color [Piksel] instance Show Cluster where show (Cluster col pixels) = "--\n" ++ show col ++ "\n-\n" ++ intercalate "\n" (map show pixels) type SelectedColors = [Color] getClusterColor :: Cluster -> Color getClusterColor (Cluster col pixels) = col setClusterColor :: Cluster -> Color -> Cluster setClusterColor (Cluster col pixels) col' = Cluster col' pixels getClusterPixels :: Cluster -> [Piksel] getClusterPixels (Cluster col pixels) = pixels setClusterPixels :: Cluster -> [Piksel] -> Cluster setClusterPixels (Cluster col pixels) pixels' = Cluster col pixels' showClusters :: [Cluster] -> IO () showClusters [] = return () showClusters (x:xs) = do print x showClusters xs isColorDifferent :: Color -> [Color] -> Bool isColorDifferent _ [] = True isColorDifferent c (x:xs) | c == x = False | otherwise = isColorDifferent c xs selectColors :: Int -> [Piksel] -> [Color] selectColors n pixels = select n (map getColor pixels) [] where select n (x:xs) selectedColors | n == 0 = selectedColors | null selectedColors = select (n - 1) xs (x : selectedColors) | isColorDifferent x selectedColors = select (n - 1) xs (x : selectedColors) | otherwise = select n xs selectedColors isNearestPixelToColor :: Color -> SelectedColors -> Piksel -> Bool isNearestPixelToColor col [] pixel = True isNearestPixelToColor col (x:xs) pixel | col == x = isNearestPixelToColor col xs pixel | distColor col (getColor pixel) <= distColor x (getColor pixel) = isNearestPixelToColor col xs pixel | otherwise = False regroupPixelsToColor :: Color -> SelectedColors -> [Piksel] -> [Piksel] regroupPixelsToColor col sc pixels = filter (isNearestPixelToColor col sc) pixels isKmeanDone :: Double -> [Cluster] -> [Cluster] -> Bool isKmeanDone _ [] [] = True isKmeanDone e (x:xs) (y:ys) | eDistColor (getClusterColor x) (getClusterColor y) > e = False | otherwise = isKmeanDone e xs ys replaceCentroids :: [Piksel] -> [Cluster] -> [Cluster] replaceCentroids pixels clusters = newClusters clusters [] [] where newClusters [] _ nc = reverse nc newClusters (x:xs) usedPixels nc = newClusters xs (newPixelGroup x usedPixels ++ usedPixels) (Cluster (newColor x) (newPixelGroup x usedPixels) : nc) newColor cluster = colorAverage (getClusterPixels cluster) newPixelGroup cluster usedPixels = regroupPixelsToColor (newColor cluster) (map (colorAverage . getClusterPixels) clusters) (groupUnusedPixels pixels usedPixels) defineKCentroids :: Int -> [Piksel] -> [Cluster] defineKCentroids k pixels = createCluster selectedColors [] [] where createCluster [] _ c = c createCluster (x:xs) usedPixels c = createCluster xs (regroupPixels x usedPixels ++ usedPixels) (Cluster x (regroupPixels x usedPixels) : c) selectedColors = selectColors k pixels regroupPixels x usedPixels = regroupPixelsToColor x selectedColors (groupUnusedPixels pixels usedPixels) kmean :: Int -> Double -> FilePath -> IO () kmean k e infile = do text <- fmap lines (readFile infile) let pixels = inputToPixels text doKmean pixels (defineKCentroids k pixels) (replaceCentroids pixels (defineKCentroids k pixels)) where doKmean pixels cx cy | isKmeanDone e cx cy = showClusters cy | otherwise = doKmean pixels cy (replaceCentroids pixels cy)
8b428f43e0a62c2852862052b722895f37c1b7bf23eb3e6fe3108c25f4beb2b5
esumii/min-caml
beta.ml
open KNormal let find x env = try M.find x env with Not_found -> x (* 置換のための関数 (caml2html: beta_find) *) let rec g env = function (* β簡約ルーチン本体 (caml2html: beta_g) *) | Unit -> Unit | Int(i) -> Int(i) | Float(d) -> Float(d) | Neg(x) -> Neg(find x env) | Add(x, y) -> Add(find x env, find y env) | Sub(x, y) -> Sub(find x env, find y env) | FNeg(x) -> FNeg(find x env) | FAdd(x, y) -> FAdd(find x env, find y env) | FSub(x, y) -> FSub(find x env, find y env) | FMul(x, y) -> FMul(find x env, find y env) | FDiv(x, y) -> FDiv(find x env, find y env) | IfEq(x, y, e1, e2) -> IfEq(find x env, find y env, g env e1, g env e2) | IfLE(x, y, e1, e2) -> IfLE(find x env, find y env, g env e1, g env e2) letのβ簡約 ( caml2html : ) (match g env e1 with | Var(y) -> Format.eprintf "beta-reducing %s = %s@." x y; g (M.add x y env) e2 | e1' -> let e2' = g env e2 in Let((x, t), e1', e2')) | LetRec({ name = xt; args = yts; body = e1 }, e2) -> LetRec({ name = xt; args = yts; body = g env e1 }, g env e2) | Var(x) -> Var(find x env) (* 変数を置換 (caml2html: beta_var) *) | Tuple(xs) -> Tuple(List.map (fun x -> find x env) xs) | LetTuple(xts, y, e) -> LetTuple(xts, find y env, g env e) | Get(x, y) -> Get(find x env, find y env) | Put(x, y, z) -> Put(find x env, find y env, find z env) | App(g, xs) -> App(find g env, List.map (fun x -> find x env) xs) | ExtArray(x) -> ExtArray(x) | ExtFunApp(x, ys) -> ExtFunApp(x, List.map (fun y -> find y env) ys) let f = g M.empty
null
https://raw.githubusercontent.com/esumii/min-caml/8860b6fbc50786a27963aff1f7639b94c244618a/beta.ml
ocaml
置換のための関数 (caml2html: beta_find) β簡約ルーチン本体 (caml2html: beta_g) 変数を置換 (caml2html: beta_var)
open KNormal | Unit -> Unit | Int(i) -> Int(i) | Float(d) -> Float(d) | Neg(x) -> Neg(find x env) | Add(x, y) -> Add(find x env, find y env) | Sub(x, y) -> Sub(find x env, find y env) | FNeg(x) -> FNeg(find x env) | FAdd(x, y) -> FAdd(find x env, find y env) | FSub(x, y) -> FSub(find x env, find y env) | FMul(x, y) -> FMul(find x env, find y env) | FDiv(x, y) -> FDiv(find x env, find y env) | IfEq(x, y, e1, e2) -> IfEq(find x env, find y env, g env e1, g env e2) | IfLE(x, y, e1, e2) -> IfLE(find x env, find y env, g env e1, g env e2) letのβ簡約 ( caml2html : ) (match g env e1 with | Var(y) -> Format.eprintf "beta-reducing %s = %s@." x y; g (M.add x y env) e2 | e1' -> let e2' = g env e2 in Let((x, t), e1', e2')) | LetRec({ name = xt; args = yts; body = e1 }, e2) -> LetRec({ name = xt; args = yts; body = g env e1 }, g env e2) | Tuple(xs) -> Tuple(List.map (fun x -> find x env) xs) | LetTuple(xts, y, e) -> LetTuple(xts, find y env, g env e) | Get(x, y) -> Get(find x env, find y env) | Put(x, y, z) -> Put(find x env, find y env, find z env) | App(g, xs) -> App(find g env, List.map (fun x -> find x env) xs) | ExtArray(x) -> ExtArray(x) | ExtFunApp(x, ys) -> ExtFunApp(x, List.map (fun y -> find y env) ys) let f = g M.empty
4298bb270d3828d739d9ca1a01035bf8571c79e3c8d3478cfdaf3089291612b5
ucsd-progsys/nate
location.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : location.ml , v 1.48.16.1 doligez Exp $ open Lexing type t = { loc_start: position; loc_end: position; loc_ghost: bool };; let none = { loc_start = dummy_pos; loc_end = dummy_pos; loc_ghost = true };; let in_file name = let loc = { pos_fname = name; pos_lnum = 1; pos_bol = 0; pos_cnum = -1; } in { loc_start = loc; loc_end = loc; loc_ghost = true } ;; let curr lexbuf = { loc_start = lexbuf.lex_start_p; loc_end = lexbuf.lex_curr_p; loc_ghost = false };; let init lexbuf fname = lexbuf.lex_curr_p <- { pos_fname = fname; pos_lnum = 1; pos_bol = 0; pos_cnum = 0; } ;; let symbol_rloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = false; };; let symbol_gloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = true; };; let rhs_loc n = { loc_start = Parsing.rhs_start_pos n; loc_end = Parsing.rhs_end_pos n; loc_ghost = false; };; let input_name = ref "" let input_lexbuf = ref (None : lexbuf option) (* Terminal info *) let status = ref Terminfo.Uninitialised let num_loc_lines = ref 0 (* number of lines already printed after input *) (* Highlight the locations using standout mode. *) let highlight_terminfo ppf num_lines lb loc1 loc2 = Format.pp_print_flush ppf (); (* avoid mixing Format and normal output *) Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in (* Do nothing if the buffer does not contain the whole phrase. *) if pos0 < 0 then raise Exit; (* Count number of lines in phrase *) let lines = ref !num_loc_lines in for i = pos0 to lb.lex_buffer_len - 1 do if lb.lex_buffer.[i] = '\n' then incr lines done; (* If too many lines, give up *) if !lines >= num_lines - 2 then raise Exit; (* Move cursor up that number of lines *) flush stdout; Terminfo.backup !lines; (* Print the input, switching to standout for the location *) let bol = ref false in print_string "# "; for pos = 0 to lb.lex_buffer_len - pos0 - 1 do if !bol then (print_string " "; bol := false); if pos = loc1.loc_start.pos_cnum || pos = loc2.loc_start.pos_cnum then Terminfo.standout true; if pos = loc1.loc_end.pos_cnum || pos = loc2.loc_end.pos_cnum then Terminfo.standout false; let c = lb.lex_buffer.[pos + pos0] in print_char c; bol := (c = '\n') done; (* Make sure standout mode is over *) Terminfo.standout false; (* Position cursor back to original location *) Terminfo.resume !num_loc_lines; flush stdout (* Highlight the location by printing it again. *) let highlight_dumb ppf lb loc = Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in (* Do nothing if the buffer does not contain the whole phrase. *) if pos0 < 0 then raise Exit; let end_pos = lb.lex_buffer_len - pos0 - 1 in (* Determine line numbers for the start and end points *) let line_start = ref 0 and line_end = ref 0 in for pos = 0 to end_pos do if lb.lex_buffer.[pos + pos0] = '\n' then begin if loc.loc_start.pos_cnum > pos then incr line_start; if loc.loc_end.pos_cnum > pos then incr line_end; end done; Print character location ( useful for Emacs ) Format.fprintf ppf "Characters %i-%i:@." loc.loc_start.pos_cnum loc.loc_end.pos_cnum; (* Print the input, underlining the location *) Format.pp_print_string ppf " "; let line = ref 0 in let pos_at_bol = ref 0 in for pos = 0 to end_pos do let c = lb.lex_buffer.[pos + pos0] in if c <> '\n' then begin if !line = !line_start && !line = !line_end then loc is on one line : print whole line Format.pp_print_char ppf c else if !line = !line_start then first line of multiline loc : print ... before if pos < loc.loc_start.pos_cnum then Format.pp_print_char ppf '.' else Format.pp_print_char ppf c else if !line = !line_end then (* last line of multiline loc: print ... after loc_end *) if pos < loc.loc_end.pos_cnum then Format.pp_print_char ppf c else Format.pp_print_char ppf '.' else if !line > !line_start && !line < !line_end then intermediate line of multiline loc : print whole line Format.pp_print_char ppf c end else begin if !line = !line_start && !line = !line_end then begin loc is on one line : underline location Format.fprintf ppf "@. "; for i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do Format.pp_print_char ppf ' ' done; for i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do Format.pp_print_char ppf '^' done end; if !line >= !line_start && !line <= !line_end then begin Format.fprintf ppf "@."; if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " " end; incr line; pos_at_bol := pos + 1; end done (* Highlight the location using one of the supported modes. *) let rec highlight_locations ppf loc1 loc2 = match !status with Terminfo.Uninitialised -> status := Terminfo.setup stdout; highlight_locations ppf loc1 loc2 | Terminfo.Bad_term -> begin match !input_lexbuf with None -> false | Some lb -> let norepeat = try Sys.getenv "TERM" = "norepeat" with Not_found -> false in if norepeat then false else try highlight_dumb ppf lb loc1; true with Exit -> false end | Terminfo.Good_term num_lines -> begin match !input_lexbuf with None -> false | Some lb -> try highlight_terminfo ppf num_lines lb loc1 loc2; true with Exit -> false end (* Print the location in some way or another *) open Format let reset () = num_loc_lines := 0 let (msg_file, msg_line, msg_chars, msg_to, msg_colon, msg_head) = ("File \"", "\", line ", ", characters ", "-", ":", "") (* return file, line, char from the given position *) let get_pos_info pos = let (filename, linenum, linebeg) = if pos.pos_fname = "" && !input_name = "" then ("", -1, 0) else if pos.pos_fname = "" then Linenum.for_position !input_name pos.pos_cnum else (pos.pos_fname, pos.pos_lnum, pos.pos_bol) in (filename, linenum, pos.pos_cnum - linebeg) ;; let print ppf loc = let (file, line, startchar) = get_pos_info loc.loc_start in let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in let (startchar, endchar) = if startchar < 0 then (0, 1) else (startchar, endchar) in if file = "" then begin if highlight_locations ppf loc none then () else fprintf ppf "Characters %i-%i:@." loc.loc_start.pos_cnum loc.loc_end.pos_cnum end else begin fprintf ppf "%s%s%s%i" msg_file file msg_line line; fprintf ppf "%s%i" msg_chars startchar; fprintf ppf "%s%i%s@.%s" msg_to endchar msg_colon msg_head; end let print_warning loc ppf w = if Warnings.is_active w then begin let printw ppf w = let n = Warnings.print ppf w in num_loc_lines := !num_loc_lines + n in fprintf ppf "%a" print loc; fprintf ppf "Warning %a@." printw w; pp_print_flush ppf (); incr num_loc_lines; end ;; let prerr_warning loc w = print_warning loc err_formatter w;; let echo_eof () = print_newline (); incr num_loc_lines
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/parsing/location.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* Terminal info number of lines already printed after input Highlight the locations using standout mode. avoid mixing Format and normal output Do nothing if the buffer does not contain the whole phrase. Count number of lines in phrase If too many lines, give up Move cursor up that number of lines Print the input, switching to standout for the location Make sure standout mode is over Position cursor back to original location Highlight the location by printing it again. Do nothing if the buffer does not contain the whole phrase. Determine line numbers for the start and end points Print the input, underlining the location last line of multiline loc: print ... after loc_end Highlight the location using one of the supported modes. Print the location in some way or another return file, line, char from the given position
, 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 Q Public License version 1.0 . $ I d : location.ml , v 1.48.16.1 doligez Exp $ open Lexing type t = { loc_start: position; loc_end: position; loc_ghost: bool };; let none = { loc_start = dummy_pos; loc_end = dummy_pos; loc_ghost = true };; let in_file name = let loc = { pos_fname = name; pos_lnum = 1; pos_bol = 0; pos_cnum = -1; } in { loc_start = loc; loc_end = loc; loc_ghost = true } ;; let curr lexbuf = { loc_start = lexbuf.lex_start_p; loc_end = lexbuf.lex_curr_p; loc_ghost = false };; let init lexbuf fname = lexbuf.lex_curr_p <- { pos_fname = fname; pos_lnum = 1; pos_bol = 0; pos_cnum = 0; } ;; let symbol_rloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = false; };; let symbol_gloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = true; };; let rhs_loc n = { loc_start = Parsing.rhs_start_pos n; loc_end = Parsing.rhs_end_pos n; loc_ghost = false; };; let input_name = ref "" let input_lexbuf = ref (None : lexbuf option) let status = ref Terminfo.Uninitialised let highlight_terminfo ppf num_lines lb loc1 loc2 = Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in if pos0 < 0 then raise Exit; let lines = ref !num_loc_lines in for i = pos0 to lb.lex_buffer_len - 1 do if lb.lex_buffer.[i] = '\n' then incr lines done; if !lines >= num_lines - 2 then raise Exit; flush stdout; Terminfo.backup !lines; let bol = ref false in print_string "# "; for pos = 0 to lb.lex_buffer_len - pos0 - 1 do if !bol then (print_string " "; bol := false); if pos = loc1.loc_start.pos_cnum || pos = loc2.loc_start.pos_cnum then Terminfo.standout true; if pos = loc1.loc_end.pos_cnum || pos = loc2.loc_end.pos_cnum then Terminfo.standout false; let c = lb.lex_buffer.[pos + pos0] in print_char c; bol := (c = '\n') done; Terminfo.standout false; Terminfo.resume !num_loc_lines; flush stdout let highlight_dumb ppf lb loc = Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in if pos0 < 0 then raise Exit; let end_pos = lb.lex_buffer_len - pos0 - 1 in let line_start = ref 0 and line_end = ref 0 in for pos = 0 to end_pos do if lb.lex_buffer.[pos + pos0] = '\n' then begin if loc.loc_start.pos_cnum > pos then incr line_start; if loc.loc_end.pos_cnum > pos then incr line_end; end done; Print character location ( useful for Emacs ) Format.fprintf ppf "Characters %i-%i:@." loc.loc_start.pos_cnum loc.loc_end.pos_cnum; Format.pp_print_string ppf " "; let line = ref 0 in let pos_at_bol = ref 0 in for pos = 0 to end_pos do let c = lb.lex_buffer.[pos + pos0] in if c <> '\n' then begin if !line = !line_start && !line = !line_end then loc is on one line : print whole line Format.pp_print_char ppf c else if !line = !line_start then first line of multiline loc : print ... before if pos < loc.loc_start.pos_cnum then Format.pp_print_char ppf '.' else Format.pp_print_char ppf c else if !line = !line_end then if pos < loc.loc_end.pos_cnum then Format.pp_print_char ppf c else Format.pp_print_char ppf '.' else if !line > !line_start && !line < !line_end then intermediate line of multiline loc : print whole line Format.pp_print_char ppf c end else begin if !line = !line_start && !line = !line_end then begin loc is on one line : underline location Format.fprintf ppf "@. "; for i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do Format.pp_print_char ppf ' ' done; for i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do Format.pp_print_char ppf '^' done end; if !line >= !line_start && !line <= !line_end then begin Format.fprintf ppf "@."; if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " " end; incr line; pos_at_bol := pos + 1; end done let rec highlight_locations ppf loc1 loc2 = match !status with Terminfo.Uninitialised -> status := Terminfo.setup stdout; highlight_locations ppf loc1 loc2 | Terminfo.Bad_term -> begin match !input_lexbuf with None -> false | Some lb -> let norepeat = try Sys.getenv "TERM" = "norepeat" with Not_found -> false in if norepeat then false else try highlight_dumb ppf lb loc1; true with Exit -> false end | Terminfo.Good_term num_lines -> begin match !input_lexbuf with None -> false | Some lb -> try highlight_terminfo ppf num_lines lb loc1 loc2; true with Exit -> false end open Format let reset () = num_loc_lines := 0 let (msg_file, msg_line, msg_chars, msg_to, msg_colon, msg_head) = ("File \"", "\", line ", ", characters ", "-", ":", "") let get_pos_info pos = let (filename, linenum, linebeg) = if pos.pos_fname = "" && !input_name = "" then ("", -1, 0) else if pos.pos_fname = "" then Linenum.for_position !input_name pos.pos_cnum else (pos.pos_fname, pos.pos_lnum, pos.pos_bol) in (filename, linenum, pos.pos_cnum - linebeg) ;; let print ppf loc = let (file, line, startchar) = get_pos_info loc.loc_start in let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in let (startchar, endchar) = if startchar < 0 then (0, 1) else (startchar, endchar) in if file = "" then begin if highlight_locations ppf loc none then () else fprintf ppf "Characters %i-%i:@." loc.loc_start.pos_cnum loc.loc_end.pos_cnum end else begin fprintf ppf "%s%s%s%i" msg_file file msg_line line; fprintf ppf "%s%i" msg_chars startchar; fprintf ppf "%s%i%s@.%s" msg_to endchar msg_colon msg_head; end let print_warning loc ppf w = if Warnings.is_active w then begin let printw ppf w = let n = Warnings.print ppf w in num_loc_lines := !num_loc_lines + n in fprintf ppf "%a" print loc; fprintf ppf "Warning %a@." printw w; pp_print_flush ppf (); incr num_loc_lines; end ;; let prerr_warning loc w = print_warning loc err_formatter w;; let echo_eof () = print_newline (); incr num_loc_lines
1f081e48cd86362650637b9a829f34771deee2e53f03ab264777fe6d46b18e40
oden-lang/oden
Typed.hs
module Oden.Core.Typed where import Oden.Core.Definition import Oden.Core.Expr import Oden.Core.Package import Oden.Core.ProtocolImplementation import Oden.Identifier import Oden.Type.Polymorphic data TypedMemberAccess = RecordFieldAccess TypedExpr Identifier | PackageMemberAccess Identifier Identifier deriving (Show, Eq, Ord) data TypedMethodReference = Unresolved ProtocolName MethodName ProtocolConstraint | Resolved ProtocolName MethodName (MethodImplementation TypedExpr) deriving (Show, Eq, Ord) type CanonicalExpr = (Scheme, TypedExpr) type TypedDefinition = Definition TypedExpr type TypedExpr = Expr TypedMethodReference Type TypedMemberAccess type TypedRange = Range TypedExpr data TypedPackage = TypedPackage PackageDeclaration [ImportedPackage TypedPackage] [TypedDefinition] deriving (Show, Eq, Ord)
null
https://raw.githubusercontent.com/oden-lang/oden/10c99b59c8b77c4db51ade9a4d8f9573db7f4d14/src/Oden/Core/Typed.hs
haskell
module Oden.Core.Typed where import Oden.Core.Definition import Oden.Core.Expr import Oden.Core.Package import Oden.Core.ProtocolImplementation import Oden.Identifier import Oden.Type.Polymorphic data TypedMemberAccess = RecordFieldAccess TypedExpr Identifier | PackageMemberAccess Identifier Identifier deriving (Show, Eq, Ord) data TypedMethodReference = Unresolved ProtocolName MethodName ProtocolConstraint | Resolved ProtocolName MethodName (MethodImplementation TypedExpr) deriving (Show, Eq, Ord) type CanonicalExpr = (Scheme, TypedExpr) type TypedDefinition = Definition TypedExpr type TypedExpr = Expr TypedMethodReference Type TypedMemberAccess type TypedRange = Range TypedExpr data TypedPackage = TypedPackage PackageDeclaration [ImportedPackage TypedPackage] [TypedDefinition] deriving (Show, Eq, Ord)
38b25336ad97f0ccc5bc143256a47979115fb527f585ef0952377a8d8d54fc56
Zulu-Inuoe/winutil
window.lisp
(in-package #:com.inuoe.winutil) (defvar %*windows* (make-hash-table) "Table of created `window' instances") (defclass window (d:disposable) ((%wndclass-wrapper :type wndclass-wrapper) (%hwnd-wrapper :type hwnd-wrapper)) (:documentation "Higher level interface to an `hwnd' allowing for generic function dispatch of wndproc")) (declaim (type window %*creating-window*)) (defvar %*creating-window*) (eval-when (:compile-toplevel :load-toplevel :execute) (setf (documentation '%*creating-window* 'variable) "The `window' currently being created")) (declaim (type (or null (cons cffi:foreign-pointer list)) %*wndclass-manager-hook*)) (defvar %*wndclass-manager-hook* nil) (pushnew '(%*wndclass-manager-hook* . nil) bt:*default-special-bindings* :test #'equal) (when (find-package #1='#:slynk) (pushnew '(%*wndclass-manager-hook* . nil) (symbol-value (find-symbol (string '#:*default-worker-thread-bindings*) #1#)) :test #'equal)) (defmsgproc window-manager-hook (code wparam msg) "Hook for cleaning up wndclass instances after their `window' has been destroyed." (loop :for wndclass :in (nreverse (cdr %*wndclass-manager-hook*)) :do (d:dispose wndclass)) (or (win32:unhook-windows-hook-ex (car %*wndclass-manager-hook*)) (win32-error)) (setf %*wndclass-manager-hook* nil) (win32:call-next-hook-ex (cffi:null-pointer) code wparam msg)) (defgeneric call-wndproc (window msg wparam lparam) (:method (window msg wparam lparam) "Try getting the hwnd of `window' and calling its wndproc." (let ((hwnd (hwnd window))) (cffi:foreign-funcall-pointer (cffi:make-pointer (win32:get-window-long-ptr hwnd win32:+gwl-wndproc+)) (:convention :stdcall) win32:hwnd hwnd win32:uint msg win32:wparam wparam win32:lparam lparam))) (:method :around ((window window) msg wparam lparam) ;; Guard against already-disposed windows (when (d:disposedp window) (error "The window ~A has already been disposed." window)) (call-next-method)) (:method ((window window) msg wparam lparam) "Pass to def-window-proc" ;; The window may have been disposed by a more ;; specialized method which then used `call-next-method' (if (not (d:disposedp window)) (win32:def-window-proc (hwnd window) msg wparam lparam) 0)) (:documentation "Invokes the wndproc of `window' with the given arguments.")) (defun %ensure-wndclass-manager () (unless %*wndclass-manager-hook* (setf %*wndclass-manager-hook* (list (not-null-or-error (win32:set-windows-hook-ex win32:+wh-getmessage+ (cffi:callback window-manager-hook) (cffi:null-pointer) (win32:get-current-thread-id))))))) (defwndproc %window-wndproc (hwnd msg wparam lparam) "wndproc used for `window' subclasses. Ensures correct context and dispatches to `call-wndproc'" (let ((hwnd-addr (cffi:pointer-address hwnd))) (case msg TODO - Looks like when a child window is created the first message ;; it receives is nccreate, as opposed to getminmaxinfo ;; need to investigate this more ((#.win32:+wm-getminmaxinfo+ #.win32:+wm-nccreate+) ;; Special hook to catch initial window creation (when (boundp '%*creating-window*) (setf (slot-value %*creating-window* '%hwnd-wrapper) %*creating-hwnd-wrapper* (slot-value (slot-value %*creating-window* '%hwnd-wrapper) '%hwnd) hwnd (gethash hwnd-addr %*windows*) %*creating-window*)) (call-wndproc (gethash hwnd-addr %*windows*) msg wparam lparam)) (#.win32:+wm-ncdestroy+ (let ((window (gethash hwnd-addr %*windows*))) (unwind-protect (call-wndproc window msg wparam lparam) (remhash hwnd-addr %*windows*) (slot-makunbound (slot-value window '%hwnd-wrapper) '%hwnd) (slot-makunbound window '%hwnd-wrapper) (%ensure-wndclass-manager) (push (slot-value window '%wndclass-wrapper) (cdr %*wndclass-manager-hook*)) (d:dispose window)))) (t (call-wndproc (gethash hwnd-addr %*windows*) msg wparam lparam))))) (defun %exe-name () "Get the current executable's path and type as <path>.<type>" (let ((path (exe-pathname))) (concatenate 'string (pathname-name path) "." (pathname-type path)))) (defmethod initialize-instance :after ((obj window) &key (class-style 0) (cls-extra 0) (wnd-extra 0) (instance (win32:get-module-handle (cffi:null-pointer))) (icon (cffi:null-pointer)) (cursor (win32:load-cursor (cffi:null-pointer) win32:+idc-arrow+)) (background (cffi:make-pointer (1+ win32:+color-window+))) (menu-name (cffi:null-pointer)) (icon-sm (cffi:null-pointer)) wndclass-name (ex-style win32:+ws-ex-overlapped-window+) (name "MainWindow") (style win32:+ws-overlappedwindow+) (x win32:+cw-usedefault+) (y win32:+cw-usedefault+) (width win32:+cw-usedefault+) (height win32:+cw-usedefault+) (parent (cffi:null-pointer)) (menu (cffi:null-pointer)) (lparam (cffi:null-pointer)) &allow-other-keys) (let* ((wndclass-name (or wndclass-name (format nil "Window[~A(~A);~A]" (let ((name (%exe-name))) (if (<= (length name) 128) name (subseq name 0 128))) (let ((name (bt:thread-name (bt:current-thread)))) (if (<= (length name) 64) name (subseq name 0 64))) (%make-guid)))) (wndclass-wrapper (make-instance 'wndclass-wrapper :style class-style :cls-extra cls-extra :wnd-extra wnd-extra :instance instance :icon icon :cursor cursor :background background :menu-name menu-name :icon-sm icon-sm :name wndclass-name :wndproc (cffi:callback %window-wndproc))) (success nil)) (unwind-protect (let ((%*creating-window* obj)) (setf (slot-value obj '%wndclass-wrapper) wndclass-wrapper) (let ((hwnd-wrapper (make-instance 'hwnd-wrapper :ex-style ex-style :wndclass wndclass-wrapper :name name :style style :x x :y y :width width :height height :parent parent :menu menu :instance instance :lparam lparam))) (unless (eq hwnd-wrapper (slot-value obj '%hwnd-wrapper)) (d:dispose hwnd-wrapper) (error "Window initialization failed"))) (setf success t)) (unless success (slot-makunbound obj '%wndclass-wrapper) (d:dispose wndclass-wrapper))))) (d:define-dispose (obj window) Do n't dispose wndclass - that 'll be done by ` window - manager ' , (when (slot-boundp obj '%hwnd-wrapper) (d:dispose (slot-value obj '%hwnd-wrapper)))) (defmethod hwnd ((obj window)) (hwnd (slot-value obj '%hwnd-wrapper))) (defmethod wndclass-name ((obj window)) (wndclass-name (slot-value obj '%wndclass-wrapper))) (defmethod wndclass-instance ((obj window)) (wndclass-instance (slot-value obj '%wndclass-wrapper))) (defmethod wndclass-atom ((obj window)) (wndclass-atom (slot-value obj '%wndclass-wrapper)))
null
https://raw.githubusercontent.com/Zulu-Inuoe/winutil/8f150117cc760c154dc18af38fd6603031a376f0/src/window.lisp
lisp
Guard against already-disposed windows The window may have been disposed by a more specialized method which then used `call-next-method' it receives is nccreate, as opposed to getminmaxinfo need to investigate this more Special hook to catch initial window creation
(in-package #:com.inuoe.winutil) (defvar %*windows* (make-hash-table) "Table of created `window' instances") (defclass window (d:disposable) ((%wndclass-wrapper :type wndclass-wrapper) (%hwnd-wrapper :type hwnd-wrapper)) (:documentation "Higher level interface to an `hwnd' allowing for generic function dispatch of wndproc")) (declaim (type window %*creating-window*)) (defvar %*creating-window*) (eval-when (:compile-toplevel :load-toplevel :execute) (setf (documentation '%*creating-window* 'variable) "The `window' currently being created")) (declaim (type (or null (cons cffi:foreign-pointer list)) %*wndclass-manager-hook*)) (defvar %*wndclass-manager-hook* nil) (pushnew '(%*wndclass-manager-hook* . nil) bt:*default-special-bindings* :test #'equal) (when (find-package #1='#:slynk) (pushnew '(%*wndclass-manager-hook* . nil) (symbol-value (find-symbol (string '#:*default-worker-thread-bindings*) #1#)) :test #'equal)) (defmsgproc window-manager-hook (code wparam msg) "Hook for cleaning up wndclass instances after their `window' has been destroyed." (loop :for wndclass :in (nreverse (cdr %*wndclass-manager-hook*)) :do (d:dispose wndclass)) (or (win32:unhook-windows-hook-ex (car %*wndclass-manager-hook*)) (win32-error)) (setf %*wndclass-manager-hook* nil) (win32:call-next-hook-ex (cffi:null-pointer) code wparam msg)) (defgeneric call-wndproc (window msg wparam lparam) (:method (window msg wparam lparam) "Try getting the hwnd of `window' and calling its wndproc." (let ((hwnd (hwnd window))) (cffi:foreign-funcall-pointer (cffi:make-pointer (win32:get-window-long-ptr hwnd win32:+gwl-wndproc+)) (:convention :stdcall) win32:hwnd hwnd win32:uint msg win32:wparam wparam win32:lparam lparam))) (:method :around ((window window) msg wparam lparam) (when (d:disposedp window) (error "The window ~A has already been disposed." window)) (call-next-method)) (:method ((window window) msg wparam lparam) "Pass to def-window-proc" (if (not (d:disposedp window)) (win32:def-window-proc (hwnd window) msg wparam lparam) 0)) (:documentation "Invokes the wndproc of `window' with the given arguments.")) (defun %ensure-wndclass-manager () (unless %*wndclass-manager-hook* (setf %*wndclass-manager-hook* (list (not-null-or-error (win32:set-windows-hook-ex win32:+wh-getmessage+ (cffi:callback window-manager-hook) (cffi:null-pointer) (win32:get-current-thread-id))))))) (defwndproc %window-wndproc (hwnd msg wparam lparam) "wndproc used for `window' subclasses. Ensures correct context and dispatches to `call-wndproc'" (let ((hwnd-addr (cffi:pointer-address hwnd))) (case msg TODO - Looks like when a child window is created the first message ((#.win32:+wm-getminmaxinfo+ #.win32:+wm-nccreate+) (when (boundp '%*creating-window*) (setf (slot-value %*creating-window* '%hwnd-wrapper) %*creating-hwnd-wrapper* (slot-value (slot-value %*creating-window* '%hwnd-wrapper) '%hwnd) hwnd (gethash hwnd-addr %*windows*) %*creating-window*)) (call-wndproc (gethash hwnd-addr %*windows*) msg wparam lparam)) (#.win32:+wm-ncdestroy+ (let ((window (gethash hwnd-addr %*windows*))) (unwind-protect (call-wndproc window msg wparam lparam) (remhash hwnd-addr %*windows*) (slot-makunbound (slot-value window '%hwnd-wrapper) '%hwnd) (slot-makunbound window '%hwnd-wrapper) (%ensure-wndclass-manager) (push (slot-value window '%wndclass-wrapper) (cdr %*wndclass-manager-hook*)) (d:dispose window)))) (t (call-wndproc (gethash hwnd-addr %*windows*) msg wparam lparam))))) (defun %exe-name () "Get the current executable's path and type as <path>.<type>" (let ((path (exe-pathname))) (concatenate 'string (pathname-name path) "." (pathname-type path)))) (defmethod initialize-instance :after ((obj window) &key (class-style 0) (cls-extra 0) (wnd-extra 0) (instance (win32:get-module-handle (cffi:null-pointer))) (icon (cffi:null-pointer)) (cursor (win32:load-cursor (cffi:null-pointer) win32:+idc-arrow+)) (background (cffi:make-pointer (1+ win32:+color-window+))) (menu-name (cffi:null-pointer)) (icon-sm (cffi:null-pointer)) wndclass-name (ex-style win32:+ws-ex-overlapped-window+) (name "MainWindow") (style win32:+ws-overlappedwindow+) (x win32:+cw-usedefault+) (y win32:+cw-usedefault+) (width win32:+cw-usedefault+) (height win32:+cw-usedefault+) (parent (cffi:null-pointer)) (menu (cffi:null-pointer)) (lparam (cffi:null-pointer)) &allow-other-keys) (let* ((wndclass-name (or wndclass-name (format nil "Window[~A(~A);~A]" (let ((name (%exe-name))) (if (<= (length name) 128) name (subseq name 0 128))) (let ((name (bt:thread-name (bt:current-thread)))) (if (<= (length name) 64) name (subseq name 0 64))) (%make-guid)))) (wndclass-wrapper (make-instance 'wndclass-wrapper :style class-style :cls-extra cls-extra :wnd-extra wnd-extra :instance instance :icon icon :cursor cursor :background background :menu-name menu-name :icon-sm icon-sm :name wndclass-name :wndproc (cffi:callback %window-wndproc))) (success nil)) (unwind-protect (let ((%*creating-window* obj)) (setf (slot-value obj '%wndclass-wrapper) wndclass-wrapper) (let ((hwnd-wrapper (make-instance 'hwnd-wrapper :ex-style ex-style :wndclass wndclass-wrapper :name name :style style :x x :y y :width width :height height :parent parent :menu menu :instance instance :lparam lparam))) (unless (eq hwnd-wrapper (slot-value obj '%hwnd-wrapper)) (d:dispose hwnd-wrapper) (error "Window initialization failed"))) (setf success t)) (unless success (slot-makunbound obj '%wndclass-wrapper) (d:dispose wndclass-wrapper))))) (d:define-dispose (obj window) Do n't dispose wndclass - that 'll be done by ` window - manager ' , (when (slot-boundp obj '%hwnd-wrapper) (d:dispose (slot-value obj '%hwnd-wrapper)))) (defmethod hwnd ((obj window)) (hwnd (slot-value obj '%hwnd-wrapper))) (defmethod wndclass-name ((obj window)) (wndclass-name (slot-value obj '%wndclass-wrapper))) (defmethod wndclass-instance ((obj window)) (wndclass-instance (slot-value obj '%wndclass-wrapper))) (defmethod wndclass-atom ((obj window)) (wndclass-atom (slot-value obj '%wndclass-wrapper)))