_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
|
---|---|---|---|---|---|---|---|---|
e084df6edd308e936d2f0a388be840f8aa4232e274cb5a11637b106cd1f155b4 | wdebeaum/step | vicinity.lisp | ;;;;
;;;; W::vicinity
;;;;
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::vicinity
(SENSES
((LF-PARENT ONT::loc-as-area)
(meta-data :origin cardiac :entry-date 20080509 :change-date nil :comments LM-vocab)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/vicinity.lisp | lisp |
W::vicinity
|
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::vicinity
(SENSES
((LF-PARENT ONT::loc-as-area)
(meta-data :origin cardiac :entry-date 20080509 :change-date nil :comments LM-vocab)
)
)
)
))
|
aeccc53793a3cca92cfed0839f7ab28d59c953891b1346133584dd23c0444097 | singpolyma/cheogram | StanzaRec.hs | module StanzaRec (StanzaRec(..), mkStanzaRec, ensureId) where
import Prelude ()
import BasicPrelude
import qualified Data.UUID as UUID (toText)
import qualified Data.UUID.V1 as UUID (nextUUID)
import qualified Data.XML.Types as XML
import qualified Network.Protocol.XMPP as XMPP
import Network.Protocol.XMPP.Internal (Stanza(..))
import Util
data StanzaRec = StanzaRec (Maybe XMPP.JID) (Maybe XMPP.JID) (Maybe Text) (Maybe Text) [XML.Element] XML.Element deriving (Show)
instance Stanza StanzaRec where
stanzaTo (StanzaRec to _ _ _ _ _) = to
stanzaFrom (StanzaRec _ from _ _ _ _) = from
stanzaID (StanzaRec _ _ sid _ _ _) = sid
stanzaLang (StanzaRec _ _ _ lang _ _) = lang
stanzaPayloads (StanzaRec _ _ _ _ payloads _) = payloads
stanzaToElement (StanzaRec _ _ _ _ _ element) = element
mkStanzaRec :: (Stanza s) => s -> StanzaRec
mkStanzaRec x = StanzaRec (stanzaTo x) (stanzaFrom x) (stanzaID x) (stanzaLang x) (stanzaPayloads x) (stanzaToElement x)
ensureId :: StanzaRec -> IO StanzaRec
ensureId (StanzaRec to from Nothing lang payloads element) = do
uuid <- (fmap.fmap) UUID.toText UUID.nextUUID
return $ StanzaRec to from uuid lang payloads $ element {
XML.elementAttributes =
(s"id", [XML.ContentText $ fromMaybe mempty uuid]) :
XML.elementAttributes element
}
ensureId s = return s
| null | https://raw.githubusercontent.com/singpolyma/cheogram/84d39a42227da069d6a4f0b442301eaa9b59d455/StanzaRec.hs | haskell | module StanzaRec (StanzaRec(..), mkStanzaRec, ensureId) where
import Prelude ()
import BasicPrelude
import qualified Data.UUID as UUID (toText)
import qualified Data.UUID.V1 as UUID (nextUUID)
import qualified Data.XML.Types as XML
import qualified Network.Protocol.XMPP as XMPP
import Network.Protocol.XMPP.Internal (Stanza(..))
import Util
data StanzaRec = StanzaRec (Maybe XMPP.JID) (Maybe XMPP.JID) (Maybe Text) (Maybe Text) [XML.Element] XML.Element deriving (Show)
instance Stanza StanzaRec where
stanzaTo (StanzaRec to _ _ _ _ _) = to
stanzaFrom (StanzaRec _ from _ _ _ _) = from
stanzaID (StanzaRec _ _ sid _ _ _) = sid
stanzaLang (StanzaRec _ _ _ lang _ _) = lang
stanzaPayloads (StanzaRec _ _ _ _ payloads _) = payloads
stanzaToElement (StanzaRec _ _ _ _ _ element) = element
mkStanzaRec :: (Stanza s) => s -> StanzaRec
mkStanzaRec x = StanzaRec (stanzaTo x) (stanzaFrom x) (stanzaID x) (stanzaLang x) (stanzaPayloads x) (stanzaToElement x)
ensureId :: StanzaRec -> IO StanzaRec
ensureId (StanzaRec to from Nothing lang payloads element) = do
uuid <- (fmap.fmap) UUID.toText UUID.nextUUID
return $ StanzaRec to from uuid lang payloads $ element {
XML.elementAttributes =
(s"id", [XML.ContentText $ fromMaybe mempty uuid]) :
XML.elementAttributes element
}
ensureId s = return s
|
|
376fc15b312bf35776971af66bcebf25fbbef617e6f8afc14a82a7e5bf1eb528 | haskell/stm | cloneTChan001.hs | import Control.Concurrent.STM
main = do
c <- newTChanIO
atomically $ writeTChan c 'a'
c1 <- atomically $ cloneTChan c
atomically (readTChan c) >>= print
atomically (readTChan c1) >>= print
atomically (writeTChan c 'b')
atomically (readTChan c) >>= print
atomically (readTChan c1) >>= print
| null | https://raw.githubusercontent.com/haskell/stm/319e380ab2ddfb99ab499b6783e22f2b4faaee38/tests/cloneTChan001.hs | haskell | import Control.Concurrent.STM
main = do
c <- newTChanIO
atomically $ writeTChan c 'a'
c1 <- atomically $ cloneTChan c
atomically (readTChan c) >>= print
atomically (readTChan c1) >>= print
atomically (writeTChan c 'b')
atomically (readTChan c) >>= print
atomically (readTChan c1) >>= print
|
|
a13f5d0e822a01df03fba85707811ad331015038be02f3f48d41d0e65f1eda5f | Mathieu-Desrochers/Schemings | sql-intern.scm | (import srfi-1)
(import (chicken condition))
(import (chicken format))
(declare (unit sql-intern))
(declare (uses date-time))
(declare (uses exceptions))
(declare (uses sqlite3))
binds a parameter of a sqlite3 - stmt *
(: sql-bind-parameter (pointer fixnum * -> noreturn))
(define (sql-bind-parameter sqlite3-stmt* parameter-number parameter-value)
(cond ((and (integer? parameter-value) (exact? parameter-value))
(sqlite3-bind-int sqlite3-stmt* parameter-number parameter-value))
((number? parameter-value)
(sqlite3-bind-double sqlite3-stmt* parameter-number parameter-value))
((string? parameter-value)
(sqlite3-bind-text sqlite3-stmt* parameter-number parameter-value -1 sqlite3-transient))
((not parameter-value)
(sqlite3-bind-null sqlite3-stmt* parameter-number))
(else
(abort
(format "failed to bind value ~A to parameter ?~A"
parameter-value
parameter-number)))))
binds the parameters of a sqlite3 - stmt *
(: sql-bind-parameters (pointer (list-of *) -> noreturn))
(define (sql-bind-parameters sqlite3-stmt* parameter-values)
(for-each
(lambda (parameter-index)
(let* ((parameter-number (+ parameter-index 1))
(parameter-value (list-ref parameter-values parameter-index))
(sql-bind-parameter-result
(sql-bind-parameter sqlite3-stmt* parameter-number parameter-value)))
(unless (= sql-bind-parameter-result sqlite3-result-ok)
(abort
(format "failed to bind value ~A to parameter ?~A with error code ~A"
parameter-value
parameter-number
sql-bind-parameter-result)))))
(iota (length parameter-values))))
invokes a procedure with a sqlite3 - stmt *
(: with-sqlite3-stmt* (forall (r) (pointer string (list-of *) (pointer -> r) -> r)))
(define (with-sqlite3-stmt* sqlite3* statement parameter-values procedure)
(with-guaranteed-release
(lambda ()
(let ((sqlite3-stmt** (malloc-sqlite3-stmt*)))
(unless sqlite3-stmt**
(abort "failed to allocate sqlite3-stmt*"))
sqlite3-stmt**))
(lambda (sqlite3-stmt**)
(with-guaranteed-release
(lambda ()
(let ((sqlite3-prepare-v2-result (sqlite3-prepare-v2 sqlite3* statement -1 sqlite3-stmt** #f)))
(unless (eq? sqlite3-prepare-v2-result sqlite3-result-ok)
(abort (format "failed to prepare statement ~A" statement)))
(resolve-sqlite3-stmt* sqlite3-stmt**)))
(lambda (sqlite3-stmt*)
(sql-bind-parameters sqlite3-stmt* parameter-values)
(procedure sqlite3-stmt*))
(lambda (sqlite3-stmt*)
(sqlite3-finalize sqlite3-stmt*))))
(lambda (sqlite3-stmt**)
(free-sqlite3-stmt* sqlite3-stmt**))))
reads a column from a sqlite3 - stmt *
(: sql-read-column (pointer fixnum -> *))
(define (sql-read-column sqlite3-stmt* column-index)
(let ((column-type (sqlite3-column-type sqlite3-stmt* column-index)))
(cond ((= column-type sqlite3-type-integer)
(sqlite3-column-int sqlite3-stmt* column-index))
((= column-type sqlite3-type-float)
(sqlite3-column-double sqlite3-stmt* column-index))
((= column-type sqlite3-type-text)
(sqlite3-column-text sqlite3-stmt* column-index))
((= column-type sqlite3-type-null) #f)
(else
(abort (format "failed to read column at index ~A" column-index))))))
;; reads all the rows from a sql-stmt*
(: sql-read-all-rows (pointer -> (list-of (list-of *))))
(define (sql-read-all-rows sqlite3-stmt*)
(letrec* ((columns-count (sqlite3-column-count sqlite3-stmt*))
(sql-read-row
(lambda ()
(map
(lambda (column-index)
(sql-read-column sqlite3-stmt* column-index))
(iota columns-count))))
(accumulate-rows
(lambda (rows)
(let ((sqlite3-step-result (sqlite3-step sqlite3-stmt*)))
(unless (or (= sqlite3-step-result sqlite3-result-row)
(= sqlite3-step-result sqlite3-result-done))
(abort (format "failed to read next row with error code ~A" sqlite3-step-result)))
(if (= sqlite3-step-result sqlite3-result-row)
(let ((row (sql-read-row)))
(accumulate-rows (cons row rows)))
rows)))))
(let ((rows (accumulate-rows '())))
(reverse rows))))
;; raises a deadlock exception
(: sql-raise-deadlock-exception (string -> noreturn))
(define (sql-raise-deadlock-exception statement)
(let ((condition (make-property-condition 'sql-deadlock 'statement statement)))
(abort condition)))
;; returns whether an exception was caused by a deadlock
(: sql-deadlock-exception? (condition -> boolean))
(define (sql-deadlock-exception? exception)
((condition-predicate 'sql-deadlock)
exception))
;; downgrades a value to a database supported format
(: table-value->sql-value (* symbol -> *))
(define (table-value->sql-value value value-type)
(cond ((eq? value-type 'boolean) (if value 1 0))
((not value) #f)
((eq? value-type 'date) (date->string value))
((eq? value-type 'date-time) (date-time->string value))
((eq? value-type 'time) (time->string* value))
(else value)))
;; upgrades a value from a database supported format
(: sql-value->table-value (* symbol -> *))
(define (sql-value->table-value value value-type)
(cond ((eq? value-type 'boolean) (eq? value 1))
((not value) #f)
((eq? value-type 'date) (or (try-string->date value) 'invalid-value))
((eq? value-type 'date-time) (or (try-string->date-time value) 'invalid-value))
((eq? value-type 'time) (or (try-string->time value) 'invalid-value))
(else value)))
| null | https://raw.githubusercontent.com/Mathieu-Desrochers/Schemings/a7c322ee37bf9f43b696c52fc290488aa2dcc238/sources/units/sql-intern.scm | scheme | reads all the rows from a sql-stmt*
raises a deadlock exception
returns whether an exception was caused by a deadlock
downgrades a value to a database supported format
upgrades a value from a database supported format | (import srfi-1)
(import (chicken condition))
(import (chicken format))
(declare (unit sql-intern))
(declare (uses date-time))
(declare (uses exceptions))
(declare (uses sqlite3))
binds a parameter of a sqlite3 - stmt *
(: sql-bind-parameter (pointer fixnum * -> noreturn))
(define (sql-bind-parameter sqlite3-stmt* parameter-number parameter-value)
(cond ((and (integer? parameter-value) (exact? parameter-value))
(sqlite3-bind-int sqlite3-stmt* parameter-number parameter-value))
((number? parameter-value)
(sqlite3-bind-double sqlite3-stmt* parameter-number parameter-value))
((string? parameter-value)
(sqlite3-bind-text sqlite3-stmt* parameter-number parameter-value -1 sqlite3-transient))
((not parameter-value)
(sqlite3-bind-null sqlite3-stmt* parameter-number))
(else
(abort
(format "failed to bind value ~A to parameter ?~A"
parameter-value
parameter-number)))))
binds the parameters of a sqlite3 - stmt *
(: sql-bind-parameters (pointer (list-of *) -> noreturn))
(define (sql-bind-parameters sqlite3-stmt* parameter-values)
(for-each
(lambda (parameter-index)
(let* ((parameter-number (+ parameter-index 1))
(parameter-value (list-ref parameter-values parameter-index))
(sql-bind-parameter-result
(sql-bind-parameter sqlite3-stmt* parameter-number parameter-value)))
(unless (= sql-bind-parameter-result sqlite3-result-ok)
(abort
(format "failed to bind value ~A to parameter ?~A with error code ~A"
parameter-value
parameter-number
sql-bind-parameter-result)))))
(iota (length parameter-values))))
invokes a procedure with a sqlite3 - stmt *
(: with-sqlite3-stmt* (forall (r) (pointer string (list-of *) (pointer -> r) -> r)))
(define (with-sqlite3-stmt* sqlite3* statement parameter-values procedure)
(with-guaranteed-release
(lambda ()
(let ((sqlite3-stmt** (malloc-sqlite3-stmt*)))
(unless sqlite3-stmt**
(abort "failed to allocate sqlite3-stmt*"))
sqlite3-stmt**))
(lambda (sqlite3-stmt**)
(with-guaranteed-release
(lambda ()
(let ((sqlite3-prepare-v2-result (sqlite3-prepare-v2 sqlite3* statement -1 sqlite3-stmt** #f)))
(unless (eq? sqlite3-prepare-v2-result sqlite3-result-ok)
(abort (format "failed to prepare statement ~A" statement)))
(resolve-sqlite3-stmt* sqlite3-stmt**)))
(lambda (sqlite3-stmt*)
(sql-bind-parameters sqlite3-stmt* parameter-values)
(procedure sqlite3-stmt*))
(lambda (sqlite3-stmt*)
(sqlite3-finalize sqlite3-stmt*))))
(lambda (sqlite3-stmt**)
(free-sqlite3-stmt* sqlite3-stmt**))))
reads a column from a sqlite3 - stmt *
(: sql-read-column (pointer fixnum -> *))
(define (sql-read-column sqlite3-stmt* column-index)
(let ((column-type (sqlite3-column-type sqlite3-stmt* column-index)))
(cond ((= column-type sqlite3-type-integer)
(sqlite3-column-int sqlite3-stmt* column-index))
((= column-type sqlite3-type-float)
(sqlite3-column-double sqlite3-stmt* column-index))
((= column-type sqlite3-type-text)
(sqlite3-column-text sqlite3-stmt* column-index))
((= column-type sqlite3-type-null) #f)
(else
(abort (format "failed to read column at index ~A" column-index))))))
(: sql-read-all-rows (pointer -> (list-of (list-of *))))
(define (sql-read-all-rows sqlite3-stmt*)
(letrec* ((columns-count (sqlite3-column-count sqlite3-stmt*))
(sql-read-row
(lambda ()
(map
(lambda (column-index)
(sql-read-column sqlite3-stmt* column-index))
(iota columns-count))))
(accumulate-rows
(lambda (rows)
(let ((sqlite3-step-result (sqlite3-step sqlite3-stmt*)))
(unless (or (= sqlite3-step-result sqlite3-result-row)
(= sqlite3-step-result sqlite3-result-done))
(abort (format "failed to read next row with error code ~A" sqlite3-step-result)))
(if (= sqlite3-step-result sqlite3-result-row)
(let ((row (sql-read-row)))
(accumulate-rows (cons row rows)))
rows)))))
(let ((rows (accumulate-rows '())))
(reverse rows))))
(: sql-raise-deadlock-exception (string -> noreturn))
(define (sql-raise-deadlock-exception statement)
(let ((condition (make-property-condition 'sql-deadlock 'statement statement)))
(abort condition)))
(: sql-deadlock-exception? (condition -> boolean))
(define (sql-deadlock-exception? exception)
((condition-predicate 'sql-deadlock)
exception))
(: table-value->sql-value (* symbol -> *))
(define (table-value->sql-value value value-type)
(cond ((eq? value-type 'boolean) (if value 1 0))
((not value) #f)
((eq? value-type 'date) (date->string value))
((eq? value-type 'date-time) (date-time->string value))
((eq? value-type 'time) (time->string* value))
(else value)))
(: sql-value->table-value (* symbol -> *))
(define (sql-value->table-value value value-type)
(cond ((eq? value-type 'boolean) (eq? value 1))
((not value) #f)
((eq? value-type 'date) (or (try-string->date value) 'invalid-value))
((eq? value-type 'date-time) (or (try-string->date-time value) 'invalid-value))
((eq? value-type 'time) (or (try-string->time value) 'invalid-value))
(else value)))
|
0d404892b39f379635fb6833bdebe2710666e1fc37310bdfbd29b374b218c22e | S8A/htdp-exercises | ex393.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex393) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; A Son.R is one of:
; – empty
– ( cons Number Son . R )
;
; Constraint If s is a Son.R,
; no number occurs twice in s
; Son
(define es '())
; Number Son -> Boolean
; is x in s
(define (in? x s) (member? x s))
; Son Son -> Son
Produces a set that contains all the elements of set1 and set2
(define (union set1 set2)
(cond
[ ( and ( empty ? set1 ) ( empty ? set2 ) ) ' ( ) ]
[ ( and ( empty ? set1 ) ( cons ? set2 ) ) set2 ]
[ ( and ( cons ? set1 ) ( empty ? set2 ) ) set1 ]
[ ( and ( cons ? set1 ) ( cons ? set2 ) )
[(empty? set1) set2]
[(cons? set1)
(local ((define first-set1 (first set1)))
(if (in? first-set1 set2)
(union (rest set1) set2)
(cons first-set1 (union (rest set1) set2))))]))
(check-expect (union '() '()) '())
(check-expect (union '() '(0 2 4 6)) '(0 2 4 6))
(check-expect (union '(0 1 3 5 6 7 9) '()) '(0 1 3 5 6 7 9))
(check-expect (union '(0 1 3 5 6 7 9) '(0 2 4 6)) '(1 3 5 7 9 0 2 4 6))
; Son Son -> Son
Produces a set that contains the elements that are both in set1 and set2
(define (intersect set1 set2)
(cond
[ ( and ( empty ? set1 ) ( empty ? set2 ) ) ' ( ) ]
[ ( and ( empty ? set1 ) ( cons ? set2 ) ) ' ( ) ]
[ ( and ( cons ? set1 ) ( empty ? set2 ) ) ' ( ) ]
[ ( and ( cons ? set1 ) ( cons ? set2 ) )
[(empty? set1) '()]
[(cons? set1)
(local ((define first-set1 (first set1)))
(if (in? first-set1 set2)
(cons first-set1
(intersect (rest set1) (remove-all first-set1 set2)))
(intersect (rest set1) set2)))]))
(check-expect (intersect '() '()) '())
(check-expect (intersect '() '(0 2 4 6)) '())
(check-expect (intersect '(0 1 3 5 6 7 9) '()) '())
(check-expect (intersect '(0 1 3 5 6 7 9) '(0 2 4 6)) '(0 6))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex393.rkt | racket | about the language level of this file in a form that our tools can easily process.
A Son.R is one of:
– empty
Constraint If s is a Son.R,
no number occurs twice in s
Son
Number Son -> Boolean
is x in s
Son Son -> Son
Son Son -> Son | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex393) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
– ( cons Number Son . R )
(define es '())
(define (in? x s) (member? x s))
Produces a set that contains all the elements of set1 and set2
(define (union set1 set2)
(cond
[ ( and ( empty ? set1 ) ( empty ? set2 ) ) ' ( ) ]
[ ( and ( empty ? set1 ) ( cons ? set2 ) ) set2 ]
[ ( and ( cons ? set1 ) ( empty ? set2 ) ) set1 ]
[ ( and ( cons ? set1 ) ( cons ? set2 ) )
[(empty? set1) set2]
[(cons? set1)
(local ((define first-set1 (first set1)))
(if (in? first-set1 set2)
(union (rest set1) set2)
(cons first-set1 (union (rest set1) set2))))]))
(check-expect (union '() '()) '())
(check-expect (union '() '(0 2 4 6)) '(0 2 4 6))
(check-expect (union '(0 1 3 5 6 7 9) '()) '(0 1 3 5 6 7 9))
(check-expect (union '(0 1 3 5 6 7 9) '(0 2 4 6)) '(1 3 5 7 9 0 2 4 6))
Produces a set that contains the elements that are both in set1 and set2
(define (intersect set1 set2)
(cond
[ ( and ( empty ? set1 ) ( empty ? set2 ) ) ' ( ) ]
[ ( and ( empty ? set1 ) ( cons ? set2 ) ) ' ( ) ]
[ ( and ( cons ? set1 ) ( empty ? set2 ) ) ' ( ) ]
[ ( and ( cons ? set1 ) ( cons ? set2 ) )
[(empty? set1) '()]
[(cons? set1)
(local ((define first-set1 (first set1)))
(if (in? first-set1 set2)
(cons first-set1
(intersect (rest set1) (remove-all first-set1 set2)))
(intersect (rest set1) set2)))]))
(check-expect (intersect '() '()) '())
(check-expect (intersect '() '(0 2 4 6)) '())
(check-expect (intersect '(0 1 3 5 6 7 9) '()) '())
(check-expect (intersect '(0 1 3 5 6 7 9) '(0 2 4 6)) '(0 6))
|
e2ca36b7b14c678193c5620faec9a7b9ea44b210bc74c09a287f4f447f70f07d | SoftwareFoundationGroupAtKyotoU/SystemFg | pp.ml | open Format
open Syntax
open Eval
let pr = fprintf
(* generic functions to generate parens depending on precedence *)
let with_paren gt ppf_e e_up ppf e =
let (>) = gt in
if e_up > e then pr ppf "(%a)" ppf_e e else pr ppf "%a" ppf_e e
(* if t is the left/only operand of t_up, do you need parentheses for t? *)
let (<) t t_up = match t, t_up with
(* -> is right associative;
forall extends to the right as far as possible
T list is left associative and binds tighter than ->:
*)
| (Arr(_,_) | Forall(_,_)), (Arr(_,_) | List _) -> true
| _ -> false
(* if t is the right operand of t_up, do you need parentheses for t? *)
let (>) t_up t = false
let rec print_type ctx ppf t =
let with_paren_L = with_paren (fun e_up e -> e < e_up)
and with_paren_R = with_paren (>) in
match t with
Int -> pp_print_string ppf "int"
| Bool -> pp_print_string ppf "bool"
| Dyn -> pp_print_string ppf "?"
| Arr(t1, t2) ->
pr ppf "%a -> %a"
(with_paren_L (print_type ctx) t) t1
(with_paren_R (print_type ctx) t) t2
| Forall(id, t0) ->
pr ppf "All %s%a" id (print_forall ((id,STVar)::ctx)) t0
| List t0 ->
pr ppf "%a list" (with_paren_L (print_type ctx) t) t0
| TyVar i -> pp_print_string ppf (fst (List.nth ctx i))
and print_forall ctx ppf t =
match t with
Forall(id, t0) -> pr ppf " %s%a" id (print_forall ((id,STVar)::ctx)) t0
| _ -> pr ppf ". %a" (print_type ctx) t
let rec print_val ppf = function
IntV i -> pp_print_int ppf i
| BoolV true -> pp_print_string ppf "true"
| BoolV false -> pp_print_string ppf "false"
| Fun _ -> pp_print_string ppf "<fun>"
| TFun _ -> pp_print_string ppf "<tfun>"
| Tagged(I, v, _) -> pr ppf "%a : Int => ?" print_val v
| Tagged(B, v, _) -> pr ppf "%a : Bool => ?" print_val v
| Tagged(Ar, v, _) -> pr ppf "%a : ?->? => ?" print_val v
| Tagged(L, v, _) -> pr ppf "%a : ? list => ?" print_val v
| Tagged(TV (_,name), v, _) -> pr ppf "%a : %s => ?" print_val v name
| NilV | ConsV(_,_) as lst -> pr ppf "[%a]" print_lst lst
and print_lst ppf = function
NilV -> ()
| ConsV(v1, NilV) -> pr ppf "%a" print_val v1
| ConsV(v1, v2) -> pr ppf "%a; %a" print_val v1 print_lst v2
| v -> raise (ImplBugV (Lexing.dummy_pos, "print_lst: nonlist value", v))
TODO : recover the tyvar name
let rec print_rawtype ppf t =
let with_paren_L = with_paren (fun e_up e -> e < e_up)
and with_paren_R = with_paren (>) in
match t with
Int -> pp_print_string ppf "int"
| Bool -> pp_print_string ppf "bool"
| Dyn -> pp_print_string ppf "?"
| Arr(t1, t2) ->
pr ppf "%a -> %a"
(with_paren_L print_rawtype t) t1
(with_paren_R print_rawtype t) t2
| Forall(id, t0) ->
pr ppf "All %s%a" id print_rawforall t0
| List t0 ->
pr ppf "%a list" (with_paren_L print_rawtype t) t0
| TyVar i -> pr ppf "#%d" i
and print_rawforall ppf t =
match t with
Forall(id, t0) -> pr ppf " %s%a" id print_rawforall t0
| _ -> pr ppf ". %a" print_rawtype t
let print_op ppf = function
Plus -> pr ppf " + "
| Mult -> pr ppf " * "
| Lt -> pr ppf " < "
| Eq -> pr ppf " = "
let rec print_rawterm ppf =
let open Syntax.FG in
function
Var (_, i) -> pr ppf "#%d" i
| IConst (_, i) -> pr ppf "%d" i
| BConst (_, true) -> pp_print_string ppf "true"
| BConst (_, false) -> pp_print_string ppf "false"
| BinOp (_, op, t1, t2) -> pr ppf "(%a %a %a)" print_rawterm t1 print_op op print_rawterm t2
| IfExp (_, t1, t2, t3) ->
pr ppf "if %a then %a else %a" print_rawterm t1 print_rawterm t2 print_rawterm t3
| FunExp (_, id, ty, t0) ->
pr ppf "fun (%s : %a) -> %a" id print_rawtype ty print_rawterm t0
| FixExp (_, id1, id2, ty1, ty2, t0) ->
pr ppf "fix %s(%s : %a) : %a = %a" id1 id2 print_rawtype ty1 print_rawtype ty2 print_rawterm t0
| AppExp (_, t1, t2) ->
pr ppf "(%a) (%a)" print_rawterm t1 print_rawterm t2
| TFunExp (_, id, t0) ->
pr ppf "fun %s -> %a" id print_rawterm t0
| TAppExp (_, t0, ty) ->
pr ppf "%a [%a]" print_rawterm t0 print_rawtype ty
| LetExp (_, id, t1, t2) ->
pr ppf "let %s = %a in %a" id print_rawterm t1 print_rawterm t2
| AscExp (_, t0, ty) ->
pr ppf "(%a : %a)" print_rawterm t0 print_rawtype ty
| CastExp (_, t0, ty1, ty2) ->
pr ppf "(%a : %a => %a)" print_rawterm t0 print_rawtype ty1 print_rawtype ty2
| NilExp (_, ty) -> pr ppf "[@%a]" print_rawtype ty
| ConsExp (_, t1, t2) -> pr ppf "(%a) :: (%a)" print_rawterm t1 print_rawterm t2
| MatchExp (_, t1, t2, id1, id2, t3) ->
pr ppf "match %a with [] -> %a | %s::%s -> %a" print_rawterm t1 print_rawterm t2 id1 id2 print_rawterm t3
let print_rawdecl ppf = function
Syntax.FG.Prog t -> print_rawterm ppf t
| Syntax.FG.Decl (id, t) -> pr ppf "let %s = %a" id print_rawterm t
let print_ctx ppf ctx = List.iter (fun (id,_) -> pr ppf "%s, " id) ctx
module FC =
struct
let rec print_rawterm ppf =
let open Syntax.FC in
function
Var (_, i) -> pr ppf "#%d" i
| IConst (_, i) -> pr ppf "%d" i
| BConst (_, true) -> pp_print_string ppf "true"
| BConst (_, false) -> pp_print_string ppf "false"
| BinOp (_, op, t1, t2) -> pr ppf "(%a %a %a)" print_rawterm t1 print_op op print_rawterm t2
| IfExp (_, t1, t2, t3) ->
pr ppf "if %a then %a else %a" print_rawterm t1 print_rawterm t2 print_rawterm t3
| (FunExp (_, _, _, _) | TSFunExp (_, _, _) | TGFunExp(_, _, _)) as t ->
pr ppf "fun %a" print_fun t
| FixExp (_, id1, id2, ty1, ty2, t0) ->
pr ppf "fix %s(%s : %a) : %a = %a" id1 id2 print_rawtype ty1 print_rawtype ty2 print_rawterm t0
| AppExp (_, t1, t2) ->
pr ppf "(%a) (%a)" print_rawterm t1 print_rawterm t2
| TAppExp (_, t0, ty) ->
pr ppf "%a [%a]" print_rawterm t0 print_rawtype ty
| CastExp (_, t0, ty1, ty2) ->
pr ppf "(%a : %a => %a)" print_rawterm t0 print_rawtype ty1 print_rawtype ty2
| NilExp (_, ty) -> pr ppf "[@%a]" print_rawtype ty
| ConsExp (_, t1, t2) -> pr ppf "(%a) :: (%a)" print_rawterm t1 print_rawterm t2
| MatchExp (_, t1, t2, id1, id2, t3) ->
pr ppf "match %a with [] -> %a | %s::%s -> %a" print_rawterm t1 print_rawterm t2 id1 id2 print_rawterm t3
and print_fun ppf =
let open Syntax.FC in
function
| FunExp (_, id, ty, t0) ->
pr ppf "(%s : %a) %a" id print_rawtype ty print_fun t0
| TSFunExp (_, id, t0) ->
pr ppf "%s %a" id print_fun t0
| TGFunExp (_, id, t0) ->
pr ppf "_%s_ %a" id print_fun t0
| t ->
pr ppf "-> %a" print_rawterm t
let print_rawdecl ppf = function
Syntax.FC.Prog t -> print_rawterm ppf t
| Syntax.FC.Decl (id, t) -> pr ppf "let %s = %a" id print_rawterm t
end
| null | https://raw.githubusercontent.com/SoftwareFoundationGroupAtKyotoU/SystemFg/b703ed6b7648e081f9476348787a476ded856141/pp.ml | ocaml | generic functions to generate parens depending on precedence
if t is the left/only operand of t_up, do you need parentheses for t?
-> is right associative;
forall extends to the right as far as possible
T list is left associative and binds tighter than ->:
if t is the right operand of t_up, do you need parentheses for t? | open Format
open Syntax
open Eval
let pr = fprintf
let with_paren gt ppf_e e_up ppf e =
let (>) = gt in
if e_up > e then pr ppf "(%a)" ppf_e e else pr ppf "%a" ppf_e e
let (<) t t_up = match t, t_up with
| (Arr(_,_) | Forall(_,_)), (Arr(_,_) | List _) -> true
| _ -> false
let (>) t_up t = false
let rec print_type ctx ppf t =
let with_paren_L = with_paren (fun e_up e -> e < e_up)
and with_paren_R = with_paren (>) in
match t with
Int -> pp_print_string ppf "int"
| Bool -> pp_print_string ppf "bool"
| Dyn -> pp_print_string ppf "?"
| Arr(t1, t2) ->
pr ppf "%a -> %a"
(with_paren_L (print_type ctx) t) t1
(with_paren_R (print_type ctx) t) t2
| Forall(id, t0) ->
pr ppf "All %s%a" id (print_forall ((id,STVar)::ctx)) t0
| List t0 ->
pr ppf "%a list" (with_paren_L (print_type ctx) t) t0
| TyVar i -> pp_print_string ppf (fst (List.nth ctx i))
and print_forall ctx ppf t =
match t with
Forall(id, t0) -> pr ppf " %s%a" id (print_forall ((id,STVar)::ctx)) t0
| _ -> pr ppf ". %a" (print_type ctx) t
let rec print_val ppf = function
IntV i -> pp_print_int ppf i
| BoolV true -> pp_print_string ppf "true"
| BoolV false -> pp_print_string ppf "false"
| Fun _ -> pp_print_string ppf "<fun>"
| TFun _ -> pp_print_string ppf "<tfun>"
| Tagged(I, v, _) -> pr ppf "%a : Int => ?" print_val v
| Tagged(B, v, _) -> pr ppf "%a : Bool => ?" print_val v
| Tagged(Ar, v, _) -> pr ppf "%a : ?->? => ?" print_val v
| Tagged(L, v, _) -> pr ppf "%a : ? list => ?" print_val v
| Tagged(TV (_,name), v, _) -> pr ppf "%a : %s => ?" print_val v name
| NilV | ConsV(_,_) as lst -> pr ppf "[%a]" print_lst lst
and print_lst ppf = function
NilV -> ()
| ConsV(v1, NilV) -> pr ppf "%a" print_val v1
| ConsV(v1, v2) -> pr ppf "%a; %a" print_val v1 print_lst v2
| v -> raise (ImplBugV (Lexing.dummy_pos, "print_lst: nonlist value", v))
TODO : recover the tyvar name
let rec print_rawtype ppf t =
let with_paren_L = with_paren (fun e_up e -> e < e_up)
and with_paren_R = with_paren (>) in
match t with
Int -> pp_print_string ppf "int"
| Bool -> pp_print_string ppf "bool"
| Dyn -> pp_print_string ppf "?"
| Arr(t1, t2) ->
pr ppf "%a -> %a"
(with_paren_L print_rawtype t) t1
(with_paren_R print_rawtype t) t2
| Forall(id, t0) ->
pr ppf "All %s%a" id print_rawforall t0
| List t0 ->
pr ppf "%a list" (with_paren_L print_rawtype t) t0
| TyVar i -> pr ppf "#%d" i
and print_rawforall ppf t =
match t with
Forall(id, t0) -> pr ppf " %s%a" id print_rawforall t0
| _ -> pr ppf ". %a" print_rawtype t
let print_op ppf = function
Plus -> pr ppf " + "
| Mult -> pr ppf " * "
| Lt -> pr ppf " < "
| Eq -> pr ppf " = "
let rec print_rawterm ppf =
let open Syntax.FG in
function
Var (_, i) -> pr ppf "#%d" i
| IConst (_, i) -> pr ppf "%d" i
| BConst (_, true) -> pp_print_string ppf "true"
| BConst (_, false) -> pp_print_string ppf "false"
| BinOp (_, op, t1, t2) -> pr ppf "(%a %a %a)" print_rawterm t1 print_op op print_rawterm t2
| IfExp (_, t1, t2, t3) ->
pr ppf "if %a then %a else %a" print_rawterm t1 print_rawterm t2 print_rawterm t3
| FunExp (_, id, ty, t0) ->
pr ppf "fun (%s : %a) -> %a" id print_rawtype ty print_rawterm t0
| FixExp (_, id1, id2, ty1, ty2, t0) ->
pr ppf "fix %s(%s : %a) : %a = %a" id1 id2 print_rawtype ty1 print_rawtype ty2 print_rawterm t0
| AppExp (_, t1, t2) ->
pr ppf "(%a) (%a)" print_rawterm t1 print_rawterm t2
| TFunExp (_, id, t0) ->
pr ppf "fun %s -> %a" id print_rawterm t0
| TAppExp (_, t0, ty) ->
pr ppf "%a [%a]" print_rawterm t0 print_rawtype ty
| LetExp (_, id, t1, t2) ->
pr ppf "let %s = %a in %a" id print_rawterm t1 print_rawterm t2
| AscExp (_, t0, ty) ->
pr ppf "(%a : %a)" print_rawterm t0 print_rawtype ty
| CastExp (_, t0, ty1, ty2) ->
pr ppf "(%a : %a => %a)" print_rawterm t0 print_rawtype ty1 print_rawtype ty2
| NilExp (_, ty) -> pr ppf "[@%a]" print_rawtype ty
| ConsExp (_, t1, t2) -> pr ppf "(%a) :: (%a)" print_rawterm t1 print_rawterm t2
| MatchExp (_, t1, t2, id1, id2, t3) ->
pr ppf "match %a with [] -> %a | %s::%s -> %a" print_rawterm t1 print_rawterm t2 id1 id2 print_rawterm t3
let print_rawdecl ppf = function
Syntax.FG.Prog t -> print_rawterm ppf t
| Syntax.FG.Decl (id, t) -> pr ppf "let %s = %a" id print_rawterm t
let print_ctx ppf ctx = List.iter (fun (id,_) -> pr ppf "%s, " id) ctx
module FC =
struct
let rec print_rawterm ppf =
let open Syntax.FC in
function
Var (_, i) -> pr ppf "#%d" i
| IConst (_, i) -> pr ppf "%d" i
| BConst (_, true) -> pp_print_string ppf "true"
| BConst (_, false) -> pp_print_string ppf "false"
| BinOp (_, op, t1, t2) -> pr ppf "(%a %a %a)" print_rawterm t1 print_op op print_rawterm t2
| IfExp (_, t1, t2, t3) ->
pr ppf "if %a then %a else %a" print_rawterm t1 print_rawterm t2 print_rawterm t3
| (FunExp (_, _, _, _) | TSFunExp (_, _, _) | TGFunExp(_, _, _)) as t ->
pr ppf "fun %a" print_fun t
| FixExp (_, id1, id2, ty1, ty2, t0) ->
pr ppf "fix %s(%s : %a) : %a = %a" id1 id2 print_rawtype ty1 print_rawtype ty2 print_rawterm t0
| AppExp (_, t1, t2) ->
pr ppf "(%a) (%a)" print_rawterm t1 print_rawterm t2
| TAppExp (_, t0, ty) ->
pr ppf "%a [%a]" print_rawterm t0 print_rawtype ty
| CastExp (_, t0, ty1, ty2) ->
pr ppf "(%a : %a => %a)" print_rawterm t0 print_rawtype ty1 print_rawtype ty2
| NilExp (_, ty) -> pr ppf "[@%a]" print_rawtype ty
| ConsExp (_, t1, t2) -> pr ppf "(%a) :: (%a)" print_rawterm t1 print_rawterm t2
| MatchExp (_, t1, t2, id1, id2, t3) ->
pr ppf "match %a with [] -> %a | %s::%s -> %a" print_rawterm t1 print_rawterm t2 id1 id2 print_rawterm t3
and print_fun ppf =
let open Syntax.FC in
function
| FunExp (_, id, ty, t0) ->
pr ppf "(%s : %a) %a" id print_rawtype ty print_fun t0
| TSFunExp (_, id, t0) ->
pr ppf "%s %a" id print_fun t0
| TGFunExp (_, id, t0) ->
pr ppf "_%s_ %a" id print_fun t0
| t ->
pr ppf "-> %a" print_rawterm t
let print_rawdecl ppf = function
Syntax.FC.Prog t -> print_rawterm ppf t
| Syntax.FC.Decl (id, t) -> pr ppf "let %s = %a" id print_rawterm t
end
|
2668ca985df66bd71c5661d1b43e33bf79c275289c52efde037f2d57d74615fd | vbmithr/breakbot | jsonrpc_utils.ml |
* Copyright ( c ) 2012 < >
*
* 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) 2012 Vincent Bernardoff <>
*
* 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.
*
*)
open Utils
open Lwt_utils
module CU = Cohttp_lwt_unix
module CB = Cohttp_lwt_body
module Rpc = struct
include Rpc
let rec filter_null = function
| Enum l -> Enum (List.map filter_null l)
| Dict d -> Dict (
List.map (fun (s,v) -> s, filter_null v) @@
List.filter (fun (s,v) -> v <> Null) d)
| oth -> oth
let rec int_to_float = function
| Enum l -> Enum (List.map int_to_float l)
| Dict d -> Dict (List.map (fun (s,v) -> s, int_to_float v) d)
| Int i -> Float (Int64.to_float i)
| oth -> oth
end
module Jsonrpc = struct
include Jsonrpc
let get ?(transform=fun i -> i) url =
lwt resp, body = Lwt.bind_opt @@ CU.Client.get url in
lwt body_str = CB.string_of_body body in
let rpc = of_string body_str in Lwt.wrap (fun () -> transform rpc)
let get_filter_null = get ~transform:Rpc.filter_null
let get_int_to_float = get ~transform:Rpc.int_to_float
end
| null | https://raw.githubusercontent.com/vbmithr/breakbot/eb82e36174d0bec97a4af197d518afcd323536b6/lib/jsonrpc_utils.ml | ocaml |
* Copyright ( c ) 2012 < >
*
* 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) 2012 Vincent Bernardoff <>
*
* 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.
*
*)
open Utils
open Lwt_utils
module CU = Cohttp_lwt_unix
module CB = Cohttp_lwt_body
module Rpc = struct
include Rpc
let rec filter_null = function
| Enum l -> Enum (List.map filter_null l)
| Dict d -> Dict (
List.map (fun (s,v) -> s, filter_null v) @@
List.filter (fun (s,v) -> v <> Null) d)
| oth -> oth
let rec int_to_float = function
| Enum l -> Enum (List.map int_to_float l)
| Dict d -> Dict (List.map (fun (s,v) -> s, int_to_float v) d)
| Int i -> Float (Int64.to_float i)
| oth -> oth
end
module Jsonrpc = struct
include Jsonrpc
let get ?(transform=fun i -> i) url =
lwt resp, body = Lwt.bind_opt @@ CU.Client.get url in
lwt body_str = CB.string_of_body body in
let rpc = of_string body_str in Lwt.wrap (fun () -> transform rpc)
let get_filter_null = get ~transform:Rpc.filter_null
let get_int_to_float = get ~transform:Rpc.int_to_float
end
|
|
02fcee9d57817d111c5d052f048c1d34be6b99d525996b9e39d310da68ec15d0 | atolab/zenoh | channel.ml |
* Copyright ( c ) 2017 , 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0 , or the Apache License , Version 2.0
* which is available at -2.0 .
*
* SPDX - License - Identifier : EPL-2.0 OR Apache-2.0
*
* Contributors :
* team , < >
* Copyright (c) 2017, 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0, or the Apache License, Version 2.0
* which is available at -2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*
* Contributors:
* ADLINK zenoh team, <>
*)
open Apero
(** NOTE: The current channel implementation uses only the default conduit,
this should be extended to support arbitrary number of conduits. *)
module InChannel : sig
type t
val create : Vle.t -> t
val rsn : t -> Vle.t
val usn : t -> Vle.t
val update_rsn : t -> Vle.t -> unit
val update_usn : t -> Vle.t -> unit
val sn_max : t -> Vle.t
end = struct
type t = { sn_max: Vle.t; mutable rsn : Vle.t; mutable usn : Vle.t }
let create sn_max = {sn_max; rsn = 0L ; usn = 0L }
let rsn c = c.rsn
let usn c = c.usn
let update_rsn c sn = c.rsn <- sn
let update_usn c sn = c.usn <- sn
let sn_max c = c.sn_max
end
module OutChannel : sig
type t
val create : Vle.t -> t
val rsn : t -> Vle.t
val usn : t -> Vle.t
val sn_max : t -> Vle.t
val next_rsn : t -> Vle.t
val next_usn : t -> Vle.t
end = struct
type t = {sn_max: Vle.t; mutable rsn : Vle.t; mutable usn : Vle.t}
let create sn_max = { sn_max; rsn = 0L; usn = 0L }
let rsn c = c.rsn
let usn c = c.usn
let sn_max c = c.sn_max
let next_rsn c =
let n = c.rsn in
c.rsn <- Vle.add c.rsn 1L ; n
let next_usn c =
let n = c.usn in
c.usn <- Vle.add c.usn 1L ; n
end
| null | https://raw.githubusercontent.com/atolab/zenoh/32e311aae6be93c001fd725b4d918b2fb4e9713d/src/zenoh-proto/channel.ml | ocaml | * NOTE: The current channel implementation uses only the default conduit,
this should be extended to support arbitrary number of conduits. |
* Copyright ( c ) 2017 , 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0 , or the Apache License , Version 2.0
* which is available at -2.0 .
*
* SPDX - License - Identifier : EPL-2.0 OR Apache-2.0
*
* Contributors :
* team , < >
* Copyright (c) 2017, 2020 ADLINK Technology Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* -2.0, or the Apache License, Version 2.0
* which is available at -2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*
* Contributors:
* ADLINK zenoh team, <>
*)
open Apero
module InChannel : sig
type t
val create : Vle.t -> t
val rsn : t -> Vle.t
val usn : t -> Vle.t
val update_rsn : t -> Vle.t -> unit
val update_usn : t -> Vle.t -> unit
val sn_max : t -> Vle.t
end = struct
type t = { sn_max: Vle.t; mutable rsn : Vle.t; mutable usn : Vle.t }
let create sn_max = {sn_max; rsn = 0L ; usn = 0L }
let rsn c = c.rsn
let usn c = c.usn
let update_rsn c sn = c.rsn <- sn
let update_usn c sn = c.usn <- sn
let sn_max c = c.sn_max
end
module OutChannel : sig
type t
val create : Vle.t -> t
val rsn : t -> Vle.t
val usn : t -> Vle.t
val sn_max : t -> Vle.t
val next_rsn : t -> Vle.t
val next_usn : t -> Vle.t
end = struct
type t = {sn_max: Vle.t; mutable rsn : Vle.t; mutable usn : Vle.t}
let create sn_max = { sn_max; rsn = 0L; usn = 0L }
let rsn c = c.rsn
let usn c = c.usn
let sn_max c = c.sn_max
let next_rsn c =
let n = c.rsn in
c.rsn <- Vle.add c.rsn 1L ; n
let next_usn c =
let n = c.usn in
c.usn <- Vle.add c.usn 1L ; n
end
|
1a8c1f38740d422adfb32dc85b8595a9a47030ac3d3b140b0df83721da046972 | qmuli/qmuli | Lang.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module Qi.Program.CF.Lang (
StackName(StackName)
, CfEff (..)
, createStack
, describeStacks
, updateStack
, deleteStack
, waitOnStackStatus
, StackStatus(..)
, AbsentDirective(..)
, StackDescription(..)
, StackDescriptionDict
)where
import Control.Monad.Freer
import Data.Aeson hiding ((.:))
import qualified Data.ByteString.Lazy as LBS
import Data.HashMap.Strict (fromList)
import Data.Map (Map)
import Network.AWS.CloudFormation (StackStatus (..))
import Network.AWS.S3.Types (ETag)
import Protolude
import Qi.Config.AWS.CF
import Qi.Config.AWS.S3
import Qi.Config.Identifier
import Qi.Core.Curry
import Qi.Program.Gen.Lang
type StackDescriptionDict = Map StackName StackDescription
newtype StackName = StackName Text
deriving (Eq, Show, Ord, ToJSON)
data StackDescription = StackDescription {
status :: StackStatus
, outputs :: [(Text, Text)]
} deriving (Show)
instance ToJSON StackDescription where
toJSON StackDescription{ status, outputs } =
object [ "status" .= String (show status :: Text)
, "outputs" .= (Object $ fromList $ second String <$> outputs)
]
data AbsentDirective = AbsentOk | NoAbsent
deriving Eq
data CfEff r where
CreateStack
:: StackName
-> LBS.ByteString
-> CfEff ()
DescribeStacks
:: CfEff StackDescriptionDict
UpdateStack
:: StackName
-> LBS.ByteString
-> CfEff ()
DeleteStack
:: StackName
-> CfEff ()
WaitOnStackStatus
:: StackName
-> StackStatus
-> AbsentDirective
-> CfEff ()
createStack
:: (Member CfEff effs)
=> StackName
-> LBS.ByteString -- S3Object
-> Eff effs ()
createStack = send .: CreateStack
describeStacks
:: (Member CfEff effs)
=> Eff effs StackDescriptionDict
describeStacks = send DescribeStacks
updateStack
:: (Member CfEff effs)
=> StackName
-> LBS.ByteString
-> Eff effs ()
updateStack = send .: UpdateStack
deleteStack
:: (Member CfEff effs)
=> StackName
-> Eff effs ()
deleteStack = send . DeleteStack
waitOnStackStatus
:: (Member CfEff effs)
=> StackName
-> StackStatus
-> AbsentDirective
-> Eff effs ()
waitOnStackStatus = send .:: WaitOnStackStatus
| null | https://raw.githubusercontent.com/qmuli/qmuli/6ca147f94642b81ab3978d502397efb60a50215b/library/Qi/Program/CF/Lang.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators #
S3Object | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
module Qi.Program.CF.Lang (
StackName(StackName)
, CfEff (..)
, createStack
, describeStacks
, updateStack
, deleteStack
, waitOnStackStatus
, StackStatus(..)
, AbsentDirective(..)
, StackDescription(..)
, StackDescriptionDict
)where
import Control.Monad.Freer
import Data.Aeson hiding ((.:))
import qualified Data.ByteString.Lazy as LBS
import Data.HashMap.Strict (fromList)
import Data.Map (Map)
import Network.AWS.CloudFormation (StackStatus (..))
import Network.AWS.S3.Types (ETag)
import Protolude
import Qi.Config.AWS.CF
import Qi.Config.AWS.S3
import Qi.Config.Identifier
import Qi.Core.Curry
import Qi.Program.Gen.Lang
type StackDescriptionDict = Map StackName StackDescription
newtype StackName = StackName Text
deriving (Eq, Show, Ord, ToJSON)
data StackDescription = StackDescription {
status :: StackStatus
, outputs :: [(Text, Text)]
} deriving (Show)
instance ToJSON StackDescription where
toJSON StackDescription{ status, outputs } =
object [ "status" .= String (show status :: Text)
, "outputs" .= (Object $ fromList $ second String <$> outputs)
]
data AbsentDirective = AbsentOk | NoAbsent
deriving Eq
data CfEff r where
CreateStack
:: StackName
-> LBS.ByteString
-> CfEff ()
DescribeStacks
:: CfEff StackDescriptionDict
UpdateStack
:: StackName
-> LBS.ByteString
-> CfEff ()
DeleteStack
:: StackName
-> CfEff ()
WaitOnStackStatus
:: StackName
-> StackStatus
-> AbsentDirective
-> CfEff ()
createStack
:: (Member CfEff effs)
=> StackName
-> Eff effs ()
createStack = send .: CreateStack
describeStacks
:: (Member CfEff effs)
=> Eff effs StackDescriptionDict
describeStacks = send DescribeStacks
updateStack
:: (Member CfEff effs)
=> StackName
-> LBS.ByteString
-> Eff effs ()
updateStack = send .: UpdateStack
deleteStack
:: (Member CfEff effs)
=> StackName
-> Eff effs ()
deleteStack = send . DeleteStack
waitOnStackStatus
:: (Member CfEff effs)
=> StackName
-> StackStatus
-> AbsentDirective
-> Eff effs ()
waitOnStackStatus = send .:: WaitOnStackStatus
|
f35539c768e150ea1d042456877f0bfb36584a2ea6bff33f13cc0b75ed5799d4 | rowangithub/DOrder | cgr1.ml | let rec loop x y =
if (x < 100) then
loop (x+2) (y+2)
else assert (x <> 4 || y <> 0)
let main x y =
if (0 <= x && x <= 2 && 0 <= y && y <= 2) then
loop x y
else ()
let _ = main (-1) (-1) | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/icfp/cgr1.ml | ocaml | let rec loop x y =
if (x < 100) then
loop (x+2) (y+2)
else assert (x <> 4 || y <> 0)
let main x y =
if (0 <= x && x <= 2 && 0 <= y && y <= 2) then
loop x y
else ()
let _ = main (-1) (-1) |
|
5ffd8ecf25f20e686de15f73f862cc1c830f24e5374f7b6d394bae982c6805d3 | rmculpepper/crypto | factory.rkt | Copyright 2018
;;
;; This library is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; This library is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
;;
You should have received a copy of the GNU Lesser General Public License
;; along with this library. If not, see </>.
#lang racket/base
(require racket/class
"../common/interfaces.rkt"
"../common/common.rkt"
"../common/factory.rkt"
"ffi.rkt"
"digest.rkt"
"pkey.rkt")
(provide decaf-factory)
(define decaf-factory%
(class* factory-base% (factory<%>)
(inherit get-cipher get-kdf)
(inherit-field ok?)
(super-new [ok? (decaf-is-ok?)] [load-error decaf-load-error])
(define/override (get-name) 'decaf)
(define/override (get-version) (and ok? '()))
(define/override (-get-digest info)
(case (send info get-spec)
[(sha512)
(new decaf-sha512-impl% (info info) (factory this))]
[else #f]))
(define/override (-get-pk spec)
(case spec
[(eddsa) (new decaf-eddsa-impl% (factory this))]
[(ecx) (new decaf-ecx-impl% (factory this))]
[else #f]))
(define/override (-get-pk-reader)
(new decaf-read-key% (factory this)))
;; ----
(define/override (info key)
(case key
[(all-ec-curves) '()]
[(all-eddsa-curves) (if ok? '(ed25519 ed448) '())]
[(all-ecx-curves) (if ok? '(x25519 x448) '())]
[else (super info key)]))
))
(define decaf-factory (new decaf-factory%))
| null | https://raw.githubusercontent.com/rmculpepper/crypto/fec745e8af7e3f4d5eaf83407dde2817de4c2eb0/crypto-lib/private/decaf/factory.rkt | racket |
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
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this library. If not, see </>.
---- | Copyright 2018
by the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
#lang racket/base
(require racket/class
"../common/interfaces.rkt"
"../common/common.rkt"
"../common/factory.rkt"
"ffi.rkt"
"digest.rkt"
"pkey.rkt")
(provide decaf-factory)
(define decaf-factory%
(class* factory-base% (factory<%>)
(inherit get-cipher get-kdf)
(inherit-field ok?)
(super-new [ok? (decaf-is-ok?)] [load-error decaf-load-error])
(define/override (get-name) 'decaf)
(define/override (get-version) (and ok? '()))
(define/override (-get-digest info)
(case (send info get-spec)
[(sha512)
(new decaf-sha512-impl% (info info) (factory this))]
[else #f]))
(define/override (-get-pk spec)
(case spec
[(eddsa) (new decaf-eddsa-impl% (factory this))]
[(ecx) (new decaf-ecx-impl% (factory this))]
[else #f]))
(define/override (-get-pk-reader)
(new decaf-read-key% (factory this)))
(define/override (info key)
(case key
[(all-ec-curves) '()]
[(all-eddsa-curves) (if ok? '(ed25519 ed448) '())]
[(all-ecx-curves) (if ok? '(x25519 x448) '())]
[else (super info key)]))
))
(define decaf-factory (new decaf-factory%))
|
24891037a7e2d8c664e20f6086933bba56ca42d9db0420e27d96c793063c795c | sim642/odep | depgraph.ml | module Dune_describe_graph = Dune_describe_graph
module Findlib_graph = Findlib_graph
module Opam_installed_graph = Opam_installed_graph
type output_type =
| Dot
| Mermaid
module Dot = Ocamlgraph_extra.Graphviz.Dot (Dot_graph.G)
module Mermaid = Ocamlgraph_extra.Mermaid.Make (Dot_graph.G)
let output t g =
match t with
| Dot -> Dot.output_graph stdout g
| Mermaid -> Mermaid.fprint_graph Format.std_formatter g
| null | https://raw.githubusercontent.com/sim642/odep/5c936790cfeb8e18182a54a88ca970f8b9c5f5b6/src/depgraph/depgraph.ml | ocaml | module Dune_describe_graph = Dune_describe_graph
module Findlib_graph = Findlib_graph
module Opam_installed_graph = Opam_installed_graph
type output_type =
| Dot
| Mermaid
module Dot = Ocamlgraph_extra.Graphviz.Dot (Dot_graph.G)
module Mermaid = Ocamlgraph_extra.Mermaid.Make (Dot_graph.G)
let output t g =
match t with
| Dot -> Dot.output_graph stdout g
| Mermaid -> Mermaid.fprint_graph Format.std_formatter g
|
|
8c71b9dfdd1b542ba7e0d832ba06c26b2343234b3e286e515a0a7f133d6b42fc | pauek/arc-sbcl | ac.lisp |
(in-package :arc/test)
(deftest t-literals
(chkev "1" 1)
(chkev "#\\a" #\a)
(chkev "\"a\"" "a")
(chkev "1.45" 1.45)
(chkev "nil" nil)
(chkev "t" t)
(chkev "(quote a)" 'a)
(chkev "(quote (1 2 3))" '(1 2 3)))
(deftest t-funcalls
(chkev "((fn () -1))" -1)
(chkev "((fn (x) (+ 1 x)) 2)" 3)
(chkev "((fn (a b) (+ a b)) 2 3)" 5)
(chkev "((fn (x . y) (cons y x)) 1 2 3)" '((2 3) . 1))
(chkev "((fn x x) '(1 2))" '((1 2)))
(chkev "((fn (x (o y 6)) (+ x y)) 5 6)" 11)
(chkev "((fn (x (o y 6)) (+ x y)) 5)" 11)
(chkev "((fn ((o a #\\a)) a) #\\b)" #\b)
(chkev "((fn ((o a)) a))" nil)
(chkev "((fn ((o a)) \"zz\"))" "zz")
(chkev "((fn (x y (o z 1)) (* z (+ x y))) 5 5)" 10)
(chkev "((fn (x y (o z 1)) (* z (+ x y))) 5 5 2)" 20)
(chkev "((fn (x) (if (< x 0) 1) 5) 1)" 5)
(chkev "(((fn (x) (fn (y) (+ x y))) 5) 10)" 15))
(deftest t-cmplx-arg
(chkev "((fn ((a b)) (- a b)) '(2 1))" 1)
(chkev "((fn (a (o b a)) (+ b a)) \"x\")" "xx")
(chkev "((fn (a (o b 2) (o c (+ a b))) (* a b c)) 1)" 6)
(chkev "((fn (a (o b 2) (o c (+ a b))) (* a b c)) 2 3)" 30)
(chkev "((fn (a (o b 2) (o c (+ a b))) (* a b c)) 2 2 2)" 8)
(chkev "((fn ((x (y z))) `((,x ,y) ,z)) '(a (b c)))" '((a b) c))
(chkev "((fn ((x (y z))) `((,x ,y) ,z)) nil)" '((nil nil) nil))
(chkev "((fn (x (y z) w) `(,x ,y ,z ,w)) 'j '(k l) 'm)" '(j k l m))
(chkev "((fn (x (y z) . w) `((,x ,y) ,z ,w)) 'j '(k l) 'm 'n 'o)"
'((j k) l (m n o)))
(chkev "((fn ((x y)) `(,x ,y)) '(a))" '(a nil))
(chkev "((fn ((x y z)) `(,x ,y ,z)) '(a b))" '(a b nil))
(chkev "((fn ((x y z)) `(,x ,y ,z)) nil)" '(nil nil nil)))
(deftest t-index
(chkev "(\"hiho\" 0)" #\h)
(chkev "(\"hiho\" 1)" #\i)
(chkev "(\"hiho\" 2)" #\h)
(chkev "(\"hiho\" 3)" #\o)
(chkerr "(\"hiho\" 4)")
(chkev "('(1 2 3) 0)" 1)
(chkev "('(1 2 3) 1)" 2)
(chkev "('(1 2 3) 2)" 3))
Avoid warning
(deftest t-env
(chkerr "(set x)")
(chkerr "(set x 1 y)")
(chkerr "(set x 1 y 2 z)")
(chkerr "(set #\a 1)")
(chkerr "(set \"h\" 'a)")
(chkev "((fn () (set x 5) x))" 5)
(chkev "((fn ((o a) (o b)) (set a -3 b a) (cons a b)))"
'(-3 . -3))
(chkev "((fn (x) (set x #\\a) x) #\\z)" #\a)
(chkev "((fn ((o x)) (set x 1) x))" 1)
(chkev "((fn ((o x 5)) ((fn ((o x 2)) x))))" 2)
(chkev "((fn ((o x)) ((fn (y) (set x y)) 3) x))" 3)
(chkerr "((fn (x y) nil))")
(chkerr "((fn ((o x) y) x))"))
(deftest t-if
(chkev "(if t 0 1)" 0)
(chkev "(if nil 0 1)" 1)
(chkev "(if t 0 nil 1 2)" 0)
(chkev "(if t 0 t 1 2)" 0)
(chkev "(if nil 0 t 1 2)" 1)
(chkev "(if nil 0 nil 1 2)" 2)
(chkev "(if nil 0 nil 1 nil 2 t 3 nil 4)" 3)
(chkev "(if nil 0 nil 1 nil 2 nil 3 t 4)" 4))
(deftest t-backq
(chkev "((fn (x) `(1 ,x)) 2)" '(1 2))
(chkev "((fn (x y) `(,x 2 ,y)) 1 3)" '(1 2 3))
(chkev "((fn (x) `(1 ,@x)) '(2 3))" '(1 2 3))
(chkev "((fn (x y) `(1 ,@x ,y)) '(2 3) 4)" '(1 2 3 4))
(chkev "((fn (x) `(1 (2 ,x))) 3)" '(1 (2 3)))
(chkev "((fn (x) `(1 (2 ,x))) '(3 4))" '(1 (2 (3 4))))
(chkev "((fn x `((1 () ,@x))) 2 3)" '((1 () 2 3))))
(deftest t-brackets
(chkev "([+ _ 1] 1)" 2)
(chkev "([cons _ 2] 1)" '(1 . 2))
(chkev "([+ _ \", ho\"] \"hi\")" "hi, ho"))
(deftest t-error
(chkerr "(err \"This is an error\")"))
| null | https://raw.githubusercontent.com/pauek/arc-sbcl/c1a5be2a55b9b3e1327409f71d9bc985577198d6/test/ac.lisp | lisp |
(in-package :arc/test)
(deftest t-literals
(chkev "1" 1)
(chkev "#\\a" #\a)
(chkev "\"a\"" "a")
(chkev "1.45" 1.45)
(chkev "nil" nil)
(chkev "t" t)
(chkev "(quote a)" 'a)
(chkev "(quote (1 2 3))" '(1 2 3)))
(deftest t-funcalls
(chkev "((fn () -1))" -1)
(chkev "((fn (x) (+ 1 x)) 2)" 3)
(chkev "((fn (a b) (+ a b)) 2 3)" 5)
(chkev "((fn (x . y) (cons y x)) 1 2 3)" '((2 3) . 1))
(chkev "((fn x x) '(1 2))" '((1 2)))
(chkev "((fn (x (o y 6)) (+ x y)) 5 6)" 11)
(chkev "((fn (x (o y 6)) (+ x y)) 5)" 11)
(chkev "((fn ((o a #\\a)) a) #\\b)" #\b)
(chkev "((fn ((o a)) a))" nil)
(chkev "((fn ((o a)) \"zz\"))" "zz")
(chkev "((fn (x y (o z 1)) (* z (+ x y))) 5 5)" 10)
(chkev "((fn (x y (o z 1)) (* z (+ x y))) 5 5 2)" 20)
(chkev "((fn (x) (if (< x 0) 1) 5) 1)" 5)
(chkev "(((fn (x) (fn (y) (+ x y))) 5) 10)" 15))
(deftest t-cmplx-arg
(chkev "((fn ((a b)) (- a b)) '(2 1))" 1)
(chkev "((fn (a (o b a)) (+ b a)) \"x\")" "xx")
(chkev "((fn (a (o b 2) (o c (+ a b))) (* a b c)) 1)" 6)
(chkev "((fn (a (o b 2) (o c (+ a b))) (* a b c)) 2 3)" 30)
(chkev "((fn (a (o b 2) (o c (+ a b))) (* a b c)) 2 2 2)" 8)
(chkev "((fn ((x (y z))) `((,x ,y) ,z)) '(a (b c)))" '((a b) c))
(chkev "((fn ((x (y z))) `((,x ,y) ,z)) nil)" '((nil nil) nil))
(chkev "((fn (x (y z) w) `(,x ,y ,z ,w)) 'j '(k l) 'm)" '(j k l m))
(chkev "((fn (x (y z) . w) `((,x ,y) ,z ,w)) 'j '(k l) 'm 'n 'o)"
'((j k) l (m n o)))
(chkev "((fn ((x y)) `(,x ,y)) '(a))" '(a nil))
(chkev "((fn ((x y z)) `(,x ,y ,z)) '(a b))" '(a b nil))
(chkev "((fn ((x y z)) `(,x ,y ,z)) nil)" '(nil nil nil)))
(deftest t-index
(chkev "(\"hiho\" 0)" #\h)
(chkev "(\"hiho\" 1)" #\i)
(chkev "(\"hiho\" 2)" #\h)
(chkev "(\"hiho\" 3)" #\o)
(chkerr "(\"hiho\" 4)")
(chkev "('(1 2 3) 0)" 1)
(chkev "('(1 2 3) 1)" 2)
(chkev "('(1 2 3) 2)" 3))
Avoid warning
(deftest t-env
(chkerr "(set x)")
(chkerr "(set x 1 y)")
(chkerr "(set x 1 y 2 z)")
(chkerr "(set #\a 1)")
(chkerr "(set \"h\" 'a)")
(chkev "((fn () (set x 5) x))" 5)
(chkev "((fn ((o a) (o b)) (set a -3 b a) (cons a b)))"
'(-3 . -3))
(chkev "((fn (x) (set x #\\a) x) #\\z)" #\a)
(chkev "((fn ((o x)) (set x 1) x))" 1)
(chkev "((fn ((o x 5)) ((fn ((o x 2)) x))))" 2)
(chkev "((fn ((o x)) ((fn (y) (set x y)) 3) x))" 3)
(chkerr "((fn (x y) nil))")
(chkerr "((fn ((o x) y) x))"))
(deftest t-if
(chkev "(if t 0 1)" 0)
(chkev "(if nil 0 1)" 1)
(chkev "(if t 0 nil 1 2)" 0)
(chkev "(if t 0 t 1 2)" 0)
(chkev "(if nil 0 t 1 2)" 1)
(chkev "(if nil 0 nil 1 2)" 2)
(chkev "(if nil 0 nil 1 nil 2 t 3 nil 4)" 3)
(chkev "(if nil 0 nil 1 nil 2 nil 3 t 4)" 4))
(deftest t-backq
(chkev "((fn (x) `(1 ,x)) 2)" '(1 2))
(chkev "((fn (x y) `(,x 2 ,y)) 1 3)" '(1 2 3))
(chkev "((fn (x) `(1 ,@x)) '(2 3))" '(1 2 3))
(chkev "((fn (x y) `(1 ,@x ,y)) '(2 3) 4)" '(1 2 3 4))
(chkev "((fn (x) `(1 (2 ,x))) 3)" '(1 (2 3)))
(chkev "((fn (x) `(1 (2 ,x))) '(3 4))" '(1 (2 (3 4))))
(chkev "((fn x `((1 () ,@x))) 2 3)" '((1 () 2 3))))
(deftest t-brackets
(chkev "([+ _ 1] 1)" 2)
(chkev "([cons _ 2] 1)" '(1 . 2))
(chkev "([+ _ \", ho\"] \"hi\")" "hi, ho"))
(deftest t-error
(chkerr "(err \"This is an error\")"))
|
|
a40fe98cff0b5a771a48307ceb20b717f9dd113672976f745499ecddd3cfe627 | schemedoc/implementation-metadata | ypsilon.scm | (title "Ypsilon")
(long-title "Ypsilon Scheme System")
(homepage-url "")
(wikipedia en "Ypsilon (Scheme implementation)")
(issue-tracker-url "")
(repology "ypsilon")
(person "Yoshikatsu Fujita")
(company "LittleWing Co. Ltd.")
(github "fujita-y/ypsilon")
(documentation
(title "Assorted documents on Google Code")
(web-url ""))
(version-control
(web-url ""))
(release
(date (2008 12 23))
(version-number "0.9.6.update3")
(source-archive
(url "-code-archive-downloads/v2/code.google.com/ypsilon/ypsilon-0.9.6.update3.tar.gz"))
(bundled-srfi-implementations
1 6 8 9 13 14 19 26 27
28 38 39 41 42 48 98))
| null | https://raw.githubusercontent.com/schemedoc/implementation-metadata/6280d9c4c73833dc5bd1c9bef9b45be6ea5beb68/schemes/ypsilon.scm | scheme | (title "Ypsilon")
(long-title "Ypsilon Scheme System")
(homepage-url "")
(wikipedia en "Ypsilon (Scheme implementation)")
(issue-tracker-url "")
(repology "ypsilon")
(person "Yoshikatsu Fujita")
(company "LittleWing Co. Ltd.")
(github "fujita-y/ypsilon")
(documentation
(title "Assorted documents on Google Code")
(web-url ""))
(version-control
(web-url ""))
(release
(date (2008 12 23))
(version-number "0.9.6.update3")
(source-archive
(url "-code-archive-downloads/v2/code.google.com/ypsilon/ypsilon-0.9.6.update3.tar.gz"))
(bundled-srfi-implementations
1 6 8 9 13 14 19 26 27
28 38 39 41 42 48 98))
|
|
7e46fb9aab79cd0e389a8069b2bc3e3fd4c6e1d70da4ab6b7dc55c5ac5a37065 | k-qy/knotation | knot.hs | This code draws the raw knots and links up to n crossings , using the ` diagrams ` library , and gives their notation . It does n't filter out links or equivalent knots / links .
Top - level approach : the code draws crossings , puts crossings next to each other to form twists , flips and adds twists / tangles to form tangles , and puts the resulting tangle in the 1 * polyhedron ( connects the NW and NE corners , and the SW and SE corners ) . Everything is connected with straight lines . If you figure out a nice way to spline / curve the entire knot , let me know !
To combine diagrams , it explicitly passes around information about its location ( corners , middle ) , calculates the new location of the combined diagram , and returns that . This could probably be done monadically .
To change the number of crossings : change the number marked CHANGE THIS .
Increaseing the number of crossings will make the diagram larger , which will make the lines really thick for some reason , so you 'll also need to change the line width , also marked CHANGE THIS .
Oh , and there are a lot of TODOs .
Related work : KnotPlot plots knots in notation in 3D.
( Last updated 9/26/15 )
Top-level approach: the code draws crossings, puts crossings next to each other to form twists, flips and adds twists/tangles to form tangles, and puts the resulting tangle in the 1* polyhedron (connects the NW and NE corners, and the SW and SE corners). Everything is connected with straight lines. If you figure out a nice way to spline/curve the entire knot, let me know!
To combine diagrams, it explicitly passes around information about its location (corners, middle), calculates the new location of the combined diagram, and returns that. This could probably be done monadically.
To change the number of crossings: change the number marked CHANGE THIS.
Increaseing the number of crossings will make the diagram larger, which will make the lines really thick for some reason, so you'll also need to change the line width, also marked CHANGE THIS.
Oh, and there are a lot of TODOs.
Related work: KnotPlot plots knots in Conway notation in 3D.
(Last updated 9/26/15) -}
-- Needed for `diagrams` library
# LANGUAGE NoMonomorphismRestriction , FlexibleContexts , TypeFamilies #
import Data.List
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Diagrams.BoundingBox
-- To compile and generate image:
-- alias chrome '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --kiosk'
( That is , in the ` fish ` shell , I use this command to tell Chrome to open something )
ghc --make knot.hs ; ./knot -o knot.svg -h 500 ; chrome knot.svg
-- -h controls the height. You can also use -w.
----------
given # crossings , produce all knots ( Dowker ) with that # crossings
-- includes duplicates and undrawable notations; ignores non-alternating knots
-- not used in the rest of the code, just for demonstration
dowkers :: Int -> [[(Int, Int)]]
dowkers n
| n <= 0 = []
| otherwise =
let (odds, evens) = (take n [1, 3 ..], take n [2, 4 ..]) in
map (zip odds) (permutations evens)
-----------
Notes on drawing :
- Straight lines for instead -- but how to prevent self - intersection ?
- Can a spline through every knot point ( in order ) work ? But then how to articulate the crossings ?
- Maybe a spline through each segment . But how to calculate the segments ? And how to figure out the extra control points ?
- Twists : should only draw ( n - 2 ) of them ; the 2 crossings at the end need to be part of the splines that connect to other twists
- Straight lines for Conway instead -- but how to prevent self-intersection?
- Can a spline through every knot point (in order) work? But then how to articulate the crossings?
- Maybe a spline through each segment. But how to calculate the segments? And how to figure out the extra control points?
- Twists: should only draw (n - 2) of them; the 2 crossings at the end need to be part of the splines that connect to other twists -}
-- Draw twists
w = 1 -- total width
h = 4 -- total height
offCenter = 0.2
twistPts (baseX, baseY) =
let w' = w / 2.0 in
let h' = h / 4.0 in
map p2 [(baseX - offCenter, baseY), (baseX - w', baseY - h'),
(baseX + w', baseY - (h' * 3)), (baseX + offCenter, baseY - h)]
spot = circle 0.1 # fc blue # lw none
-- connect the dots. takes Points (not coords)
mkSpline showPts points =
if showPts then
position (zip points (repeat spot)) <> cubicSpline False points
else cubicSpline False points -- spline not closed
mkTwist base = mkSpline True (twistPts base)
twistOffsetX = 0
delta = 0.2
twistOffsetY = h / 2.0 + delta
twistOffsetP n = (twistOffsetX, n * twistOffsetY)
smash xs = foldl (<>) mempty xs
-- twist :: Diagram B
twist n base =
let translateBy n obj = obj # translate (r2 $ twistOffsetP n) in
let twists = take n $ zipWith translateBy [0,1..] (repeat $ mkTwist base) in
let halfTwists = [mempty] in -- [topHalf 0, bottomHalf n] -- TODO
smash $ twists ++ halfTwists
-- hcat [mkTwist False, mkTwist False]
mkTwist False ||| mkTwist False
cubicSplineEx :: Diagram B
cubicSplineEx = twist 3 (0, 0) # rotateBy (1/4)
# centerXY # pad 1.1
-------
Draw the 1 * polyhedron
type Pt = (Double, Double)
data TangleCorners = TangleCorners { -- northwest, northeast, etc. + location of mid
nw :: Pt
, ne :: Pt
, sw :: Pt
, se :: Pt
, midX :: Double
, midY :: Double -- delete this or use bounding box instead?
} deriving (Show)
tanglePoints = TangleCorners { nw = (-1, 1), ne = (1, 0.5),
sw = (-1, -0.5), se = (1, -1),
midX = 0, midY = 0 }
average xs = sum xs / genericLength xs
TODO
-- assuming it doesn't use sw and se
TODO abstract out w/ bottomPts
topPts tangle =
let (nw', ne') = (nw tangle, ne tangle) in
-- the points may be at diff y-level, so choose the higher y as
-- a baseline for the padding points' ys
let bottomY = max (snd nw') (snd ne') in
let height = average [abs $ fst nw', abs $ fst ne'] / 2 in
let midpt = (midX tangle, bottomY + height) in
-- polyDelta vs. height?
let leftpad = (fst nw' - polyDelta, bottomY + polyDelta) in
let rightpad = (fst ne' + polyDelta, bottomY + polyDelta) in
-- padding points currently unused
map p2 [ nw ' , leftpad , midpt , rightpad , ' ]
map p2 [nw', midpt, ne']
bottomPts tangle =
-- let tangleFlipY = tangle in
-- map flipY $ topPts tangleFlipY
let (sw', se') = (sw tangle, se tangle) in
let bottomY = min (snd sw') (snd se') in
let height = average [abs $ fst sw', abs $ fst se'] / 2 in
let midpt = (midX tangle, bottomY - height {- todo -} ) in
let leftpad = (fst sw' - polyDelta, bottomY - polyDelta) in
let rightpad = (fst se' + polyDelta, bottomY - polyDelta) in
map p2 [ sw ' , leftpad , midpt , rightpad , se ' ]
map p2 [sw', midpt, se']
-- Usage: main = mkPolyhedron1 tanglePoints
-- maybe don't render the diagram, but pass the list of segments?
mkPolyhedron1 :: (Diagram B, TangleCorners) -> Diagram B
mkPolyhedron1 (tangle, tanglePts) =
let (topRes, botRes) = (topPts tanglePts, bottomPts tanglePts) in
tangle
<> mkSpline False (init topRes)
<> mkSpline False (tail topRes)
<> mkSpline False (init botRes)
<> mkSpline False (tail botRes)
-- TODO: put curved spline back; this is a hack
right now it just connects things with 2 straight lines
-- <> mkSpline False (topPts tanglePts)
< > mkSpline False ( )
---
Draw the 1 crossing ( not -1 )
-- crossing :: Int -> Diagram B
crossing n = atPoints ( trailVertices $ regPoly n 1 ) ( map node [ 1 .. n ] )
# connectOutside ( 1 : : Int ) ( 3 : : Int ) # connectOutside ( 2 : : Int ) ( 4 : : Int )
r45 = rotateBy (1/8)
r90 = rotateBy (1/4)
r180 = rotateBy (1/2)
gap' = 0.35
-- crossing length
clen = sqrt 2 / 2
tPts t = [nw t, ne t, sw t, se t]
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)
box : : Colour a - > TangleCorners - > Diagram B
box color tc = let spot txt = text txt # fontSizeL 0.1 # fc white
<> circle 0.1 # fc color # lw none in
let pts = map p2 (tPts tc) in -- TODO: midX, midY
position (zip pts [spot "nw", spot "ne", spot "sw", spot "se"])
TODO : return the 7 relevant points ( overleft , overmid , overright ,
underleft , underleft ' , ' , )
or 3 relevant segments
overcross :: (Diagram B, TangleCorners)
overcross = let right = unitX in
let top = (1 - gap') *^ r90 unitX in
let left = r180 right in
let bt = r180 top in
let (gap_b, gap_t) = (r2 (0, -gap'), r2 (0, gap')) in
TODO factor out repeated parts
let left' = lineFromOffsets [left] # strokeLine in
let right' = lineFromOffsets [right] # strokeLine in
let bt' = lineFromOffsets [bt] # strokeLine # translate gap_b in
let top' = lineFromOffsets [top] # strokeLine # translate gap_t in
-- let diagram = left' <> right' <> bt' <> top' in
let diagram = mconcat $ map (translate (r2 (clen, 0)) . r45) [left', right', bt', top'] in
let coords = TangleCorners -- TODO: remove reliance on coords
-- top -> nw, left -> ne, left -> sw, bot -> se
{ nw = (0, clen), ne = (2 * clen, clen),
sw = (0, -clen), se = (2 * clen, -clen),
midX = clen, midY = 0 } in
(diagram, coords)
undercross :: (Diagram B, TangleCorners)
undercross = (fst overcross # rotateBy (1/4), snd overcross)
twistSqH :: (Diagram B, TangleCorners) -> Int -> (Diagram B, TangleCorners)
twistSqH crossing n = let width' = clen * fromIntegral n in
let newCoords = TangleCorners
{ nw = (0, clen), ne = (2 * width', clen),
sw = (0, -clen), se = (2 * width', -clen),
midX = width', midY = 0 } in
-- TODO: remove reliance on coords
-- confusing: coords could be relative, then whole diagram translated
(hcat $ replicate n $ fst crossing, newCoords)
midX ' t = ( fst $ nw t + fst $ ne t ) / 2
midY ' t = ( snd $ nw t + snd $ sw t ) / 2
meant to be used as [ p2 ` diff ` p1 ] , where 2 is new and 1 is original
pdiff p2 p1 = (fst p2 - fst p1, snd p2 - snd p1)
mapCorners :: (P2 Double -> P2 Double) -> TangleCorners -> TangleCorners
mapCorners transform' tc =
let transP p = unp2 $ transform' $ p2 p in
let (nw', ne') = (transP $ nw tc, transP $ ne tc) in
let (sw', se') = (transP $ sw tc, transP $ se tc) in
TangleCorners {
nw = nw', ne = ne',
sw = sw', se = se',
-- by default -- may not be correct for non-rect corners
midX = (fst nw' + fst ne') / 2,
midY = (snd nw' + snd sw') / 2 }
-- Tangle addition
-- assuming that d2 is always rectangular; d1 might not be
tangleAdd :: (Diagram B, TangleCorners) -> (Diagram B, TangleCorners)
-> (Diagram B, TangleCorners)
tangleAdd (d1, c1) (d2, c2) =
position 2nd tangle on right - middle of 1st
let d1_midY = (snd (nw c1) + snd (sw c1)) / 2 in
TODO this should be proportionate to something
-- TODO: calculate X such that we can connect in straight line
TODO or use midX ' etc
let d2halfwidth = (fst (ne c2) - fst (nw c2)) / 2 in
let d2center' = (fst (ne c1) + d2halfwidth + spc, d1_midY) in
let d2vector = r2 $ pdiff d2center' d2center in
let rightAndCenter = translate d2vector in
TODO fix type inference
let (d2', c2') = (rightAndCenter' d2, mapCorners rightAndCenter c2) in
-- let (d2', c2') = (rightAndCenter d2, mapCorners rightAndCenter c2) in
combine from the 2 diagrams
{ nw = nw c1, ne = ne c2',
sw = sw c1, se = se c2',
midX = (fst (nw c1) + fst (ne c2')) / 2,
-- note use of d1's midY
TODO
-- TODO: calculate middle/handle point
let topAdd = mkSpline False (map p2 [ne c1, nw c2']) in
let bottomAdd = mkSpline False (map p2 [se c1, sw c2']) in
(d1 <> d2'
-- <> box green c1
-- <> box red c2'
< > box blue coordsCombine
<> topAdd <> bottomAdd
, coordsCombine)
-- Tangle multiplication (calls tangle addition)
tangleMult :: (Diagram B, TangleCorners) -> (Diagram B, TangleCorners)
-> (Diagram B, TangleCorners)
tangleMult (d1, coords1) (d2, coords2) =
let transform' = reflectY . rotateBy (1/4) in
let d1' = transform' d1 in
-- TODO pass Points around
let transP p = unp2 $ transform' $ p2 p in
let (nw', ne') = (transP (nw coords1), transP (ne coords1)) in
let (sw', se') = (transP (sw coords1), transP (se coords1)) in
let coords1' = TangleCorners
points are transformed and their locations have changed WRT compass
{ nw = nw', ne = sw',
sw = ne', se = se',
TODO
TODO
tangleAdd (d1', coords1') (d2, coords2)
-- TODO: code to draw just tangle, flip / rotate tangle
-- note to self: natural foldl!
drawTangleN :: [Int] -> Diagram B
drawTangleN [] = mempty
drawTangleN tangle@(t:ts) =
let twistAndMultiply acc n = tangleMult acc (twistSqH overcross n) in
let tangleFinal = foldl twistAndMultiply (twistSqH overcross t) ts in
let name = intersperse ' ' $ concatMap show tangle in
let knot = mkPolyhedron1 tangleFinal # lw 1.4 # pad 1.4 in
-- CHANGE THIS: lw = line width
-- align text with bottom middle of diagram
-- doesn't actually work, but leaving code in case I figure it out
let bbox = boundingBox knot in
let textp = case getCorners bbox of
Nothing -> p2 (0, 0)
Just (bt_lt, top_rt) ->
let ((bx, by), (tx, ty)) = (unp2 bt_lt, unp2 top_rt) in
p2 (average [bx, tx], by)
in
let kcenter = case boxCenter bbox of
Nothing -> p2 (0, 0)
Just c -> c in
let text_diag = text name # fontSizeL 2
# font " freeserif " # pad 1.2 # centerX in
position [ ( , text_diag ) , ( kcenter , knot ) ]
-- Put the knot's notation somewhat near the knot (hard to align)
(alignedText 1 1 name # fontSizeL 1.2
# font "freeserif" # pad 1.2 # centerX)
=== knot
# pad 1.2
--------------
partitions :: Int -> [[Int]]
partitions n
| n <= 0 = [[]]
| otherwise =
let choose n = [1, 2 .. n] in
let subpartition y = map (y :) $ partitions (n - y) in
concatMap subpartition (choose n)
partitionsUpTo :: Int -> [(Int, [[Int]])]
partitionsUpTo n
| n <= 0 = []
| otherwise = map (\x -> (x, partitions x)) [1..n]
rawKnotsToNCrossings :: Diagram B
rawKnotsToNCrossings =
let notations = partitionsUpTo 7 in -- CHANGE THIS
TODO break lines into fives and put " knots of n crossings " text
-- let drawn = map (\(crossings, tangles) -> (crossings, map drawTangleN tangles))
-- notations in
let drawn' = map (\(crossings, tangles) -> hcat $ map drawTangleN tangles)
notations in
vcat drawn'
--------------
-- unused
testDiagram :: Diagram B
testDiagram =
(drawTangleN [1]
||| drawTangleN [2]
||| drawTangleN [3])
===
(drawTangleN [1, 1]
||| drawTangleN [2, 1]
||| drawTangleN [2, 3])
===
(drawTangleN [3, 2]
||| drawTangleN [1, 4]
||| drawTangleN [4, 1])
===
(drawTangleN [1, 1, 1]
||| drawTangleN [2, 1, 3]
||| drawTangleN [6, 6, 6])
===
(drawTangleN [2, 1, 1, 1, 2]
||| drawTangleN [ 6 , 6 , 6 , 6 , 6 , 6 ]
||| drawTangleN [1, 2, 3, 4, 5])
-- TODO monadically pass around coords
TODO display tangle numbers , enumerate all
TODO confirm that this is right
TODO crossings rendered badly when img too large
TODO fix forking at intersections
TODO get rid of whitespace and use proportional LW
main = mainWith $ rawKnotsToNCrossings # centerXY # pad 1.01
| null | https://raw.githubusercontent.com/k-qy/knotation/2730ec0b02df97077bede8f17b96d89a854554ee/knot.hs | haskell | Needed for `diagrams` library
To compile and generate image:
alias chrome '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --kiosk'
make knot.hs ; ./knot -o knot.svg -h 500 ; chrome knot.svg
-h controls the height. You can also use -w.
--------
includes duplicates and undrawable notations; ignores non-alternating knots
not used in the rest of the code, just for demonstration
---------
but how to prevent self - intersection ?
but how to prevent self-intersection?
Draw twists
total width
total height
connect the dots. takes Points (not coords)
spline not closed
twist :: Diagram B
[topHalf 0, bottomHalf n] -- TODO
hcat [mkTwist False, mkTwist False]
-----
northwest, northeast, etc. + location of mid
delete this or use bounding box instead?
assuming it doesn't use sw and se
the points may be at diff y-level, so choose the higher y as
a baseline for the padding points' ys
polyDelta vs. height?
padding points currently unused
let tangleFlipY = tangle in
map flipY $ topPts tangleFlipY
todo
Usage: main = mkPolyhedron1 tanglePoints
maybe don't render the diagram, but pass the list of segments?
TODO: put curved spline back; this is a hack
<> mkSpline False (topPts tanglePts)
-
crossing :: Int -> Diagram B
crossing length
TODO: midX, midY
let diagram = left' <> right' <> bt' <> top' in
TODO: remove reliance on coords
top -> nw, left -> ne, left -> sw, bot -> se
TODO: remove reliance on coords
confusing: coords could be relative, then whole diagram translated
by default -- may not be correct for non-rect corners
Tangle addition
assuming that d2 is always rectangular; d1 might not be
TODO: calculate X such that we can connect in straight line
let (d2', c2') = (rightAndCenter d2, mapCorners rightAndCenter c2) in
note use of d1's midY
TODO: calculate middle/handle point
<> box green c1
<> box red c2'
Tangle multiplication (calls tangle addition)
TODO pass Points around
TODO: code to draw just tangle, flip / rotate tangle
note to self: natural foldl!
CHANGE THIS: lw = line width
align text with bottom middle of diagram
doesn't actually work, but leaving code in case I figure it out
Put the knot's notation somewhat near the knot (hard to align)
------------
CHANGE THIS
let drawn = map (\(crossings, tangles) -> (crossings, map drawTangleN tangles))
notations in
------------
unused
TODO monadically pass around coords | This code draws the raw knots and links up to n crossings , using the ` diagrams ` library , and gives their notation . It does n't filter out links or equivalent knots / links .
Top - level approach : the code draws crossings , puts crossings next to each other to form twists , flips and adds twists / tangles to form tangles , and puts the resulting tangle in the 1 * polyhedron ( connects the NW and NE corners , and the SW and SE corners ) . Everything is connected with straight lines . If you figure out a nice way to spline / curve the entire knot , let me know !
To combine diagrams , it explicitly passes around information about its location ( corners , middle ) , calculates the new location of the combined diagram , and returns that . This could probably be done monadically .
To change the number of crossings : change the number marked CHANGE THIS .
Increaseing the number of crossings will make the diagram larger , which will make the lines really thick for some reason , so you 'll also need to change the line width , also marked CHANGE THIS .
Oh , and there are a lot of TODOs .
Related work : KnotPlot plots knots in notation in 3D.
( Last updated 9/26/15 )
Top-level approach: the code draws crossings, puts crossings next to each other to form twists, flips and adds twists/tangles to form tangles, and puts the resulting tangle in the 1* polyhedron (connects the NW and NE corners, and the SW and SE corners). Everything is connected with straight lines. If you figure out a nice way to spline/curve the entire knot, let me know!
To combine diagrams, it explicitly passes around information about its location (corners, middle), calculates the new location of the combined diagram, and returns that. This could probably be done monadically.
To change the number of crossings: change the number marked CHANGE THIS.
Increaseing the number of crossings will make the diagram larger, which will make the lines really thick for some reason, so you'll also need to change the line width, also marked CHANGE THIS.
Oh, and there are a lot of TODOs.
Related work: KnotPlot plots knots in Conway notation in 3D.
(Last updated 9/26/15) -}
# LANGUAGE NoMonomorphismRestriction , FlexibleContexts , TypeFamilies #
import Data.List
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Diagrams.BoundingBox
( That is , in the ` fish ` shell , I use this command to tell Chrome to open something )
given # crossings , produce all knots ( Dowker ) with that # crossings
dowkers :: Int -> [[(Int, Int)]]
dowkers n
| n <= 0 = []
| otherwise =
let (odds, evens) = (take n [1, 3 ..], take n [2, 4 ..]) in
map (zip odds) (permutations evens)
Notes on drawing :
- Can a spline through every knot point ( in order ) work ? But then how to articulate the crossings ?
- Maybe a spline through each segment . But how to calculate the segments ? And how to figure out the extra control points ?
- Twists : should only draw ( n - 2 ) of them ; the 2 crossings at the end need to be part of the splines that connect to other twists
- Can a spline through every knot point (in order) work? But then how to articulate the crossings?
- Maybe a spline through each segment. But how to calculate the segments? And how to figure out the extra control points?
- Twists: should only draw (n - 2) of them; the 2 crossings at the end need to be part of the splines that connect to other twists -}
offCenter = 0.2
twistPts (baseX, baseY) =
let w' = w / 2.0 in
let h' = h / 4.0 in
map p2 [(baseX - offCenter, baseY), (baseX - w', baseY - h'),
(baseX + w', baseY - (h' * 3)), (baseX + offCenter, baseY - h)]
spot = circle 0.1 # fc blue # lw none
mkSpline showPts points =
if showPts then
position (zip points (repeat spot)) <> cubicSpline False points
mkTwist base = mkSpline True (twistPts base)
twistOffsetX = 0
delta = 0.2
twistOffsetY = h / 2.0 + delta
twistOffsetP n = (twistOffsetX, n * twistOffsetY)
smash xs = foldl (<>) mempty xs
twist n base =
let translateBy n obj = obj # translate (r2 $ twistOffsetP n) in
let twists = take n $ zipWith translateBy [0,1..] (repeat $ mkTwist base) in
smash $ twists ++ halfTwists
mkTwist False ||| mkTwist False
cubicSplineEx :: Diagram B
cubicSplineEx = twist 3 (0, 0) # rotateBy (1/4)
# centerXY # pad 1.1
Draw the 1 * polyhedron
type Pt = (Double, Double)
nw :: Pt
, ne :: Pt
, sw :: Pt
, se :: Pt
, midX :: Double
} deriving (Show)
tanglePoints = TangleCorners { nw = (-1, 1), ne = (1, 0.5),
sw = (-1, -0.5), se = (1, -1),
midX = 0, midY = 0 }
average xs = sum xs / genericLength xs
TODO
TODO abstract out w/ bottomPts
topPts tangle =
let (nw', ne') = (nw tangle, ne tangle) in
let bottomY = max (snd nw') (snd ne') in
let height = average [abs $ fst nw', abs $ fst ne'] / 2 in
let midpt = (midX tangle, bottomY + height) in
let leftpad = (fst nw' - polyDelta, bottomY + polyDelta) in
let rightpad = (fst ne' + polyDelta, bottomY + polyDelta) in
map p2 [ nw ' , leftpad , midpt , rightpad , ' ]
map p2 [nw', midpt, ne']
bottomPts tangle =
let (sw', se') = (sw tangle, se tangle) in
let bottomY = min (snd sw') (snd se') in
let height = average [abs $ fst sw', abs $ fst se'] / 2 in
let leftpad = (fst sw' - polyDelta, bottomY - polyDelta) in
let rightpad = (fst se' + polyDelta, bottomY - polyDelta) in
map p2 [ sw ' , leftpad , midpt , rightpad , se ' ]
map p2 [sw', midpt, se']
mkPolyhedron1 :: (Diagram B, TangleCorners) -> Diagram B
mkPolyhedron1 (tangle, tanglePts) =
let (topRes, botRes) = (topPts tanglePts, bottomPts tanglePts) in
tangle
<> mkSpline False (init topRes)
<> mkSpline False (tail topRes)
<> mkSpline False (init botRes)
<> mkSpline False (tail botRes)
right now it just connects things with 2 straight lines
< > mkSpline False ( )
Draw the 1 crossing ( not -1 )
crossing n = atPoints ( trailVertices $ regPoly n 1 ) ( map node [ 1 .. n ] )
# connectOutside ( 1 : : Int ) ( 3 : : Int ) # connectOutside ( 2 : : Int ) ( 4 : : Int )
r45 = rotateBy (1/8)
r90 = rotateBy (1/4)
r180 = rotateBy (1/2)
gap' = 0.35
clen = sqrt 2 / 2
tPts t = [nw t, ne t, sw t, se t]
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)
box : : Colour a - > TangleCorners - > Diagram B
box color tc = let spot txt = text txt # fontSizeL 0.1 # fc white
<> circle 0.1 # fc color # lw none in
position (zip pts [spot "nw", spot "ne", spot "sw", spot "se"])
TODO : return the 7 relevant points ( overleft , overmid , overright ,
underleft , underleft ' , ' , )
or 3 relevant segments
overcross :: (Diagram B, TangleCorners)
overcross = let right = unitX in
let top = (1 - gap') *^ r90 unitX in
let left = r180 right in
let bt = r180 top in
let (gap_b, gap_t) = (r2 (0, -gap'), r2 (0, gap')) in
TODO factor out repeated parts
let left' = lineFromOffsets [left] # strokeLine in
let right' = lineFromOffsets [right] # strokeLine in
let bt' = lineFromOffsets [bt] # strokeLine # translate gap_b in
let top' = lineFromOffsets [top] # strokeLine # translate gap_t in
let diagram = mconcat $ map (translate (r2 (clen, 0)) . r45) [left', right', bt', top'] in
{ nw = (0, clen), ne = (2 * clen, clen),
sw = (0, -clen), se = (2 * clen, -clen),
midX = clen, midY = 0 } in
(diagram, coords)
undercross :: (Diagram B, TangleCorners)
undercross = (fst overcross # rotateBy (1/4), snd overcross)
twistSqH :: (Diagram B, TangleCorners) -> Int -> (Diagram B, TangleCorners)
twistSqH crossing n = let width' = clen * fromIntegral n in
let newCoords = TangleCorners
{ nw = (0, clen), ne = (2 * width', clen),
sw = (0, -clen), se = (2 * width', -clen),
midX = width', midY = 0 } in
(hcat $ replicate n $ fst crossing, newCoords)
midX ' t = ( fst $ nw t + fst $ ne t ) / 2
midY ' t = ( snd $ nw t + snd $ sw t ) / 2
meant to be used as [ p2 ` diff ` p1 ] , where 2 is new and 1 is original
pdiff p2 p1 = (fst p2 - fst p1, snd p2 - snd p1)
mapCorners :: (P2 Double -> P2 Double) -> TangleCorners -> TangleCorners
mapCorners transform' tc =
let transP p = unp2 $ transform' $ p2 p in
let (nw', ne') = (transP $ nw tc, transP $ ne tc) in
let (sw', se') = (transP $ sw tc, transP $ se tc) in
TangleCorners {
nw = nw', ne = ne',
sw = sw', se = se',
midX = (fst nw' + fst ne') / 2,
midY = (snd nw' + snd sw') / 2 }
tangleAdd :: (Diagram B, TangleCorners) -> (Diagram B, TangleCorners)
-> (Diagram B, TangleCorners)
tangleAdd (d1, c1) (d2, c2) =
position 2nd tangle on right - middle of 1st
let d1_midY = (snd (nw c1) + snd (sw c1)) / 2 in
TODO this should be proportionate to something
TODO or use midX ' etc
let d2halfwidth = (fst (ne c2) - fst (nw c2)) / 2 in
let d2center' = (fst (ne c1) + d2halfwidth + spc, d1_midY) in
let d2vector = r2 $ pdiff d2center' d2center in
let rightAndCenter = translate d2vector in
TODO fix type inference
let (d2', c2') = (rightAndCenter' d2, mapCorners rightAndCenter c2) in
combine from the 2 diagrams
{ nw = nw c1, ne = ne c2',
sw = sw c1, se = se c2',
midX = (fst (nw c1) + fst (ne c2')) / 2,
TODO
let topAdd = mkSpline False (map p2 [ne c1, nw c2']) in
let bottomAdd = mkSpline False (map p2 [se c1, sw c2']) in
(d1 <> d2'
< > box blue coordsCombine
<> topAdd <> bottomAdd
, coordsCombine)
tangleMult :: (Diagram B, TangleCorners) -> (Diagram B, TangleCorners)
-> (Diagram B, TangleCorners)
tangleMult (d1, coords1) (d2, coords2) =
let transform' = reflectY . rotateBy (1/4) in
let d1' = transform' d1 in
let transP p = unp2 $ transform' $ p2 p in
let (nw', ne') = (transP (nw coords1), transP (ne coords1)) in
let (sw', se') = (transP (sw coords1), transP (se coords1)) in
let coords1' = TangleCorners
points are transformed and their locations have changed WRT compass
{ nw = nw', ne = sw',
sw = ne', se = se',
TODO
TODO
tangleAdd (d1', coords1') (d2, coords2)
drawTangleN :: [Int] -> Diagram B
drawTangleN [] = mempty
drawTangleN tangle@(t:ts) =
let twistAndMultiply acc n = tangleMult acc (twistSqH overcross n) in
let tangleFinal = foldl twistAndMultiply (twistSqH overcross t) ts in
let name = intersperse ' ' $ concatMap show tangle in
let knot = mkPolyhedron1 tangleFinal # lw 1.4 # pad 1.4 in
let bbox = boundingBox knot in
let textp = case getCorners bbox of
Nothing -> p2 (0, 0)
Just (bt_lt, top_rt) ->
let ((bx, by), (tx, ty)) = (unp2 bt_lt, unp2 top_rt) in
p2 (average [bx, tx], by)
in
let kcenter = case boxCenter bbox of
Nothing -> p2 (0, 0)
Just c -> c in
let text_diag = text name # fontSizeL 2
# font " freeserif " # pad 1.2 # centerX in
position [ ( , text_diag ) , ( kcenter , knot ) ]
(alignedText 1 1 name # fontSizeL 1.2
# font "freeserif" # pad 1.2 # centerX)
=== knot
# pad 1.2
partitions :: Int -> [[Int]]
partitions n
| n <= 0 = [[]]
| otherwise =
let choose n = [1, 2 .. n] in
let subpartition y = map (y :) $ partitions (n - y) in
concatMap subpartition (choose n)
partitionsUpTo :: Int -> [(Int, [[Int]])]
partitionsUpTo n
| n <= 0 = []
| otherwise = map (\x -> (x, partitions x)) [1..n]
rawKnotsToNCrossings :: Diagram B
rawKnotsToNCrossings =
TODO break lines into fives and put " knots of n crossings " text
let drawn' = map (\(crossings, tangles) -> hcat $ map drawTangleN tangles)
notations in
vcat drawn'
testDiagram :: Diagram B
testDiagram =
(drawTangleN [1]
||| drawTangleN [2]
||| drawTangleN [3])
===
(drawTangleN [1, 1]
||| drawTangleN [2, 1]
||| drawTangleN [2, 3])
===
(drawTangleN [3, 2]
||| drawTangleN [1, 4]
||| drawTangleN [4, 1])
===
(drawTangleN [1, 1, 1]
||| drawTangleN [2, 1, 3]
||| drawTangleN [6, 6, 6])
===
(drawTangleN [2, 1, 1, 1, 2]
||| drawTangleN [ 6 , 6 , 6 , 6 , 6 , 6 ]
||| drawTangleN [1, 2, 3, 4, 5])
TODO display tangle numbers , enumerate all
TODO confirm that this is right
TODO crossings rendered badly when img too large
TODO fix forking at intersections
TODO get rid of whitespace and use proportional LW
main = mainWith $ rawKnotsToNCrossings # centerXY # pad 1.01
|
7e884176be70442c56379b69d38c8e0a89acb6a20ae6474db66f80e195676a12 | mcorbin/meuse | git.clj | (ns meuse.git
"Interacts with a git repository"
(:require [meuse.config :as config]
[meuse.log :as log]
[meuse.metric :as metric]
[exoscale.cloak :as cloak]
[exoscale.ex :as ex]
[mount.core :refer [defstate]]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.string :as string])
(:import (org.eclipse.jgit.api Git)
(org.eclipse.jgit.api ResetCommand$ResetType)
(org.eclipse.jgit.transport CredentialsProvider
RefSpec
UsernamePasswordCredentialsProvider)))
(defprotocol IGit
(add [this])
(commit [this msg-header msg-body])
(get-lock [this])
(pull [this])
(reset-hard [this])
(clean [this])
(push [this]))
(defn git-cmd
[path args]
(log/debug {} "git command" (string/join " " args))
(metric/with-time :git.shell {"command" (first args)}
(let [result (apply shell/sh "git" "-C" path args)]
(log/debug {} "git command status code=" (:exit result)
"out=" (:out result)
"err=" (:err result))
(when-not (= 0 (:exit result))
(throw (ex/ex-fault (format "error executing git command %s: %s %s"
(first args)
(:out result)
(:err result))
{:exit-code (:exit result)
:stdout (:out result)
:stderr (:err result)
:command args}))))))
(defrecord LocalRepository [path target lock]
IGit
(add [this]
(git-cmd path ["add" "."]))
(commit [this msg-header msg-body]
(git-cmd path ["commit" "-m" msg-header "-m" msg-body]))
(get-lock [this]
lock)
(push [this]
(git-cmd path (concat ["push"] (string/split target #"/"))))
(reset-hard [this]
(git-cmd path (concat ["reset"] (string/split target #"/"))))
(clean [this]
(git-cmd path ["clean" "-f" "-d"]))
(pull [this]
(git-cmd path (concat ["pull"] (string/split target #"/")))))
(defrecord JGitFileRepository [target
lock
^Git git
^CredentialsProvider credentials]
IGit
(add [this]
(metric/with-time :git.jgit {"command" "add"}
(doto (.add git)
(.addFilepattern ".")
(.call))))
(commit [this msg-header msg-body]
(metric/with-time :git.jgit {"command" "commit"}
(doto (.commit git)
(.setMessage (str msg-header "\n\n" msg-body))
(.call))))
(get-lock [this]
lock)
(pull [this]
(metric/with-time :git.jgit {"command" "pull"}
(let [[remote branch] (string/split target #"/")]
(doto (.pull git)
(.setCredentialsProvider credentials)
(.setRemote remote)
(.setRemoteBranchName branch)
(.call)))))
(reset-hard [this]
(metric/with-time :git.jgit {"command" "reset"}
(doto (.reset git)
(.setMode ResetCommand$ResetType/HARD)
(.call))))
(clean [this]
(metric/with-time :git.jgit {"command" "clean"}
(doto (.clean git)
(.setCleanDirectories true)
(.call))))
(push [this]
(metric/with-time :git.jgit {"command" "push"}
(let [[remote branch] (string/split target #"/")
ref-spec (RefSpec. branch)]
(doto (.push git)
(.setCredentialsProvider credentials)
(.setRemote remote)
(.setRefSpecs (into-array [ref-spec]))
(.call))))))
(defn build-jgit
[config]
(map->JGitFileRepository
{:credentials (UsernamePasswordCredentialsProvider.
(:username config)
(:password config))
:git (Git/open (io/file (:path config)))
:lock (java.lang.Object.)
:target (:target config)}))
(defn build-local-git
[config]
(map->LocalRepository
{:path (:path config)
:lock (java.lang.Object.)
:target (:target config)}))
(defstate git
:start (condp = (get-in config/config [:metadata :type])
"jgit" (build-jgit (cloak/unmask (:metadata config/config)))
"shell" (build-local-git (:metadata config/config))
(build-local-git (:metadata config/config))))
| null | https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/git.clj | clojure | (ns meuse.git
"Interacts with a git repository"
(:require [meuse.config :as config]
[meuse.log :as log]
[meuse.metric :as metric]
[exoscale.cloak :as cloak]
[exoscale.ex :as ex]
[mount.core :refer [defstate]]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.string :as string])
(:import (org.eclipse.jgit.api Git)
(org.eclipse.jgit.api ResetCommand$ResetType)
(org.eclipse.jgit.transport CredentialsProvider
RefSpec
UsernamePasswordCredentialsProvider)))
(defprotocol IGit
(add [this])
(commit [this msg-header msg-body])
(get-lock [this])
(pull [this])
(reset-hard [this])
(clean [this])
(push [this]))
(defn git-cmd
[path args]
(log/debug {} "git command" (string/join " " args))
(metric/with-time :git.shell {"command" (first args)}
(let [result (apply shell/sh "git" "-C" path args)]
(log/debug {} "git command status code=" (:exit result)
"out=" (:out result)
"err=" (:err result))
(when-not (= 0 (:exit result))
(throw (ex/ex-fault (format "error executing git command %s: %s %s"
(first args)
(:out result)
(:err result))
{:exit-code (:exit result)
:stdout (:out result)
:stderr (:err result)
:command args}))))))
(defrecord LocalRepository [path target lock]
IGit
(add [this]
(git-cmd path ["add" "."]))
(commit [this msg-header msg-body]
(git-cmd path ["commit" "-m" msg-header "-m" msg-body]))
(get-lock [this]
lock)
(push [this]
(git-cmd path (concat ["push"] (string/split target #"/"))))
(reset-hard [this]
(git-cmd path (concat ["reset"] (string/split target #"/"))))
(clean [this]
(git-cmd path ["clean" "-f" "-d"]))
(pull [this]
(git-cmd path (concat ["pull"] (string/split target #"/")))))
(defrecord JGitFileRepository [target
lock
^Git git
^CredentialsProvider credentials]
IGit
(add [this]
(metric/with-time :git.jgit {"command" "add"}
(doto (.add git)
(.addFilepattern ".")
(.call))))
(commit [this msg-header msg-body]
(metric/with-time :git.jgit {"command" "commit"}
(doto (.commit git)
(.setMessage (str msg-header "\n\n" msg-body))
(.call))))
(get-lock [this]
lock)
(pull [this]
(metric/with-time :git.jgit {"command" "pull"}
(let [[remote branch] (string/split target #"/")]
(doto (.pull git)
(.setCredentialsProvider credentials)
(.setRemote remote)
(.setRemoteBranchName branch)
(.call)))))
(reset-hard [this]
(metric/with-time :git.jgit {"command" "reset"}
(doto (.reset git)
(.setMode ResetCommand$ResetType/HARD)
(.call))))
(clean [this]
(metric/with-time :git.jgit {"command" "clean"}
(doto (.clean git)
(.setCleanDirectories true)
(.call))))
(push [this]
(metric/with-time :git.jgit {"command" "push"}
(let [[remote branch] (string/split target #"/")
ref-spec (RefSpec. branch)]
(doto (.push git)
(.setCredentialsProvider credentials)
(.setRemote remote)
(.setRefSpecs (into-array [ref-spec]))
(.call))))))
(defn build-jgit
[config]
(map->JGitFileRepository
{:credentials (UsernamePasswordCredentialsProvider.
(:username config)
(:password config))
:git (Git/open (io/file (:path config)))
:lock (java.lang.Object.)
:target (:target config)}))
(defn build-local-git
[config]
(map->LocalRepository
{:path (:path config)
:lock (java.lang.Object.)
:target (:target config)}))
(defstate git
:start (condp = (get-in config/config [:metadata :type])
"jgit" (build-jgit (cloak/unmask (:metadata config/config)))
"shell" (build-local-git (:metadata config/config))
(build-local-git (:metadata config/config))))
|
|
622795464abb7bf4af5ff761577b9b299fb306d93c7e8593a9406921b40294e7 | cldwalker/nbb-clis | test_runner.cljs | (ns test-runner
(:require [clojure.test :as t]
[nbb.core :as nbb]
[logseq-roundtrip-test]
[logseq-block-move-test]))
(defn init []
(t/run-tests 'logseq-roundtrip-test
'logseq-block-move-test))
(when (= nbb/*file* (:file (meta #'init)))
(init))
| null | https://raw.githubusercontent.com/cldwalker/nbb-clis/3b4e346aaee6e9cdb7cae4a7a7fcdb900c54ee96/test/test_runner.cljs | clojure | (ns test-runner
(:require [clojure.test :as t]
[nbb.core :as nbb]
[logseq-roundtrip-test]
[logseq-block-move-test]))
(defn init []
(t/run-tests 'logseq-roundtrip-test
'logseq-block-move-test))
(when (= nbb/*file* (:file (meta #'init)))
(init))
|
|
a7120b14bc386edb60caae2d1af0a8423be9fcc1f4504e42667b5f69ecc97662 | LeventErkok/sbv | GCD.hs | -----------------------------------------------------------------------------
-- |
Module : Documentation . SBV.Examples . CodeGeneration . GCD
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
Computing GCD symbolically , and generating C code for it . This example
-- illustrates symbolic termination related issues when programming with
SBV , when the termination of a recursive algorithm crucially depends
-- on the value of a symbolic variable. The technique we use is to statically
-- enforce termination by using a recursion depth counter.
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall -Werror #-}
module Documentation.SBV.Examples.CodeGeneration.GCD where
import Data.SBV
import Data.SBV.Tools.CodeGen
-- $setup
-- >>> -- For doctest purposes only:
-- >>> import Data.SBV
> > > import Data . SBV.Tools . CodeGen
-----------------------------------------------------------------------------
-- * Computing GCD
-----------------------------------------------------------------------------
| The symbolic GCD algorithm , over two 8 - bit numbers . We define @sgcd a 0@ to
be @a@ for all @a@ , which implies @sgcd 0 0 = 0@. Note that this is essentially
Euclid 's algorithm , except with a recursion depth counter . We need the depth
-- counter since the algorithm is not /symbolically terminating/, as we don't have
a means of determining that the second argument ( @b@ ) will eventually reach 0 in a symbolic
context . Hence we stop after 12 iterations . Why 12 ? We 've empirically determined that this
algorithm will recurse at most 12 times for arbitrary 8 - bit numbers . Of course , this is
-- a claim that we shall prove below.
sgcd :: SWord8 -> SWord8 -> SWord8
sgcd a b = go a b 12
where go :: SWord8 -> SWord8 -> SWord8 -> SWord8
go x y c = ite (c .== 0 .|| y .== 0) -- stop if y is 0, or if we reach the recursion depth
x
(go y y' (c-1))
where (_, y') = x `sQuotRem` y
-----------------------------------------------------------------------------
-- * Verification
-----------------------------------------------------------------------------
$ VerificationIntro
We prove that ' sgcd ' does indeed compute the common divisor of the given numbers .
Our predicate takes @x@ , @y@ , and @k@. We show that what ' sgcd ' returns is indeed a common divisor ,
and it is at least as large as any given @k@ , provided @k@ is a common divisor as well .
We prove that 'sgcd' does indeed compute the common divisor of the given numbers.
Our predicate takes @x@, @y@, and @k@. We show that what 'sgcd' returns is indeed a common divisor,
and it is at least as large as any given @k@, provided @k@ is a common divisor as well.
-}
-- | We have:
--
-- >>> prove sgcdIsCorrect
Q.E.D.
sgcdIsCorrect :: SWord8 -> SWord8 -> SWord8 -> SBool
if y is 0
(k' .== x) -- then k' must be x, nothing else to prove by definition
(isCommonDivisor k' .&& -- otherwise, k' is a common divisor and
(isCommonDivisor k .=> k' .>= k)) -- if k is a common divisor as well, then k' is at least as large as k
where k' = sgcd x y
isCommonDivisor a = z1 .== 0 .&& z2 .== 0
where (_, z1) = x `sQuotRem` a
(_, z2) = y `sQuotRem` a
-----------------------------------------------------------------------------
-- * Code generation
-----------------------------------------------------------------------------
$ VerificationIntro
Now that we have proof our ' sgcd ' implementation is correct , we can go ahead
and generate C code for it .
Now that we have proof our 'sgcd' implementation is correct, we can go ahead
and generate C code for it.
-}
-- | This call will generate the required C files. The following is the function
-- body generated for 'sgcd'. (We are not showing the generated header, @Makefile@,
-- and the driver programs for brevity.) Note that the generated function is
a constant time algorithm for GCD . It is not necessarily fastest , but it will take
precisely the same amount of time for all values of @x@ and @y@.
--
> / * File : " sgcd.c " . Automatically generated by SBV . Do not edit ! * /
-- >
-- > #include <stdio.h>
-- > #include <stdlib.h>
-- > #include <inttypes.h>
-- > #include <stdint.h>
-- > #include <stdbool.h>
-- > #include "sgcd.h"
-- >
-- > SWord8 sgcd(const SWord8 x, const SWord8 y)
-- > {
-- > const SWord8 s0 = x;
-- > const SWord8 s1 = y;
> const SBool s3 = s1 = = 0 ;
-- > const SWord8 s4 = (s1 == 0) ? s0 : (s0 % s1);
-- > const SWord8 s5 = s3 ? s0 : s4;
-- > const SBool s6 = 0 == s5;
-- > const SWord8 s7 = (s5 == 0) ? s1 : (s1 % s5);
> const SWord8 s8 = s6 ? s1 : s7 ;
-- > const SBool s9 = 0 == s8;
-- > const SWord8 s10 = (s8 == 0) ? s5 : (s5 % s8);
-- > const SWord8 s11 = s9 ? s5 : s10;
> const SBool s12 = 0 = = s11 ;
> ( s11 = = 0 ) ? s8 : ( s8 % s11 ) ;
-- > const SWord8 s14 = s12 ? s8 : s13;
-- > const SBool s15 = 0 == s14;
> const SWord8 s16 = ( s14 = = 0 ) ? s11 : ( s11 % s14 ) ;
> const SWord8 s17 = s15 ? s11 : s16 ;
> const SBool s18 = 0 = = s17 ;
> const SWord8 s19 = ( s17 = = 0 ) ? s14 : ( s14 % s17 ) ;
-- > const SWord8 s20 = s18 ? s14 : s19;
-- > const SBool s21 = 0 == s20;
> const SWord8 s22 = ( s20 = = 0 ) ? s17 : ( s17 % s20 ) ;
> const SWord8 s23 = s21 ? s17 : s22 ;
-- > const SBool s24 = 0 == s23;
-- > const SWord8 s25 = (s23 == 0) ? s20 : (s20 % s23);
> const SWord8 s26 = s24 ? s20 : ;
-- > const SBool s27 = 0 == s26;
> const SWord8 s28 = ( s26 = = 0 ) ? s23 : ( s23 % s26 ) ;
-- > const SWord8 s29 = s27 ? s23 : s28;
> const SBool s30 = 0 = = s29 ;
> const SWord8 s31 = ( s29 = = 0 ) ? s26 : ( s26 % s29 ) ;
-- > const SWord8 s32 = s30 ? s26 : s31;
> const SBool s33 = 0 = = s32 ;
-- > const SWord8 s34 = (s32 == 0) ? s29 : (s29 % s32);
> const SWord8 s35 = s33 ? s29 : s34 ;
> const SBool s36 = 0 = = s35 ;
> const SWord8 s37 = s36 ? s32 : s35 ;
> const SWord8 s38 = s33 ? s29 : s37 ;
> const SWord8 s39 = s30 ? s26 : s38 ;
-- > const SWord8 s40 = s27 ? s23 : s39;
-- > const SWord8 s41 = s24 ? s20 : s40;
> const SWord8 s42 = s21 ? s17 : s41 ;
-- > const SWord8 s43 = s18 ? s14 : s42;
-- > const SWord8 s44 = s15 ? s11 : s43;
> const SWord8 s45 = s12 ? s8 : s44 ;
-- > const SWord8 s46 = s9 ? s5 : s45;
> const SWord8 s47 = s6 ? s1 : ;
-- > const SWord8 s48 = s3 ? s0 : s47;
-- >
-- > return s48;
-- > }
genGCDInC :: IO ()
genGCDInC = compileToC Nothing "sgcd" $ do
x <- cgInput "x"
y <- cgInput "y"
cgReturn $ sgcd x y
| null | https://raw.githubusercontent.com/LeventErkok/sbv/0d791d9f4d1de6bd915b6d7d3f9a550385cb27a5/Documentation/SBV/Examples/CodeGeneration/GCD.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Maintainer:
Stability : experimental
illustrates symbolic termination related issues when programming with
on the value of a symbolic variable. The technique we use is to statically
enforce termination by using a recursion depth counter.
---------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror #
$setup
>>> -- For doctest purposes only:
>>> import Data.SBV
---------------------------------------------------------------------------
* Computing GCD
---------------------------------------------------------------------------
counter since the algorithm is not /symbolically terminating/, as we don't have
a claim that we shall prove below.
stop if y is 0, or if we reach the recursion depth
---------------------------------------------------------------------------
* Verification
---------------------------------------------------------------------------
| We have:
>>> prove sgcdIsCorrect
then k' must be x, nothing else to prove by definition
otherwise, k' is a common divisor and
if k is a common divisor as well, then k' is at least as large as k
---------------------------------------------------------------------------
* Code generation
---------------------------------------------------------------------------
| This call will generate the required C files. The following is the function
body generated for 'sgcd'. (We are not showing the generated header, @Makefile@,
and the driver programs for brevity.) Note that the generated function is
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <inttypes.h>
> #include <stdint.h>
> #include <stdbool.h>
> #include "sgcd.h"
>
> SWord8 sgcd(const SWord8 x, const SWord8 y)
> {
> const SWord8 s0 = x;
> const SWord8 s1 = y;
> const SWord8 s4 = (s1 == 0) ? s0 : (s0 % s1);
> const SWord8 s5 = s3 ? s0 : s4;
> const SBool s6 = 0 == s5;
> const SWord8 s7 = (s5 == 0) ? s1 : (s1 % s5);
> const SBool s9 = 0 == s8;
> const SWord8 s10 = (s8 == 0) ? s5 : (s5 % s8);
> const SWord8 s11 = s9 ? s5 : s10;
> const SWord8 s14 = s12 ? s8 : s13;
> const SBool s15 = 0 == s14;
> const SWord8 s20 = s18 ? s14 : s19;
> const SBool s21 = 0 == s20;
> const SBool s24 = 0 == s23;
> const SWord8 s25 = (s23 == 0) ? s20 : (s20 % s23);
> const SBool s27 = 0 == s26;
> const SWord8 s29 = s27 ? s23 : s28;
> const SWord8 s32 = s30 ? s26 : s31;
> const SWord8 s34 = (s32 == 0) ? s29 : (s29 % s32);
> const SWord8 s40 = s27 ? s23 : s39;
> const SWord8 s41 = s24 ? s20 : s40;
> const SWord8 s43 = s18 ? s14 : s42;
> const SWord8 s44 = s15 ? s11 : s43;
> const SWord8 s46 = s9 ? s5 : s45;
> const SWord8 s48 = s3 ? s0 : s47;
>
> return s48;
> } | Module : Documentation . SBV.Examples . CodeGeneration . GCD
Copyright : ( c )
Computing GCD symbolically , and generating C code for it . This example
SBV , when the termination of a recursive algorithm crucially depends
module Documentation.SBV.Examples.CodeGeneration.GCD where
import Data.SBV
import Data.SBV.Tools.CodeGen
> > > import Data . SBV.Tools . CodeGen
| The symbolic GCD algorithm , over two 8 - bit numbers . We define @sgcd a 0@ to
be @a@ for all @a@ , which implies @sgcd 0 0 = 0@. Note that this is essentially
Euclid 's algorithm , except with a recursion depth counter . We need the depth
a means of determining that the second argument ( @b@ ) will eventually reach 0 in a symbolic
context . Hence we stop after 12 iterations . Why 12 ? We 've empirically determined that this
algorithm will recurse at most 12 times for arbitrary 8 - bit numbers . Of course , this is
sgcd :: SWord8 -> SWord8 -> SWord8
sgcd a b = go a b 12
where go :: SWord8 -> SWord8 -> SWord8 -> SWord8
x
(go y y' (c-1))
where (_, y') = x `sQuotRem` y
$ VerificationIntro
We prove that ' sgcd ' does indeed compute the common divisor of the given numbers .
Our predicate takes @x@ , @y@ , and @k@. We show that what ' sgcd ' returns is indeed a common divisor ,
and it is at least as large as any given @k@ , provided @k@ is a common divisor as well .
We prove that 'sgcd' does indeed compute the common divisor of the given numbers.
Our predicate takes @x@, @y@, and @k@. We show that what 'sgcd' returns is indeed a common divisor,
and it is at least as large as any given @k@, provided @k@ is a common divisor as well.
-}
Q.E.D.
sgcdIsCorrect :: SWord8 -> SWord8 -> SWord8 -> SBool
if y is 0
where k' = sgcd x y
isCommonDivisor a = z1 .== 0 .&& z2 .== 0
where (_, z1) = x `sQuotRem` a
(_, z2) = y `sQuotRem` a
$ VerificationIntro
Now that we have proof our ' sgcd ' implementation is correct , we can go ahead
and generate C code for it .
Now that we have proof our 'sgcd' implementation is correct, we can go ahead
and generate C code for it.
-}
a constant time algorithm for GCD . It is not necessarily fastest , but it will take
precisely the same amount of time for all values of @x@ and @y@.
> / * File : " sgcd.c " . Automatically generated by SBV . Do not edit ! * /
> const SBool s3 = s1 = = 0 ;
> const SWord8 s8 = s6 ? s1 : s7 ;
> const SBool s12 = 0 = = s11 ;
> ( s11 = = 0 ) ? s8 : ( s8 % s11 ) ;
> const SWord8 s16 = ( s14 = = 0 ) ? s11 : ( s11 % s14 ) ;
> const SWord8 s17 = s15 ? s11 : s16 ;
> const SBool s18 = 0 = = s17 ;
> const SWord8 s19 = ( s17 = = 0 ) ? s14 : ( s14 % s17 ) ;
> const SWord8 s22 = ( s20 = = 0 ) ? s17 : ( s17 % s20 ) ;
> const SWord8 s23 = s21 ? s17 : s22 ;
> const SWord8 s26 = s24 ? s20 : ;
> const SWord8 s28 = ( s26 = = 0 ) ? s23 : ( s23 % s26 ) ;
> const SBool s30 = 0 = = s29 ;
> const SWord8 s31 = ( s29 = = 0 ) ? s26 : ( s26 % s29 ) ;
> const SBool s33 = 0 = = s32 ;
> const SWord8 s35 = s33 ? s29 : s34 ;
> const SBool s36 = 0 = = s35 ;
> const SWord8 s37 = s36 ? s32 : s35 ;
> const SWord8 s38 = s33 ? s29 : s37 ;
> const SWord8 s39 = s30 ? s26 : s38 ;
> const SWord8 s42 = s21 ? s17 : s41 ;
> const SWord8 s45 = s12 ? s8 : s44 ;
> const SWord8 s47 = s6 ? s1 : ;
genGCDInC :: IO ()
genGCDInC = compileToC Nothing "sgcd" $ do
x <- cgInput "x"
y <- cgInput "y"
cgReturn $ sgcd x y
|
41676da41fb24bd00c6daf6b6c22eeba4447f8533008c216cbd6a6b36316089e | manuel-serrano/hop | tyflow.scm | ;*=====================================================================*/
* serrano / prgm / project / hop / hop / js2scheme / tyflow.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Sun Oct 16 06:12:13 2016 * /
* Last change : Sun Mar 6 16:55:10 2022 ( serrano ) * /
* Copyright : 2016 - 22 * /
;* ------------------------------------------------------------- */
;* js2scheme type inference */
;* ------------------------------------------------------------- */
* This pass does not assume any type decoration in the AST , not * /
;* even for literals and constants. */
;* ------------------------------------------------------------- */
;* This stage assigns types to variable declarations and variable */
;* references. At a declaration site, the types are: */
;* */
;* itype: the initial type of the variable */
;* utype: the user given type, enforced on assignments */
* vtype : the final type of the variable ( used by scheme ) * /
;* */
;* Types of declared variables have the following properties: */
;* 1- itype < vtype */
* 2- for in ref(v ) , T(ref(v ) ) < vtype * /
* 3- if utype ! = unknown then itype = vtype = utype * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __js2scheme_tyflow
(include "ast.sch"
"usage.sch")
(import __js2scheme_ast
__js2scheme_dump
__js2scheme_compile
__js2scheme_stage
__js2scheme_syntax
__js2scheme_utils
__js2scheme_classutils
__js2scheme_type-hint
__js2scheme_use
__js2scheme_alpha)
(export j2s-tyflow-stage))
;*---------------------------------------------------------------------*/
* - stage ... * /
;*---------------------------------------------------------------------*/
(define j2s-tyflow-stage
(instantiate::J2SStageProc
(name "tyflow")
(comment "Dataflow type inference")
(proc j2s-typing!)))
;*---------------------------------------------------------------------*/
;* debug-tyflow ... */
;*---------------------------------------------------------------------*/
(define debug-tyflow #f)
;*---------------------------------------------------------------------*/
;* j2s-typing! ::obj ... */
;*---------------------------------------------------------------------*/
(define (j2s-typing! this args)
(when (isa? this J2SProgram)
(type-program! this args)
this))
;*---------------------------------------------------------------------*/
;* utype-compatible? ... */
;*---------------------------------------------------------------------*/
(define (utype-compatible? utype type)
(or (eq? type 'magic) (type-subtype? type utype)))
;*---------------------------------------------------------------------*/
;* tyflow-type ... */
;* ------------------------------------------------------------- */
;* Maps to tyflow understood types. */
;*---------------------------------------------------------------------*/
(define (tyflow-type ty)
(j2s-hint-type ty))
;*---------------------------------------------------------------------*/
;* type-program! ... */
;*---------------------------------------------------------------------*/
(define (type-program! this::J2SProgram conf)
(define j2s-verbose (config-get conf :verbose 0))
(with-access::J2SProgram this (headers decls nodes mode)
(when (>=fx j2s-verbose 3) (display " " (current-error-port)))
;; main fix point
(if (config-get conf :optim-tyflow #f)
(let ((ctx (cons mode 0)))
(let loop ((i 1))
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port) "~a." i)
(flush-output-port (current-error-port)))
(let ((ofix (cdr ctx)))
;; type all the nodes
(node-type-seq (append headers decls nodes) '() ctx 'void)
(cond
((not (=fx (cdr ctx) ofix))
(loop (+fx i 1)))
((config-get conf :optim-tyflow-resolve #f)
;; type check resolution
(let ((reset-for-resolve (j2s-resolve! this conf ctx)))
(cond
((not (=fx (cdr ctx) ofix))
(loop (+fx i 1)))
((config-get conf :optim-hint #f)
;; hint node-type optimization
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port) "hint"))
(let ((dups (j2s-hint! this conf)))
(cond
((pair? dups)
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port)
(format " [~(,)]."
(map (lambda (d)
(with-access::J2SDecl d (id)
id))
dups))))
(for-each reset-type! decls)
(for-each reset-type! nodes)
(loop (+fx i 1)))
(reset-for-resolve
(for-each reset-type! decls)
(for-each reset-type! nodes)
(loop (+fx i 1)))
((force-type this 'unknown 'any #f)
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port) "."))
(loop (+fx i 1))))))
((force-type this 'unknown 'any #f)
(loop (+fx i 1))))))))))
(begin
(force-record-method-type this)
(force-type this 'unknown 'any #t)))
(when (config-get conf :optim-hintblock)
(when (>=fx (config-get conf :verbose 0) 4)
(display " hint-block" (current-error-port)))
(j2s-hint-block! this conf))
(unless (config-get conf :optim-integer)
(force-type this 'integer 'number #f))
(force-type this 'unknown 'any #t)
(cleanup-hint! this)
(program-cleanup! this))
this)
;*---------------------------------------------------------------------*/
;* program-cleanup! ... */
;*---------------------------------------------------------------------*/
(define (program-cleanup! this::J2SProgram)
(with-access::J2SProgram this (headers decls nodes direct-eval)
(reinit-use-count! this)
(unless direct-eval
(set! decls (filter-dead-declarations decls))
(for-each j2s-hint-meta-noopt! decls))
this))
;*---------------------------------------------------------------------*/
;* dump-env ... */
;*---------------------------------------------------------------------*/
(define (dump-env env)
(map (lambda (e)
(cons (with-access::J2SDecl (car e) (id key)
(format "~a:~a" id key))
(type->sexp (cdr e))))
env))
;*---------------------------------------------------------------------*/
;* unfix! ... */
;*---------------------------------------------------------------------*/
(define (unfix! ctx reason)
(tprint "--- UNFIX (" (cdr ctx) ") reason=" reason)
(set-cdr! ctx (+fx 1 (cdr ctx))))
(define-macro (unfix! ctx reason)
`(set-cdr! ,ctx (+fx 1 (cdr ,ctx))))
;*---------------------------------------------------------------------*/
;* return ... */
;*---------------------------------------------------------------------*/
(define (return ty env::pair-nil bk::pair-nil)
(values ty env bk))
;*---------------------------------------------------------------------*/
* - set ! ... * /
;* ------------------------------------------------------------- */
;* Assign a unique type to a variable declaration. */
;*---------------------------------------------------------------------*/
(define (decl-vtype-set! decl::J2SDecl ty::obj ctx::pair)
(with-access::J2SDecl decl (ctype vtype id loc)
[assert (ty) (or (eq? vtype 'unknown) (eq? vtype ty))]
(unless (memq ctype '(any unknown))
(set! ty ctype))
(when (or (eq? vtype 'unknown) (not (eq? vtype ty)))
(unfix! ctx (format "J2SDecl.vset(~a, ~a) vtype=~a/~a" id loc
(type->sexp vtype) (type->sexp ty)))
(set! vtype (tyflow-type ty)))))
;*---------------------------------------------------------------------*/
* - add ! ... * /
;* ------------------------------------------------------------- */
;* Add a new type to a variable declaration. */
;*---------------------------------------------------------------------*/
(define (decl-vtype-add! decl::J2SDecl ty ctx::pair)
(with-access::J2SDecl decl (ctype vtype id loc)
(unless (eq? ctype 'any)
(set! ty ctype))
(unless (or (eq? ty 'unknown) (type-subtype? ty vtype) (eq? vtype 'any))
(unfix! ctx (format "J2SDecl.vadd(~a, ~a) vtype=~a/~a" id loc
(type->sexp vtype) (type->sexp ty)))
(set! vtype (tyflow-type (merge-types vtype ty))))))
;*---------------------------------------------------------------------*/
* - add ! ... * /
;* ------------------------------------------------------------- */
;* Add a new initial type to a variable declaration. */
;*---------------------------------------------------------------------*/
(define (decl-itype-add! decl::J2SDecl ty ctx::pair)
(with-access::J2SDecl decl (ctype itype id)
(unless (eq? ctype 'any)
(set! ty ctype))
(unless (or (eq? ty 'unknown) (type-subtype? ty itype) (eq? itype 'any))
(unfix! ctx (format "J2SDecl.iadd(~a) itype=~a/~a" id
(type->sexp itype) (type->sexp ty)))
(set! itype (tyflow-type (merge-types itype ty))))))
;*---------------------------------------------------------------------*/
;* expr-type-add! ... */
;* ------------------------------------------------------------- */
;* Set the expression type and if needed update the ctx stamp. */
;*---------------------------------------------------------------------*/
(define (expr-type-add! this::J2SExpr env::pair-nil ctx::pair ty
#!optional (bk '()))
(with-access::J2SExpr this (type loc)
(unless (or (eq? ty 'unknown) (eq? type ty))
(let ((ntype (merge-types type ty)))
(unless (eq? ntype type)
(unfix! ctx
(format "J2SExpr.add(~a) ~a ~a/~a -> ~a"
loc (j2s->sexp this)
(type->sexp ty)
(type->sexp type)
(type->sexp ntype)))
(set! type (tyflow-type ntype)))))
(return type env bk)))
;*---------------------------------------------------------------------*/
;* class-element-type-add! ... */
;*---------------------------------------------------------------------*/
(define (class-element-type-add! this::J2SClassElement ctx::pair ty)
(with-access::J2SClassElement this (type loc)
(unless (or (eq? ty 'unknown) (eq? type ty))
(let ((ntype (merge-types type ty)))
(unless (eq? ntype type)
(unfix! ctx
(format "J2SClassElement.add(~a) ~a ~a/~a -> ~a"
loc (j2s->sexp this)
(type->sexp ty)
(type->sexp type)
(type->sexp ntype)))
(set! type (tyflow-type ntype))))) ))
;*---------------------------------------------------------------------*/
;* class-element-access-type-add! ... */
;*---------------------------------------------------------------------*/
(define (class-element-access-type-add! this::J2SAccess ctx::pair ty)
(let ((el (class-private-element-access this)))
(class-element-type-add! el ctx ty)))
;*---------------------------------------------------------------------*/
;* merge-types ... */
;*---------------------------------------------------------------------*/
(define (merge-types left right)
(cond
((eq? left right) left)
((and (eq? left 'arrow) (eq? right 'function)) 'arrow)
((and (eq? left 'function) (eq? right 'arrow)) 'arrow)
((eq? left 'unknown) right)
((eq? right 'unknown) left)
((and (type-integer? left) (type-integer? right)) 'integer)
((and (type-integer? left) (eq? right 'number)) 'number)
((and (eq? left 'number) (type-integer? right)) 'number)
((and (eq? left 'number) (eq? right 'integer)) 'number)
((type-subtype? left right) right)
((type-subtype? right left) left)
(else 'any)))
;*---------------------------------------------------------------------*/
;* typnum? ... */
;*---------------------------------------------------------------------*/
(define (typnum? ty)
(memq ty '(index length indexof integer real bigint number)))
;*---------------------------------------------------------------------*/
;* funtype ... */
;*---------------------------------------------------------------------*/
(define (funtype this::J2SFun)
(cond
((isa? this J2SArrow) 'arrow)
((isa? this J2SSvc) 'service)
(else 'function)))
;*---------------------------------------------------------------------*/
;* env? ... */
;*---------------------------------------------------------------------*/
(define (env? o)
;; heuristic check (not very precise but should be enough)
(or (null? o)
(and (pair? o)
(isa? (caar o) J2SDecl)
(symbol? (cdar o)))))
;*---------------------------------------------------------------------*/
;* extend-env ... */
;*---------------------------------------------------------------------*/
(define (extend-env::pair-nil env::pair-nil decl::J2SDecl ty)
(let ((old (env-lookup env decl)))
(if (eq? ty 'unknown)
env
(cons (cons decl ty) env))))
;*---------------------------------------------------------------------*/
;* refine-env ... */
;* ------------------------------------------------------------- */
* add ty > only if is not already in env or if the * /
;* current type is a super type of ty. */
;*---------------------------------------------------------------------*/
(define (refine-env::pair-nil env::pair-nil decl::J2SDecl ty)
(let ((old (env-lookup env decl)))
(if (or (not old) (type-subtype? ty old) (memq old '(any unknown)))
(cons (cons decl ty) env)
env)))
;*---------------------------------------------------------------------*/
;* env-lookup ... */
;*---------------------------------------------------------------------*/
(define (env-lookup env::pair-nil decl::J2SDecl)
(let ((c (assq decl env)))
(if (pair? c)
(cdr c)
(with-access::J2SDecl decl (ctype vtype)
(if (eq? ctype 'any) vtype ctype)))))
;*---------------------------------------------------------------------*/
;* env-nocapture ... */
;*---------------------------------------------------------------------*/
(define (env-nocapture env::pair-nil)
(map (lambda (c)
(with-access::J2SDecl (car c) (escape)
(if (and escape (decl-usage-has? (car c) '(assig)))
(cons (car c) 'any)
c)))
env))
;*---------------------------------------------------------------------*/
;* env-merge ... */
;*---------------------------------------------------------------------*/
(define (env-merge::pair-nil left::pair-nil right::pair-nil)
(define (merge2 env1 env2)
(filter-map (lambda (entry)
(let* ((decl (car entry))
(typl (cdr entry))
(typf (env-lookup env2 decl))
(typm (if (eq? typf 'unknown)
'unknown
(merge-types typl typf))))
(unless (eq? typm 'unknown)
(cons decl typm))))
env1))
(merge2 right (merge2 left right)))
;*---------------------------------------------------------------------*/
;* env-override ... */
;*---------------------------------------------------------------------*/
(define (env-override left::pair-nil right::pair-nil)
(append right
(filter (lambda (l)
(not (assq (car l) right)))
left)))
;*---------------------------------------------------------------------*/
;* node-type-args ... */
;* ------------------------------------------------------------- */
;* Type all the arguments and return a new environment. The */
;* arguments are typed as left to right sequence. */
;*---------------------------------------------------------------------*/
(define (node-type-args::pair-nil args env::pair-nil ctx::pair)
(let loop ((args args)
(env env)
(bks '()))
(if (null? args)
(values env bks)
(multiple-value-bind (_ enva bk)
(node-type (car args) env ctx)
(loop (cdr args) enva (append bk bks))))))
;*---------------------------------------------------------------------*/
;* node-type-seq ... */
;*---------------------------------------------------------------------*/
(define (node-type-seq nodes::pair-nil env::pair-nil ctx::pair initty)
(let loop ((nodes nodes)
(ty initty)
(env env)
(bks '()))
(if (null? nodes)
(return ty env bks)
(multiple-value-bind (tyn envn bk)
(node-type (car nodes) env ctx)
(if (pair? bk)
(multiple-value-bind (tyr envr bkr)
(node-type-seq (cdr nodes) envn ctx initty)
(return tyr (env-merge envn envr) (append bk bks)))
(loop (cdr nodes) tyn envn (append bk bks)))))))
;*---------------------------------------------------------------------*/
;* filter-breaks ... */
;*---------------------------------------------------------------------*/
(define (filter-breaks bks::pair-nil node)
(filter (lambda (b::J2SStmt)
(or (isa? b J2SReturn)
(isa? b J2SThrow)
(with-access::J2SBreak b (target)
(not (eq? target node)))))
bks))
;*---------------------------------------------------------------------*/
;* node-type ::J2SNode ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SNode env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SNode"
(return 'any '() '())))
;*---------------------------------------------------------------------*/
;* node-type ::J2SMeta ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SMeta env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SMeta"
(with-access::J2SMeta this (stmt)
(node-type stmt env ctx))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SExpr ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SExpr env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SExpr"
(call-next-method)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SNull ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SNull env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SNull"
(expr-type-add! this env ctx 'null)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SUndefined ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SUndefined env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'undefined))
;*---------------------------------------------------------------------*/
;* node-type ::J2SArrayAbsent ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SArrayAbsent env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'undefined))
;*---------------------------------------------------------------------*/
;* node-type ::J2SNumber ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SNumber env::pair-nil ctx::pair)
(with-access::J2SNumber this (val type)
(expr-type-add! this env ctx
(if (flonum? val) 'real (if (bignum? val) 'bigint 'integer)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SBool ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SBool env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'bool))
;*---------------------------------------------------------------------*/
;* node-type ::J2SString ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SString env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'string))
;*---------------------------------------------------------------------*/
;* node-type ::J2SNativeString ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SNativeString env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'scmstring))
;*---------------------------------------------------------------------*/
;* node-type ::J2SRegExp ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SRegExp env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'regexp))
;*---------------------------------------------------------------------*/
;* node-type ::J2SLiteralCnst ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SLiteralCnst env::pair-nil ctx::pair)
(with-access::J2SLiteralCnst this (val)
(multiple-value-bind (tyv env bk)
(node-type val env ctx)
(expr-type-add! this env ctx tyv bk))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCmap ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCmap env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'cmap))
;*---------------------------------------------------------------------*/
;* node-type ::J2STemplate ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2STemplate env::pair-nil ctx::pair)
(with-access::J2STemplate this (exprs)
(multiple-value-bind (env bk)
(node-type-args exprs env ctx)
(expr-type-add! this env ctx 'string bk))))
;*---------------------------------------------------------------------*/
;* node-type ::J2STilde ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2STilde env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'tilde))
;*---------------------------------------------------------------------*/
;* node-type ::J2SArray ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SArray env::pair-nil ctx::pair)
(with-access::J2SArray this (exprs len isvector type)
(multiple-value-bind (env bk)
(node-type-args exprs env ctx)
(expr-type-add! this env ctx type bk))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SSpread ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SSpread env::pair-nil ctx::pair)
(with-access::J2SSpread this (expr len)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(expr-type-add! this enve ctx tye bke))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SPragma ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SPragma env::pair-nil ctx::pair)
(with-access::J2SPragma this (lang expr type)
(cond
((eq? lang 'scheme)
(if (eq? type 'unknown)
(expr-type-add! this env ctx 'any)
(return type env env)))
((isa? expr J2SNode)
(multiple-value-bind (_ _ bk)
(node-type expr env ctx)
(if (eq? type 'unknown)
(expr-type-add! this env ctx 'any bk)
(return type env env))))
(else
(expr-type-add! this env ctx 'any)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SPropertyInit ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SPropertyInit env::pair-nil ctx::pair)
'unknown)
;*---------------------------------------------------------------------*/
;* node-type ::J2SDataPropertyInit ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDataPropertyInit env::pair-nil ctx::pair)
(with-access::J2SDataPropertyInit this (val)
(node-type val env ctx)))
;*---------------------------------------------------------------------*/
* node - type : : J2SAccessorPropertyInit ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SAccessorPropertyInit env::pair-nil ctx::pair)
(with-access::J2SAccessorPropertyInit this (get set)
(call-default-walker)
(return 'void env '())))
;*---------------------------------------------------------------------*/
;* node-type ::J2SObjInit ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SObjInit env::pair-nil ctx::pair)
(with-access::J2SObjInit this (inits)
(let ((args (append-map (lambda (init)
(cond
((isa? init J2SDataPropertyInit)
(with-access::J2SDataPropertyInit init (name val)
(list name val)))
((isa? init J2SAccessorPropertyInit)
(with-access::J2SAccessorPropertyInit init (name get set)
(list name get set)))))
inits)))
(multiple-value-bind (env bk)
(node-type-args args env ctx)
(expr-type-add! this env ctx 'object bk)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SParen ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SParen env::pair-nil ctx::pair)
(with-access::J2SParen this (expr)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(expr-type-add! this enve ctx tye bke))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SSequence ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SSequence env::pair-nil ctx::pair)
(define (node-type* nodes::pair-nil env::pair-nil ctx::pair)
(let loop ((nodes nodes)
(ty 'undefined)
(env env)
(bks '()))
(if (null? nodes)
(return ty env bks)
(multiple-value-bind (tyn envn bk)
(node-type (car nodes) env ctx)
(if (pair? bk)
(multiple-value-bind (tyr envr bkr)
(node-type-seq (cdr nodes) envn ctx 'unknown)
(return tyr (env-merge envn envr) (append bk bk bks)))
(loop (cdr nodes) tyn envn (append bk bks)))))))
(with-trace 'j2s-tyflow (format "node-type ::J2SSequence ~a" (cdr ctx))
(with-access::J2SSequence this (exprs)
(multiple-value-bind (tye env bk)
(node-type* exprs env ctx)
(expr-type-add! this env ctx tye bk)))))
;*---------------------------------------------------------------------*/
* node - type : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SBindExit env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SBindExit ~a" (cdr ctx))
(with-access::J2SBindExit this (stmt type loc)
(multiple-value-bind (typ env bk)
(node-type stmt env ctx)
(return type env bk)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SHopRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SHopRef env::pair-nil ctx::pair)
(with-access::J2SHopRef this (type)
(return type env '())))
;*---------------------------------------------------------------------*/
;* node-type ::J2SUnresolvedRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SUnresolvedRef env::pair-nil ctx::pair)
(with-access::J2SUnresolvedRef this (id)
(cond
((memq id '(console))
(expr-type-add! this env ctx 'object))
((eq? id 'undefined)
(expr-type-add! this env ctx 'undefined))
(else
(let ((cla (class-of this)))
(if (or (not cla) (eq? cla 'unknown))
(expr-type-add! this env ctx 'any)
(expr-type-add! this env ctx 'object)))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SGlobalRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SGlobalRef env::pair-nil ctx::pair)
(with-access::J2SGlobalRef this (decl id)
(cond
((eq? id 'undefined)
(decl-vtype-add! decl 'undefined ctx)
(expr-type-add! this env ctx 'undefined))
((eq? id 'NaN)
(decl-vtype-add! decl 'real ctx)
(expr-type-add! this env ctx 'real))
((memq id '(Math String Error Regex Date Function Array Promise))
(decl-vtype-add! decl 'object ctx)
(expr-type-add! this env ctx 'object))
((not (decl-ronly? decl))
(multiple-value-bind (tyv env bk)
(call-next-method)
(decl-vtype-add! decl tyv ctx)
(return tyv env bk)))
(else
(decl-vtype-add! decl 'any ctx)
(expr-type-add! this env ctx 'any)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SRef env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SRef ~a" (cdr ctx))
(with-access::J2SRef this (decl loc)
(trace-item "loc=" loc)
(with-access::J2SDecl decl (id key vtype scope)
(let ((nenv env))
(when (and (isa? decl J2SDeclFun) (not (constructor-only? decl)))
(set! nenv (env-nocapture env))
(with-access::J2SDeclFun decl (val id)
(if (isa? val J2SMethod)
(escape-method val ctx)
(escape-fun val ctx #f))))
(if (and (memq scope '(%scope global tls))
(not (eq? vtype 'unknown)))
(expr-type-add! this nenv ctx vtype)
(let ((ty (env-lookup env decl)))
(expr-type-add! this nenv ctx ty))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SSuper ... */
;*---------------------------------------------------------------------*/
(define-method (node-type this::J2SSuper env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SSuper ~a" (cdr ctx))
(with-access::J2SSuper this (decl loc super context)
(cond
((isa? super J2SClass)
(expr-type-add! this env ctx super))
((isa? context J2SClass)
(expr-type-add! this env ctx (or (j2s-class-super-val context) 'any)))
(else
(let ((ty (env-lookup env decl)))
(if (isa? ty J2SClass)
(expr-type-add! this env ctx (or (j2s-class-super-val ty) 'any))
(expr-type-add! this env ctx 'any))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SWithRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SWithRef env::pair-nil ctx::pair)
(with-access::J2SWithRef this (expr)
(node-type expr '() ctx)
(expr-type-add! this env ctx 'any)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SKontRef ... */
;*---------------------------------------------------------------------*/
(define-method (node-type this::J2SKontRef env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'any))
;*---------------------------------------------------------------------*/
;* node-type ::J2SDecl ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDecl env::pair-nil ctx::pair)
(decl-itype-add! this 'undefined ctx)
(decl-vtype-add! this 'undefined ctx)
(return 'void (extend-env env this 'undefined) '()))
;*---------------------------------------------------------------------*/
* node - type : : J2SDeclImport ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDeclImport env::pair-nil ctx::pair)
(decl-itype-add! this 'any ctx)
(decl-vtype-add! this 'any ctx)
(return 'void (extend-env env this 'any) '()))
;*---------------------------------------------------------------------*/
;* node-type ::J2SDeclArguments ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDeclArguments env::pair-nil ctx::pair)
(decl-itype-add! this 'arguments ctx)
(decl-vtype-add! this 'arguments ctx)
(return 'void (extend-env env this 'arguments) '()))
;*---------------------------------------------------------------------*/
;* node-type ::J2SDeclInit ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDeclInit env::pair-nil ctx::pair)
(with-access::J2SDeclInit this (val id loc _usage writable ctype utype mtype)
(multiple-value-bind (ty env bk)
(node-type val env ctx)
;; check the special case
;; declinit v = new Record();
(when (isa? val J2SNew)
(with-access::J2SNew val (clazz)
(when (isa? clazz J2SRef)
(with-access::J2SRef clazz (decl)
(when (isa? decl J2SDeclClass)
(with-access::J2SDeclClass decl (val)
(when (isa? val J2SRecord)
(unless (decl-usage-has? decl '(assig))
(set! mtype val)))))))))
(cond
((not (memq ctype '(any unknown)))
(decl-vtype-set! this ctype ctx)
(return 'void (extend-env env this ctype) bk))
((and (not (eq? utype 'unknown)) (eq? (car ctx) 'hopscript))
(decl-vtype-set! this utype ctx)
(let ((tyv (j2s-type val)))
(unless (utype-compatible? utype tyv)
(if (memq tyv '(unknown any object))
(set! val (J2SCheck utype val))
(utype-error val utype tyv))))
(return 'void (extend-env env this utype) bk))
((decl-usage-has? this '(eval))
(decl-vtype-add! this 'any ctx)
(return 'void (extend-env env this ty) bk))
((or (eq? ty 'unknown) (not ty))
(return 'void env bk))
((and (not writable)
(not (decl-usage-has? this '(uninit)))
(decl-usage-has? this '(assig)))
;; wait for the ::J2SInit expression for assigning a type
;; to this constant
(return 'void env bk))
(else
(decl-vtype-add! this ty ctx)
(return 'void (extend-env env this ty) bk))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SDeclFun ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDeclFun env::pair-nil ctx::pair)
(define (node-type-optional-args val env ctx)
(with-access::J2SFun val (params)
(for-each (lambda (p)
(when (isa? p J2SDeclInit)
(node-type p env ctx)))
params)))
(define (node-type-ctor-only val)
(with-access::J2SFun val (generator rtype thisp)
(when generator
(set! rtype 'any))
(when (isa? thisp J2SDecl)
(decl-itype-add! thisp 'object ctx))))
(with-access::J2SDeclFun this (val scope id loc)
(if (isa? val J2SFun)
(node-type-optional-args val env ctx)
(with-access::J2SMethod val (function method)
(node-type-optional-args function env ctx)
(node-type-optional-args method env ctx)))
(let ((ty (if (isa? this J2SDeclSvc) 'service 'function)))
(if (decl-ronly? this)
(decl-vtype-set! this ty ctx)
(decl-vtype-add! this ty ctx)))
(cond
((or (isa? this J2SDeclSvc) (eq? scope 'export))
;; services and exported function are as escaping functions,
;; the arguments and return types are "any"
(if (isa? val J2SFun)
(escape-fun val ctx #f)
(escape-method val ctx)))
((constructor-only? this)
;; a mere constructor
(if (isa? val J2SFun)
(node-type-ctor-only val)
(with-access::J2SMethod val (function method)
(node-type-ctor-only function)
(node-type-ctor-only method)))))
(multiple-value-bind (tyf env _)
(if (isa? val J2SMethod)
(node-type val env ctx)
(node-type-fun val (node-type-fun-decl val env ctx) ctx))
(return 'void (extend-env env this tyf) '()))))
;*---------------------------------------------------------------------*/
* node - type : : J2SDeclClass ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDeclClass env::pair-nil ctx::pair)
(define (node-type-class this)
(with-access::J2SDeclClass this (val)
(let ((ty (if (isa? val J2SClass)
(with-access::J2SClass val (need-dead-zone-check)
(if need-dead-zone-check 'any 'function))
'any)))
(if (decl-ronly? this)
(decl-vtype-set! this ty ctx)
(decl-vtype-add! this ty ctx))
(multiple-value-bind (tyf env bk)
(node-type val env ctx)
(return ty env bk)))))
(define (node-type-record this)
(with-access::J2SDeclClass this (val id)
(with-access::J2SRecord val (itype type)
(decl-vtype-set! this 'function ctx)
(multiple-value-bind (tyf env bk)
(node-type val env ctx)
(return 'function env bk)))))
(with-access::J2SDeclClass this (val)
(call-default-walker)
(if (isa? val J2SRecord)
(node-type-record this)
(node-type-class this))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SAssig ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SAssig env::pair-nil ctx::pair)
(define (this-assig? lhs)
(when (isa? lhs J2SAccess)
(with-access::J2SAccess lhs (obj)
(when (isa? obj J2SThis)
(with-access::J2SThis obj (decl)
decl)))))
(with-trace 'j2s-tyflow (format "node-type ::J2SAssig ~a" (cdr ctx))
(with-access::J2SAssig this (lhs rhs loc)
(let loop ((lhs lhs))
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(cond
;; variable assignment
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable id utype)
(multiple-value-bind (tyr env rbk)
(node-type rhs envl ctx)
(cond
((and (not writable) (not (isa? this J2SInit)))
(let ((nenv (extend-env env decl tyv)))
(expr-type-add! this nenv ctx tyv
(append lbk rbk))))
((and (not (eq? utype 'unknown))
(eq? (car ctx) 'hopscript))
(unless (utype-compatible? utype tyr)
(if (memq tyr '(unknown any object))
(set! rhs (J2SCheck utype rhs))
(utype-error rhs utype tyv)))
(expr-type-add! this env ctx utype
(append lbk rbk)))
(tyr
(with-access::J2SRef lhs (decl loc)
(decl-vtype-add! decl tyr ctx)
(let ((nenv (extend-env env decl tyr)))
(expr-type-add! this nenv ctx tyr
(append lbk rbk)))))
(else
(return 'unknown env (append lbk rbk))))))))
((isa? lhs J2SWithRef)
(with-access::J2SWithRef lhs (expr)
(loop expr)))
((this-assig? lhs)
=>
(lambda (decl)
;; "this" property assignment
(with-access::J2SDecl decl (vtype)
(let* ((ty (if (isa? vtype J2SRecord) vtype 'object))
(envt (extend-env envl decl ty)))
(multiple-value-bind (tyr nenv rbk)
(node-type rhs envt ctx)
(if tyr
(begin
(when (class-private-element-access lhs)
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this nenv ctx tyr (append lbk rbk)))
(return 'unknown envt (append lbk rbk))))))))
(else
;; a non variable assignment
(multiple-value-bind (tyr nenv rbk)
(node-type rhs envl ctx)
(if tyr
(begin
(when (and (isa? lhs J2SAccess)
(class-private-element-access lhs))
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this nenv ctx tyr (append lbk rbk)))
(return 'unknown env (append lbk rbk)))))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SAssigOp ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SAssigOp env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SAssigOp ~a" (cdr ctx))
(with-access::J2SAssigOp this (lhs rhs op)
(multiple-value-bind (tyr envr bkr)
(node-type-binary op lhs rhs env ctx)
(cond
((isa? lhs J2SRef)
;; a variable assignment
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable)
(cond
((not writable)
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(let ((nenv (extend-env env decl tyv)))
(expr-type-add! this nenv ctx tyv
(append lbk bkr)))))
(else
(decl-vtype-add! decl tyr ctx)
(let ((nenv (extend-env envr decl tyr)))
(expr-type-add! this nenv ctx tyr bkr)))))))
(else
;; a non variable assinment
(when (and (isa? lhs J2SAccess)
(class-private-element-access lhs))
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this envr ctx tyr bkr)))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SPostfix ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SPostfix env::pair-nil ctx::pair)
(define (numty ty)
postctx expressions only evaluate as numbers
(cond
((eq? ty 'unknown) 'unknown)
((type-number? ty) ty)
(else 'number)))
(with-access::J2SPostfix this (lhs rhs op type loc)
(multiple-value-bind (tyr envr bkr)
(node-type rhs env ctx)
(multiple-value-bind (tyv __ lbk)
(node-type lhs env ctx)
(expr-type-add! rhs envr ctx (numty tyr) bkr)
(cond
((isa? lhs J2SRef)
;; a variable assignment
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable)
(cond
((not writable)
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(let ((nenv (extend-env env decl (numty tyv))))
(expr-type-add! this nenv ctx (numty tyv)
(append lbk bkr)))))
(else
(let* ((ntyr (numty tyr))
(nty (if (eq? ntyr 'unknown) (numty tyv) ntyr)))
(decl-vtype-add! decl nty ctx)
(let ((nenv (extend-env envr decl nty)))
(expr-type-add! this nenv ctx nty
(append lbk bkr)))))))))
(else
;; a non variable assignment
(when (and (isa? lhs J2SAccess)
(class-private-element-access lhs))
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this envr ctx (numty tyr) bkr)))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SPrefix ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SPrefix env::pair-nil ctx::pair)
(define (numty ty)
;; prectx expressions only evaluate as numbers
(cond
((eq? ty 'unknown) 'unknown)
((type-number? ty) ty)
(else 'number)))
(with-access::J2SPrefix this (lhs rhs op)
(multiple-value-bind (tyr envr bkr)
(node-type rhs env ctx)
(expr-type-add! rhs envr ctx (numty tyr) bkr)
(multiple-value-bind (tyv __ lbk)
(node-type lhs env ctx)
(cond
((isa? lhs J2SRef)
;; a variable assignment
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable)
(cond
((not writable)
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(let ((nenv (extend-env env decl (numty tyv))))
(expr-type-add! this nenv ctx (numty tyv)
(append lbk bkr)))))
(else
(decl-vtype-add! decl (numty tyr) ctx)
(let ((nenv (extend-env envr decl (numty tyr))))
(expr-type-add! this nenv ctx (numty tyr)
(append lbk bkr))))))))
(else
;; a non variable assignment
(expr-type-add! this envr ctx (numty tyr) bkr)))))))
;*---------------------------------------------------------------------*/
* node - type : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDProducer env::pair-nil ctx::pair)
(with-access::J2SDProducer this (expr type)
(multiple-value-bind (ty env bk)
(node-type expr env ctx)
(return type env bk))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SDConsumer ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDConsumer env::pair-nil ctx::pair)
(with-access::J2SDConsumer this (expr)
(multiple-value-bind (ty env bk)
(node-type expr env ctx)
(expr-type-add! this env ctx ty bk))))
;*---------------------------------------------------------------------*/
;* node-type-fun ... */
;*---------------------------------------------------------------------*/
(define (node-type-fun this::J2SFun env::pair-nil ctx::pair)
(with-access::J2SFun this (body thisp params %info vararg argumentsp type loc mode rtype rutype mode)
(let ((envp (map (lambda (p::J2SDecl)
(with-access::J2SDecl p (itype utype vtype id)
(cond
((and (not (eq? utype 'unknown)) (eq? mode 'hopscript))
(set! itype utype)
(decl-vtype-set! p utype ctx)
(cons p utype))
((decl-usage-has? p '(rest))
(decl-vtype-add! p 'array ctx)
(cons p 'array))
(vararg
(decl-vtype-add! p 'any ctx)
(cons p 'any))
(else
(cons p itype)))))
params)))
;; transfer all itypes to vtypes
(for-each (lambda (decl)
(with-access::J2SDecl decl (itype)
(decl-vtype-add! decl itype ctx)))
params)
;; rutype
(unless (or (memq rutype '(unknown any))
(not (eq? (car ctx) 'hopscript))
(eq? rtype rutype))
(set! rtype rutype))
(let ((fenv (append envp env)))
(when thisp
(with-access::J2SDecl thisp (vtype ctype itype loc)
(unless (or (eq? vtype 'object) (isa? vtype J2SClass))
(decl-vtype-add! thisp itype ctx))
(set! fenv
(extend-env fenv thisp
(if (eq? ctype 'any) itype ctype)))))
(when argumentsp
(decl-itype-add! argumentsp 'arguments ctx)
(decl-vtype-add! argumentsp 'arguments ctx)
(set! fenv (extend-env fenv argumentsp 'arguments)))
(multiple-value-bind (_ envf _)
(node-type body fenv (cons mode (cdr ctx)))
(set! %info envf)))
(expr-type-add! this env ctx (funtype this)))))
;*---------------------------------------------------------------------*/
;* node-type-fun-decl ::J2SFun ... */
;*---------------------------------------------------------------------*/
(define (node-type-fun-decl this::J2SFun env::pair-nil ctx)
(with-access::J2SFun this (body decl)
(when (isa? decl J2SDecl)
(let ((ty (funtype this)))
(decl-vtype-set! decl ty ctx)))
(filter-map (lambda (c)
(let ((d (car c))
(t (cdr c)))
(with-access::J2SDecl d (vtype)
(if (decl-ronly? d)
c
(cons d vtype)))))
env)))
;*---------------------------------------------------------------------*/
;* escape-fun ... */
;*---------------------------------------------------------------------*/
(define (escape-fun val::J2SFun ctx met::bool)
(define (escape-type rtype)
(case rtype
((unknown undefined any obj object null) rtype)
(else 'any)))
(with-access::J2SFun val (params rtype rutype thisp name mode)
(when (and (not met) thisp)
(decl-vtype-add! thisp 'any ctx))
(when (or (eq? rutype 'unknown) (not (eq? mode 'hopscript)))
(set! rtype (tyflow-type (escape-type rtype))))
(for-each (lambda (p::J2SDecl)
(with-access::J2SDecl p (itype utype)
(when (or (eq? utype 'unknown)
(not (eq? mode 'hopscript)))
(decl-itype-add! p 'any ctx))))
params)))
;*---------------------------------------------------------------------*/
;* escape-method ... */
;*---------------------------------------------------------------------*/
(define (escape-method fun::J2SMethod ctx)
(with-access::J2SMethod fun (method function)
(escape-fun function ctx #f)
(escape-fun method ctx #t)))
;*---------------------------------------------------------------------*/
;* node-type-fun-or-method ... */
;*---------------------------------------------------------------------*/
(define (node-type-fun-or-method this::J2SFun env::pair-nil ctx::pair met::bool)
(escape-fun this ctx met)
(node-type-fun this (node-type-fun-decl this (env-nocapture env) ctx) ctx))
;*---------------------------------------------------------------------*/
;* node-type ::J2SFun ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SFun env::pair-nil ctx::pair)
(node-type-fun-or-method this env ctx #f))
;*---------------------------------------------------------------------*/
;* node-type ::J2SMethod ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SMethod env::pair-nil ctx::pair)
(with-access::J2SMethod this (method function)
(node-type-fun-or-method function env ctx #f)
(node-type-fun-or-method method env ctx #t)
(expr-type-add! this env ctx 'function)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCall ... */
;* ------------------------------------------------------------- */
;* Function calls may affect the node-type environment, depending */
;* on the called function. Each case comes with a special rule, */
;* detailed in the code below. */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCall env::pair-nil ctx::pair)
(with-access::J2SCall this (fun thisargs args protocol type loc)
(multiple-value-bind (tty env bkt)
(if (pair? thisargs)
(node-type (car thisargs) env ctx)
(values 'unknown env '()))
(multiple-value-bind (rty env bkc)
(node-type-call fun protocol tty args env ctx)
(expr-type-add! this env ctx rty (append bkt bkc))))))
;*---------------------------------------------------------------------*/
;* node-type-call ... */
;*---------------------------------------------------------------------*/
(define (node-type-call callee protocol tty args env ctx)
(define (unknown-call-env env)
;; compute a new node-type environment where all mutated globals
;; and all mutated captured locals are removed
(filter (lambda (e)
(with-access::J2SDecl (car e) (writable scope escape id)
(or (decl-ronly? (car e))
(not writable)
(and (memq scope '(local letblock inner))
(not escape)))))
env))
(define (global-call-env env)
;; compute a new node-type environment where all mutated globals
;; and all mutated captured locals are removed
(filter (lambda (e)
(with-access::J2SDecl (car e) (writable scope escape id)
(or (decl-ronly? (car e))
(not writable)
(or (memq scope '(local letblock inner))))))
env))
(define (local-call-env env)
(unknown-call-env env))
(define (type-known-call-args fun::J2SFun args env bk)
(with-access::J2SFun fun (rtype params vararg mode thisp mode)
(when thisp
(decl-itype-add! thisp
(cond
((not (eq? tty 'unknown)) tty)
((eq? mode 'strict) 'object)
(else 'undefined))
ctx))
(let loop ((params params)
(args args))
(when (pair? params)
(with-access::J2SDecl (car params) (id utype)
(cond
(vararg
(decl-itype-add! (car params) 'any ctx))
((and (null? (cdr params)) (decl-usage-has? (car params) '(rest)))
(decl-itype-add! (car params) 'array ctx))
((null? args)
(unless (or (eq? utype 'unknown) (not (eq? mode 'hopscript)))
(unless (utype-compatible? utype 'undefined)
(utype-error (car params) utype 'undefined)))
(decl-itype-add! (car params) 'undefined ctx)
(loop (cdr params) '()))
((and (not (eq? utype 'unknown))
(eq? mode 'hopscript))
(let ((ty (j2s-type (car args))))
(cond
((utype-compatible? utype ty)
(decl-itype-add! (car params) ty ctx)
(loop (cdr params) (cdr args)))
((memq ty '(unknown any object))
(with-access::J2SExpr (car args) (loc)
(set-car! args (J2SCheck utype (car args)))
(decl-itype-add! (car params) utype ctx)
(loop (cdr params) (cdr args))))
(else
(utype-error (car args) utype ty)))))
(else
(decl-itype-add! (car params) (j2s-type (car args)) ctx)
(loop (cdr params) (cdr args)))))))))
(define (type-inline-call fun::J2SFun args env bk)
;; type a direct function call: ((function (...) { ... })( ... ))
;; side effects are automatically handled when
;; node-type the function body
(type-known-call-args fun args env bk)
(multiple-value-bind (_ envf _)
(node-type-fun callee env ctx)
(with-access::J2SFun fun (rtype mode %info)
(let* ((oenv (if (env? %info) (env-override env %info) env))
(nenv (local-call-env oenv)))
(return rtype nenv bk)))))
(define (type-known-call ref::J2SRef fun::J2SFun args env bk)
;; type a known constant function call: F( ... )
;; the new node-type environment is a merge of env and the environment
;; produced by the function
(with-access::J2SRef ref (decl)
(expr-type-add! ref env ctx (funtype fun))
(type-known-call-args fun args env bk)
(with-access::J2SDecl decl (scope id)
(with-access::J2SFun fun (rtype %info)
(let* ((oenv (if (env? %info) (env-override env %info) env))
(nenv (if (memq scope '(global %scope tls))
(global-call-env oenv)
(local-call-env oenv))))
(return rtype nenv bk))))))
(define (type-ref-call callee args env bk)
call a JS variable , check is it a known function
(with-access::J2SRef callee (decl)
(cond
((isa? decl J2SDeclFun)
(with-access::J2SDeclFun decl (val)
(if (decl-ronly? decl)
(if (isa? val J2SMethod)
(with-access::J2SMethod val (function method)
(if (eq? tty 'object)
(type-known-call callee method args env bk)
(type-known-call callee function args env bk)))
(type-known-call callee val args env bk))
(type-unknown-call callee env bk))))
((isa? decl J2SDeclInit)
(with-access::J2SDeclInit decl (val)
(cond
((is-builtin-ref? callee 'Array)
(return 'array env bk))
((is-builtin-ref? callee 'BigInt)
(return 'bigint env bk))
((and (decl-ronly? decl) (isa? val J2SFun))
(type-known-call callee val args env bk))
((and (decl-ronly? decl) (isa? val J2SMethod))
(with-access::J2SMethod val (function method)
(if (eq? tty 'object)
(type-known-call callee method args env bk)
(type-known-call callee function args env bk))))
(else
(type-unknown-call callee env bk)))))
(else
(type-unknown-call callee env bk)))))
(define (is-global? obj ident)
(cond
((isa? obj J2SGlobalRef)
(with-access::J2SGlobalRef obj (id decl)
(when (eq? id ident)
(decl-ronly? decl))))
((isa? obj J2SRef)
(with-access::J2SRef obj (decl)
(when (isa? decl J2SDeclExtern)
(with-access::J2SDeclExtern decl (id)
(when (eq? id ident)
(decl-ronly? decl))))))))
(define (type-method-call callee args env bk)
;; type a method call: O.m( ... )
(multiple-value-bind (_ env bk)
(node-type callee env ctx)
(with-access::J2SAccess callee (obj field)
(let* ((fn (j2s-field-name field))
(ty (if (string? fn)
(car (find-builtin-method-type obj fn))
'any)))
(cond
((eq? ty 'any)
;; the method is unknown, filter out the node-type env
(return ty (unknown-call-env env) bk))
((eq? ty 'anumber)
(if (pair? args)
(let ((aty (j2s-type (car args))))
(if (memq aty '(integer real))
(return aty env bk)
(return 'number env bk)))
(return 'number env bk)))
(else
(return (tyflow-type ty) env bk)))))))
(define (type-hop-call callee args env bk)
;; type a hop (foreign function) call: H( ... )
;; hop calls have no effect on the node-type env
(with-access::J2SHopRef callee (rtype loc)
(return rtype env bk)))
(define (type-global-call callee args env bk)
(node-type callee env ctx)
(cond
((is-global? callee 'Array)
(return 'array (unknown-call-env env) bk))
((is-global? callee 'String)
(return 'string (unknown-call-env env) bk))
((is-global? callee 'parseInt)
(return 'number (unknown-call-env env) bk))
((is-global? callee 'isNaN)
(return 'bool (unknown-call-env env) bk))
((is-global? callee 'unescape)
(return 'string (unknown-call-env env) bk))
((is-global? callee 'encodeURI)
(return 'string (unknown-call-env env) bk))
((is-global? callee 'encodeURIComponent)
(return 'string (unknown-call-env env) bk))
(else
(type-unknown-call callee env bk))))
(define (type-unknown-call callee env bk)
;; type a unknown function call: expr( ... )
;; filter out the node-type env
(multiple-value-bind (_ env bk)
(node-type callee env ctx)
(return 'any (unknown-call-env env) bk)))
(multiple-value-bind (env bk)
(node-type-args args env ctx)
(cond
((eq? protocol 'spread) (type-unknown-call callee env bk))
((isa? callee J2SFun) (type-inline-call callee args env bk))
((isa? callee J2SRef) (type-ref-call callee args env bk))
((isa? callee J2SHopRef) (type-hop-call callee args env bk))
((isa? callee J2SAccess) (type-method-call callee args env bk))
((isa? callee J2SGlobalRef) (type-global-call callee args env bk))
(else (type-unknown-call callee env bk)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCond ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCond env::pair-nil ctx::pair)
(with-access::J2SCond this (test then else)
(multiple-value-bind (tyi env bki)
(node-type test env ctx)
(multiple-value-bind (tyt envt bkt)
(node-type then env ctx)
(multiple-value-bind (tye enve bke)
(node-type else env ctx)
(let ((envc (env-merge envt enve))
(typc (merge-types tyt tye))
(bk (append bki bkt bke)))
(expr-type-add! this envc ctx typc bk)))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SNew ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SNew env::pair-nil ctx::pair)
(define (class-type clazz)
(cond
((isa? clazz J2SUnresolvedRef)
(with-access::J2SUnresolvedRef clazz (id)
(case id
((Array) 'array)
((Vector) 'jsvector)
((Date) 'date)
((RegExp) 'regexp)
((Int8Array) 'int8array)
((Uint8Array) 'uint8array)
((Map) 'map)
((WeakMap) 'weakmap)
((Set) 'set)
((WeakSet) 'weakset)
(else 'object))))
((isa? clazz J2SRef)
(with-access::J2SRef clazz (decl)
(cond
((isa? decl J2SDeclExtern)
(with-access::J2SDeclExtern decl (id)
(when (decl-ronly? decl)
(case id
((Array) 'array)
((Vector) 'jsvector)
((Int8Array) 'int8array)
((Uint8Array) 'uint8array)
((Date) 'date)
((RegExp) 'regexp)
((Map) 'map)
((WeakMap) 'weakmap)
((Set) 'set)
((WeakSet) 'weakset)
(else 'object)))))
((isa? decl J2SDeclClass)
(with-access::J2SDeclClass decl (val)
(if (isa? val J2SClass)
val
'object)))
(else
'object))))
(else
'object)))
(with-trace 'j2s-tyflow "node-type ::J2SNew"
(with-access::J2SNew this (clazz args loc protocol)
(multiple-value-bind (_ env bk)
(node-type clazz env ctx)
(multiple-value-bind (_ env bk)
(node-type-call clazz protocol 'object args env ctx)
(expr-type-add! this env ctx (class-type clazz) bk))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SUnary ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SUnary env::pair-nil ctx::pair)
(define (non-zero-integer? ty expr)
(when (type-integer? ty)
(or (not (isa? expr J2SNumber))
(with-access::J2SNumber expr (val)
(not (= val 0))))))
(with-access::J2SUnary this (op expr)
(multiple-value-bind (ty env bk)
(node-type expr env ctx)
(let* ((tnum (if (eq? ty 'real) 'real 'number))
(tye (case op
((+) (if (non-zero-integer? ty expr) 'integer tnum))
((-) (if (non-zero-integer? ty expr) 'integer tnum))
((~) 'integer)
((!) 'bool)
((typeof) 'string)
(else 'any))))
(expr-type-add! this env ctx tye bk)))))
;*---------------------------------------------------------------------*/
;* node-type-binary ... */
;*---------------------------------------------------------------------*/
(define (node-type-binary op lhs::J2SExpr rhs::J2SExpr env::pair-nil ctx::pair)
(multiple-value-bind (typl envl bkl)
(node-type lhs env ctx)
(multiple-value-bind (typr envr bkr)
(node-type rhs envl ctx)
(let ((typ (case op
((+)
(cond
((and (eq? typl 'real) (eq? typr 'real))
'real)
((and (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((and (type-integer? typl) (type-integer? typr))
'integer)
((or (and (type-integer? typl) (eq? typr 'bool))
(and (eq? typl 'bool) (type-integer? typr)))
'integer)
((and (typnum? typl) (typnum? typr))
'number)
((or (eq? typl 'string) (eq? typr 'string))
'string)
((or (eq? typl 'any) (eq? typr 'any))
'any)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
(else
'unknown)))
((++)
(cond
((and (eq? typl 'real) (eq? typr 'real))
'real)
((and (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((and (type-integer? typl) (type-integer? typr))
'integer)
((and (typnum? typl) (typnum? typr))
'number)
((or (eq? typl 'string) (eq? typr 'string))
'number)
((or (eq? typl 'any) (eq? typr 'any))
'number)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
(else
'unknown)))
((- -- * **)
(cond
((or (eq? typl 'real) (eq? typr 'real))
'real)
((or (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((and (type-integer? typl) (type-integer? typr))
'integer)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
(else
'number)))
((/)
(cond
((or (eq? typl 'real) (eq? typr 'real))
'real)
((or (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((eq? typr 'integer)
'number)
((eq? typr 'unknown)
'unknown)
(else
'real)))
((%)
(cond
((or (eq? typl 'real) (eq? typr 'real))
'real)
((or (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
((or (eq? typl 'any) (eq? typr 'any))
'number)
(else
'number)))
((== === != !== < <= > >= eq?)
'bool)
((in)
(when (isa? rhs J2SRef)
(with-access::J2SRef rhs (decl)
(set! env (extend-env env decl 'object))))
'bool)
((instanceof)
(when (isa? rhs J2SRef)
(with-access::J2SRef rhs (decl)
(set! env (extend-env env decl 'function))))
'bool)
((&& OR OR*)
(cond
((or (eq? typr 'any) (eq? typl 'any))
'any)
((or (eq? typr 'unknown) (eq? typl 'unknown))
'unknown)
(else
(merge-types typr typl))))
((<< >> >>> ^ & BIT_OR)
'integer)
(else
'any))))
(return typ (if (memq op '(OR OR*)) (env-merge envl envr) envr)
(append bkl bkr))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SBinary ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SBinary env::pair-nil ctx::pair)
(with-access::J2SBinary this (op lhs rhs)
(multiple-value-bind (typ env bk)
(node-type-binary op lhs rhs env ctx)
(expr-type-add! this env ctx typ bk))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SAccess ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SAccess env::pair-nil ctx::pair)
(define (is-number-ref? expr::J2SNode)
(when (isa? expr J2SUnresolvedRef)
(with-access::J2SUnresolvedRef expr (id)
(eq? id 'Number))))
(define (is-math-ref? expr::J2SNode)
(when (isa? expr J2SRef)
(with-access::J2SRef expr (decl)
(when (isa? decl J2SDeclExtern)
(with-access::J2SDecl decl (id)
(eq? id 'Math))))))
(with-access::J2SAccess this (obj field loc)
(multiple-value-bind (tyo envo bko)
(node-type obj env ctx)
(multiple-value-bind (tyf envf bkf)
(node-type field envo ctx)
(cond
((and (memq tyo '(array string jsvector)) (j2s-field-length? field))
(with-access::J2SString field (val)
(expr-type-add! this envf ctx 'integer (append bko bkf))))
((and (eq? tyo 'arguments)
(isa? obj J2SRef)
(j2s-field-length? field)
(with-access::J2SRef obj (decl)
MS 13may2021 : because of the new arguments
;; optimization, alias arguments are optimized too
( isa ? )
(not (decl-usage-has? decl '(set ref))))))
;; The length field of a arguments is not necessarily
;; an number (when assigned a random value, see
;; S10.6_A5_T4.js test.
;; arguments.length is known to return and integer only
;; if arguments is not assigned anything and not passed
;; to anyone.
(with-access::J2SString field (val)
(expr-type-add! this envf ctx 'integer (append bko bkf))))
((not (j2s-field-name field))
(expr-type-add! this envf ctx 'any (append bko bkf)))
((eq? tyo 'string)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (string-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((eq? tyo 'regexp)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (regexp-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((eq? tyo 'number)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (number-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((eq? tyo 'array)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (array-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((is-number-ref? obj)
(let ((name (j2s-field-name field)))
(if (member name
'("POSITIVE_INFINITY" "NEGATIVE_INFINITY"))
(expr-type-add! this envf ctx 'number
(append bko bkf))
(expr-type-add! this envf ctx 'any
(append bko bkf)))))
((is-math-ref? obj)
(let ((name (j2s-field-name field)))
(if (member name
'("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI"
"SQRT1_2" "SQRT2"))
(expr-type-add! this envf ctx 'real
(append bko bkf))
(expr-type-add! this envf ctx 'any
(append bko bkf)))))
((isa? tyo J2SRecord)
(if (isa? field J2SString)
(with-access::J2SString field (val)
(multiple-value-bind (index el)
(j2s-class-get-property tyo val)
(if (isa? el J2SClassElement)
(with-access::J2SClassElement el (type)
(expr-type-add! this envf ctx type (append bko bkf)))
(expr-type-add! this envf ctx 'unknown (append bko bkf)))))
(expr-type-add! this envf ctx 'any (append bko bkf))))
((class-private-element-access this)
=>
(lambda (el)
(with-access::J2SClassElement el (type)
(expr-type-add! this envf ctx type (append bko bkf)))))
((eq? tyo 'unknown)
(expr-type-add! this envf ctx 'unknown (append bko bkf)))
(else
(expr-type-add! this envf ctx 'any (append bko bkf))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCacheCheck ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCacheCheck env::pair-nil ctx::pair)
(with-access::J2SCacheCheck this (loc obj)
(multiple-value-bind (typf envf bkf)
(node-type obj env ctx)
(expr-type-add! this envf ctx 'bool bkf))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCacheUpdate ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCacheUpdate env::pair-nil ctx::pair)
(multiple-value-bind (typf envf bkf)
(call-default-walker)
(expr-type-add! this envf ctx 'undefined bkf)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCheck ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCheck env::pair-nil ctx::pair)
(with-access::J2SCheck this (type)
(call-default-walker)
(return type env '())))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCast ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCast env::pair-nil ctx::pair)
(with-access::J2SCast this (type)
(call-default-walker)
(return type env '())))
;*---------------------------------------------------------------------*/
;* node-type ::J2SNop ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SNop env::pair-nil ctx::pair)
(return 'void env '()))
;*---------------------------------------------------------------------*/
* node - type : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SStmtExpr env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SStmtExpr"
(with-access::J2SStmtExpr this (expr loc)
(trace-item "loc=" loc)
(multiple-value-bind (typ env bk)
(node-type expr env ctx)
(return typ env bk)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SSeq ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SSeq env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SSeq"
(with-access::J2SSeq this (nodes loc)
(trace-item "loc=" loc)
(node-type-seq nodes env ctx 'void))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SLabel ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SLabel env::pair-nil ctx::pair)
(call-default-walker))
;*---------------------------------------------------------------------*/
* node - type : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SLetBlock env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SLetBlock ~a" (cdr ctx))
(with-access::J2SLetBlock this (decls nodes loc)
(trace-item "loc=" loc)
(let ((ienv (filter-map (lambda (d::J2SDecl)
(with-access::J2SDecl d (vtype)
(unless (eq? vtype 'unknown)
(cons d vtype))))
decls)))
(multiple-value-bind (_ denv bk)
(node-type-seq decls (append ienv env) ctx 'void)
(multiple-value-bind (typ benv bks)
(node-type-seq nodes denv ctx 'void)
(let ((nenv (filter (lambda (d)
(not (memq (car d) decls)))
benv)))
(return typ nenv (append bk bks)))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SWith ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SWith env::pair-nil ctx::pair)
(with-access::J2SWith this (obj block)
(multiple-value-bind (tye enve bke)
(node-type obj env ctx)
(multiple-value-bind (tyb envb bkb)
(node-type block enve ctx)
(return 'void envb (append bke bkb))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SReturn ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SReturn env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SReturn"
(with-access::J2SReturn this (expr from loc)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(cond
((isa? from J2SFun)
(with-access::J2SFun from (rtype rutype)
(when (and (not (eq? rutype 'unknown))
(eq? (car ctx) 'hopscript)
(not (utype-compatible? rutype tye)))
(if (memq tye '(unknown any object))
(begin
(set! tye rutype)
(set! expr (J2SCheck rutype expr)))
(utype-error expr rutype tye)))
(let ((tyr (merge-types rtype tye)))
(unless (eq? tyr rtype)
(unfix! ctx
(format "J2SReturn(~a) e=~a ~a/~a" loc
(type->sexp tye) (type->sexp tyr) (type->sexp rtype)))
(set! rtype tyr)))
(values 'void enve (list this))))
((isa? from J2SBindExit)
(with-access::J2SBindExit from (type loc utype)
(when (and (not (eq? utype 'unknown))
(eq? (car ctx) 'hopscript)
(not (utype-compatible? utype tye)))
(if (memq tye '(unknown any object))
(begin
(set! tye utype)
(set! expr (J2SCheck utype expr)))
(utype-error expr utype tye)))
(let ((tyr (merge-types type tye)))
(unless (eq? tyr type)
(unfix! ctx
(format "J2SReturn(~a) e=~a ~a/~a" loc
(type->sexp tye) (type->sexp tyr) (type->sexp type)))
(set! type tyr))))
(values 'void enve (list this)))
((isa? from J2SExpr)
(expr-type-add! from env ctx tye)
(values 'void enve (list this)))
(else
(values 'void enve (list this))))))))
;*---------------------------------------------------------------------*/
* node - type : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SReturnYield env::pair-nil ctx::pair)
(with-access::J2SReturnYield this (expr kont)
(node-type kont env ctx)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(values 'void enve (list this)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SKont ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SKont env::pair-nil ctx::pair)
(with-access::J2SKont this (body exn param)
(with-access::J2SDecl param (%info itype)
(unless (eq? itype 'unknown)
(decl-vtype-add! param itype ctx)))
(with-access::J2SDecl exn (%info itype)
(unless (eq? itype 'unknown)
(decl-vtype-add! exn itype ctx)))
(node-type body env ctx)
(expr-type-add! this env ctx 'procedure)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SIf ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SIf env::pair-nil ctx::pair)
(define (isa-and? test)
(when (isa? test J2SBinary)
(with-access::J2SBinary test (op lhs rhs)
(when (eq? op '&&)
(node-type-one-positive-test? lhs)))))
(define (node-type-one-positive-test? test)
(cond
((isa? test J2SBinary)
(with-access::J2SBinary test (op)
(memq op '(== === eq? instanceof))))
((isa? test J2SCall)
;; we assume that the only type predicate are positive tests
#t)
(else
#f)))
(define (node-type-one-test test envt enve)
(multiple-value-bind (op decl typ ref)
(j2s-expr-type-test test)
(if (or (and (symbol? typ) (j2s-known-type typ)) (isa? typ J2SClass))
(case op
((== === eq?) (values (extend-env envt decl typ) enve))
((!= !==) (values envt (extend-env enve decl typ)))
((instanceof) (values (extend-env envt decl typ) enve))
((!instanceof) (values envt (extend-env enve decl typ)))
((<=) (values (refine-env envt decl typ) enve))
(else (values envt enve)))
(values envt enve))))
(define (node-type-test test envt enve)
(if (isa-and? test)
(with-access::J2SBinary test (lhs rhs)
(multiple-value-bind (nenvt nenve)
(node-type-test lhs envt enve)
(node-type-test rhs nenvt nenve)))
(node-type-one-test test envt enve)))
(with-trace 'j2s-tyflow (format "node-type ::J2SIf ~a" (cdr ctx))
(with-access::J2SIf this (test then else loc)
(trace-item "loc=" loc)
(multiple-value-bind (tyi env bki)
(node-type test env ctx)
(multiple-value-bind (envt enve)
(node-type-test test env env)
(multiple-value-bind (tyt envt bkt)
(node-type then envt ctx)
(multiple-value-bind (tye enve bke)
(node-type else enve ctx)
(let ((bk (append bki bke bkt)))
(return (merge-types tyt tye)
(env-merge envt enve) bk)))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SSwitch ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SSwitch env::pair-nil ctx::pair)
(with-access::J2SSwitch this (key cases)
(multiple-value-bind (typk envk bk)
(node-type key env ctx)
(let ((bks '())
(typ #f))
(let loop ((cases cases)
(env envk))
(when (pair? cases)
(multiple-value-bind (t e b)
(node-type (car cases) env ctx)
(set! bks (append b bks))
(set! typ (if (not typ) t (merge-types typ t)))
(with-access::J2SCase (car cases) (cascade)
(if cascade
(loop (cdr cases) e)
(loop (cdr cases) envk))))))
(return typ '() bks)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCase ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCase env::pair-nil ctx::pair)
(with-access::J2SCase this (expr body cascade)
(multiple-value-bind (typx envx bk)
(node-type expr env ctx)
(multiple-value-bind (typb envb bkb)
(node-type body envx ctx)
(return typb envb (append bkb bk))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SBreak ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SBreak env::pair-nil ctx::pair)
(return 'void env (list this)))
;*---------------------------------------------------------------------*/
;* node-type ::J2SWhile ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SWhile env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SWhile"
(with-access::J2SWhile this (test body loc)
(trace-item "loc=" loc)
(let loop ((env env)
(i 0))
(let ((octx (cdr ctx)))
(trace-item "while seq loc=" loc)
(multiple-value-bind (typ envb bk)
(node-type-seq (list test body) env ctx 'void)
(let ((nenv (env-merge env envb)))
(if (=fx octx (cdr ctx))
(return typ nenv (filter-breaks bk this))
(loop nenv (+fx i 1))))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SDo ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SDo env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SDo"
(with-access::J2SDo this (test body loc)
(trace-item "loc=" loc)
(let loop ((env env))
(let ((octx (cdr ctx)))
(trace-item "while seq loc=" loc)
(multiple-value-bind (typ envb bk)
(node-type-seq (list body test) env ctx 'void)
(let ((nenv (env-merge env envb)))
(if (=fx octx (cdr ctx))
(return typ nenv (filter-breaks bk this))
(loop nenv)))))))))
;*---------------------------------------------------------------------*/
* node - type : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SFor env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SFor ~a" (cdr ctx))
(with-access::J2SFor this (init test incr body loc)
(trace-item "loc=" loc)
(let loop ((env env))
(let ((octx (cdr ctx)))
(trace-item "for seq loc=" loc)
(trace-item "for seq octx=" octx)
(multiple-value-bind (typ envb bk)
(node-type-seq (list init test body incr) env ctx 'void)
(let ((nenv (env-merge env envb)))
(trace-item "for seq nctx=" (cdr ctx) " octx=" octx)
(if (=fx octx (cdr ctx))
(return typ nenv (filter-breaks bk this))
(loop nenv)))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SForIn ... */
;* ------------------------------------------------------------- */
;* !!! WARNING: After the for..in loop the key variable is */
;* undefined if the object contains no property. */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SForIn env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SForIn"
(with-access::J2SForIn this (lhs obj body op loc)
(trace-item "loc=" loc)
(let ((decl (cond
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl) decl))
((isa? lhs J2SGlobalRef)
(with-access::J2SGlobalRef lhs (decl) decl))))
(ty (if (eq? op 'in) 'string 'any)))
(when decl (decl-vtype-add! decl ty ctx))
(expr-type-add! lhs env ctx ty '())
(let loop ((env (if decl (extend-env env decl ty) env)))
(let ((octx (cdr ctx)))
(trace-item "for seq loc=" loc)
(multiple-value-bind (typ envb bk)
(node-type-seq (list obj body) env ctx 'void)
(cond
((not (=fx octx (cdr ctx)))
(loop (env-merge env envb)))
((eq? op 'in)
(when decl (decl-vtype-add! decl 'undefined ctx))
(return typ (if decl (extend-env envb decl 'any) env)
(filter-breaks bk this)))
(else
(return typ envb
(filter-breaks bk this)))))))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2STry ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2STry env::pair-nil ctx::pair)
(with-access::J2STry this (body catch finally)
(multiple-value-bind (_ envb bkb)
(node-type body env ctx)
(multiple-value-bind (_ envc bkh)
(node-type catch env ctx)
(multiple-value-bind (_ envf bkf)
(node-type finally (env-merge envb envc) ctx)
(return 'void envf (append bkb bkh bkf)))))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SCatch ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SCatch env::pair-nil ctx::pair)
(with-access::J2SCatch this (body param)
(decl-vtype-add! param 'any ctx)
(node-type body env ctx)))
;*---------------------------------------------------------------------*/
* node - type : : J2SThrow ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SThrow env::pair-nil ctx::pair)
(with-access::J2SThrow this (expr)
(multiple-value-bind (_ env bk)
(node-type expr env ctx)
(return 'void env (cons this bk)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SClass ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SClass env::pair-nil ctx::pair)
(with-access::J2SClass this (expr decl super elements need-dead-zone-check)
(for-each (lambda (e)
(node-type e env ctx))
elements)
(when decl
(decl-vtype-add! decl (if need-dead-zone-check 'any 'function) ctx))
(multiple-value-bind (tys env bki)
(node-type super env ctx)
(expr-type-add! this env ctx
(if (isa? this J2SRecord) 'record 'class)))))
;*---------------------------------------------------------------------*/
;* node-type ::J2SClassElement ... */
;*---------------------------------------------------------------------*/
(define-walk-method (node-type this::J2SClassElement env::pair-nil ctx::pair)
(with-access::J2SClassElement this (prop type clazz static usage)
(cond
((j2s-class-property-constructor? prop)
(if (isa? clazz J2SRecord)
(with-access::J2SDataPropertyInit prop (val)
(with-access::J2SFun val (thisp params)
;; record constructors escape (even if not syntactically)
(for-each (lambda (p::J2SDecl)
(with-access::J2SDecl p (itype utype)
(decl-itype-add! p 'any ctx)))
params)
(with-access::J2SDecl thisp (itype vtype eloc mtype)
(set! mtype clazz)
(set! itype clazz)
(decl-vtype-set! thisp clazz ctx))
J2SRecord constructor does not escape
(node-type-fun val env ctx)))
(with-access::J2SDataPropertyInit prop (val)
(with-access::J2SFun val (thisp params)
(with-access::J2SDecl thisp (ctype itype vtype eloc mtype)
(unless (or (not (eq? ctype 'any)) (eq? itype 'object))
(set! mtype clazz)
(set! itype 'object)
(set! vtype 'any)
(unfix! ctx "constructor type")))
(node-type prop env ctx)))))
(else
(let ((vty (node-type prop env ctx)))
(when (eq? type 'unknown)
(cond
((usage-has? usage '(uninit))
(if (j2s-class-element-private? this)
(class-element-type-add! this ctx 'undefined)
(class-element-type-add! this ctx 'any)))
((not (eq? vty 'unknown))
(class-element-type-add! this ctx vty)))))))
(return 'void env '())))
;*---------------------------------------------------------------------*/
;* j2s-resolve! ... */
;* ------------------------------------------------------------- */
* statically type checks using type informations * /
* computed by the NODE - TYPE method . * /
;*---------------------------------------------------------------------*/
(define (j2s-resolve! this::J2SProgram args ctx)
(with-access::J2SProgram this (headers decls nodes)
(let ((ofix (cdr ctx)))
(set! headers (map! (lambda (o) (resolve! o ctx)) headers))
(set! decls (map! (lambda (o) (resolve! o ctx)) decls))
(set! nodes (map! (lambda (o) (resolve! o ctx)) nodes))
(>fx (cdr ctx) ofix))))
;*---------------------------------------------------------------------*/
;* resolve! ::J2SNode ... */
;*---------------------------------------------------------------------*/
(define-walk-method (resolve! this::J2SNode ctx::pair)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* resolve! ::J2SBinary ... */
;*---------------------------------------------------------------------*/
(define-walk-method (resolve! this::J2SBinary ctx)
(define (eq-typeof? type typ)
(or (eq? type typ)
(and (memq type '(date array)) (eq? typ 'object))
(and (eq? typ 'number) (memq type '(integer index real bigint)))
(and (eq? typ 'function) (memq type '(function arrow)))
(and (eq? type 'bool))))
(with-access::J2SBinary this (loc op)
(case op
((&&)
(with-access::J2SBinary this (lhs rhs loc)
(set! lhs (resolve! lhs ctx))
(set! rhs (resolve! rhs ctx))
(cond
((and (isa? lhs J2SBool) (isa? rhs J2SBool))
(with-access::J2SBool lhs ((lval val))
(with-access::J2SBool rhs ((rval val))
(J2SBool (and lval rval)))))
((isa? lhs J2SBool)
(with-access::J2SBool lhs (val)
(if val rhs (J2SBool #f))))
((isa? rhs J2SBool)
no reduction can be applied if is false , see
;; -international.org/ecma-262/5.1/#sec-11.7.3
(with-access::J2SBool rhs (val)
(if val lhs this)))
(else
this))))
((OR)
(with-access::J2SBinary this (lhs rhs loc)
(set! lhs (resolve! lhs ctx))
(set! rhs (resolve! rhs ctx))
(cond
((and (isa? lhs J2SBool) (isa? rhs J2SBool))
(with-access::J2SBool lhs ((lval val))
(with-access::J2SBool rhs ((rval val))
(J2SBool (or lval rval)))))
((isa? lhs J2SBool)
(with-access::J2SBool lhs (val)
(if val (J2SBool #t) rhs)))
(else
this))))
(else
(multiple-value-bind (op decl typ ref)
(j2s-expr-type-test this)
(case op
((== === eq?)
(with-access::J2SExpr ref (type)
(cond
((eq-typeof? type typ)
(unfix! ctx "resolve.J2SBinary")
(J2SBool #t))
((memq type '(unknown any))
(call-default-walker))
((and (eq? type 'number) (memq typ '(integer index)))
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary")
(J2SBool #f)))))
((!= !==)
(with-access::J2SExpr ref (type)
(cond
((eq-typeof? type typ)
(unfix! ctx "resolve.J2SBinary")
(J2SBool #f))
((memq type '(unknown any))
(call-default-walker))
((and (eq? type 'number) (memq typ '(integer index)))
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary")
(J2SBool #t)))))
((instanceof)
(with-access::J2SExpr ref (type)
(cond
((or (memq type '(unknown any object)) (eq? typ 'object))
(call-default-walker))
((type-subtype? type typ)
(unfix! ctx "resolve.J2SBinary.instanceof")
(J2SBool #t))
((type-maybe-subtype? type typ)
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary.instanceof")
(J2SBool #f)))))
((!instanceof)
(with-access::J2SExpr ref (type)
(cond
((or (memq type '(unknown any object)) (eq? typ 'object))
(call-default-walker))
((type-subtype? type typ)
(unfix! ctx "resolve.J2SBinary.!instanceof")
(J2SBool #f))
((type-maybe-subtype? type typ)
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary.!instanceof")
(J2SBool #t)))))
(else
(call-default-walker))))))))
;*---------------------------------------------------------------------*/
* resolve ! : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (resolve! this::J2SCacheCheck ctx::pair)
(call-default-walker)
(with-access::J2SCacheCheck this (loc obj owner)
(let ((to (j2s-type obj)))
(cond
((and (isa? owner J2SRecord)
(not (memq to '(any unknown object)))
(or (and (isa? (j2s-vtype obj) J2SRecord)
(not (or (type-subtype? owner to)
(type-subtype? to owner))))
(not (isa? (j2s-vtype obj) J2SRecord))))
;; inlining invalidated by the type inference
(unfix! ctx "resolve.J2SCacheCheck")
(J2SBool #f))
((and (isa? owner J2SClass) (eq? (j2s-mtype obj) owner))
;; inlining validated by the type inference
(unfix! ctx "resolve.J2SCacheCheck")
(J2SBool #t))
(else
this)))))
;*---------------------------------------------------------------------*/
;* resolve! ::J2SIf ... */
;*---------------------------------------------------------------------*/
(define-walk-method (resolve! this::J2SIf ctx::pair)
(define (is-true? expr)
(cond
((isa? expr J2SBool)
(with-access::J2SBool expr (val) val))
((isa? expr J2SBinary)
(with-access::J2SBinary expr (lhs rhs op)
(and (eq? op '==)
(memq (j2s-type lhs) '(null undefined))
(memq (j2s-type rhs) '(null undefined)))))))
(define (is-false? expr)
(cond
((isa? expr J2SBool)
(with-access::J2SBool expr (val) (not val)))
((isa? expr J2SBinary)
(with-access::J2SBinary expr (lhs rhs op)
(and (eq? op '!=)
(memq (j2s-type lhs) '(null undefined))
(memq (j2s-type rhs) '(null undefined)))))))
(let ((ts (if-check-cache-cascade-classes this)))
(let ((nthis (if (and (pair? ts) (pair? (cdr ts)))
(if-check-cache-cascade-resolve! this ts)
this)))
(if (isa? nthis J2SIf)
(with-access::J2SIf nthis (test then else)
(set! test (resolve! test ctx))
(with-access::J2SExpr test (type)
(cond
((memq type '(any unknown))
(set! then (resolve! then ctx))
(set! else (resolve! else ctx))
nthis)
((is-true? test)
(unfix! ctx "resolve.J2SIf")
(resolve! then ctx))
((is-false? test)
(unfix! ctx "resolve.J2SIf")
(resolve! else ctx))
(else
(set! then (resolve! then ctx))
(set! else (resolve! else ctx))
nthis))))
(begin
(unfix! ctx "resolve.J2SIfCascade")
nthis)))))
;*---------------------------------------------------------------------*/
;* resolve! ::J2SCall ... */
;*---------------------------------------------------------------------*/
(define-walk-method (resolve! this::J2SCall ctx::pair)
(define (same-type typ tyr)
(cond
((eq? typ tyr) #t)
((and (eq? typ 'integer) (memq tyr '(number integer))) #unspecified)
((type-subtype? typ tyr) #t)
((not (type-maybe-subtype? typ tyr)) #f)
(else #unspecified)))
(with-access::J2SCall this (loc)
(multiple-value-bind (op decl typ ref)
(j2s-expr-type-test this)
(if (or (not op) (not ref) (memq (j2s-type ref) '(any unknown)))
(call-default-walker)
(case op
((==)
(let ((b (or (same-type typ (j2s-type ref))
(same-type (j2s-type ref) typ))))
(if (boolean? b)
(begin
(unfix! ctx "resolve.J2SCall")
(J2SBool b))
(call-default-walker))))
((!=)
(let ((b (or (same-type typ (j2s-type ref))
(same-type (j2s-type ref) typ))))
(if (boolean? b)
(begin
(unfix! ctx "resolve.J2SCall")
(J2SBool (not b)))
(call-default-walker))))
((<=)
(let ((rtyp (j2s-type ref)))
(cond
((type-subtype? rtyp typ)
(unfix! ctx "resolve.J2SCall")
(J2SBool #t))
((memq rtyp '(unknown any))
(call-default-walker))
(else
(unfix! ctx "resolve.J2SCall")
(J2SBool #f)))))
(else
(call-default-walker)))))))
;*---------------------------------------------------------------------*/
;* force-type ... */
;*---------------------------------------------------------------------*/
(define (force-type::bool this::J2SNode from to final::bool)
(let ((cell (make-cell #f)))
(force-type! this from to cell final)
(cell-ref cell)))
;*---------------------------------------------------------------------*/
;* force-type! ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SNode from to cell::cell final::bool)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SExpr ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SExpr from to cell final)
(with-access::J2SExpr this (type loc)
(when (and (eq? type from) (not (eq? type to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! type to)))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SFun ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SFun from to cell final)
(with-access::J2SFun this (rtype thisp loc type params)
(when (isa? thisp J2SNode) (force-type! thisp from to cell final))
(when (and (eq? type from) (not (eq? type to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! type to))
(when (and (eq? rtype from) (not (eq? rtype to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! rtype to)))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-type! ::J2JRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SRef from to cell final)
(with-access::J2SRef this (decl type loc)
(when (isa? decl J2SDeclArguments)
(force-type! decl from to cell final))
(when (eq? type from)
(set! type to)
(cell-set! cell #t))
(call-default-walker)))
;*---------------------------------------------------------------------*/
;* force-type! ::J2JHopRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SHopRef from to cell final)
(with-access::J2SHopRef this (type)
(when (eq? type from)
(set! type to)
(cell-set! cell #t)))
this)
;*---------------------------------------------------------------------*/
;* force-type! ::J2JGlobalRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SGlobalRef from to cell final)
(with-access::J2SGlobalRef this (type loc decl)
(with-access::J2SDecl decl (vtype)
(when (and (eq? vtype from) (not (eq? vtype to)))
(set! vtype to)
(cell-set! cell #t)))
(when (and (eq? type from) (not (eq? type to)))
(set! type to)
(cell-set! cell #t)))
this)
;*---------------------------------------------------------------------*/
;* force-type! ::J2SDecl ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SDecl from to cell final)
(with-access::J2SDecl this (vtype loc id)
(when (and (eq? vtype from) (not (eq? vtype to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! vtype to)))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SDeclInit ... */
;* ------------------------------------------------------------- */
;* It might be situation where the declaration is not uninit */
;* but the declaration and the initialization are still split. */
;* For instance, it might be that a constant is initialized */
;* with an object but declared with the undefined value. This */
;* function handles these situation to preserve a well typed */
* ast . It uses two situations : * /
;* 1- either it changes the value of the declaration to use */
;* a well-type constant */
;* 2- it changes the variable type */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SDeclInit from to cell final)
(define (type->init type val)
(with-access::J2SExpr val (loc)
(case type
((number integer) (J2SNumber/type 'number 0))
((string) (J2SString ""))
((bool) (J2SBool #f))
((null) (J2SNull))
((object) (J2SHopRef/type '%this 'object))
(else #f))))
(define (type-eq? t1 t2)
(or (eq? t1 t2)
(and (eq? t1 'number) (eq? t2 'integer))
(and (eq? t1 'integer) (eq? t2 'number))))
(with-access::J2SDeclInit this (vtype loc val)
(when (and (eq? vtype from) (not (eq? vtype to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! vtype to))
(when (and final
(not (eq? vtype 'any))
(not (type-eq? vtype (j2s-type val))))
(cond
((decl-usage-has? this '(uninit))
(error "force-type!"
(format "Declaration inconsistent with init (~a/~a)"
(type->sexp vtype) (type->sexp (j2s-type val)))
(j2s->sexp this)))
((type->init vtype val)
=>
(lambda (v)
(set! val v)))
(else
(set! vtype 'any))))
(call-default-walker)))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SCatch ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SCatch from to cell final)
(with-access::J2SCatch this (param)
(force-type! param from to cell final)
(call-default-walker)))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SClass ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SClass from to cell final)
(with-access::J2SClass this (elements type)
(when (eq? type from) (set! type to))
(for-each (lambda (el)
(with-access::J2SClassElement el (type)
(when (eq? type from) (set! type to))))
elements))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SPostfix ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SPostfix from to cell final)
(with-access::J2SPostfix this (type)
(when (eq? type 'unknown)
(set! type 'number)
(cell-set! cell #t)))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-type! ::J2SPrefix ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-type! this::J2SPrefix from to cell final)
(with-access::J2SPrefix this (type)
(when (eq? type 'unknown)
(set! type 'number)
(cell-set! cell #t)))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-record-method-type ::J2SNode ... */
;* ------------------------------------------------------------- */
;* Even when no type analysis is performed, the type of the */
;* record method receiver has to be properly set. Otherwise, */
;* the compilation of super.method in the scheme code */
;* generation stage will produce code for classes instead of */
;* code for records. */
;*---------------------------------------------------------------------*/
(define-walk-method (force-record-method-type this::J2SNode)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-record-method-type ::J2SClassElement ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-record-method-type this::J2SClassElement)
(define (force-type-record-method val::J2SFun clazz)
(with-access::J2SFun val (thisp body loc)
(let ((self (duplicate::J2SDeclInit thisp
(key (ast-decl-key))
(id '!this)
(_scmid '!this)
(vtype clazz)
(itype clazz)
(val (J2SCast clazz (J2SRef thisp)))
(binder 'let-opt)
(hint '())))
(endloc (node-endloc body)))
(set! body
(J2SLetRecBlock #f (list self)
(j2s-alpha body (list thisp) (list self)))))))
(with-access::J2SClassElement this (prop type clazz static usage)
(cond
((j2s-class-property-constructor? prop)
(force-record-method-type prop))
(else
(when (and (not static)
(isa? prop J2SMethodPropertyInit)
(isa? clazz J2SRecord))
(with-access::J2SMethodPropertyInit prop (val)
(with-access::J2SFun val (thisp)
(with-access::J2SDecl thisp (vtype)
(when (eq? vtype 'unknown)
(force-type-record-method val clazz))))))
(force-record-method-type prop)))))
;*---------------------------------------------------------------------*/
;* force-record-method-type ::J2SFun ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-record-method-type this::J2SFun)
#unspecified)
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SNode ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SNode)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SRef)
(with-access::J2SRef this (type)
(when (eq? type 'any)
(set! type 'unknown)))
this)
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SDecl ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SDecl)
(call-default-walker)
(with-access::J2SDecl this (vtype)
(when (eq? vtype 'any)
(set! vtype 'unknown)))
this)
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SDeclFun ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SDeclFun)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SNumber ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SNumber)
this)
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SExpr ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SExpr)
(with-access::J2SExpr this (type)
(when (eq? type 'any)
(set! type 'unknown)))
(call-default-walker))
;*---------------------------------------------------------------------*/
* reset - type ! : : ... * /
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SBindExit)
(with-access::J2SBindExit this (type)
(when (eq? type 'any)
(set! type 'unknown)))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* reset-type! ::J2SHopRef ... */
;*---------------------------------------------------------------------*/
(define-walk-method (reset-type! this::J2SHopRef)
this)
;*---------------------------------------------------------------------*/
;* force-unary-type! ::J2SNode ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-unary-type! this::J2SNode)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* force-unary-type! ::J2SUnary ... */
;*---------------------------------------------------------------------*/
(define-walk-method (force-unary-type! this::J2SUnary)
(define (non-zero-integer? expr)
(when (isa? expr J2SNumber)
(with-access::J2SNumber expr (val)
(not (= val 0)))))
(with-access::J2SUnary this (op expr type)
(when (eq? type 'integer)
(unless (non-zero-integer? expr)
(when (memq op '(+ -))
(set! type 'number)))))
this)
;*---------------------------------------------------------------------*/
;* cleanup-hint! ... */
;*---------------------------------------------------------------------*/
(define-walk-method (cleanup-hint! this::J2SNode)
(call-default-walker))
;*---------------------------------------------------------------------*/
;* cleanup-hint! ::J2SDecl ... */
;*---------------------------------------------------------------------*/
(define-walk-method (cleanup-hint! this::J2SDecl)
(with-access::J2SDecl this (hint vtype)
(unless (memq vtype '(number any))
(set! hint (filter (lambda (h) (=fx (cdr h) (minvalfx))) hint))))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* cleanup-hint! ::J2SExpr ... */
;*---------------------------------------------------------------------*/
(define-walk-method (cleanup-hint! this::J2SExpr)
(with-access::J2SExpr this (hint type)
(unless (memq type '(number any))
(set! hint (filter (lambda (h) (=fx (cdr h) (minvalfx))) hint))))
(call-default-walker))
;*---------------------------------------------------------------------*/
;* utype-error ... */
;*---------------------------------------------------------------------*/
(define (utype-error this::J2SExpr utype tyv)
(with-access::J2SExpr this (loc)
(raise
(instantiate::&type-error
(proc "hopc")
(msg (format "Illegal type, \"~a\" expected"
(type-name utype '())))
(obj (type-name tyv '()))
(type (type-name utype '()))
(fname (cadr loc))
(location (caddr loc))))))
;*---------------------------------------------------------------------*/
;* if-check-cache-cascade-classes ... */
;* ------------------------------------------------------------- */
;* Returns the list of all the types tested in a cachecheck */
;* cascade. */
;*---------------------------------------------------------------------*/
(define (if-check-cache-cascade-classes::pair-nil this::J2SIf)
(with-access::J2SIf this (test else)
(if (isa? test J2SCacheCheck)
(with-access::J2SCacheCheck test ((o0 obj) (t0 owner))
(if (and (isa? o0 J2SRef) (isa? t0 J2SClass) (isa? (j2s-vtype o0) J2SClass))
(with-access::J2SRef o0 ((d0 decl))
(let loop ((else else)
(ts (list t0)))
(if (isa? else J2SIf)
(with-access::J2SIf else (test else)
(if (isa? test J2SCacheCheck)
(with-access::J2SCacheCheck test ((o1 obj) (t1 owner))
(if (isa? o1 J2SRef)
(with-access::J2SRef o1 ((d1 decl))
(if (eq? d0 d1)
(loop else
(if (isa? t1 J2SClass) (cons t1 ts) ts))
ts))
ts))
ts))
ts)))
'()))
'())))
;*---------------------------------------------------------------------*/
;* if-check-cache-cascade-resolve! ... */
;* ------------------------------------------------------------- */
;* Remove the inlined method that the type analysis elimitated. */
;*---------------------------------------------------------------------*/
(define (if-check-cache-cascade-resolve! this::J2SIf ts::pair)
(define (resolve! this ts)
(if (isa? this J2SIf)
(with-access::J2SIf this (test then else)
(with-access::J2SCacheCheck test (owner)
(if (memq owner ts)
invalidate that
(resolve! else ts)
(begin
(set! else (resolve! else ts))
this))))
this))
(with-access::J2SIf this (test else)
(with-access::J2SCacheCheck test (obj)
(let* ((to (j2s-vtype obj))
(fts (filter (lambda (t) (type-subtype? to t)) ts)))
(if (or (null? fts) (null? (cdr fts)))
this
(let ((sts (sort type-subtype? fts)))
keep the first super types ,
;; eliminate all other smaller types
(resolve! this (cdr sts))))))))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/0ba67faea16481d8a09b997c5b6ad919cd7babb9/js2scheme/tyflow.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* js2scheme type inference */
* ------------------------------------------------------------- */
* even for literals and constants. */
* ------------------------------------------------------------- */
* This stage assigns types to variable declarations and variable */
* references. At a declaration site, the types are: */
* */
* itype: the initial type of the variable */
* utype: the user given type, enforced on assignments */
* */
* Types of declared variables have the following properties: */
* 1- itype < vtype */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* debug-tyflow ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* j2s-typing! ::obj ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* utype-compatible? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* tyflow-type ... */
* ------------------------------------------------------------- */
* Maps to tyflow understood types. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* type-program! ... */
*---------------------------------------------------------------------*/
main fix point
type all the nodes
type check resolution
hint node-type optimization
*---------------------------------------------------------------------*/
* program-cleanup! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* dump-env ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* unfix! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* return ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* Assign a unique type to a variable declaration. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* Add a new type to a variable declaration. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* Add a new initial type to a variable declaration. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* expr-type-add! ... */
* ------------------------------------------------------------- */
* Set the expression type and if needed update the ctx stamp. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* class-element-type-add! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* class-element-access-type-add! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* merge-types ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* typnum? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* funtype ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* env? ... */
*---------------------------------------------------------------------*/
heuristic check (not very precise but should be enough)
*---------------------------------------------------------------------*/
* extend-env ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* refine-env ... */
* ------------------------------------------------------------- */
* current type is a super type of ty. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* env-lookup ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* env-nocapture ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* env-merge ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* env-override ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type-args ... */
* ------------------------------------------------------------- */
* Type all the arguments and return a new environment. The */
* arguments are typed as left to right sequence. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type-seq ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* filter-breaks ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SNode ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SMeta ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SExpr ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SNull ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SUndefined ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SArrayAbsent ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SNumber ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SBool ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SString ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SNativeString ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SRegExp ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SLiteralCnst ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCmap ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2STemplate ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2STilde ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SArray ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SSpread ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SPragma ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SPropertyInit ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SDataPropertyInit ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SObjInit ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SParen ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SSequence ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SHopRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SUnresolvedRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SGlobalRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SSuper ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SWithRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SKontRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SDecl ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SDeclArguments ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SDeclInit ... */
*---------------------------------------------------------------------*/
check the special case
declinit v = new Record();
wait for the ::J2SInit expression for assigning a type
to this constant
*---------------------------------------------------------------------*/
* node-type ::J2SDeclFun ... */
*---------------------------------------------------------------------*/
services and exported function are as escaping functions,
the arguments and return types are "any"
a mere constructor
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SAssig ... */
*---------------------------------------------------------------------*/
variable assignment
"this" property assignment
a non variable assignment
*---------------------------------------------------------------------*/
* node-type ::J2SAssigOp ... */
*---------------------------------------------------------------------*/
a variable assignment
a non variable assinment
*---------------------------------------------------------------------*/
* node-type ::J2SPostfix ... */
*---------------------------------------------------------------------*/
a variable assignment
a non variable assignment
*---------------------------------------------------------------------*/
* node-type ::J2SPrefix ... */
*---------------------------------------------------------------------*/
prectx expressions only evaluate as numbers
a variable assignment
a non variable assignment
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SDConsumer ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type-fun ... */
*---------------------------------------------------------------------*/
transfer all itypes to vtypes
rutype
*---------------------------------------------------------------------*/
* node-type-fun-decl ::J2SFun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* escape-fun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* escape-method ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type-fun-or-method ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SFun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SMethod ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCall ... */
* ------------------------------------------------------------- */
* Function calls may affect the node-type environment, depending */
* on the called function. Each case comes with a special rule, */
* detailed in the code below. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type-call ... */
*---------------------------------------------------------------------*/
compute a new node-type environment where all mutated globals
and all mutated captured locals are removed
compute a new node-type environment where all mutated globals
and all mutated captured locals are removed
type a direct function call: ((function (...) { ... })( ... ))
side effects are automatically handled when
node-type the function body
type a known constant function call: F( ... )
the new node-type environment is a merge of env and the environment
produced by the function
type a method call: O.m( ... )
the method is unknown, filter out the node-type env
type a hop (foreign function) call: H( ... )
hop calls have no effect on the node-type env
type a unknown function call: expr( ... )
filter out the node-type env
*---------------------------------------------------------------------*/
* node-type ::J2SCond ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SNew ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SUnary ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type-binary ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SBinary ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SAccess ... */
*---------------------------------------------------------------------*/
optimization, alias arguments are optimized too
The length field of a arguments is not necessarily
an number (when assigned a random value, see
S10.6_A5_T4.js test.
arguments.length is known to return and integer only
if arguments is not assigned anything and not passed
to anyone.
*---------------------------------------------------------------------*/
* node-type ::J2SCacheCheck ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCacheUpdate ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCheck ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCast ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SNop ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SSeq ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SLabel ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SWith ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SReturn ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SKont ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SIf ... */
*---------------------------------------------------------------------*/
we assume that the only type predicate are positive tests
*---------------------------------------------------------------------*/
* node-type ::J2SSwitch ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCase ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SBreak ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SWhile ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SDo ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SForIn ... */
* ------------------------------------------------------------- */
* !!! WARNING: After the for..in loop the key variable is */
* undefined if the object contains no property. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2STry ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SCatch ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SClass ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* node-type ::J2SClassElement ... */
*---------------------------------------------------------------------*/
record constructors escape (even if not syntactically)
*---------------------------------------------------------------------*/
* j2s-resolve! ... */
* ------------------------------------------------------------- */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* resolve! ::J2SNode ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* resolve! ::J2SBinary ... */
*---------------------------------------------------------------------*/
-international.org/ecma-262/5.1/#sec-11.7.3
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
inlining invalidated by the type inference
inlining validated by the type inference
*---------------------------------------------------------------------*/
* resolve! ::J2SIf ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* resolve! ::J2SCall ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SExpr ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SFun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2JRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2JHopRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2JGlobalRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SDecl ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SDeclInit ... */
* ------------------------------------------------------------- */
* It might be situation where the declaration is not uninit */
* but the declaration and the initialization are still split. */
* For instance, it might be that a constant is initialized */
* with an object but declared with the undefined value. This */
* function handles these situation to preserve a well typed */
* 1- either it changes the value of the declaration to use */
* a well-type constant */
* 2- it changes the variable type */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SCatch ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SClass ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SPostfix ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-type! ::J2SPrefix ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-record-method-type ::J2SNode ... */
* ------------------------------------------------------------- */
* Even when no type analysis is performed, the type of the */
* record method receiver has to be properly set. Otherwise, */
* the compilation of super.method in the scheme code */
* generation stage will produce code for classes instead of */
* code for records. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-record-method-type ::J2SClassElement ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-record-method-type ::J2SFun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SNode ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SDecl ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SDeclFun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SNumber ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SExpr ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-type! ::J2SHopRef ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-unary-type! ::J2SNode ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* force-unary-type! ::J2SUnary ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* cleanup-hint! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* cleanup-hint! ::J2SDecl ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* cleanup-hint! ::J2SExpr ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* utype-error ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* if-check-cache-cascade-classes ... */
* ------------------------------------------------------------- */
* Returns the list of all the types tested in a cachecheck */
* cascade. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* if-check-cache-cascade-resolve! ... */
* ------------------------------------------------------------- */
* Remove the inlined method that the type analysis elimitated. */
*---------------------------------------------------------------------*/
eliminate all other smaller types | * serrano / prgm / project / hop / hop / js2scheme / tyflow.scm * /
* Author : * /
* Creation : Sun Oct 16 06:12:13 2016 * /
* Last change : Sun Mar 6 16:55:10 2022 ( serrano ) * /
* Copyright : 2016 - 22 * /
* This pass does not assume any type decoration in the AST , not * /
* vtype : the final type of the variable ( used by scheme ) * /
* 2- for in ref(v ) , T(ref(v ) ) < vtype * /
* 3- if utype ! = unknown then itype = vtype = utype * /
(module __js2scheme_tyflow
(include "ast.sch"
"usage.sch")
(import __js2scheme_ast
__js2scheme_dump
__js2scheme_compile
__js2scheme_stage
__js2scheme_syntax
__js2scheme_utils
__js2scheme_classutils
__js2scheme_type-hint
__js2scheme_use
__js2scheme_alpha)
(export j2s-tyflow-stage))
* - stage ... * /
(define j2s-tyflow-stage
(instantiate::J2SStageProc
(name "tyflow")
(comment "Dataflow type inference")
(proc j2s-typing!)))
(define debug-tyflow #f)
(define (j2s-typing! this args)
(when (isa? this J2SProgram)
(type-program! this args)
this))
(define (utype-compatible? utype type)
(or (eq? type 'magic) (type-subtype? type utype)))
(define (tyflow-type ty)
(j2s-hint-type ty))
(define (type-program! this::J2SProgram conf)
(define j2s-verbose (config-get conf :verbose 0))
(with-access::J2SProgram this (headers decls nodes mode)
(when (>=fx j2s-verbose 3) (display " " (current-error-port)))
(if (config-get conf :optim-tyflow #f)
(let ((ctx (cons mode 0)))
(let loop ((i 1))
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port) "~a." i)
(flush-output-port (current-error-port)))
(let ((ofix (cdr ctx)))
(node-type-seq (append headers decls nodes) '() ctx 'void)
(cond
((not (=fx (cdr ctx) ofix))
(loop (+fx i 1)))
((config-get conf :optim-tyflow-resolve #f)
(let ((reset-for-resolve (j2s-resolve! this conf ctx)))
(cond
((not (=fx (cdr ctx) ofix))
(loop (+fx i 1)))
((config-get conf :optim-hint #f)
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port) "hint"))
(let ((dups (j2s-hint! this conf)))
(cond
((pair? dups)
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port)
(format " [~(,)]."
(map (lambda (d)
(with-access::J2SDecl d (id)
id))
dups))))
(for-each reset-type! decls)
(for-each reset-type! nodes)
(loop (+fx i 1)))
(reset-for-resolve
(for-each reset-type! decls)
(for-each reset-type! nodes)
(loop (+fx i 1)))
((force-type this 'unknown 'any #f)
(when (>=fx j2s-verbose 3)
(fprintf (current-error-port) "."))
(loop (+fx i 1))))))
((force-type this 'unknown 'any #f)
(loop (+fx i 1))))))))))
(begin
(force-record-method-type this)
(force-type this 'unknown 'any #t)))
(when (config-get conf :optim-hintblock)
(when (>=fx (config-get conf :verbose 0) 4)
(display " hint-block" (current-error-port)))
(j2s-hint-block! this conf))
(unless (config-get conf :optim-integer)
(force-type this 'integer 'number #f))
(force-type this 'unknown 'any #t)
(cleanup-hint! this)
(program-cleanup! this))
this)
(define (program-cleanup! this::J2SProgram)
(with-access::J2SProgram this (headers decls nodes direct-eval)
(reinit-use-count! this)
(unless direct-eval
(set! decls (filter-dead-declarations decls))
(for-each j2s-hint-meta-noopt! decls))
this))
(define (dump-env env)
(map (lambda (e)
(cons (with-access::J2SDecl (car e) (id key)
(format "~a:~a" id key))
(type->sexp (cdr e))))
env))
(define (unfix! ctx reason)
(tprint "--- UNFIX (" (cdr ctx) ") reason=" reason)
(set-cdr! ctx (+fx 1 (cdr ctx))))
(define-macro (unfix! ctx reason)
`(set-cdr! ,ctx (+fx 1 (cdr ,ctx))))
(define (return ty env::pair-nil bk::pair-nil)
(values ty env bk))
* - set ! ... * /
(define (decl-vtype-set! decl::J2SDecl ty::obj ctx::pair)
(with-access::J2SDecl decl (ctype vtype id loc)
[assert (ty) (or (eq? vtype 'unknown) (eq? vtype ty))]
(unless (memq ctype '(any unknown))
(set! ty ctype))
(when (or (eq? vtype 'unknown) (not (eq? vtype ty)))
(unfix! ctx (format "J2SDecl.vset(~a, ~a) vtype=~a/~a" id loc
(type->sexp vtype) (type->sexp ty)))
(set! vtype (tyflow-type ty)))))
* - add ! ... * /
(define (decl-vtype-add! decl::J2SDecl ty ctx::pair)
(with-access::J2SDecl decl (ctype vtype id loc)
(unless (eq? ctype 'any)
(set! ty ctype))
(unless (or (eq? ty 'unknown) (type-subtype? ty vtype) (eq? vtype 'any))
(unfix! ctx (format "J2SDecl.vadd(~a, ~a) vtype=~a/~a" id loc
(type->sexp vtype) (type->sexp ty)))
(set! vtype (tyflow-type (merge-types vtype ty))))))
* - add ! ... * /
(define (decl-itype-add! decl::J2SDecl ty ctx::pair)
(with-access::J2SDecl decl (ctype itype id)
(unless (eq? ctype 'any)
(set! ty ctype))
(unless (or (eq? ty 'unknown) (type-subtype? ty itype) (eq? itype 'any))
(unfix! ctx (format "J2SDecl.iadd(~a) itype=~a/~a" id
(type->sexp itype) (type->sexp ty)))
(set! itype (tyflow-type (merge-types itype ty))))))
(define (expr-type-add! this::J2SExpr env::pair-nil ctx::pair ty
#!optional (bk '()))
(with-access::J2SExpr this (type loc)
(unless (or (eq? ty 'unknown) (eq? type ty))
(let ((ntype (merge-types type ty)))
(unless (eq? ntype type)
(unfix! ctx
(format "J2SExpr.add(~a) ~a ~a/~a -> ~a"
loc (j2s->sexp this)
(type->sexp ty)
(type->sexp type)
(type->sexp ntype)))
(set! type (tyflow-type ntype)))))
(return type env bk)))
(define (class-element-type-add! this::J2SClassElement ctx::pair ty)
(with-access::J2SClassElement this (type loc)
(unless (or (eq? ty 'unknown) (eq? type ty))
(let ((ntype (merge-types type ty)))
(unless (eq? ntype type)
(unfix! ctx
(format "J2SClassElement.add(~a) ~a ~a/~a -> ~a"
loc (j2s->sexp this)
(type->sexp ty)
(type->sexp type)
(type->sexp ntype)))
(set! type (tyflow-type ntype))))) ))
(define (class-element-access-type-add! this::J2SAccess ctx::pair ty)
(let ((el (class-private-element-access this)))
(class-element-type-add! el ctx ty)))
(define (merge-types left right)
(cond
((eq? left right) left)
((and (eq? left 'arrow) (eq? right 'function)) 'arrow)
((and (eq? left 'function) (eq? right 'arrow)) 'arrow)
((eq? left 'unknown) right)
((eq? right 'unknown) left)
((and (type-integer? left) (type-integer? right)) 'integer)
((and (type-integer? left) (eq? right 'number)) 'number)
((and (eq? left 'number) (type-integer? right)) 'number)
((and (eq? left 'number) (eq? right 'integer)) 'number)
((type-subtype? left right) right)
((type-subtype? right left) left)
(else 'any)))
(define (typnum? ty)
(memq ty '(index length indexof integer real bigint number)))
(define (funtype this::J2SFun)
(cond
((isa? this J2SArrow) 'arrow)
((isa? this J2SSvc) 'service)
(else 'function)))
(define (env? o)
(or (null? o)
(and (pair? o)
(isa? (caar o) J2SDecl)
(symbol? (cdar o)))))
(define (extend-env::pair-nil env::pair-nil decl::J2SDecl ty)
(let ((old (env-lookup env decl)))
(if (eq? ty 'unknown)
env
(cons (cons decl ty) env))))
* add ty > only if is not already in env or if the * /
(define (refine-env::pair-nil env::pair-nil decl::J2SDecl ty)
(let ((old (env-lookup env decl)))
(if (or (not old) (type-subtype? ty old) (memq old '(any unknown)))
(cons (cons decl ty) env)
env)))
(define (env-lookup env::pair-nil decl::J2SDecl)
(let ((c (assq decl env)))
(if (pair? c)
(cdr c)
(with-access::J2SDecl decl (ctype vtype)
(if (eq? ctype 'any) vtype ctype)))))
(define (env-nocapture env::pair-nil)
(map (lambda (c)
(with-access::J2SDecl (car c) (escape)
(if (and escape (decl-usage-has? (car c) '(assig)))
(cons (car c) 'any)
c)))
env))
(define (env-merge::pair-nil left::pair-nil right::pair-nil)
(define (merge2 env1 env2)
(filter-map (lambda (entry)
(let* ((decl (car entry))
(typl (cdr entry))
(typf (env-lookup env2 decl))
(typm (if (eq? typf 'unknown)
'unknown
(merge-types typl typf))))
(unless (eq? typm 'unknown)
(cons decl typm))))
env1))
(merge2 right (merge2 left right)))
(define (env-override left::pair-nil right::pair-nil)
(append right
(filter (lambda (l)
(not (assq (car l) right)))
left)))
(define (node-type-args::pair-nil args env::pair-nil ctx::pair)
(let loop ((args args)
(env env)
(bks '()))
(if (null? args)
(values env bks)
(multiple-value-bind (_ enva bk)
(node-type (car args) env ctx)
(loop (cdr args) enva (append bk bks))))))
(define (node-type-seq nodes::pair-nil env::pair-nil ctx::pair initty)
(let loop ((nodes nodes)
(ty initty)
(env env)
(bks '()))
(if (null? nodes)
(return ty env bks)
(multiple-value-bind (tyn envn bk)
(node-type (car nodes) env ctx)
(if (pair? bk)
(multiple-value-bind (tyr envr bkr)
(node-type-seq (cdr nodes) envn ctx initty)
(return tyr (env-merge envn envr) (append bk bks)))
(loop (cdr nodes) tyn envn (append bk bks)))))))
(define (filter-breaks bks::pair-nil node)
(filter (lambda (b::J2SStmt)
(or (isa? b J2SReturn)
(isa? b J2SThrow)
(with-access::J2SBreak b (target)
(not (eq? target node)))))
bks))
(define-walk-method (node-type this::J2SNode env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SNode"
(return 'any '() '())))
(define-walk-method (node-type this::J2SMeta env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SMeta"
(with-access::J2SMeta this (stmt)
(node-type stmt env ctx))))
(define-walk-method (node-type this::J2SExpr env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SExpr"
(call-next-method)))
(define-walk-method (node-type this::J2SNull env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SNull"
(expr-type-add! this env ctx 'null)))
(define-walk-method (node-type this::J2SUndefined env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'undefined))
(define-walk-method (node-type this::J2SArrayAbsent env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'undefined))
(define-walk-method (node-type this::J2SNumber env::pair-nil ctx::pair)
(with-access::J2SNumber this (val type)
(expr-type-add! this env ctx
(if (flonum? val) 'real (if (bignum? val) 'bigint 'integer)))))
(define-walk-method (node-type this::J2SBool env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'bool))
(define-walk-method (node-type this::J2SString env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'string))
(define-walk-method (node-type this::J2SNativeString env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'scmstring))
(define-walk-method (node-type this::J2SRegExp env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'regexp))
(define-walk-method (node-type this::J2SLiteralCnst env::pair-nil ctx::pair)
(with-access::J2SLiteralCnst this (val)
(multiple-value-bind (tyv env bk)
(node-type val env ctx)
(expr-type-add! this env ctx tyv bk))))
(define-walk-method (node-type this::J2SCmap env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'cmap))
(define-walk-method (node-type this::J2STemplate env::pair-nil ctx::pair)
(with-access::J2STemplate this (exprs)
(multiple-value-bind (env bk)
(node-type-args exprs env ctx)
(expr-type-add! this env ctx 'string bk))))
(define-walk-method (node-type this::J2STilde env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'tilde))
(define-walk-method (node-type this::J2SArray env::pair-nil ctx::pair)
(with-access::J2SArray this (exprs len isvector type)
(multiple-value-bind (env bk)
(node-type-args exprs env ctx)
(expr-type-add! this env ctx type bk))))
(define-walk-method (node-type this::J2SSpread env::pair-nil ctx::pair)
(with-access::J2SSpread this (expr len)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(expr-type-add! this enve ctx tye bke))))
(define-walk-method (node-type this::J2SPragma env::pair-nil ctx::pair)
(with-access::J2SPragma this (lang expr type)
(cond
((eq? lang 'scheme)
(if (eq? type 'unknown)
(expr-type-add! this env ctx 'any)
(return type env env)))
((isa? expr J2SNode)
(multiple-value-bind (_ _ bk)
(node-type expr env ctx)
(if (eq? type 'unknown)
(expr-type-add! this env ctx 'any bk)
(return type env env))))
(else
(expr-type-add! this env ctx 'any)))))
(define-walk-method (node-type this::J2SPropertyInit env::pair-nil ctx::pair)
'unknown)
(define-walk-method (node-type this::J2SDataPropertyInit env::pair-nil ctx::pair)
(with-access::J2SDataPropertyInit this (val)
(node-type val env ctx)))
* node - type : : J2SAccessorPropertyInit ... * /
(define-walk-method (node-type this::J2SAccessorPropertyInit env::pair-nil ctx::pair)
(with-access::J2SAccessorPropertyInit this (get set)
(call-default-walker)
(return 'void env '())))
(define-walk-method (node-type this::J2SObjInit env::pair-nil ctx::pair)
(with-access::J2SObjInit this (inits)
(let ((args (append-map (lambda (init)
(cond
((isa? init J2SDataPropertyInit)
(with-access::J2SDataPropertyInit init (name val)
(list name val)))
((isa? init J2SAccessorPropertyInit)
(with-access::J2SAccessorPropertyInit init (name get set)
(list name get set)))))
inits)))
(multiple-value-bind (env bk)
(node-type-args args env ctx)
(expr-type-add! this env ctx 'object bk)))))
(define-walk-method (node-type this::J2SParen env::pair-nil ctx::pair)
(with-access::J2SParen this (expr)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(expr-type-add! this enve ctx tye bke))))
(define-walk-method (node-type this::J2SSequence env::pair-nil ctx::pair)
(define (node-type* nodes::pair-nil env::pair-nil ctx::pair)
(let loop ((nodes nodes)
(ty 'undefined)
(env env)
(bks '()))
(if (null? nodes)
(return ty env bks)
(multiple-value-bind (tyn envn bk)
(node-type (car nodes) env ctx)
(if (pair? bk)
(multiple-value-bind (tyr envr bkr)
(node-type-seq (cdr nodes) envn ctx 'unknown)
(return tyr (env-merge envn envr) (append bk bk bks)))
(loop (cdr nodes) tyn envn (append bk bks)))))))
(with-trace 'j2s-tyflow (format "node-type ::J2SSequence ~a" (cdr ctx))
(with-access::J2SSequence this (exprs)
(multiple-value-bind (tye env bk)
(node-type* exprs env ctx)
(expr-type-add! this env ctx tye bk)))))
* node - type : : ... * /
(define-walk-method (node-type this::J2SBindExit env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SBindExit ~a" (cdr ctx))
(with-access::J2SBindExit this (stmt type loc)
(multiple-value-bind (typ env bk)
(node-type stmt env ctx)
(return type env bk)))))
(define-walk-method (node-type this::J2SHopRef env::pair-nil ctx::pair)
(with-access::J2SHopRef this (type)
(return type env '())))
(define-walk-method (node-type this::J2SUnresolvedRef env::pair-nil ctx::pair)
(with-access::J2SUnresolvedRef this (id)
(cond
((memq id '(console))
(expr-type-add! this env ctx 'object))
((eq? id 'undefined)
(expr-type-add! this env ctx 'undefined))
(else
(let ((cla (class-of this)))
(if (or (not cla) (eq? cla 'unknown))
(expr-type-add! this env ctx 'any)
(expr-type-add! this env ctx 'object)))))))
(define-walk-method (node-type this::J2SGlobalRef env::pair-nil ctx::pair)
(with-access::J2SGlobalRef this (decl id)
(cond
((eq? id 'undefined)
(decl-vtype-add! decl 'undefined ctx)
(expr-type-add! this env ctx 'undefined))
((eq? id 'NaN)
(decl-vtype-add! decl 'real ctx)
(expr-type-add! this env ctx 'real))
((memq id '(Math String Error Regex Date Function Array Promise))
(decl-vtype-add! decl 'object ctx)
(expr-type-add! this env ctx 'object))
((not (decl-ronly? decl))
(multiple-value-bind (tyv env bk)
(call-next-method)
(decl-vtype-add! decl tyv ctx)
(return tyv env bk)))
(else
(decl-vtype-add! decl 'any ctx)
(expr-type-add! this env ctx 'any)))))
(define-walk-method (node-type this::J2SRef env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SRef ~a" (cdr ctx))
(with-access::J2SRef this (decl loc)
(trace-item "loc=" loc)
(with-access::J2SDecl decl (id key vtype scope)
(let ((nenv env))
(when (and (isa? decl J2SDeclFun) (not (constructor-only? decl)))
(set! nenv (env-nocapture env))
(with-access::J2SDeclFun decl (val id)
(if (isa? val J2SMethod)
(escape-method val ctx)
(escape-fun val ctx #f))))
(if (and (memq scope '(%scope global tls))
(not (eq? vtype 'unknown)))
(expr-type-add! this nenv ctx vtype)
(let ((ty (env-lookup env decl)))
(expr-type-add! this nenv ctx ty))))))))
(define-method (node-type this::J2SSuper env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SSuper ~a" (cdr ctx))
(with-access::J2SSuper this (decl loc super context)
(cond
((isa? super J2SClass)
(expr-type-add! this env ctx super))
((isa? context J2SClass)
(expr-type-add! this env ctx (or (j2s-class-super-val context) 'any)))
(else
(let ((ty (env-lookup env decl)))
(if (isa? ty J2SClass)
(expr-type-add! this env ctx (or (j2s-class-super-val ty) 'any))
(expr-type-add! this env ctx 'any))))))))
(define-walk-method (node-type this::J2SWithRef env::pair-nil ctx::pair)
(with-access::J2SWithRef this (expr)
(node-type expr '() ctx)
(expr-type-add! this env ctx 'any)))
(define-method (node-type this::J2SKontRef env::pair-nil ctx::pair)
(expr-type-add! this env ctx 'any))
(define-walk-method (node-type this::J2SDecl env::pair-nil ctx::pair)
(decl-itype-add! this 'undefined ctx)
(decl-vtype-add! this 'undefined ctx)
(return 'void (extend-env env this 'undefined) '()))
* node - type : : J2SDeclImport ... * /
(define-walk-method (node-type this::J2SDeclImport env::pair-nil ctx::pair)
(decl-itype-add! this 'any ctx)
(decl-vtype-add! this 'any ctx)
(return 'void (extend-env env this 'any) '()))
(define-walk-method (node-type this::J2SDeclArguments env::pair-nil ctx::pair)
(decl-itype-add! this 'arguments ctx)
(decl-vtype-add! this 'arguments ctx)
(return 'void (extend-env env this 'arguments) '()))
(define-walk-method (node-type this::J2SDeclInit env::pair-nil ctx::pair)
(with-access::J2SDeclInit this (val id loc _usage writable ctype utype mtype)
(multiple-value-bind (ty env bk)
(node-type val env ctx)
(when (isa? val J2SNew)
(with-access::J2SNew val (clazz)
(when (isa? clazz J2SRef)
(with-access::J2SRef clazz (decl)
(when (isa? decl J2SDeclClass)
(with-access::J2SDeclClass decl (val)
(when (isa? val J2SRecord)
(unless (decl-usage-has? decl '(assig))
(set! mtype val)))))))))
(cond
((not (memq ctype '(any unknown)))
(decl-vtype-set! this ctype ctx)
(return 'void (extend-env env this ctype) bk))
((and (not (eq? utype 'unknown)) (eq? (car ctx) 'hopscript))
(decl-vtype-set! this utype ctx)
(let ((tyv (j2s-type val)))
(unless (utype-compatible? utype tyv)
(if (memq tyv '(unknown any object))
(set! val (J2SCheck utype val))
(utype-error val utype tyv))))
(return 'void (extend-env env this utype) bk))
((decl-usage-has? this '(eval))
(decl-vtype-add! this 'any ctx)
(return 'void (extend-env env this ty) bk))
((or (eq? ty 'unknown) (not ty))
(return 'void env bk))
((and (not writable)
(not (decl-usage-has? this '(uninit)))
(decl-usage-has? this '(assig)))
(return 'void env bk))
(else
(decl-vtype-add! this ty ctx)
(return 'void (extend-env env this ty) bk))))))
(define-walk-method (node-type this::J2SDeclFun env::pair-nil ctx::pair)
(define (node-type-optional-args val env ctx)
(with-access::J2SFun val (params)
(for-each (lambda (p)
(when (isa? p J2SDeclInit)
(node-type p env ctx)))
params)))
(define (node-type-ctor-only val)
(with-access::J2SFun val (generator rtype thisp)
(when generator
(set! rtype 'any))
(when (isa? thisp J2SDecl)
(decl-itype-add! thisp 'object ctx))))
(with-access::J2SDeclFun this (val scope id loc)
(if (isa? val J2SFun)
(node-type-optional-args val env ctx)
(with-access::J2SMethod val (function method)
(node-type-optional-args function env ctx)
(node-type-optional-args method env ctx)))
(let ((ty (if (isa? this J2SDeclSvc) 'service 'function)))
(if (decl-ronly? this)
(decl-vtype-set! this ty ctx)
(decl-vtype-add! this ty ctx)))
(cond
((or (isa? this J2SDeclSvc) (eq? scope 'export))
(if (isa? val J2SFun)
(escape-fun val ctx #f)
(escape-method val ctx)))
((constructor-only? this)
(if (isa? val J2SFun)
(node-type-ctor-only val)
(with-access::J2SMethod val (function method)
(node-type-ctor-only function)
(node-type-ctor-only method)))))
(multiple-value-bind (tyf env _)
(if (isa? val J2SMethod)
(node-type val env ctx)
(node-type-fun val (node-type-fun-decl val env ctx) ctx))
(return 'void (extend-env env this tyf) '()))))
* node - type : : J2SDeclClass ... * /
(define-walk-method (node-type this::J2SDeclClass env::pair-nil ctx::pair)
(define (node-type-class this)
(with-access::J2SDeclClass this (val)
(let ((ty (if (isa? val J2SClass)
(with-access::J2SClass val (need-dead-zone-check)
(if need-dead-zone-check 'any 'function))
'any)))
(if (decl-ronly? this)
(decl-vtype-set! this ty ctx)
(decl-vtype-add! this ty ctx))
(multiple-value-bind (tyf env bk)
(node-type val env ctx)
(return ty env bk)))))
(define (node-type-record this)
(with-access::J2SDeclClass this (val id)
(with-access::J2SRecord val (itype type)
(decl-vtype-set! this 'function ctx)
(multiple-value-bind (tyf env bk)
(node-type val env ctx)
(return 'function env bk)))))
(with-access::J2SDeclClass this (val)
(call-default-walker)
(if (isa? val J2SRecord)
(node-type-record this)
(node-type-class this))))
(define-walk-method (node-type this::J2SAssig env::pair-nil ctx::pair)
(define (this-assig? lhs)
(when (isa? lhs J2SAccess)
(with-access::J2SAccess lhs (obj)
(when (isa? obj J2SThis)
(with-access::J2SThis obj (decl)
decl)))))
(with-trace 'j2s-tyflow (format "node-type ::J2SAssig ~a" (cdr ctx))
(with-access::J2SAssig this (lhs rhs loc)
(let loop ((lhs lhs))
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(cond
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable id utype)
(multiple-value-bind (tyr env rbk)
(node-type rhs envl ctx)
(cond
((and (not writable) (not (isa? this J2SInit)))
(let ((nenv (extend-env env decl tyv)))
(expr-type-add! this nenv ctx tyv
(append lbk rbk))))
((and (not (eq? utype 'unknown))
(eq? (car ctx) 'hopscript))
(unless (utype-compatible? utype tyr)
(if (memq tyr '(unknown any object))
(set! rhs (J2SCheck utype rhs))
(utype-error rhs utype tyv)))
(expr-type-add! this env ctx utype
(append lbk rbk)))
(tyr
(with-access::J2SRef lhs (decl loc)
(decl-vtype-add! decl tyr ctx)
(let ((nenv (extend-env env decl tyr)))
(expr-type-add! this nenv ctx tyr
(append lbk rbk)))))
(else
(return 'unknown env (append lbk rbk))))))))
((isa? lhs J2SWithRef)
(with-access::J2SWithRef lhs (expr)
(loop expr)))
((this-assig? lhs)
=>
(lambda (decl)
(with-access::J2SDecl decl (vtype)
(let* ((ty (if (isa? vtype J2SRecord) vtype 'object))
(envt (extend-env envl decl ty)))
(multiple-value-bind (tyr nenv rbk)
(node-type rhs envt ctx)
(if tyr
(begin
(when (class-private-element-access lhs)
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this nenv ctx tyr (append lbk rbk)))
(return 'unknown envt (append lbk rbk))))))))
(else
(multiple-value-bind (tyr nenv rbk)
(node-type rhs envl ctx)
(if tyr
(begin
(when (and (isa? lhs J2SAccess)
(class-private-element-access lhs))
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this nenv ctx tyr (append lbk rbk)))
(return 'unknown env (append lbk rbk)))))))))))
(define-walk-method (node-type this::J2SAssigOp env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SAssigOp ~a" (cdr ctx))
(with-access::J2SAssigOp this (lhs rhs op)
(multiple-value-bind (tyr envr bkr)
(node-type-binary op lhs rhs env ctx)
(cond
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable)
(cond
((not writable)
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(let ((nenv (extend-env env decl tyv)))
(expr-type-add! this nenv ctx tyv
(append lbk bkr)))))
(else
(decl-vtype-add! decl tyr ctx)
(let ((nenv (extend-env envr decl tyr)))
(expr-type-add! this nenv ctx tyr bkr)))))))
(else
(when (and (isa? lhs J2SAccess)
(class-private-element-access lhs))
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this envr ctx tyr bkr)))))))
(define-walk-method (node-type this::J2SPostfix env::pair-nil ctx::pair)
(define (numty ty)
postctx expressions only evaluate as numbers
(cond
((eq? ty 'unknown) 'unknown)
((type-number? ty) ty)
(else 'number)))
(with-access::J2SPostfix this (lhs rhs op type loc)
(multiple-value-bind (tyr envr bkr)
(node-type rhs env ctx)
(multiple-value-bind (tyv __ lbk)
(node-type lhs env ctx)
(expr-type-add! rhs envr ctx (numty tyr) bkr)
(cond
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable)
(cond
((not writable)
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(let ((nenv (extend-env env decl (numty tyv))))
(expr-type-add! this nenv ctx (numty tyv)
(append lbk bkr)))))
(else
(let* ((ntyr (numty tyr))
(nty (if (eq? ntyr 'unknown) (numty tyv) ntyr)))
(decl-vtype-add! decl nty ctx)
(let ((nenv (extend-env envr decl nty)))
(expr-type-add! this nenv ctx nty
(append lbk bkr)))))))))
(else
(when (and (isa? lhs J2SAccess)
(class-private-element-access lhs))
(class-element-access-type-add! lhs ctx tyr))
(expr-type-add! this envr ctx (numty tyr) bkr)))))))
(define-walk-method (node-type this::J2SPrefix env::pair-nil ctx::pair)
(define (numty ty)
(cond
((eq? ty 'unknown) 'unknown)
((type-number? ty) ty)
(else 'number)))
(with-access::J2SPrefix this (lhs rhs op)
(multiple-value-bind (tyr envr bkr)
(node-type rhs env ctx)
(expr-type-add! rhs envr ctx (numty tyr) bkr)
(multiple-value-bind (tyv __ lbk)
(node-type lhs env ctx)
(cond
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl)
(with-access::J2SDecl decl (writable)
(cond
((not writable)
(multiple-value-bind (tyv envl lbk)
(node-type lhs env ctx)
(let ((nenv (extend-env env decl (numty tyv))))
(expr-type-add! this nenv ctx (numty tyv)
(append lbk bkr)))))
(else
(decl-vtype-add! decl (numty tyr) ctx)
(let ((nenv (extend-env envr decl (numty tyr))))
(expr-type-add! this nenv ctx (numty tyr)
(append lbk bkr))))))))
(else
(expr-type-add! this envr ctx (numty tyr) bkr)))))))
* node - type : : ... * /
(define-walk-method (node-type this::J2SDProducer env::pair-nil ctx::pair)
(with-access::J2SDProducer this (expr type)
(multiple-value-bind (ty env bk)
(node-type expr env ctx)
(return type env bk))))
(define-walk-method (node-type this::J2SDConsumer env::pair-nil ctx::pair)
(with-access::J2SDConsumer this (expr)
(multiple-value-bind (ty env bk)
(node-type expr env ctx)
(expr-type-add! this env ctx ty bk))))
(define (node-type-fun this::J2SFun env::pair-nil ctx::pair)
(with-access::J2SFun this (body thisp params %info vararg argumentsp type loc mode rtype rutype mode)
(let ((envp (map (lambda (p::J2SDecl)
(with-access::J2SDecl p (itype utype vtype id)
(cond
((and (not (eq? utype 'unknown)) (eq? mode 'hopscript))
(set! itype utype)
(decl-vtype-set! p utype ctx)
(cons p utype))
((decl-usage-has? p '(rest))
(decl-vtype-add! p 'array ctx)
(cons p 'array))
(vararg
(decl-vtype-add! p 'any ctx)
(cons p 'any))
(else
(cons p itype)))))
params)))
(for-each (lambda (decl)
(with-access::J2SDecl decl (itype)
(decl-vtype-add! decl itype ctx)))
params)
(unless (or (memq rutype '(unknown any))
(not (eq? (car ctx) 'hopscript))
(eq? rtype rutype))
(set! rtype rutype))
(let ((fenv (append envp env)))
(when thisp
(with-access::J2SDecl thisp (vtype ctype itype loc)
(unless (or (eq? vtype 'object) (isa? vtype J2SClass))
(decl-vtype-add! thisp itype ctx))
(set! fenv
(extend-env fenv thisp
(if (eq? ctype 'any) itype ctype)))))
(when argumentsp
(decl-itype-add! argumentsp 'arguments ctx)
(decl-vtype-add! argumentsp 'arguments ctx)
(set! fenv (extend-env fenv argumentsp 'arguments)))
(multiple-value-bind (_ envf _)
(node-type body fenv (cons mode (cdr ctx)))
(set! %info envf)))
(expr-type-add! this env ctx (funtype this)))))
(define (node-type-fun-decl this::J2SFun env::pair-nil ctx)
(with-access::J2SFun this (body decl)
(when (isa? decl J2SDecl)
(let ((ty (funtype this)))
(decl-vtype-set! decl ty ctx)))
(filter-map (lambda (c)
(let ((d (car c))
(t (cdr c)))
(with-access::J2SDecl d (vtype)
(if (decl-ronly? d)
c
(cons d vtype)))))
env)))
(define (escape-fun val::J2SFun ctx met::bool)
(define (escape-type rtype)
(case rtype
((unknown undefined any obj object null) rtype)
(else 'any)))
(with-access::J2SFun val (params rtype rutype thisp name mode)
(when (and (not met) thisp)
(decl-vtype-add! thisp 'any ctx))
(when (or (eq? rutype 'unknown) (not (eq? mode 'hopscript)))
(set! rtype (tyflow-type (escape-type rtype))))
(for-each (lambda (p::J2SDecl)
(with-access::J2SDecl p (itype utype)
(when (or (eq? utype 'unknown)
(not (eq? mode 'hopscript)))
(decl-itype-add! p 'any ctx))))
params)))
(define (escape-method fun::J2SMethod ctx)
(with-access::J2SMethod fun (method function)
(escape-fun function ctx #f)
(escape-fun method ctx #t)))
(define (node-type-fun-or-method this::J2SFun env::pair-nil ctx::pair met::bool)
(escape-fun this ctx met)
(node-type-fun this (node-type-fun-decl this (env-nocapture env) ctx) ctx))
(define-walk-method (node-type this::J2SFun env::pair-nil ctx::pair)
(node-type-fun-or-method this env ctx #f))
(define-walk-method (node-type this::J2SMethod env::pair-nil ctx::pair)
(with-access::J2SMethod this (method function)
(node-type-fun-or-method function env ctx #f)
(node-type-fun-or-method method env ctx #t)
(expr-type-add! this env ctx 'function)))
(define-walk-method (node-type this::J2SCall env::pair-nil ctx::pair)
(with-access::J2SCall this (fun thisargs args protocol type loc)
(multiple-value-bind (tty env bkt)
(if (pair? thisargs)
(node-type (car thisargs) env ctx)
(values 'unknown env '()))
(multiple-value-bind (rty env bkc)
(node-type-call fun protocol tty args env ctx)
(expr-type-add! this env ctx rty (append bkt bkc))))))
(define (node-type-call callee protocol tty args env ctx)
(define (unknown-call-env env)
(filter (lambda (e)
(with-access::J2SDecl (car e) (writable scope escape id)
(or (decl-ronly? (car e))
(not writable)
(and (memq scope '(local letblock inner))
(not escape)))))
env))
(define (global-call-env env)
(filter (lambda (e)
(with-access::J2SDecl (car e) (writable scope escape id)
(or (decl-ronly? (car e))
(not writable)
(or (memq scope '(local letblock inner))))))
env))
(define (local-call-env env)
(unknown-call-env env))
(define (type-known-call-args fun::J2SFun args env bk)
(with-access::J2SFun fun (rtype params vararg mode thisp mode)
(when thisp
(decl-itype-add! thisp
(cond
((not (eq? tty 'unknown)) tty)
((eq? mode 'strict) 'object)
(else 'undefined))
ctx))
(let loop ((params params)
(args args))
(when (pair? params)
(with-access::J2SDecl (car params) (id utype)
(cond
(vararg
(decl-itype-add! (car params) 'any ctx))
((and (null? (cdr params)) (decl-usage-has? (car params) '(rest)))
(decl-itype-add! (car params) 'array ctx))
((null? args)
(unless (or (eq? utype 'unknown) (not (eq? mode 'hopscript)))
(unless (utype-compatible? utype 'undefined)
(utype-error (car params) utype 'undefined)))
(decl-itype-add! (car params) 'undefined ctx)
(loop (cdr params) '()))
((and (not (eq? utype 'unknown))
(eq? mode 'hopscript))
(let ((ty (j2s-type (car args))))
(cond
((utype-compatible? utype ty)
(decl-itype-add! (car params) ty ctx)
(loop (cdr params) (cdr args)))
((memq ty '(unknown any object))
(with-access::J2SExpr (car args) (loc)
(set-car! args (J2SCheck utype (car args)))
(decl-itype-add! (car params) utype ctx)
(loop (cdr params) (cdr args))))
(else
(utype-error (car args) utype ty)))))
(else
(decl-itype-add! (car params) (j2s-type (car args)) ctx)
(loop (cdr params) (cdr args)))))))))
(define (type-inline-call fun::J2SFun args env bk)
(type-known-call-args fun args env bk)
(multiple-value-bind (_ envf _)
(node-type-fun callee env ctx)
(with-access::J2SFun fun (rtype mode %info)
(let* ((oenv (if (env? %info) (env-override env %info) env))
(nenv (local-call-env oenv)))
(return rtype nenv bk)))))
(define (type-known-call ref::J2SRef fun::J2SFun args env bk)
(with-access::J2SRef ref (decl)
(expr-type-add! ref env ctx (funtype fun))
(type-known-call-args fun args env bk)
(with-access::J2SDecl decl (scope id)
(with-access::J2SFun fun (rtype %info)
(let* ((oenv (if (env? %info) (env-override env %info) env))
(nenv (if (memq scope '(global %scope tls))
(global-call-env oenv)
(local-call-env oenv))))
(return rtype nenv bk))))))
(define (type-ref-call callee args env bk)
call a JS variable , check is it a known function
(with-access::J2SRef callee (decl)
(cond
((isa? decl J2SDeclFun)
(with-access::J2SDeclFun decl (val)
(if (decl-ronly? decl)
(if (isa? val J2SMethod)
(with-access::J2SMethod val (function method)
(if (eq? tty 'object)
(type-known-call callee method args env bk)
(type-known-call callee function args env bk)))
(type-known-call callee val args env bk))
(type-unknown-call callee env bk))))
((isa? decl J2SDeclInit)
(with-access::J2SDeclInit decl (val)
(cond
((is-builtin-ref? callee 'Array)
(return 'array env bk))
((is-builtin-ref? callee 'BigInt)
(return 'bigint env bk))
((and (decl-ronly? decl) (isa? val J2SFun))
(type-known-call callee val args env bk))
((and (decl-ronly? decl) (isa? val J2SMethod))
(with-access::J2SMethod val (function method)
(if (eq? tty 'object)
(type-known-call callee method args env bk)
(type-known-call callee function args env bk))))
(else
(type-unknown-call callee env bk)))))
(else
(type-unknown-call callee env bk)))))
(define (is-global? obj ident)
(cond
((isa? obj J2SGlobalRef)
(with-access::J2SGlobalRef obj (id decl)
(when (eq? id ident)
(decl-ronly? decl))))
((isa? obj J2SRef)
(with-access::J2SRef obj (decl)
(when (isa? decl J2SDeclExtern)
(with-access::J2SDeclExtern decl (id)
(when (eq? id ident)
(decl-ronly? decl))))))))
(define (type-method-call callee args env bk)
(multiple-value-bind (_ env bk)
(node-type callee env ctx)
(with-access::J2SAccess callee (obj field)
(let* ((fn (j2s-field-name field))
(ty (if (string? fn)
(car (find-builtin-method-type obj fn))
'any)))
(cond
((eq? ty 'any)
(return ty (unknown-call-env env) bk))
((eq? ty 'anumber)
(if (pair? args)
(let ((aty (j2s-type (car args))))
(if (memq aty '(integer real))
(return aty env bk)
(return 'number env bk)))
(return 'number env bk)))
(else
(return (tyflow-type ty) env bk)))))))
(define (type-hop-call callee args env bk)
(with-access::J2SHopRef callee (rtype loc)
(return rtype env bk)))
(define (type-global-call callee args env bk)
(node-type callee env ctx)
(cond
((is-global? callee 'Array)
(return 'array (unknown-call-env env) bk))
((is-global? callee 'String)
(return 'string (unknown-call-env env) bk))
((is-global? callee 'parseInt)
(return 'number (unknown-call-env env) bk))
((is-global? callee 'isNaN)
(return 'bool (unknown-call-env env) bk))
((is-global? callee 'unescape)
(return 'string (unknown-call-env env) bk))
((is-global? callee 'encodeURI)
(return 'string (unknown-call-env env) bk))
((is-global? callee 'encodeURIComponent)
(return 'string (unknown-call-env env) bk))
(else
(type-unknown-call callee env bk))))
(define (type-unknown-call callee env bk)
(multiple-value-bind (_ env bk)
(node-type callee env ctx)
(return 'any (unknown-call-env env) bk)))
(multiple-value-bind (env bk)
(node-type-args args env ctx)
(cond
((eq? protocol 'spread) (type-unknown-call callee env bk))
((isa? callee J2SFun) (type-inline-call callee args env bk))
((isa? callee J2SRef) (type-ref-call callee args env bk))
((isa? callee J2SHopRef) (type-hop-call callee args env bk))
((isa? callee J2SAccess) (type-method-call callee args env bk))
((isa? callee J2SGlobalRef) (type-global-call callee args env bk))
(else (type-unknown-call callee env bk)))))
(define-walk-method (node-type this::J2SCond env::pair-nil ctx::pair)
(with-access::J2SCond this (test then else)
(multiple-value-bind (tyi env bki)
(node-type test env ctx)
(multiple-value-bind (tyt envt bkt)
(node-type then env ctx)
(multiple-value-bind (tye enve bke)
(node-type else env ctx)
(let ((envc (env-merge envt enve))
(typc (merge-types tyt tye))
(bk (append bki bkt bke)))
(expr-type-add! this envc ctx typc bk)))))))
(define-walk-method (node-type this::J2SNew env::pair-nil ctx::pair)
(define (class-type clazz)
(cond
((isa? clazz J2SUnresolvedRef)
(with-access::J2SUnresolvedRef clazz (id)
(case id
((Array) 'array)
((Vector) 'jsvector)
((Date) 'date)
((RegExp) 'regexp)
((Int8Array) 'int8array)
((Uint8Array) 'uint8array)
((Map) 'map)
((WeakMap) 'weakmap)
((Set) 'set)
((WeakSet) 'weakset)
(else 'object))))
((isa? clazz J2SRef)
(with-access::J2SRef clazz (decl)
(cond
((isa? decl J2SDeclExtern)
(with-access::J2SDeclExtern decl (id)
(when (decl-ronly? decl)
(case id
((Array) 'array)
((Vector) 'jsvector)
((Int8Array) 'int8array)
((Uint8Array) 'uint8array)
((Date) 'date)
((RegExp) 'regexp)
((Map) 'map)
((WeakMap) 'weakmap)
((Set) 'set)
((WeakSet) 'weakset)
(else 'object)))))
((isa? decl J2SDeclClass)
(with-access::J2SDeclClass decl (val)
(if (isa? val J2SClass)
val
'object)))
(else
'object))))
(else
'object)))
(with-trace 'j2s-tyflow "node-type ::J2SNew"
(with-access::J2SNew this (clazz args loc protocol)
(multiple-value-bind (_ env bk)
(node-type clazz env ctx)
(multiple-value-bind (_ env bk)
(node-type-call clazz protocol 'object args env ctx)
(expr-type-add! this env ctx (class-type clazz) bk))))))
(define-walk-method (node-type this::J2SUnary env::pair-nil ctx::pair)
(define (non-zero-integer? ty expr)
(when (type-integer? ty)
(or (not (isa? expr J2SNumber))
(with-access::J2SNumber expr (val)
(not (= val 0))))))
(with-access::J2SUnary this (op expr)
(multiple-value-bind (ty env bk)
(node-type expr env ctx)
(let* ((tnum (if (eq? ty 'real) 'real 'number))
(tye (case op
((+) (if (non-zero-integer? ty expr) 'integer tnum))
((-) (if (non-zero-integer? ty expr) 'integer tnum))
((~) 'integer)
((!) 'bool)
((typeof) 'string)
(else 'any))))
(expr-type-add! this env ctx tye bk)))))
(define (node-type-binary op lhs::J2SExpr rhs::J2SExpr env::pair-nil ctx::pair)
(multiple-value-bind (typl envl bkl)
(node-type lhs env ctx)
(multiple-value-bind (typr envr bkr)
(node-type rhs envl ctx)
(let ((typ (case op
((+)
(cond
((and (eq? typl 'real) (eq? typr 'real))
'real)
((and (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((and (type-integer? typl) (type-integer? typr))
'integer)
((or (and (type-integer? typl) (eq? typr 'bool))
(and (eq? typl 'bool) (type-integer? typr)))
'integer)
((and (typnum? typl) (typnum? typr))
'number)
((or (eq? typl 'string) (eq? typr 'string))
'string)
((or (eq? typl 'any) (eq? typr 'any))
'any)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
(else
'unknown)))
((++)
(cond
((and (eq? typl 'real) (eq? typr 'real))
'real)
((and (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((and (type-integer? typl) (type-integer? typr))
'integer)
((and (typnum? typl) (typnum? typr))
'number)
((or (eq? typl 'string) (eq? typr 'string))
'number)
((or (eq? typl 'any) (eq? typr 'any))
'number)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
(else
'unknown)))
((- -- * **)
(cond
((or (eq? typl 'real) (eq? typr 'real))
'real)
((or (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((and (type-integer? typl) (type-integer? typr))
'integer)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
(else
'number)))
((/)
(cond
((or (eq? typl 'real) (eq? typr 'real))
'real)
((or (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((eq? typr 'integer)
'number)
((eq? typr 'unknown)
'unknown)
(else
'real)))
((%)
(cond
((or (eq? typl 'real) (eq? typr 'real))
'real)
((or (eq? typl 'bigint) (eq? typr 'bigint))
'bigint)
((or (eq? typl 'unknown) (eq? typr 'unknown))
'unknown)
((or (eq? typl 'any) (eq? typr 'any))
'number)
(else
'number)))
((== === != !== < <= > >= eq?)
'bool)
((in)
(when (isa? rhs J2SRef)
(with-access::J2SRef rhs (decl)
(set! env (extend-env env decl 'object))))
'bool)
((instanceof)
(when (isa? rhs J2SRef)
(with-access::J2SRef rhs (decl)
(set! env (extend-env env decl 'function))))
'bool)
((&& OR OR*)
(cond
((or (eq? typr 'any) (eq? typl 'any))
'any)
((or (eq? typr 'unknown) (eq? typl 'unknown))
'unknown)
(else
(merge-types typr typl))))
((<< >> >>> ^ & BIT_OR)
'integer)
(else
'any))))
(return typ (if (memq op '(OR OR*)) (env-merge envl envr) envr)
(append bkl bkr))))))
(define-walk-method (node-type this::J2SBinary env::pair-nil ctx::pair)
(with-access::J2SBinary this (op lhs rhs)
(multiple-value-bind (typ env bk)
(node-type-binary op lhs rhs env ctx)
(expr-type-add! this env ctx typ bk))))
(define-walk-method (node-type this::J2SAccess env::pair-nil ctx::pair)
(define (is-number-ref? expr::J2SNode)
(when (isa? expr J2SUnresolvedRef)
(with-access::J2SUnresolvedRef expr (id)
(eq? id 'Number))))
(define (is-math-ref? expr::J2SNode)
(when (isa? expr J2SRef)
(with-access::J2SRef expr (decl)
(when (isa? decl J2SDeclExtern)
(with-access::J2SDecl decl (id)
(eq? id 'Math))))))
(with-access::J2SAccess this (obj field loc)
(multiple-value-bind (tyo envo bko)
(node-type obj env ctx)
(multiple-value-bind (tyf envf bkf)
(node-type field envo ctx)
(cond
((and (memq tyo '(array string jsvector)) (j2s-field-length? field))
(with-access::J2SString field (val)
(expr-type-add! this envf ctx 'integer (append bko bkf))))
((and (eq? tyo 'arguments)
(isa? obj J2SRef)
(j2s-field-length? field)
(with-access::J2SRef obj (decl)
MS 13may2021 : because of the new arguments
( isa ? )
(not (decl-usage-has? decl '(set ref))))))
(with-access::J2SString field (val)
(expr-type-add! this envf ctx 'integer (append bko bkf))))
((not (j2s-field-name field))
(expr-type-add! this envf ctx 'any (append bko bkf)))
((eq? tyo 'string)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (string-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((eq? tyo 'regexp)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (regexp-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((eq? tyo 'number)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (number-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((eq? tyo 'array)
(let* ((fn (j2s-field-name field))
(ty (if (eq? (car (array-method-type fn)) 'any)
'any 'function)))
(expr-type-add! this envf ctx ty (append bko bkf))))
((is-number-ref? obj)
(let ((name (j2s-field-name field)))
(if (member name
'("POSITIVE_INFINITY" "NEGATIVE_INFINITY"))
(expr-type-add! this envf ctx 'number
(append bko bkf))
(expr-type-add! this envf ctx 'any
(append bko bkf)))))
((is-math-ref? obj)
(let ((name (j2s-field-name field)))
(if (member name
'("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI"
"SQRT1_2" "SQRT2"))
(expr-type-add! this envf ctx 'real
(append bko bkf))
(expr-type-add! this envf ctx 'any
(append bko bkf)))))
((isa? tyo J2SRecord)
(if (isa? field J2SString)
(with-access::J2SString field (val)
(multiple-value-bind (index el)
(j2s-class-get-property tyo val)
(if (isa? el J2SClassElement)
(with-access::J2SClassElement el (type)
(expr-type-add! this envf ctx type (append bko bkf)))
(expr-type-add! this envf ctx 'unknown (append bko bkf)))))
(expr-type-add! this envf ctx 'any (append bko bkf))))
((class-private-element-access this)
=>
(lambda (el)
(with-access::J2SClassElement el (type)
(expr-type-add! this envf ctx type (append bko bkf)))))
((eq? tyo 'unknown)
(expr-type-add! this envf ctx 'unknown (append bko bkf)))
(else
(expr-type-add! this envf ctx 'any (append bko bkf))))))))
(define-walk-method (node-type this::J2SCacheCheck env::pair-nil ctx::pair)
(with-access::J2SCacheCheck this (loc obj)
(multiple-value-bind (typf envf bkf)
(node-type obj env ctx)
(expr-type-add! this envf ctx 'bool bkf))))
(define-walk-method (node-type this::J2SCacheUpdate env::pair-nil ctx::pair)
(multiple-value-bind (typf envf bkf)
(call-default-walker)
(expr-type-add! this envf ctx 'undefined bkf)))
(define-walk-method (node-type this::J2SCheck env::pair-nil ctx::pair)
(with-access::J2SCheck this (type)
(call-default-walker)
(return type env '())))
(define-walk-method (node-type this::J2SCast env::pair-nil ctx::pair)
(with-access::J2SCast this (type)
(call-default-walker)
(return type env '())))
(define-walk-method (node-type this::J2SNop env::pair-nil ctx::pair)
(return 'void env '()))
* node - type : : ... * /
(define-walk-method (node-type this::J2SStmtExpr env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SStmtExpr"
(with-access::J2SStmtExpr this (expr loc)
(trace-item "loc=" loc)
(multiple-value-bind (typ env bk)
(node-type expr env ctx)
(return typ env bk)))))
(define-walk-method (node-type this::J2SSeq env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SSeq"
(with-access::J2SSeq this (nodes loc)
(trace-item "loc=" loc)
(node-type-seq nodes env ctx 'void))))
(define-walk-method (node-type this::J2SLabel env::pair-nil ctx::pair)
(call-default-walker))
* node - type : : ... * /
(define-walk-method (node-type this::J2SLetBlock env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SLetBlock ~a" (cdr ctx))
(with-access::J2SLetBlock this (decls nodes loc)
(trace-item "loc=" loc)
(let ((ienv (filter-map (lambda (d::J2SDecl)
(with-access::J2SDecl d (vtype)
(unless (eq? vtype 'unknown)
(cons d vtype))))
decls)))
(multiple-value-bind (_ denv bk)
(node-type-seq decls (append ienv env) ctx 'void)
(multiple-value-bind (typ benv bks)
(node-type-seq nodes denv ctx 'void)
(let ((nenv (filter (lambda (d)
(not (memq (car d) decls)))
benv)))
(return typ nenv (append bk bks)))))))))
(define-walk-method (node-type this::J2SWith env::pair-nil ctx::pair)
(with-access::J2SWith this (obj block)
(multiple-value-bind (tye enve bke)
(node-type obj env ctx)
(multiple-value-bind (tyb envb bkb)
(node-type block enve ctx)
(return 'void envb (append bke bkb))))))
(define-walk-method (node-type this::J2SReturn env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SReturn"
(with-access::J2SReturn this (expr from loc)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(cond
((isa? from J2SFun)
(with-access::J2SFun from (rtype rutype)
(when (and (not (eq? rutype 'unknown))
(eq? (car ctx) 'hopscript)
(not (utype-compatible? rutype tye)))
(if (memq tye '(unknown any object))
(begin
(set! tye rutype)
(set! expr (J2SCheck rutype expr)))
(utype-error expr rutype tye)))
(let ((tyr (merge-types rtype tye)))
(unless (eq? tyr rtype)
(unfix! ctx
(format "J2SReturn(~a) e=~a ~a/~a" loc
(type->sexp tye) (type->sexp tyr) (type->sexp rtype)))
(set! rtype tyr)))
(values 'void enve (list this))))
((isa? from J2SBindExit)
(with-access::J2SBindExit from (type loc utype)
(when (and (not (eq? utype 'unknown))
(eq? (car ctx) 'hopscript)
(not (utype-compatible? utype tye)))
(if (memq tye '(unknown any object))
(begin
(set! tye utype)
(set! expr (J2SCheck utype expr)))
(utype-error expr utype tye)))
(let ((tyr (merge-types type tye)))
(unless (eq? tyr type)
(unfix! ctx
(format "J2SReturn(~a) e=~a ~a/~a" loc
(type->sexp tye) (type->sexp tyr) (type->sexp type)))
(set! type tyr))))
(values 'void enve (list this)))
((isa? from J2SExpr)
(expr-type-add! from env ctx tye)
(values 'void enve (list this)))
(else
(values 'void enve (list this))))))))
* node - type : : ... * /
(define-walk-method (node-type this::J2SReturnYield env::pair-nil ctx::pair)
(with-access::J2SReturnYield this (expr kont)
(node-type kont env ctx)
(multiple-value-bind (tye enve bke)
(node-type expr env ctx)
(values 'void enve (list this)))))
(define-walk-method (node-type this::J2SKont env::pair-nil ctx::pair)
(with-access::J2SKont this (body exn param)
(with-access::J2SDecl param (%info itype)
(unless (eq? itype 'unknown)
(decl-vtype-add! param itype ctx)))
(with-access::J2SDecl exn (%info itype)
(unless (eq? itype 'unknown)
(decl-vtype-add! exn itype ctx)))
(node-type body env ctx)
(expr-type-add! this env ctx 'procedure)))
(define-walk-method (node-type this::J2SIf env::pair-nil ctx::pair)
(define (isa-and? test)
(when (isa? test J2SBinary)
(with-access::J2SBinary test (op lhs rhs)
(when (eq? op '&&)
(node-type-one-positive-test? lhs)))))
(define (node-type-one-positive-test? test)
(cond
((isa? test J2SBinary)
(with-access::J2SBinary test (op)
(memq op '(== === eq? instanceof))))
((isa? test J2SCall)
#t)
(else
#f)))
(define (node-type-one-test test envt enve)
(multiple-value-bind (op decl typ ref)
(j2s-expr-type-test test)
(if (or (and (symbol? typ) (j2s-known-type typ)) (isa? typ J2SClass))
(case op
((== === eq?) (values (extend-env envt decl typ) enve))
((!= !==) (values envt (extend-env enve decl typ)))
((instanceof) (values (extend-env envt decl typ) enve))
((!instanceof) (values envt (extend-env enve decl typ)))
((<=) (values (refine-env envt decl typ) enve))
(else (values envt enve)))
(values envt enve))))
(define (node-type-test test envt enve)
(if (isa-and? test)
(with-access::J2SBinary test (lhs rhs)
(multiple-value-bind (nenvt nenve)
(node-type-test lhs envt enve)
(node-type-test rhs nenvt nenve)))
(node-type-one-test test envt enve)))
(with-trace 'j2s-tyflow (format "node-type ::J2SIf ~a" (cdr ctx))
(with-access::J2SIf this (test then else loc)
(trace-item "loc=" loc)
(multiple-value-bind (tyi env bki)
(node-type test env ctx)
(multiple-value-bind (envt enve)
(node-type-test test env env)
(multiple-value-bind (tyt envt bkt)
(node-type then envt ctx)
(multiple-value-bind (tye enve bke)
(node-type else enve ctx)
(let ((bk (append bki bke bkt)))
(return (merge-types tyt tye)
(env-merge envt enve) bk)))))))))
(define-walk-method (node-type this::J2SSwitch env::pair-nil ctx::pair)
(with-access::J2SSwitch this (key cases)
(multiple-value-bind (typk envk bk)
(node-type key env ctx)
(let ((bks '())
(typ #f))
(let loop ((cases cases)
(env envk))
(when (pair? cases)
(multiple-value-bind (t e b)
(node-type (car cases) env ctx)
(set! bks (append b bks))
(set! typ (if (not typ) t (merge-types typ t)))
(with-access::J2SCase (car cases) (cascade)
(if cascade
(loop (cdr cases) e)
(loop (cdr cases) envk))))))
(return typ '() bks)))))
(define-walk-method (node-type this::J2SCase env::pair-nil ctx::pair)
(with-access::J2SCase this (expr body cascade)
(multiple-value-bind (typx envx bk)
(node-type expr env ctx)
(multiple-value-bind (typb envb bkb)
(node-type body envx ctx)
(return typb envb (append bkb bk))))))
(define-walk-method (node-type this::J2SBreak env::pair-nil ctx::pair)
(return 'void env (list this)))
(define-walk-method (node-type this::J2SWhile env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SWhile"
(with-access::J2SWhile this (test body loc)
(trace-item "loc=" loc)
(let loop ((env env)
(i 0))
(let ((octx (cdr ctx)))
(trace-item "while seq loc=" loc)
(multiple-value-bind (typ envb bk)
(node-type-seq (list test body) env ctx 'void)
(let ((nenv (env-merge env envb)))
(if (=fx octx (cdr ctx))
(return typ nenv (filter-breaks bk this))
(loop nenv (+fx i 1))))))))))
(define-walk-method (node-type this::J2SDo env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SDo"
(with-access::J2SDo this (test body loc)
(trace-item "loc=" loc)
(let loop ((env env))
(let ((octx (cdr ctx)))
(trace-item "while seq loc=" loc)
(multiple-value-bind (typ envb bk)
(node-type-seq (list body test) env ctx 'void)
(let ((nenv (env-merge env envb)))
(if (=fx octx (cdr ctx))
(return typ nenv (filter-breaks bk this))
(loop nenv)))))))))
* node - type : : ... * /
(define-walk-method (node-type this::J2SFor env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow (format "node-type ::J2SFor ~a" (cdr ctx))
(with-access::J2SFor this (init test incr body loc)
(trace-item "loc=" loc)
(let loop ((env env))
(let ((octx (cdr ctx)))
(trace-item "for seq loc=" loc)
(trace-item "for seq octx=" octx)
(multiple-value-bind (typ envb bk)
(node-type-seq (list init test body incr) env ctx 'void)
(let ((nenv (env-merge env envb)))
(trace-item "for seq nctx=" (cdr ctx) " octx=" octx)
(if (=fx octx (cdr ctx))
(return typ nenv (filter-breaks bk this))
(loop nenv)))))))))
(define-walk-method (node-type this::J2SForIn env::pair-nil ctx::pair)
(with-trace 'j2s-tyflow "node-type ::J2SForIn"
(with-access::J2SForIn this (lhs obj body op loc)
(trace-item "loc=" loc)
(let ((decl (cond
((isa? lhs J2SRef)
(with-access::J2SRef lhs (decl) decl))
((isa? lhs J2SGlobalRef)
(with-access::J2SGlobalRef lhs (decl) decl))))
(ty (if (eq? op 'in) 'string 'any)))
(when decl (decl-vtype-add! decl ty ctx))
(expr-type-add! lhs env ctx ty '())
(let loop ((env (if decl (extend-env env decl ty) env)))
(let ((octx (cdr ctx)))
(trace-item "for seq loc=" loc)
(multiple-value-bind (typ envb bk)
(node-type-seq (list obj body) env ctx 'void)
(cond
((not (=fx octx (cdr ctx)))
(loop (env-merge env envb)))
((eq? op 'in)
(when decl (decl-vtype-add! decl 'undefined ctx))
(return typ (if decl (extend-env envb decl 'any) env)
(filter-breaks bk this)))
(else
(return typ envb
(filter-breaks bk this)))))))))))
(define-walk-method (node-type this::J2STry env::pair-nil ctx::pair)
(with-access::J2STry this (body catch finally)
(multiple-value-bind (_ envb bkb)
(node-type body env ctx)
(multiple-value-bind (_ envc bkh)
(node-type catch env ctx)
(multiple-value-bind (_ envf bkf)
(node-type finally (env-merge envb envc) ctx)
(return 'void envf (append bkb bkh bkf)))))))
(define-walk-method (node-type this::J2SCatch env::pair-nil ctx::pair)
(with-access::J2SCatch this (body param)
(decl-vtype-add! param 'any ctx)
(node-type body env ctx)))
* node - type : : J2SThrow ... * /
(define-walk-method (node-type this::J2SThrow env::pair-nil ctx::pair)
(with-access::J2SThrow this (expr)
(multiple-value-bind (_ env bk)
(node-type expr env ctx)
(return 'void env (cons this bk)))))
(define-walk-method (node-type this::J2SClass env::pair-nil ctx::pair)
(with-access::J2SClass this (expr decl super elements need-dead-zone-check)
(for-each (lambda (e)
(node-type e env ctx))
elements)
(when decl
(decl-vtype-add! decl (if need-dead-zone-check 'any 'function) ctx))
(multiple-value-bind (tys env bki)
(node-type super env ctx)
(expr-type-add! this env ctx
(if (isa? this J2SRecord) 'record 'class)))))
(define-walk-method (node-type this::J2SClassElement env::pair-nil ctx::pair)
(with-access::J2SClassElement this (prop type clazz static usage)
(cond
((j2s-class-property-constructor? prop)
(if (isa? clazz J2SRecord)
(with-access::J2SDataPropertyInit prop (val)
(with-access::J2SFun val (thisp params)
(for-each (lambda (p::J2SDecl)
(with-access::J2SDecl p (itype utype)
(decl-itype-add! p 'any ctx)))
params)
(with-access::J2SDecl thisp (itype vtype eloc mtype)
(set! mtype clazz)
(set! itype clazz)
(decl-vtype-set! thisp clazz ctx))
J2SRecord constructor does not escape
(node-type-fun val env ctx)))
(with-access::J2SDataPropertyInit prop (val)
(with-access::J2SFun val (thisp params)
(with-access::J2SDecl thisp (ctype itype vtype eloc mtype)
(unless (or (not (eq? ctype 'any)) (eq? itype 'object))
(set! mtype clazz)
(set! itype 'object)
(set! vtype 'any)
(unfix! ctx "constructor type")))
(node-type prop env ctx)))))
(else
(let ((vty (node-type prop env ctx)))
(when (eq? type 'unknown)
(cond
((usage-has? usage '(uninit))
(if (j2s-class-element-private? this)
(class-element-type-add! this ctx 'undefined)
(class-element-type-add! this ctx 'any)))
((not (eq? vty 'unknown))
(class-element-type-add! this ctx vty)))))))
(return 'void env '())))
* statically type checks using type informations * /
* computed by the NODE - TYPE method . * /
(define (j2s-resolve! this::J2SProgram args ctx)
(with-access::J2SProgram this (headers decls nodes)
(let ((ofix (cdr ctx)))
(set! headers (map! (lambda (o) (resolve! o ctx)) headers))
(set! decls (map! (lambda (o) (resolve! o ctx)) decls))
(set! nodes (map! (lambda (o) (resolve! o ctx)) nodes))
(>fx (cdr ctx) ofix))))
(define-walk-method (resolve! this::J2SNode ctx::pair)
(call-default-walker))
(define-walk-method (resolve! this::J2SBinary ctx)
(define (eq-typeof? type typ)
(or (eq? type typ)
(and (memq type '(date array)) (eq? typ 'object))
(and (eq? typ 'number) (memq type '(integer index real bigint)))
(and (eq? typ 'function) (memq type '(function arrow)))
(and (eq? type 'bool))))
(with-access::J2SBinary this (loc op)
(case op
((&&)
(with-access::J2SBinary this (lhs rhs loc)
(set! lhs (resolve! lhs ctx))
(set! rhs (resolve! rhs ctx))
(cond
((and (isa? lhs J2SBool) (isa? rhs J2SBool))
(with-access::J2SBool lhs ((lval val))
(with-access::J2SBool rhs ((rval val))
(J2SBool (and lval rval)))))
((isa? lhs J2SBool)
(with-access::J2SBool lhs (val)
(if val rhs (J2SBool #f))))
((isa? rhs J2SBool)
no reduction can be applied if is false , see
(with-access::J2SBool rhs (val)
(if val lhs this)))
(else
this))))
((OR)
(with-access::J2SBinary this (lhs rhs loc)
(set! lhs (resolve! lhs ctx))
(set! rhs (resolve! rhs ctx))
(cond
((and (isa? lhs J2SBool) (isa? rhs J2SBool))
(with-access::J2SBool lhs ((lval val))
(with-access::J2SBool rhs ((rval val))
(J2SBool (or lval rval)))))
((isa? lhs J2SBool)
(with-access::J2SBool lhs (val)
(if val (J2SBool #t) rhs)))
(else
this))))
(else
(multiple-value-bind (op decl typ ref)
(j2s-expr-type-test this)
(case op
((== === eq?)
(with-access::J2SExpr ref (type)
(cond
((eq-typeof? type typ)
(unfix! ctx "resolve.J2SBinary")
(J2SBool #t))
((memq type '(unknown any))
(call-default-walker))
((and (eq? type 'number) (memq typ '(integer index)))
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary")
(J2SBool #f)))))
((!= !==)
(with-access::J2SExpr ref (type)
(cond
((eq-typeof? type typ)
(unfix! ctx "resolve.J2SBinary")
(J2SBool #f))
((memq type '(unknown any))
(call-default-walker))
((and (eq? type 'number) (memq typ '(integer index)))
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary")
(J2SBool #t)))))
((instanceof)
(with-access::J2SExpr ref (type)
(cond
((or (memq type '(unknown any object)) (eq? typ 'object))
(call-default-walker))
((type-subtype? type typ)
(unfix! ctx "resolve.J2SBinary.instanceof")
(J2SBool #t))
((type-maybe-subtype? type typ)
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary.instanceof")
(J2SBool #f)))))
((!instanceof)
(with-access::J2SExpr ref (type)
(cond
((or (memq type '(unknown any object)) (eq? typ 'object))
(call-default-walker))
((type-subtype? type typ)
(unfix! ctx "resolve.J2SBinary.!instanceof")
(J2SBool #f))
((type-maybe-subtype? type typ)
(call-default-walker))
(else
(unfix! ctx "resolve.J2SBinary.!instanceof")
(J2SBool #t)))))
(else
(call-default-walker))))))))
* resolve ! : : ... * /
(define-walk-method (resolve! this::J2SCacheCheck ctx::pair)
(call-default-walker)
(with-access::J2SCacheCheck this (loc obj owner)
(let ((to (j2s-type obj)))
(cond
((and (isa? owner J2SRecord)
(not (memq to '(any unknown object)))
(or (and (isa? (j2s-vtype obj) J2SRecord)
(not (or (type-subtype? owner to)
(type-subtype? to owner))))
(not (isa? (j2s-vtype obj) J2SRecord))))
(unfix! ctx "resolve.J2SCacheCheck")
(J2SBool #f))
((and (isa? owner J2SClass) (eq? (j2s-mtype obj) owner))
(unfix! ctx "resolve.J2SCacheCheck")
(J2SBool #t))
(else
this)))))
(define-walk-method (resolve! this::J2SIf ctx::pair)
(define (is-true? expr)
(cond
((isa? expr J2SBool)
(with-access::J2SBool expr (val) val))
((isa? expr J2SBinary)
(with-access::J2SBinary expr (lhs rhs op)
(and (eq? op '==)
(memq (j2s-type lhs) '(null undefined))
(memq (j2s-type rhs) '(null undefined)))))))
(define (is-false? expr)
(cond
((isa? expr J2SBool)
(with-access::J2SBool expr (val) (not val)))
((isa? expr J2SBinary)
(with-access::J2SBinary expr (lhs rhs op)
(and (eq? op '!=)
(memq (j2s-type lhs) '(null undefined))
(memq (j2s-type rhs) '(null undefined)))))))
(let ((ts (if-check-cache-cascade-classes this)))
(let ((nthis (if (and (pair? ts) (pair? (cdr ts)))
(if-check-cache-cascade-resolve! this ts)
this)))
(if (isa? nthis J2SIf)
(with-access::J2SIf nthis (test then else)
(set! test (resolve! test ctx))
(with-access::J2SExpr test (type)
(cond
((memq type '(any unknown))
(set! then (resolve! then ctx))
(set! else (resolve! else ctx))
nthis)
((is-true? test)
(unfix! ctx "resolve.J2SIf")
(resolve! then ctx))
((is-false? test)
(unfix! ctx "resolve.J2SIf")
(resolve! else ctx))
(else
(set! then (resolve! then ctx))
(set! else (resolve! else ctx))
nthis))))
(begin
(unfix! ctx "resolve.J2SIfCascade")
nthis)))))
(define-walk-method (resolve! this::J2SCall ctx::pair)
(define (same-type typ tyr)
(cond
((eq? typ tyr) #t)
((and (eq? typ 'integer) (memq tyr '(number integer))) #unspecified)
((type-subtype? typ tyr) #t)
((not (type-maybe-subtype? typ tyr)) #f)
(else #unspecified)))
(with-access::J2SCall this (loc)
(multiple-value-bind (op decl typ ref)
(j2s-expr-type-test this)
(if (or (not op) (not ref) (memq (j2s-type ref) '(any unknown)))
(call-default-walker)
(case op
((==)
(let ((b (or (same-type typ (j2s-type ref))
(same-type (j2s-type ref) typ))))
(if (boolean? b)
(begin
(unfix! ctx "resolve.J2SCall")
(J2SBool b))
(call-default-walker))))
((!=)
(let ((b (or (same-type typ (j2s-type ref))
(same-type (j2s-type ref) typ))))
(if (boolean? b)
(begin
(unfix! ctx "resolve.J2SCall")
(J2SBool (not b)))
(call-default-walker))))
((<=)
(let ((rtyp (j2s-type ref)))
(cond
((type-subtype? rtyp typ)
(unfix! ctx "resolve.J2SCall")
(J2SBool #t))
((memq rtyp '(unknown any))
(call-default-walker))
(else
(unfix! ctx "resolve.J2SCall")
(J2SBool #f)))))
(else
(call-default-walker)))))))
(define (force-type::bool this::J2SNode from to final::bool)
(let ((cell (make-cell #f)))
(force-type! this from to cell final)
(cell-ref cell)))
(define-walk-method (force-type! this::J2SNode from to cell::cell final::bool)
(call-default-walker))
(define-walk-method (force-type! this::J2SExpr from to cell final)
(with-access::J2SExpr this (type loc)
(when (and (eq? type from) (not (eq? type to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! type to)))
(call-default-walker))
(define-walk-method (force-type! this::J2SFun from to cell final)
(with-access::J2SFun this (rtype thisp loc type params)
(when (isa? thisp J2SNode) (force-type! thisp from to cell final))
(when (and (eq? type from) (not (eq? type to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! type to))
(when (and (eq? rtype from) (not (eq? rtype to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! rtype to)))
(call-default-walker))
(define-walk-method (force-type! this::J2SRef from to cell final)
(with-access::J2SRef this (decl type loc)
(when (isa? decl J2SDeclArguments)
(force-type! decl from to cell final))
(when (eq? type from)
(set! type to)
(cell-set! cell #t))
(call-default-walker)))
(define-walk-method (force-type! this::J2SHopRef from to cell final)
(with-access::J2SHopRef this (type)
(when (eq? type from)
(set! type to)
(cell-set! cell #t)))
this)
(define-walk-method (force-type! this::J2SGlobalRef from to cell final)
(with-access::J2SGlobalRef this (type loc decl)
(with-access::J2SDecl decl (vtype)
(when (and (eq? vtype from) (not (eq? vtype to)))
(set! vtype to)
(cell-set! cell #t)))
(when (and (eq? type from) (not (eq? type to)))
(set! type to)
(cell-set! cell #t)))
this)
(define-walk-method (force-type! this::J2SDecl from to cell final)
(with-access::J2SDecl this (vtype loc id)
(when (and (eq? vtype from) (not (eq? vtype to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! vtype to)))
(call-default-walker))
* ast . It uses two situations : * /
(define-walk-method (force-type! this::J2SDeclInit from to cell final)
(define (type->init type val)
(with-access::J2SExpr val (loc)
(case type
((number integer) (J2SNumber/type 'number 0))
((string) (J2SString ""))
((bool) (J2SBool #f))
((null) (J2SNull))
((object) (J2SHopRef/type '%this 'object))
(else #f))))
(define (type-eq? t1 t2)
(or (eq? t1 t2)
(and (eq? t1 'number) (eq? t2 'integer))
(and (eq? t1 'integer) (eq? t2 'number))))
(with-access::J2SDeclInit this (vtype loc val)
(when (and (eq? vtype from) (not (eq? vtype to)))
(when (and (eq? from 'unknown) debug-tyflow)
(tprint "*** COMPILER WARNING : unpexected `unknown' type " loc
" " (j2s->sexp this)))
(cell-set! cell #t)
(set! vtype to))
(when (and final
(not (eq? vtype 'any))
(not (type-eq? vtype (j2s-type val))))
(cond
((decl-usage-has? this '(uninit))
(error "force-type!"
(format "Declaration inconsistent with init (~a/~a)"
(type->sexp vtype) (type->sexp (j2s-type val)))
(j2s->sexp this)))
((type->init vtype val)
=>
(lambda (v)
(set! val v)))
(else
(set! vtype 'any))))
(call-default-walker)))
(define-walk-method (force-type! this::J2SCatch from to cell final)
(with-access::J2SCatch this (param)
(force-type! param from to cell final)
(call-default-walker)))
(define-walk-method (force-type! this::J2SClass from to cell final)
(with-access::J2SClass this (elements type)
(when (eq? type from) (set! type to))
(for-each (lambda (el)
(with-access::J2SClassElement el (type)
(when (eq? type from) (set! type to))))
elements))
(call-default-walker))
(define-walk-method (force-type! this::J2SPostfix from to cell final)
(with-access::J2SPostfix this (type)
(when (eq? type 'unknown)
(set! type 'number)
(cell-set! cell #t)))
(call-default-walker))
(define-walk-method (force-type! this::J2SPrefix from to cell final)
(with-access::J2SPrefix this (type)
(when (eq? type 'unknown)
(set! type 'number)
(cell-set! cell #t)))
(call-default-walker))
(define-walk-method (force-record-method-type this::J2SNode)
(call-default-walker))
(define-walk-method (force-record-method-type this::J2SClassElement)
(define (force-type-record-method val::J2SFun clazz)
(with-access::J2SFun val (thisp body loc)
(let ((self (duplicate::J2SDeclInit thisp
(key (ast-decl-key))
(id '!this)
(_scmid '!this)
(vtype clazz)
(itype clazz)
(val (J2SCast clazz (J2SRef thisp)))
(binder 'let-opt)
(hint '())))
(endloc (node-endloc body)))
(set! body
(J2SLetRecBlock #f (list self)
(j2s-alpha body (list thisp) (list self)))))))
(with-access::J2SClassElement this (prop type clazz static usage)
(cond
((j2s-class-property-constructor? prop)
(force-record-method-type prop))
(else
(when (and (not static)
(isa? prop J2SMethodPropertyInit)
(isa? clazz J2SRecord))
(with-access::J2SMethodPropertyInit prop (val)
(with-access::J2SFun val (thisp)
(with-access::J2SDecl thisp (vtype)
(when (eq? vtype 'unknown)
(force-type-record-method val clazz))))))
(force-record-method-type prop)))))
(define-walk-method (force-record-method-type this::J2SFun)
#unspecified)
(define-walk-method (reset-type! this::J2SNode)
(call-default-walker))
(define-walk-method (reset-type! this::J2SRef)
(with-access::J2SRef this (type)
(when (eq? type 'any)
(set! type 'unknown)))
this)
(define-walk-method (reset-type! this::J2SDecl)
(call-default-walker)
(with-access::J2SDecl this (vtype)
(when (eq? vtype 'any)
(set! vtype 'unknown)))
this)
(define-walk-method (reset-type! this::J2SDeclFun)
(call-default-walker))
(define-walk-method (reset-type! this::J2SNumber)
this)
(define-walk-method (reset-type! this::J2SExpr)
(with-access::J2SExpr this (type)
(when (eq? type 'any)
(set! type 'unknown)))
(call-default-walker))
* reset - type ! : : ... * /
(define-walk-method (reset-type! this::J2SBindExit)
(with-access::J2SBindExit this (type)
(when (eq? type 'any)
(set! type 'unknown)))
(call-default-walker))
(define-walk-method (reset-type! this::J2SHopRef)
this)
(define-walk-method (force-unary-type! this::J2SNode)
(call-default-walker))
(define-walk-method (force-unary-type! this::J2SUnary)
(define (non-zero-integer? expr)
(when (isa? expr J2SNumber)
(with-access::J2SNumber expr (val)
(not (= val 0)))))
(with-access::J2SUnary this (op expr type)
(when (eq? type 'integer)
(unless (non-zero-integer? expr)
(when (memq op '(+ -))
(set! type 'number)))))
this)
(define-walk-method (cleanup-hint! this::J2SNode)
(call-default-walker))
(define-walk-method (cleanup-hint! this::J2SDecl)
(with-access::J2SDecl this (hint vtype)
(unless (memq vtype '(number any))
(set! hint (filter (lambda (h) (=fx (cdr h) (minvalfx))) hint))))
(call-default-walker))
(define-walk-method (cleanup-hint! this::J2SExpr)
(with-access::J2SExpr this (hint type)
(unless (memq type '(number any))
(set! hint (filter (lambda (h) (=fx (cdr h) (minvalfx))) hint))))
(call-default-walker))
(define (utype-error this::J2SExpr utype tyv)
(with-access::J2SExpr this (loc)
(raise
(instantiate::&type-error
(proc "hopc")
(msg (format "Illegal type, \"~a\" expected"
(type-name utype '())))
(obj (type-name tyv '()))
(type (type-name utype '()))
(fname (cadr loc))
(location (caddr loc))))))
(define (if-check-cache-cascade-classes::pair-nil this::J2SIf)
(with-access::J2SIf this (test else)
(if (isa? test J2SCacheCheck)
(with-access::J2SCacheCheck test ((o0 obj) (t0 owner))
(if (and (isa? o0 J2SRef) (isa? t0 J2SClass) (isa? (j2s-vtype o0) J2SClass))
(with-access::J2SRef o0 ((d0 decl))
(let loop ((else else)
(ts (list t0)))
(if (isa? else J2SIf)
(with-access::J2SIf else (test else)
(if (isa? test J2SCacheCheck)
(with-access::J2SCacheCheck test ((o1 obj) (t1 owner))
(if (isa? o1 J2SRef)
(with-access::J2SRef o1 ((d1 decl))
(if (eq? d0 d1)
(loop else
(if (isa? t1 J2SClass) (cons t1 ts) ts))
ts))
ts))
ts))
ts)))
'()))
'())))
(define (if-check-cache-cascade-resolve! this::J2SIf ts::pair)
(define (resolve! this ts)
(if (isa? this J2SIf)
(with-access::J2SIf this (test then else)
(with-access::J2SCacheCheck test (owner)
(if (memq owner ts)
invalidate that
(resolve! else ts)
(begin
(set! else (resolve! else ts))
this))))
this))
(with-access::J2SIf this (test else)
(with-access::J2SCacheCheck test (obj)
(let* ((to (j2s-vtype obj))
(fts (filter (lambda (t) (type-subtype? to t)) ts)))
(if (or (null? fts) (null? (cdr fts)))
this
(let ((sts (sort type-subtype? fts)))
keep the first super types ,
(resolve! this (cdr sts))))))))
|
8ae2a3f8a277651e72c0dc5f755b9157d6d899878b60ede6af5445fc1acfb984 | rabbitmq/rabbitmq-amqp1.0-client | amqp10_client_frame_reader.erl | 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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(amqp10_client_frame_reader).
-behaviour(gen_statem).
-include("amqp10_client.hrl").
-include_lib("amqp10_common/include/amqp10_framing.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% API
-export([start_link/2,
set_connection/2,
close/1,
register_session/3,
unregister_session/4]).
%% gen_statem callbacks
-export([init/1,
callback_mode/0,
handle_event/4,
code_change/4,
terminate/3]).
-define(RABBIT_TCP_OPTS, [binary,
{packet, 0},
{active, false},
{nodelay, true}]).
-type frame_type() :: amqp | sasl.
-record(frame_state,
{data_offset :: 2..255,
type :: frame_type(),
channel :: non_neg_integer(),
frame_length :: pos_integer()}).
-record(state,
{connection_sup :: pid(),
socket :: amqp10_client_connection:amqp10_socket() | undefined,
buffer = <<>> :: binary(),
frame_state :: #frame_state{} | undefined,
connection :: pid() | undefined,
heartbeat_timer_ref :: reference() | undefined,
connection_config = #{} :: amqp10_client_connection:connection_config(),
outgoing_channels = #{},
incoming_channels = #{}}).
%%%===================================================================
%%% API
%%%===================================================================
-spec start_link(pid(), amqp10_client_connection:connection_config()) ->
{ok, pid()} | ignore | {error, any()}.
start_link(Sup, Config) ->
gen_statem:start_link(?MODULE, [Sup, Config], []).
@private
%% @doc
%% Passes the connection process PID to the reader process.
%%
%% This function is called when a connection supervision tree is
%% started.
-spec set_connection(Reader :: pid(), ConnectionPid :: pid()) -> ok.
set_connection(Reader, Connection) ->
gen_statem:cast(Reader, {set_connection, Connection}).
close(Reader) ->
gen_statem:cast(Reader, close).
register_session(Reader, Session, OutgoingChannel) ->
gen_statem:cast(Reader, {register_session, Session, OutgoingChannel}).
unregister_session(Reader, Session, OutgoingChannel, IncomingChannel) ->
gen_statem:cast(Reader, {unregister_session, Session, OutgoingChannel, IncomingChannel}).
%%%===================================================================
%%% gen_statem callbacks
%%%===================================================================
callback_mode() ->
[handle_event_function].
init([Sup, ConnConfig]) when is_map(ConnConfig) ->
Port = maps:get(port, ConnConfig, 5672),
%% combined the list of `addresses' with the value of the original `address' option if provided
Addresses0 = maps:get(addresses, ConnConfig, []),
Addresses = case maps:get(address, ConnConfig, undefined) of
undefined -> Addresses0;
Address -> Addresses0 ++ [Address]
end,
Result = lists:foldl(fun (Address, {error, _}) ->
gen_tcp:connect(Address, Port, ?RABBIT_TCP_OPTS);
(_Address, {ok, Socket}) ->
{ok, Socket}
end,
{error, undefined}, Addresses),
case Result of
{ok, Socket0} ->
Socket = case ConnConfig of
#{tls_opts := {secure_port, Opts}} ->
{ok, SslSock} = ssl:connect(Socket0, Opts),
{ssl, SslSock};
_ -> {tcp, Socket0}
end,
State = #state{connection_sup = Sup, socket = Socket,
connection_config = ConnConfig},
{ok, expecting_connection_pid, State};
{error, Reason} ->
{stop, Reason}
end.
handle_event(cast, {set_connection, ConnectionPid}, expecting_connection_pid,
State=#state{socket = Socket}) ->
ok = amqp10_client_connection:socket_ready(ConnectionPid, Socket),
set_active_once(State),
State1 = State#state{connection = ConnectionPid},
{next_state, expecting_frame_header, State1};
handle_event(cast, {register_session, Session, OutgoingChannel}, _StateName,
#state{socket = Socket, outgoing_channels = OutgoingChannels} = State) ->
ok = amqp10_client_session:socket_ready(Session, Socket),
OutgoingChannels1 = OutgoingChannels#{OutgoingChannel => Session},
State1 = State#state{outgoing_channels = OutgoingChannels1},
{keep_state, State1};
handle_event(cast, {unregister_session, _Session, OutgoingChannel, IncomingChannel}, _StateName,
State=#state{outgoing_channels = OutgoingChannels,
incoming_channels = IncomingChannels}) ->
OutgoingChannels1 = maps:remove(OutgoingChannel, OutgoingChannels),
IncomingChannels1 = maps:remove(IncomingChannel, IncomingChannels),
State1 = State#state{outgoing_channels = OutgoingChannels1,
incoming_channels = IncomingChannels1},
{keep_state, State1};
handle_event(cast, close, _StateName, State = #state{socket = Socket}) ->
close_socket(Socket),
{stop, normal, State#state{socket = undefined}};
handle_event({call, From}, _Action, _State, _Data) ->
{keep_state_and_data, [{reply, From, ok}]};
handle_event(info, {Tcp, _, Packet}, StateName, #state{buffer = Buffer} = State)
when Tcp == tcp orelse Tcp == ssl ->
Data = <<Buffer/binary, Packet/binary>>,
case handle_input(StateName, Data, State) of
{ok, NextState, Remaining, NewState0} ->
NewState = defer_heartbeat_timer(NewState0),
set_active_once(NewState),
{next_state, NextState, NewState#state{buffer = Remaining}};
{error, Reason, NewState} ->
{stop, Reason, NewState}
end;
handle_event(info, {TcpError, _, Reason}, StateName, State)
when TcpError == tcp_error orelse TcpError == ssl_error ->
error_logger:warning_msg("AMQP 1.0 connection socket errored, connection state: '~s', reason: '~p'~n",
[StateName, Reason]),
State1 = State#state{socket = undefined,
buffer = <<>>,
frame_state = undefined},
{stop, {error, Reason}, State1};
handle_event(info, {TcpClosed, _}, StateName, State)
when TcpClosed == tcp_closed orelse TcpClosed == ssl_closed ->
error_logger:warning_msg("AMQP 1.0 connection socket was closed, connection state: '~s'~n",
[StateName]),
State1 = State#state{socket = undefined,
buffer = <<>>,
frame_state = undefined},
{stop, normal, State1};
handle_event(info, heartbeat, _StateName, #state{connection = Connection}) ->
amqp10_client_connection:close(Connection,
{resource_limit_exceeded, <<"remote idle-time-out">>}),
% do not stop as may want to read the peer's close frame
keep_state_and_data.
terminate(normal, _StateName, #state{connection_sup = _Sup, socket = Socket}) ->
maybe_close_socket(Socket);
terminate(_Reason, _StateName, #state{connection_sup = _Sup, socket = Socket}) ->
maybe_close_socket(Socket).
code_change(_Vsn, State, Data, _Extra) ->
{ok, State, Data}.
%%%===================================================================
Internal functions
%%%===================================================================
maybe_close_socket(undefined) ->
ok;
maybe_close_socket(Socket) ->
close_socket(Socket).
close_socket({tcp, Socket}) ->
gen_tcp:close(Socket);
close_socket({ssl, Socket}) ->
ssl:close(Socket).
set_active_once(#state{socket = {tcp, Socket}}) ->
ok = inet:setopts(Socket, [{active, once}]);
set_active_once(#state{socket = {ssl, Socket}}) ->
ok = ssl:setopts(Socket, [{active, once}]).
handle_input(expecting_frame_header,
<<"AMQP", Protocol/unsigned, Maj/unsigned, Min/unsigned,
Rev/unsigned, Rest/binary>>,
#state{connection = ConnectionPid} = State)
when Protocol =:= 0 orelse Protocol =:= 3 ->
ok = amqp10_client_connection:protocol_header_received(
ConnectionPid, Protocol, Maj, Min, Rev),
handle_input(expecting_frame_header, Rest, State);
handle_input(expecting_frame_header,
<<Length:32/unsigned, DOff:8/unsigned, Type/unsigned,
Channel:16/unsigned, Rest/binary>>, State)
when DOff >= 2 andalso (Type =:= 0 orelse Type =:= 1) ->
AFS = #frame_state{frame_length = Length, channel = Channel,
type = frame_type(Type), data_offset = DOff},
handle_input(expecting_extended_frame_header, Rest,
State#state{frame_state = AFS});
handle_input(expecting_frame_header, <<_:8/binary, _/binary>>, State) ->
{error, invalid_protocol_header, State};
handle_input(expecting_extended_frame_header, Data,
#state{frame_state =
#frame_state{data_offset = DOff}} = State) ->
Skip = DOff * 4 - 8,
case Data of
<<_:Skip/binary, Rest/binary>> ->
handle_input(expecting_frame_body, Rest, State);
_ ->
{ok, expecting_extended_frame_header, Data, State}
end;
handle_input(expecting_frame_body, Data,
#state{frame_state = #frame_state{frame_length = Length,
type = FrameType,
data_offset = DOff,
channel = Channel}} = State) ->
Skip = DOff * 4 - 8,
BodyLength = Length - Skip - 8,
case {Data, BodyLength} of
{<<_:BodyLength/binary, Rest/binary>>, 0} ->
% heartbeat
handle_input(expecting_frame_header, Rest, State);
{<<FrameBody:BodyLength/binary, Rest/binary>>, _} ->
State1 = State#state{frame_state = undefined},
{PerfDesc, Payload} = amqp10_binary_parser:parse(FrameBody),
Perf = amqp10_framing:decode(PerfDesc),
State2 = route_frame(Channel, FrameType, {Perf, Payload}, State1),
handle_input(expecting_frame_header, Rest, State2);
_ ->
{ok, expecting_frame_body, Data, State}
end;
handle_input(StateName, Data, State) ->
{ok, StateName, Data, State}.
%%% LOCAL
defer_heartbeat_timer(State =
#state{heartbeat_timer_ref = TRef,
connection_config = #{idle_time_out := T}})
when is_number(T) andalso T > 0 ->
_ = case TRef of
undefined -> ok;
_ -> _ = erlang:cancel_timer(TRef)
end,
NewTRef = erlang:send_after(T * 2, self(), heartbeat),
State#state{heartbeat_timer_ref = NewTRef};
defer_heartbeat_timer(State) -> State.
route_frame(Channel, FrameType, {Performative, Payload} = Frame, State0) ->
{DestinationPid, State} = find_destination(Channel, FrameType, Performative,
State0),
?DBG("FRAME -> ~p ~p~n ~p~n", [Channel, DestinationPid, Performative]),
case Payload of
<<>> -> ok = gen_statem:cast(DestinationPid, Performative);
_ -> ok = gen_statem:cast(DestinationPid, Frame)
end,
State.
-spec find_destination(amqp10_client_types:channel(), frame_type(),
amqp10_client_types:amqp10_performative(), #state{}) ->
{pid(), #state{}}.
find_destination(0, amqp, Frame, #state{connection = ConnPid} = State)
when is_record(Frame, 'v1_0.open') orelse
is_record(Frame, 'v1_0.close') ->
{ConnPid, State};
find_destination(_Channel, sasl, _Frame,
#state{connection = ConnPid} = State) ->
{ConnPid, State};
find_destination(Channel, amqp,
#'v1_0.begin'{remote_channel = {ushort, OutgoingChannel}},
#state{outgoing_channels = OutgoingChannels,
incoming_channels = IncomingChannels} = State) ->
#{OutgoingChannel := Session} = OutgoingChannels,
IncomingChannels1 = IncomingChannels#{Channel => Session},
State1 = State#state{incoming_channels = IncomingChannels1},
{Session, State1};
find_destination(Channel, amqp, _Frame,
#state{incoming_channels = IncomingChannels} = State) ->
#{Channel := Session} = IncomingChannels,
{Session, State}.
frame_type(0) -> amqp;
frame_type(1) -> sasl.
-ifdef(TEST).
find_destination_test_() ->
Pid = self(),
State = #state{connection = Pid, outgoing_channels = #{3 => Pid}},
StateConn = #state{connection = Pid},
StateWithIncoming = State#state{incoming_channels = #{7 => Pid}},
StateWithIncoming0 = State#state{incoming_channels = #{0 => Pid}},
Tests = [{0, #'v1_0.open'{}, State, State, amqp},
{0, #'v1_0.close'{}, State, State, amqp},
{7, #'v1_0.begin'{remote_channel = {ushort, 3}}, State,
StateWithIncoming, amqp},
{0, #'v1_0.begin'{remote_channel = {ushort, 3}}, State,
StateWithIncoming0, amqp},
{7, #'v1_0.end'{}, StateWithIncoming, StateWithIncoming, amqp},
{7, #'v1_0.attach'{}, StateWithIncoming, StateWithIncoming, amqp},
{7, #'v1_0.flow'{}, StateWithIncoming, StateWithIncoming, amqp},
{0, #'v1_0.sasl_init'{}, StateConn, StateConn, sasl}
],
[?_assertMatch({Pid, NewState},
find_destination(Channel, Type, Frame, InputState))
|| {Channel, Frame, InputState, NewState, Type} <- Tests].
-endif.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-amqp1.0-client/010830f12ea967aa34bdadc79bddebfd35387406/src/amqp10_client_frame_reader.erl | erlang |
API
gen_statem callbacks
===================================================================
API
===================================================================
@doc
Passes the connection process PID to the reader process.
This function is called when a connection supervision tree is
started.
===================================================================
gen_statem callbacks
===================================================================
combined the list of `addresses' with the value of the original `address' option if provided
do not stop as may want to read the peer's close frame
===================================================================
===================================================================
heartbeat
LOCAL | 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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(amqp10_client_frame_reader).
-behaviour(gen_statem).
-include("amqp10_client.hrl").
-include_lib("amqp10_common/include/amqp10_framing.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-export([start_link/2,
set_connection/2,
close/1,
register_session/3,
unregister_session/4]).
-export([init/1,
callback_mode/0,
handle_event/4,
code_change/4,
terminate/3]).
-define(RABBIT_TCP_OPTS, [binary,
{packet, 0},
{active, false},
{nodelay, true}]).
-type frame_type() :: amqp | sasl.
-record(frame_state,
{data_offset :: 2..255,
type :: frame_type(),
channel :: non_neg_integer(),
frame_length :: pos_integer()}).
-record(state,
{connection_sup :: pid(),
socket :: amqp10_client_connection:amqp10_socket() | undefined,
buffer = <<>> :: binary(),
frame_state :: #frame_state{} | undefined,
connection :: pid() | undefined,
heartbeat_timer_ref :: reference() | undefined,
connection_config = #{} :: amqp10_client_connection:connection_config(),
outgoing_channels = #{},
incoming_channels = #{}}).
-spec start_link(pid(), amqp10_client_connection:connection_config()) ->
{ok, pid()} | ignore | {error, any()}.
start_link(Sup, Config) ->
gen_statem:start_link(?MODULE, [Sup, Config], []).
@private
-spec set_connection(Reader :: pid(), ConnectionPid :: pid()) -> ok.
set_connection(Reader, Connection) ->
gen_statem:cast(Reader, {set_connection, Connection}).
close(Reader) ->
gen_statem:cast(Reader, close).
register_session(Reader, Session, OutgoingChannel) ->
gen_statem:cast(Reader, {register_session, Session, OutgoingChannel}).
unregister_session(Reader, Session, OutgoingChannel, IncomingChannel) ->
gen_statem:cast(Reader, {unregister_session, Session, OutgoingChannel, IncomingChannel}).
callback_mode() ->
[handle_event_function].
init([Sup, ConnConfig]) when is_map(ConnConfig) ->
Port = maps:get(port, ConnConfig, 5672),
Addresses0 = maps:get(addresses, ConnConfig, []),
Addresses = case maps:get(address, ConnConfig, undefined) of
undefined -> Addresses0;
Address -> Addresses0 ++ [Address]
end,
Result = lists:foldl(fun (Address, {error, _}) ->
gen_tcp:connect(Address, Port, ?RABBIT_TCP_OPTS);
(_Address, {ok, Socket}) ->
{ok, Socket}
end,
{error, undefined}, Addresses),
case Result of
{ok, Socket0} ->
Socket = case ConnConfig of
#{tls_opts := {secure_port, Opts}} ->
{ok, SslSock} = ssl:connect(Socket0, Opts),
{ssl, SslSock};
_ -> {tcp, Socket0}
end,
State = #state{connection_sup = Sup, socket = Socket,
connection_config = ConnConfig},
{ok, expecting_connection_pid, State};
{error, Reason} ->
{stop, Reason}
end.
handle_event(cast, {set_connection, ConnectionPid}, expecting_connection_pid,
State=#state{socket = Socket}) ->
ok = amqp10_client_connection:socket_ready(ConnectionPid, Socket),
set_active_once(State),
State1 = State#state{connection = ConnectionPid},
{next_state, expecting_frame_header, State1};
handle_event(cast, {register_session, Session, OutgoingChannel}, _StateName,
#state{socket = Socket, outgoing_channels = OutgoingChannels} = State) ->
ok = amqp10_client_session:socket_ready(Session, Socket),
OutgoingChannels1 = OutgoingChannels#{OutgoingChannel => Session},
State1 = State#state{outgoing_channels = OutgoingChannels1},
{keep_state, State1};
handle_event(cast, {unregister_session, _Session, OutgoingChannel, IncomingChannel}, _StateName,
State=#state{outgoing_channels = OutgoingChannels,
incoming_channels = IncomingChannels}) ->
OutgoingChannels1 = maps:remove(OutgoingChannel, OutgoingChannels),
IncomingChannels1 = maps:remove(IncomingChannel, IncomingChannels),
State1 = State#state{outgoing_channels = OutgoingChannels1,
incoming_channels = IncomingChannels1},
{keep_state, State1};
handle_event(cast, close, _StateName, State = #state{socket = Socket}) ->
close_socket(Socket),
{stop, normal, State#state{socket = undefined}};
handle_event({call, From}, _Action, _State, _Data) ->
{keep_state_and_data, [{reply, From, ok}]};
handle_event(info, {Tcp, _, Packet}, StateName, #state{buffer = Buffer} = State)
when Tcp == tcp orelse Tcp == ssl ->
Data = <<Buffer/binary, Packet/binary>>,
case handle_input(StateName, Data, State) of
{ok, NextState, Remaining, NewState0} ->
NewState = defer_heartbeat_timer(NewState0),
set_active_once(NewState),
{next_state, NextState, NewState#state{buffer = Remaining}};
{error, Reason, NewState} ->
{stop, Reason, NewState}
end;
handle_event(info, {TcpError, _, Reason}, StateName, State)
when TcpError == tcp_error orelse TcpError == ssl_error ->
error_logger:warning_msg("AMQP 1.0 connection socket errored, connection state: '~s', reason: '~p'~n",
[StateName, Reason]),
State1 = State#state{socket = undefined,
buffer = <<>>,
frame_state = undefined},
{stop, {error, Reason}, State1};
handle_event(info, {TcpClosed, _}, StateName, State)
when TcpClosed == tcp_closed orelse TcpClosed == ssl_closed ->
error_logger:warning_msg("AMQP 1.0 connection socket was closed, connection state: '~s'~n",
[StateName]),
State1 = State#state{socket = undefined,
buffer = <<>>,
frame_state = undefined},
{stop, normal, State1};
handle_event(info, heartbeat, _StateName, #state{connection = Connection}) ->
amqp10_client_connection:close(Connection,
{resource_limit_exceeded, <<"remote idle-time-out">>}),
keep_state_and_data.
terminate(normal, _StateName, #state{connection_sup = _Sup, socket = Socket}) ->
maybe_close_socket(Socket);
terminate(_Reason, _StateName, #state{connection_sup = _Sup, socket = Socket}) ->
maybe_close_socket(Socket).
code_change(_Vsn, State, Data, _Extra) ->
{ok, State, Data}.
Internal functions
maybe_close_socket(undefined) ->
ok;
maybe_close_socket(Socket) ->
close_socket(Socket).
close_socket({tcp, Socket}) ->
gen_tcp:close(Socket);
close_socket({ssl, Socket}) ->
ssl:close(Socket).
set_active_once(#state{socket = {tcp, Socket}}) ->
ok = inet:setopts(Socket, [{active, once}]);
set_active_once(#state{socket = {ssl, Socket}}) ->
ok = ssl:setopts(Socket, [{active, once}]).
handle_input(expecting_frame_header,
<<"AMQP", Protocol/unsigned, Maj/unsigned, Min/unsigned,
Rev/unsigned, Rest/binary>>,
#state{connection = ConnectionPid} = State)
when Protocol =:= 0 orelse Protocol =:= 3 ->
ok = amqp10_client_connection:protocol_header_received(
ConnectionPid, Protocol, Maj, Min, Rev),
handle_input(expecting_frame_header, Rest, State);
handle_input(expecting_frame_header,
<<Length:32/unsigned, DOff:8/unsigned, Type/unsigned,
Channel:16/unsigned, Rest/binary>>, State)
when DOff >= 2 andalso (Type =:= 0 orelse Type =:= 1) ->
AFS = #frame_state{frame_length = Length, channel = Channel,
type = frame_type(Type), data_offset = DOff},
handle_input(expecting_extended_frame_header, Rest,
State#state{frame_state = AFS});
handle_input(expecting_frame_header, <<_:8/binary, _/binary>>, State) ->
{error, invalid_protocol_header, State};
handle_input(expecting_extended_frame_header, Data,
#state{frame_state =
#frame_state{data_offset = DOff}} = State) ->
Skip = DOff * 4 - 8,
case Data of
<<_:Skip/binary, Rest/binary>> ->
handle_input(expecting_frame_body, Rest, State);
_ ->
{ok, expecting_extended_frame_header, Data, State}
end;
handle_input(expecting_frame_body, Data,
#state{frame_state = #frame_state{frame_length = Length,
type = FrameType,
data_offset = DOff,
channel = Channel}} = State) ->
Skip = DOff * 4 - 8,
BodyLength = Length - Skip - 8,
case {Data, BodyLength} of
{<<_:BodyLength/binary, Rest/binary>>, 0} ->
handle_input(expecting_frame_header, Rest, State);
{<<FrameBody:BodyLength/binary, Rest/binary>>, _} ->
State1 = State#state{frame_state = undefined},
{PerfDesc, Payload} = amqp10_binary_parser:parse(FrameBody),
Perf = amqp10_framing:decode(PerfDesc),
State2 = route_frame(Channel, FrameType, {Perf, Payload}, State1),
handle_input(expecting_frame_header, Rest, State2);
_ ->
{ok, expecting_frame_body, Data, State}
end;
handle_input(StateName, Data, State) ->
{ok, StateName, Data, State}.
defer_heartbeat_timer(State =
#state{heartbeat_timer_ref = TRef,
connection_config = #{idle_time_out := T}})
when is_number(T) andalso T > 0 ->
_ = case TRef of
undefined -> ok;
_ -> _ = erlang:cancel_timer(TRef)
end,
NewTRef = erlang:send_after(T * 2, self(), heartbeat),
State#state{heartbeat_timer_ref = NewTRef};
defer_heartbeat_timer(State) -> State.
route_frame(Channel, FrameType, {Performative, Payload} = Frame, State0) ->
{DestinationPid, State} = find_destination(Channel, FrameType, Performative,
State0),
?DBG("FRAME -> ~p ~p~n ~p~n", [Channel, DestinationPid, Performative]),
case Payload of
<<>> -> ok = gen_statem:cast(DestinationPid, Performative);
_ -> ok = gen_statem:cast(DestinationPid, Frame)
end,
State.
-spec find_destination(amqp10_client_types:channel(), frame_type(),
amqp10_client_types:amqp10_performative(), #state{}) ->
{pid(), #state{}}.
find_destination(0, amqp, Frame, #state{connection = ConnPid} = State)
when is_record(Frame, 'v1_0.open') orelse
is_record(Frame, 'v1_0.close') ->
{ConnPid, State};
find_destination(_Channel, sasl, _Frame,
#state{connection = ConnPid} = State) ->
{ConnPid, State};
find_destination(Channel, amqp,
#'v1_0.begin'{remote_channel = {ushort, OutgoingChannel}},
#state{outgoing_channels = OutgoingChannels,
incoming_channels = IncomingChannels} = State) ->
#{OutgoingChannel := Session} = OutgoingChannels,
IncomingChannels1 = IncomingChannels#{Channel => Session},
State1 = State#state{incoming_channels = IncomingChannels1},
{Session, State1};
find_destination(Channel, amqp, _Frame,
#state{incoming_channels = IncomingChannels} = State) ->
#{Channel := Session} = IncomingChannels,
{Session, State}.
frame_type(0) -> amqp;
frame_type(1) -> sasl.
-ifdef(TEST).
find_destination_test_() ->
Pid = self(),
State = #state{connection = Pid, outgoing_channels = #{3 => Pid}},
StateConn = #state{connection = Pid},
StateWithIncoming = State#state{incoming_channels = #{7 => Pid}},
StateWithIncoming0 = State#state{incoming_channels = #{0 => Pid}},
Tests = [{0, #'v1_0.open'{}, State, State, amqp},
{0, #'v1_0.close'{}, State, State, amqp},
{7, #'v1_0.begin'{remote_channel = {ushort, 3}}, State,
StateWithIncoming, amqp},
{0, #'v1_0.begin'{remote_channel = {ushort, 3}}, State,
StateWithIncoming0, amqp},
{7, #'v1_0.end'{}, StateWithIncoming, StateWithIncoming, amqp},
{7, #'v1_0.attach'{}, StateWithIncoming, StateWithIncoming, amqp},
{7, #'v1_0.flow'{}, StateWithIncoming, StateWithIncoming, amqp},
{0, #'v1_0.sasl_init'{}, StateConn, StateConn, sasl}
],
[?_assertMatch({Pid, NewState},
find_destination(Channel, Type, Frame, InputState))
|| {Channel, Frame, InputState, NewState, Type} <- Tests].
-endif.
|
b15966dccdfdef4ae55b0cc50ed519f8dc43ab146a8555b203e5a5ef916baecd | frasertweedale/hs-tax-ato | Common.hs | -- This file is part of hs-tax-ato
Copyright ( C ) 2018 Fraser Tweedale
--
-- hs-tax-ato is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see </>.
{-|
Common taxes and helpers.
-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
module Data.Tax.ATO.Common
(
-- * Tax tables
TaxTables(..)
-- * Classes
, HasIncome(..)
-- * Common taxes and helpers
, medicareLevy
, medicareLevySurcharge
, lowIncomeTaxOffset
, lowIncomeTaxOffset2021
, lamito
, corporateTax
-- * Convenience functions
, thresholds'
, marginal'
) where
import Control.Lens (Getter, review, to, view)
import Data.Bifunctor (first)
import Data.Tax
import Data.Tax.ATO.PrivateHealthInsuranceRebate
| A set of tax tables for a particular financial year
data TaxTables y a = TaxTables
{ ttIndividualIncomeTax :: Tax (Money a) (Money a)
, ttMedicareLevy :: Tax (Money a) (Money a)
, ttMedicareLevySurcharge :: Tax (Money a) (Money a)
, ttHelp :: Tax (Money a) (Money a)
, ttSfss :: Tax (Money a) (Money a)
, ttAdditional :: Tax (Money a) (Money a)
^ Additional taxes and offsets that apply at EOY
, ttPHIRebateRates :: PrivateHealthInsuranceRebateRates a
}
| The Medicare levy , incorporating the Medicare levy reduction .
The rate is 10 % of the income above the given shade - in threshold
or 2 % of the total income , whichever is less .
--
medicareLevy :: (Fractional a, Ord a) => Money a -> Tax (Money a) (Money a)
medicareLevy l = lesserOf (above l 0.1) (flat 0.02)
| /Medicare levy surcharge ( MLS)/. Certain exemptions are available .
--
_ _ Known issues _ _ : the MLS is levied on taxable income + fringe
-- benefits, but this is not implemented properly yet. The
-- thresholds are affected by family income and number of
-- dependents; this also is not implemented.
medicareLevySurcharge :: (Fractional a, Ord a) => Tax (Money a) (Money a)
medicareLevySurcharge =
threshold (review money 90000) 0.01
<> threshold (review money 105000) 0.0025
<> threshold (review money 140000) 0.0025
| /Low income tax offset ( LITO)/. $ 445 , reduced by 1.5c for
every dollar earned over $ 37,000 . The lump amount may change in
-- the future.
lowIncomeTaxOffset :: (Fractional a, Ord a) => Tax (Money a) (Money a)
lowIncomeTaxOffset =
limit mempty
(lump (review money (-445)) <> above (review money 37000) 0.015)
| /Low income tax offset/ , 2020–21 version .
lowIncomeTaxOffset2021 :: (Fractional a, Ord a) => Tax (Money a) (Money a)
lowIncomeTaxOffset2021 =
limit mempty $
lump (review money (-700))
<> above (review money 37500) 0.05
<> above (review money 45000) (-0.035)
| Low and middle income tax offset . FY2019 , 2020 , 2021 .
--
lamito :: (Fractional a, Ord a) => Tax (Money a) (Money a)
lamito = limit mempty $
greaterOf (lump (review money (-1080)))
( lump (review money (-255))
<> above (review money 37000) (-0.075) )
<> above (review money 90000) 0.03
| The corporate tax rate of 30 % . In the future , different rates may
-- be levied depending on business turnover/income.
corporateTax :: (Fractional a) => Tax (Money a) (Money a)
corporateTax = flat 0.3
thresholds', marginal'
:: (Fractional a, Ord a) => [(a, a)] -> Tax (Money a) (Money a)
thresholds' = thresholds . fmap (first (review money))
-- ^ Convenience wrapper for 'thresholds'. Turns the thresholds into 'Money'
marginal' = marginal . fmap (first (review money))
-- ^ Convenience wrapper for 'marginal'. Turns the margins into 'Money'
-- | Types that have an income value.
class HasIncome a b c where
income :: Getter (a b) (Money c)
instance (Foldable t, HasIncome x a a, Num a) => HasIncome t (x a) a where
income = to (foldMap (view income))
| null | https://raw.githubusercontent.com/frasertweedale/hs-tax-ato/bddb0b14e4754d22eed301f4639c99bf43eccd52/src/Data/Tax/ATO/Common.hs | haskell | This file is part of hs-tax-ato
hs-tax-ato is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
along with this program. If not, see </>.
|
Common taxes and helpers.
* Tax tables
* Classes
* Common taxes and helpers
* Convenience functions
benefits, but this is not implemented properly yet. The
thresholds are affected by family income and number of
dependents; this also is not implemented.
the future.
be levied depending on business turnover/income.
^ Convenience wrapper for 'thresholds'. Turns the thresholds into 'Money'
^ Convenience wrapper for 'marginal'. Turns the margins into 'Money'
| Types that have an income value. | Copyright ( C ) 2018 Fraser Tweedale
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU Affero General Public License
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
module Data.Tax.ATO.Common
(
TaxTables(..)
, HasIncome(..)
, medicareLevy
, medicareLevySurcharge
, lowIncomeTaxOffset
, lowIncomeTaxOffset2021
, lamito
, corporateTax
, thresholds'
, marginal'
) where
import Control.Lens (Getter, review, to, view)
import Data.Bifunctor (first)
import Data.Tax
import Data.Tax.ATO.PrivateHealthInsuranceRebate
| A set of tax tables for a particular financial year
data TaxTables y a = TaxTables
{ ttIndividualIncomeTax :: Tax (Money a) (Money a)
, ttMedicareLevy :: Tax (Money a) (Money a)
, ttMedicareLevySurcharge :: Tax (Money a) (Money a)
, ttHelp :: Tax (Money a) (Money a)
, ttSfss :: Tax (Money a) (Money a)
, ttAdditional :: Tax (Money a) (Money a)
^ Additional taxes and offsets that apply at EOY
, ttPHIRebateRates :: PrivateHealthInsuranceRebateRates a
}
| The Medicare levy , incorporating the Medicare levy reduction .
The rate is 10 % of the income above the given shade - in threshold
or 2 % of the total income , whichever is less .
medicareLevy :: (Fractional a, Ord a) => Money a -> Tax (Money a) (Money a)
medicareLevy l = lesserOf (above l 0.1) (flat 0.02)
| /Medicare levy surcharge ( MLS)/. Certain exemptions are available .
_ _ Known issues _ _ : the MLS is levied on taxable income + fringe
medicareLevySurcharge :: (Fractional a, Ord a) => Tax (Money a) (Money a)
medicareLevySurcharge =
threshold (review money 90000) 0.01
<> threshold (review money 105000) 0.0025
<> threshold (review money 140000) 0.0025
| /Low income tax offset ( LITO)/. $ 445 , reduced by 1.5c for
every dollar earned over $ 37,000 . The lump amount may change in
lowIncomeTaxOffset :: (Fractional a, Ord a) => Tax (Money a) (Money a)
lowIncomeTaxOffset =
limit mempty
(lump (review money (-445)) <> above (review money 37000) 0.015)
| /Low income tax offset/ , 2020–21 version .
lowIncomeTaxOffset2021 :: (Fractional a, Ord a) => Tax (Money a) (Money a)
lowIncomeTaxOffset2021 =
limit mempty $
lump (review money (-700))
<> above (review money 37500) 0.05
<> above (review money 45000) (-0.035)
| Low and middle income tax offset . FY2019 , 2020 , 2021 .
lamito :: (Fractional a, Ord a) => Tax (Money a) (Money a)
lamito = limit mempty $
greaterOf (lump (review money (-1080)))
( lump (review money (-255))
<> above (review money 37000) (-0.075) )
<> above (review money 90000) 0.03
| The corporate tax rate of 30 % . In the future , different rates may
corporateTax :: (Fractional a) => Tax (Money a) (Money a)
corporateTax = flat 0.3
thresholds', marginal'
:: (Fractional a, Ord a) => [(a, a)] -> Tax (Money a) (Money a)
thresholds' = thresholds . fmap (first (review money))
marginal' = marginal . fmap (first (review money))
class HasIncome a b c where
income :: Getter (a b) (Money c)
instance (Foldable t, HasIncome x a a, Num a) => HasIncome t (x a) a where
income = to (foldMap (view income))
|
7025ddf6ca6e21775c50b0866a8656c645d59c2758729d1a62236ef9b8d82663 | metabase/metabase | bookmark_test.clj | (ns metabase.api.bookmark-test
"Tests for /api/bookmark endpoints."
(:require
[clojure.test :refer :all]
[metabase.models.bookmark
:refer [BookmarkOrdering CardBookmark CollectionBookmark DashboardBookmark]]
[metabase.models.card :refer [Card]]
[metabase.models.collection :refer [Collection]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.interface :as mi]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]))
(deftest bookmarks-test
(mt/initialize-if-needed! :db)
(testing "POST /api/bookmark/:model/:model-id"
(mt/with-temp* [Collection [{coll-id :id :as collection} {:name "Test Collection"}]
Card [card {:name "Test Card", :display "area", :collection_id coll-id}]
Dashboard [dashboard {:name "Test Dashboard", :collection_id coll-id}]]
(testing "check that we can bookmark a Collection"
(is (= (u/the-id collection)
(->> (mt/user-http-request :rasta :post 200 (str "bookmark/collection/" (u/the-id collection)))
:collection_id))))
(testing "check that we can bookmark a Card"
(is (= (u/the-id card)
(->> (mt/user-http-request :rasta :post 200 (str "bookmark/card/" (u/the-id card)))
:card_id))))
(let [card-result (->> (mt/user-http-request :rasta :get 200 "bookmark")
(filter #(= (:type %) "card"))
first)]
(testing "check a card bookmark has `:display` key"
(is (contains? card-result :display)))
(testing "check a card bookmark has `:dataset` key"
(is (contains? card-result :dataset))))
(testing "check that we can bookmark a Dashboard"
(is (= (u/the-id dashboard)
(->> (mt/user-http-request :rasta :post 200 (str "bookmark/dashboard/" (u/the-id dashboard)))
:dashboard_id))))
(testing "check that we can retreive the user's bookmarks"
(let [result (mt/user-http-request :rasta :get 200 "bookmark")]
(is (= #{"card" "collection" "dashboard"}
(into #{} (map :type) result)))))
(testing "check that we can delete bookmarks"
(mt/user-http-request :rasta :delete 204 (str "bookmark/card/" (u/the-id card)))
(is (= #{"collection" "dashboard"}
(->> (mt/user-http-request :rasta :get 200 "bookmark")
(map :type)
set)))
(mt/user-http-request :rasta :delete 204 (str "bookmark/collection/" (u/the-id collection)))
(mt/user-http-request :rasta :delete 204 (str "bookmark/dashboard/" (u/the-id dashboard)))
(is (= #{}
(->> (mt/user-http-request :rasta :get 200 "bookmark")
(map :type)
set)))))))
(defn bookmark-models [user-id & models]
(doseq [model models]
(cond
(mi/instance-of? Collection model)
(db/insert! CollectionBookmark
{:user_id user-id
:collection_id (u/the-id model)})
(mi/instance-of? Card model)
(db/insert! CardBookmark
{:user_id user-id
:card_id (u/the-id model)})
(mi/instance-of? Dashboard model)
(db/insert! DashboardBookmark
{:user_id user-id
:dashboard_id (u/the-id model)})
:else
(throw (ex-info "Unknown type" {:user-id user-id :model model})))))
(deftest bookmarks-on-archived-items-test
(testing "POST /api/bookmark/:model/:model-id"
(mt/with-temp* [Collection [archived-collection {:name "Test Collection" :archived true}]
Card [archived-card {:name "Test Card" :archived true}]
Dashboard [archived-dashboard {:name "Test Dashboard" :archived true}]]
(bookmark-models (mt/user->id :rasta) archived-collection archived-card archived-dashboard)
(testing "check that we don't receive bookmarks of archived items"
(is (= #{}
(->> (mt/user-http-request :rasta :get 200 "bookmark")
(map :type)
set)))))))
(deftest bookmarks-ordering-test
(testing "PUT /api/bookmark/ordering"
(mt/with-temp* [Collection [collection {:name "Test Collection"}]
Card [card {:name "Test Card"}]
Dashboard [dashboard {:name "Test Dashboard"}]]
(mt/with-model-cleanup [BookmarkOrdering]
(bookmark-models (mt/user->id :rasta) collection card dashboard)
(testing "Check that ordering works"
(is (= nil
(mt/user-http-request :rasta :put 204 "bookmark/ordering"
{:orderings [{:type "dashboard" :item_id (u/the-id dashboard)}
{:type "card" :item_id (u/the-id card)}
{:type "collection" :item_id (u/the-id collection)}]})))
(is (= ["dashboard" "card" "collection"]
(map :type
(mt/user-http-request :rasta :get 200 "bookmark")))))
(testing "Check that re-ordering works"
(is (= nil
(mt/user-http-request :rasta :put 204 "bookmark/ordering"
{:orderings [{:type "card" :item_id (u/the-id card)}
{:type "collection" :item_id (u/the-id collection)}
{:type "dashboard" :item_id (u/the-id dashboard)}]})))
(is (= ["card" "collection" "dashboard"]
(map :type
(mt/user-http-request :rasta :get 200 "bookmark")))))))))
| null | https://raw.githubusercontent.com/metabase/metabase/3b8f0d881c19c96bfdff95a275440db97b1e0173/test/metabase/api/bookmark_test.clj | clojure | (ns metabase.api.bookmark-test
"Tests for /api/bookmark endpoints."
(:require
[clojure.test :refer :all]
[metabase.models.bookmark
:refer [BookmarkOrdering CardBookmark CollectionBookmark DashboardBookmark]]
[metabase.models.card :refer [Card]]
[metabase.models.collection :refer [Collection]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.interface :as mi]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]))
(deftest bookmarks-test
(mt/initialize-if-needed! :db)
(testing "POST /api/bookmark/:model/:model-id"
(mt/with-temp* [Collection [{coll-id :id :as collection} {:name "Test Collection"}]
Card [card {:name "Test Card", :display "area", :collection_id coll-id}]
Dashboard [dashboard {:name "Test Dashboard", :collection_id coll-id}]]
(testing "check that we can bookmark a Collection"
(is (= (u/the-id collection)
(->> (mt/user-http-request :rasta :post 200 (str "bookmark/collection/" (u/the-id collection)))
:collection_id))))
(testing "check that we can bookmark a Card"
(is (= (u/the-id card)
(->> (mt/user-http-request :rasta :post 200 (str "bookmark/card/" (u/the-id card)))
:card_id))))
(let [card-result (->> (mt/user-http-request :rasta :get 200 "bookmark")
(filter #(= (:type %) "card"))
first)]
(testing "check a card bookmark has `:display` key"
(is (contains? card-result :display)))
(testing "check a card bookmark has `:dataset` key"
(is (contains? card-result :dataset))))
(testing "check that we can bookmark a Dashboard"
(is (= (u/the-id dashboard)
(->> (mt/user-http-request :rasta :post 200 (str "bookmark/dashboard/" (u/the-id dashboard)))
:dashboard_id))))
(testing "check that we can retreive the user's bookmarks"
(let [result (mt/user-http-request :rasta :get 200 "bookmark")]
(is (= #{"card" "collection" "dashboard"}
(into #{} (map :type) result)))))
(testing "check that we can delete bookmarks"
(mt/user-http-request :rasta :delete 204 (str "bookmark/card/" (u/the-id card)))
(is (= #{"collection" "dashboard"}
(->> (mt/user-http-request :rasta :get 200 "bookmark")
(map :type)
set)))
(mt/user-http-request :rasta :delete 204 (str "bookmark/collection/" (u/the-id collection)))
(mt/user-http-request :rasta :delete 204 (str "bookmark/dashboard/" (u/the-id dashboard)))
(is (= #{}
(->> (mt/user-http-request :rasta :get 200 "bookmark")
(map :type)
set)))))))
(defn bookmark-models [user-id & models]
(doseq [model models]
(cond
(mi/instance-of? Collection model)
(db/insert! CollectionBookmark
{:user_id user-id
:collection_id (u/the-id model)})
(mi/instance-of? Card model)
(db/insert! CardBookmark
{:user_id user-id
:card_id (u/the-id model)})
(mi/instance-of? Dashboard model)
(db/insert! DashboardBookmark
{:user_id user-id
:dashboard_id (u/the-id model)})
:else
(throw (ex-info "Unknown type" {:user-id user-id :model model})))))
(deftest bookmarks-on-archived-items-test
(testing "POST /api/bookmark/:model/:model-id"
(mt/with-temp* [Collection [archived-collection {:name "Test Collection" :archived true}]
Card [archived-card {:name "Test Card" :archived true}]
Dashboard [archived-dashboard {:name "Test Dashboard" :archived true}]]
(bookmark-models (mt/user->id :rasta) archived-collection archived-card archived-dashboard)
(testing "check that we don't receive bookmarks of archived items"
(is (= #{}
(->> (mt/user-http-request :rasta :get 200 "bookmark")
(map :type)
set)))))))
(deftest bookmarks-ordering-test
(testing "PUT /api/bookmark/ordering"
(mt/with-temp* [Collection [collection {:name "Test Collection"}]
Card [card {:name "Test Card"}]
Dashboard [dashboard {:name "Test Dashboard"}]]
(mt/with-model-cleanup [BookmarkOrdering]
(bookmark-models (mt/user->id :rasta) collection card dashboard)
(testing "Check that ordering works"
(is (= nil
(mt/user-http-request :rasta :put 204 "bookmark/ordering"
{:orderings [{:type "dashboard" :item_id (u/the-id dashboard)}
{:type "card" :item_id (u/the-id card)}
{:type "collection" :item_id (u/the-id collection)}]})))
(is (= ["dashboard" "card" "collection"]
(map :type
(mt/user-http-request :rasta :get 200 "bookmark")))))
(testing "Check that re-ordering works"
(is (= nil
(mt/user-http-request :rasta :put 204 "bookmark/ordering"
{:orderings [{:type "card" :item_id (u/the-id card)}
{:type "collection" :item_id (u/the-id collection)}
{:type "dashboard" :item_id (u/the-id dashboard)}]})))
(is (= ["card" "collection" "dashboard"]
(map :type
(mt/user-http-request :rasta :get 200 "bookmark")))))))))
|
|
14517165cedbbd55f019f248d52920f53ee95532db77bb0e18acb79c217f95a8 | composewell/streamly | Type.hs | -- |
Module : Streamly . Internal . Data . Unfold . Type
Copyright : ( c ) 2019 Composewell Technologies
-- License : BSD3
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
-- To run the examples in this module:
--
> > > import qualified Streamly . Data . Stream as Stream
> > > import qualified Streamly . Data . Fold as Fold
> > > import qualified Streamly . Internal . Data . Unfold as Unfold
module Streamly.Internal.Data.Unfold.Type
( Unfold (..)
-- * Basic Constructors
, mkUnfoldM
, mkUnfoldrM
, unfoldrM
, unfoldr
, functionM
, function
, identity
-- * From Values
, fromEffect
, fromPure
-- * From Containers
, fromList
-- * Transformations
, lmap
, lmapM
, map
, map2
, mapM
, mapM2
, both
, first
, second
-- * Trimming
, takeWhileMWithInput
, takeWhileM
, takeWhile
-- * Nesting
, ConcatState (..)
, many
, many2
, manyInterleave
-- , manyInterleave2
-- Applicative
, crossApplySnd
, crossApplyFst
, crossWithM
, crossWith
, cross
, crossApply
Monad
, concatMapM
, concatMap
, bind
, zipWithM
, zipWith
)
where
#include "inline.hs"
import Control . Arrow ( Arrow ( .. ) )
import Control . Category ( Category ( .. ) )
import Control.Monad ((>=>))
import Data.Void (Void)
import Fusion.Plugin.Types (Fuse(..))
import Streamly.Internal.Data.Tuple.Strict (Tuple'(..))
import Streamly.Internal.Data.Stream.StreamD.Step (Step(..))
import Prelude hiding (map, mapM, concatMap, zipWith, takeWhile)
-- $setup
> > > import qualified Streamly . Data . Stream as Stream
> > > import qualified Streamly . Data . Fold as Fold
> > > import qualified Streamly . Internal . Data . Unfold as Unfold
------------------------------------------------------------------------------
-- Monadic Unfolds
------------------------------------------------------------------------------
-- The order of arguments allows 'Category' and 'Arrow' instances but precludes
contravariant and contra - applicative .
--
-- An unfold is akin to a reader. It is the streaming equivalent of a reader.
-- The argument @a@ is the environment of the reader. That's the reason the
-- default unfolds in various modules are called "read".
--
| An @Unfold m a b@ is a generator of a stream of values of type @b@ from a
-- seed of type 'a' in 'Monad' @m@.
--
data Unfold m a b =
-- | @Unfold step inject@
forall s. Unfold (s -> m (Step s b)) (a -> m s)
------------------------------------------------------------------------------
-- Basic constructors
------------------------------------------------------------------------------
-- | Make an unfold from @step@ and @inject@ functions.
--
-- /Pre-release/
# INLINE mkUnfoldM #
mkUnfoldM :: (s -> m (Step s b)) -> (a -> m s) -> Unfold m a b
mkUnfoldM = Unfold
-- | Make an unfold from a step function.
--
-- See also: 'unfoldrM'
--
-- /Pre-release/
# INLINE mkUnfoldrM #
mkUnfoldrM :: Applicative m => (a -> m (Step a b)) -> Unfold m a b
mkUnfoldrM step = Unfold step pure
-- The type 'Step' is isomorphic to 'Maybe'. Ideally unfoldrM should be the
same as mkUnfoldrM , this is for compatibility with traditional Maybe based
-- unfold step functions.
--
-- | Build a stream by unfolding a /monadic/ step function starting from a seed.
-- The step function returns the next element in the stream and the next seed
-- value. When it is done it returns 'Nothing' and the stream ends.
--
# INLINE unfoldrM #
unfoldrM :: Applicative m => (a -> m (Maybe (b, a))) -> Unfold m a b
unfoldrM next = Unfold step pure
where
# INLINE_LATE step #
step st =
(\case
Just (x, s) -> Yield x s
Nothing -> Stop) <$> next st
-- | Like 'unfoldrM' but uses a pure step function.
--
-- >>> :{
-- f [] = Nothing
-- f (x:xs) = Just (x, xs)
-- :}
--
> > > Unfold.fold Fold.toList ( Unfold.unfoldr f ) [ 1,2,3 ]
-- [1,2,3]
--
# INLINE unfoldr #
unfoldr :: Applicative m => (a -> Maybe (b, a)) -> Unfold m a b
unfoldr step = unfoldrM (pure . step)
------------------------------------------------------------------------------
-- Map input
------------------------------------------------------------------------------
-- | Map a function on the input argument of the 'Unfold'.
--
> > > u = Unfold.lmap ( fmap ( +1 ) ) Unfold.fromList
> > > Unfold.fold Fold.toList u [ 1 .. 5 ]
[ 2,3,4,5,6 ]
--
-- @
-- lmap f = Unfold.many (Unfold.function f)
-- @
--
# INLINE_NORMAL lmap #
lmap :: (a -> c) -> Unfold m c b -> Unfold m a b
lmap f (Unfold ustep uinject) = Unfold ustep (uinject Prelude.. f)
-- | Map an action on the input argument of the 'Unfold'.
--
-- @
-- lmapM f = Unfold.many (Unfold.functionM f)
-- @
--
# INLINE_NORMAL lmapM #
lmapM :: Monad m => (a -> m c) -> Unfold m c b -> Unfold m a b
lmapM f (Unfold ustep uinject) = Unfold ustep (f >=> uinject)
-- | Supply the seed to an unfold closing the input end of the unfold.
--
-- @
-- both a = Unfold.lmap (Prelude.const a)
-- @
--
-- /Pre-release/
--
{-# INLINE_NORMAL both #-}
both :: a -> Unfold m a b -> Unfold m Void b
both a = lmap (Prelude.const a)
| Supply the first component of the tuple to an unfold that accepts a tuple
as a seed resulting in a fold that accepts the second component of the tuple
-- as a seed.
--
-- @
-- first a = Unfold.lmap (a, )
-- @
--
-- /Pre-release/
--
{-# INLINE_NORMAL first #-}
first :: a -> Unfold m (a, b) c -> Unfold m b c
first a = lmap (a, )
| Supply the second component of the tuple to an unfold that accepts a tuple
as a seed resulting in a fold that accepts the first component of the tuple
-- as a seed.
--
-- @
second b = Unfold.lmap ( , b )
-- @
--
-- /Pre-release/
--
# INLINE_NORMAL second #
second :: b -> Unfold m (a, b) c -> Unfold m a c
second b = lmap (, b)
------------------------------------------------------------------------------
-- Filter input
------------------------------------------------------------------------------
{-# INLINE_NORMAL takeWhileMWithInput #-}
takeWhileMWithInput :: Monad m =>
(a -> b -> m Bool) -> Unfold m a b -> Unfold m a b
takeWhileMWithInput f (Unfold step1 inject1) = Unfold step inject
where
inject a = do
s <- inject1 a
return $ Tuple' a s
# INLINE_LATE step #
step (Tuple' a st) = do
r <- step1 st
case r of
Yield x s -> do
b <- f a x
return $ if b then Yield x (Tuple' a s) else Stop
Skip s -> return $ Skip (Tuple' a s)
Stop -> return Stop
-- | Same as 'takeWhile' but with a monadic predicate.
--
{-# INLINE_NORMAL takeWhileM #-}
takeWhileM :: Monad m => (b -> m Bool) -> Unfold m a b -> Unfold m a b
-- XXX Check if the compiler simplifies the following to the same as the custom
implementation below ( the Tuple ' should help eliminate the unused param ):
--
-- takeWhileM f = takeWhileMWithInput (\_ b -> f b)
takeWhileM f (Unfold step1 inject1) = Unfold step inject1
where
# INLINE_LATE step #
step st = do
r <- step1 st
case r of
Yield x s -> do
b <- f x
return $ if b then Yield x s else Stop
Skip s -> return $ Skip s
Stop -> return Stop
-- | End the stream generated by the 'Unfold' as soon as the predicate fails
-- on an element.
--
# INLINE takeWhile #
takeWhile :: Monad m => (b -> Bool) -> Unfold m a b -> Unfold m a b
takeWhile f = takeWhileM (return . f)
------------------------------------------------------------------------------
-- Functor
------------------------------------------------------------------------------
{-# INLINE_NORMAL mapM2 #-}
mapM2 :: Monad m => (a -> b -> m c) -> Unfold m a b -> Unfold m a c
mapM2 f (Unfold ustep uinject) = Unfold step inject
where
inject a = do
r <- uinject a
return (a, r)
# INLINE_LATE step #
step (inp, st) = do
r <- ustep st
case r of
Yield x s -> f inp x >>= \a -> return $ Yield a (inp, s)
Skip s -> return $ Skip (inp, s)
Stop -> return Stop
-- | Apply a monadic function to each element of the stream and replace it
-- with the output of the resulting action.
--
-- >>> mapM f = Unfold.mapM2 (const f)
--
# INLINE_NORMAL mapM #
mapM :: Monad m => (b -> m c) -> Unfold m a b -> Unfold m a c
-- mapM f = mapM2 (const f)
mapM f (Unfold ustep uinject) = Unfold step uinject
where
# INLINE_LATE step #
step st = do
r <- ustep st
case r of
Yield x s -> f x >>= \a -> return $ Yield a s
Skip s -> return $ Skip s
Stop -> return Stop
-- XXX We can also introduce a withInput combinator which will output the input
-- seed along with the output as a tuple.
-- |
--
> > > map2 f = Unfold.mapM2 ( \a b - > pure ( f a b ) )
--
-- Note that the seed may mutate (e.g. if the seed is a Handle or IORef) as
-- stream is generated from it, so we need to be careful when reusing the seed
-- while the stream is being generated from it.
--
{-# INLINE_NORMAL map2 #-}
map2 :: Functor m => (a -> b -> c) -> Unfold m a b -> Unfold m a c
-- map2 f = mapM2 (\a b -> pure (f a b))
map2 f (Unfold ustep uinject) = Unfold step (\a -> (a,) <$> uinject a)
where
func a r =
case r of
Yield x s -> Yield (f a x) (a, s)
Skip s -> Skip (a, s)
Stop -> Stop
# INLINE_LATE step #
step (a, st) = fmap (func a) (ustep st)
| Map a function on the output of the unfold ( the type ) .
--
-- >>> map f = Unfold.map2 (const f)
--
-- /Pre-release/
{-# INLINE_NORMAL map #-}
map :: Functor m => (b -> c) -> Unfold m a b -> Unfold m a c
map f = map2 ( const f )
map f (Unfold ustep uinject) = Unfold step uinject
where
# INLINE_LATE step #
step st = fmap (fmap f) (ustep st)
| Maps a function on the output of the unfold ( the type ) .
instance Functor m => Functor (Unfold m a) where
# INLINE fmap #
fmap = map
------------------------------------------------------------------------------
-- Applicative
------------------------------------------------------------------------------
-- XXX Shouldn't this be Unfold m (m a) a ?
-- | The unfold discards its input and generates a function stream using the
-- supplied monadic action.
--
-- /Pre-release/
# INLINE fromEffect #
fromEffect :: Applicative m => m b -> Unfold m a b
fromEffect m = Unfold step inject
where
inject _ = pure False
step False = (`Yield` True) <$> m
step True = pure Stop
XXX Should n't this be Unfold m a a ? Which is identity . Should this function
even exist for . Should we have applicative / Monad for unfolds ?
--
-- | Discards the unfold input and always returns the argument of 'fromPure'.
--
-- > fromPure = fromEffect . pure
--
-- /Pre-release/
fromPure :: Applicative m => b -> Unfold m a b
fromPure = fromEffect Prelude.. pure
XXX Check if " unfold ( fromList [ 1 .. 10 ] ) " fuses , if it does n't we can use
-- rewrite rules to rewrite list enumerations to unfold enumerations.
-- | Convert a list of pure values to a 'Stream'
--
# INLINE_LATE fromList #
fromList :: Applicative m => Unfold m [a] a
fromList = Unfold step pure
where
# INLINE_LATE step #
step (x:xs) = pure $ Yield x xs
step [] = pure Stop
| Outer product discarding the first element .
--
-- /Unimplemented/
--
{-# INLINE_NORMAL crossApplySnd #-}
crossApplySnd :: -- Monad m =>
Unfold m a b -> Unfold m a c -> Unfold m a c
crossApplySnd (Unfold _step1 _inject1) (Unfold _step2 _inject2) = undefined
| Outer product discarding the second element .
--
-- /Unimplemented/
--
{-# INLINE_NORMAL crossApplyFst #-}
crossApplyFst :: -- Monad m =>
Unfold m a b -> Unfold m a c -> Unfold m a b
crossApplyFst (Unfold _step1 _inject1) (Unfold _step2 _inject2) = undefined
{-# ANN type Many2State Fuse #-}
data Many2State x s1 s2 = Many2Outer x s1 | Many2Inner x s1 s2
{-# INLINE_NORMAL many2 #-}
many2 :: Monad m => Unfold m (a, b) c -> Unfold m a b -> Unfold m a c
many2 (Unfold step2 inject2) (Unfold step1 inject1) = Unfold step inject
where
inject a = do
s <- inject1 a
return $ Many2Outer a s
# INLINE_LATE step #
step (Many2Outer a st) = do
r <- step1 st
case r of
Yield b s -> do
innerSt <- inject2 (a, b)
return $ Skip (Many2Inner a s innerSt)
Skip s -> return $ Skip (Many2Outer a s)
Stop -> return Stop
step (Many2Inner a ost ist) = do
r <- step2 ist
return $ case r of
Yield x s -> Yield x (Many2Inner a ost s)
Skip s -> Skip (Many2Inner a ost s)
Stop -> Skip (Many2Outer a ost)
data Cross a s1 b s2 = CrossOuter a s1 | CrossInner a s1 b s2
-- | Create a cross product (vector product or cartesian product) of the
output streams of two unfolds using a monadic combining function .
--
-- >>> f1 f u = Unfold.mapM2 (\(_, c) b -> f b c) (Unfold.lmap fst u)
-- >>> crossWithM f u = Unfold.many2 (f1 f u)
--
-- /Pre-release/
{-# INLINE_NORMAL crossWithM #-}
crossWithM :: Monad m =>
(b -> c -> m d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
-- crossWithM f u1 u2 = many2 (mapM2 (\(_, b) c -> f b c) (lmap fst u2)) u1
crossWithM f (Unfold step1 inject1) (Unfold step2 inject2) = Unfold step inject
where
inject a = do
s1 <- inject1 a
return $ CrossOuter a s1
# INLINE_LATE step #
step (CrossOuter a s1) = do
r <- step1 s1
case r of
Yield b s -> do
s2 <- inject2 a
return $ Skip (CrossInner a s b s2)
Skip s -> return $ Skip (CrossOuter a s)
Stop -> return Stop
step (CrossInner a s1 b s2) = do
r <- step2 s2
case r of
Yield c s -> f b c >>= \d -> return $ Yield d (CrossInner a s1 b s)
Skip s -> return $ Skip (CrossInner a s1 b s)
Stop -> return $ Skip (CrossOuter a s1)
-- | Like 'crossWithM' but uses a pure combining function.
--
> crossWith f = crossWithM ( \b c - > return $ f b c )
--
> > > u1 = Unfold.lmap fst Unfold.fromList
> > > u2 = Unfold.lmap snd Unfold.fromList
> > > u = Unfold.crossWith ( , ) u1 u2
-- >>> Unfold.fold Fold.toList u ([1,2,3], [4,5,6])
-- [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
--
# INLINE crossWith #
crossWith :: Monad m =>
(b -> c -> d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
crossWith f = crossWithM (\b c -> return $ f b c)
-- | See 'crossWith'.
--
-- Definition:
--
-- >>> cross = Unfold.crossWith (,)
--
-- To create a cross product of the streams generated from a tuple we can
-- write:
--
-- >>> :{
cross : : = > Unfold m a b - > Unfold m c d - > Unfold m ( a , c ) ( b , d )
-- cross u1 u2 = Unfold.cross (Unfold.lmap fst u1) (Unfold.lmap snd u2)
-- :}
--
-- /Pre-release/
{-# INLINE_NORMAL cross #-}
cross :: Monad m => Unfold m a b -> Unfold m a c -> Unfold m a (b, c)
cross = crossWith (,)
crossApply :: Monad m => Unfold m a (b -> c) -> Unfold m a b -> Unfold m a c
crossApply u1 u2 = fmap (\(a, b) -> a b) (cross u1 u2)
-- XXX Applicative makes sense for unfolds, but monad does not. Use streams for
-- monad.
-- | Example :
--
-- > > > rlist = Unfold.lmap fst Unfold.fromList
-- > > > llist = Unfold.lmap snd Unfold.fromList
-- > > > Stream.fold Fold.toList ( ( , ) < $ > rlist < * > llist ) ( [ 1,2],[3,4 ] )
-- [ ( ) ]
--
instance = > Applicative ( Unfold m a ) where
{ - # INLINE pure #
-- | Example:
--
-- >>> rlist = Unfold.lmap fst Unfold.fromList
-- >>> llist = Unfold.lmap snd Unfold.fromList
-- >>> Stream.fold Fold.toList $ Stream.unfold ((,) <$> rlist <*> llist) ([1,2],[3,4])
-- [(1,3),(1,4),(2,3),(2,4)]
--
instance Monad m => Applicative (Unfold m a) where
{-# INLINE pure #-}
pure = fromPure
{-# INLINE (<*>) #-}
(<*>) = apply
{ - # INLINE ( * > ) # - }
-- (*>) = apSequence
{ - # INLINE ( < * ) # - }
-- (<*) = apDiscardSnd
-}
------------------------------------------------------------------------------
Monad
------------------------------------------------------------------------------
data ConcatMapState m b s1 x =
ConcatMapOuter x s1
| forall s2. ConcatMapInner x s1 s2 (s2 -> m (Step s2 b))
-- XXX This is experimental. We should rather use streams if concatMap like
-- functionality is needed. This is no more efficient than streams.
-- | Map an unfold generating action to each element of an unfold and
-- flatten the results into a single stream.
--
{-# INLINE_NORMAL concatMapM #-}
concatMapM :: Monad m
=> (b -> m (Unfold m a c)) -> Unfold m a b -> Unfold m a c
concatMapM f (Unfold step1 inject1) = Unfold step inject
where
inject x = do
s <- inject1 x
return $ ConcatMapOuter x s
# INLINE_LATE step #
step (ConcatMapOuter seed st) = do
r <- step1 st
case r of
Yield x s -> do
Unfold step2 inject2 <- f x
innerSt <- inject2 seed
return $ Skip (ConcatMapInner seed s innerSt step2)
Skip s -> return $ Skip (ConcatMapOuter seed s)
Stop -> return Stop
step (ConcatMapInner seed ost ist istep) = do
r <- istep ist
return $ case r of
Yield x s -> Yield x (ConcatMapInner seed ost s istep)
Skip s -> Skip (ConcatMapInner seed ost s istep)
Stop -> Skip (ConcatMapOuter seed ost)
# INLINE concatMap #
concatMap :: Monad m => (b -> Unfold m a c) -> Unfold m a b -> Unfold m a c
concatMap f = concatMapM (return Prelude.. f)
infixl 1 `bind`
# INLINE bind #
bind :: Monad m => Unfold m a b -> (b -> Unfold m a c) -> Unfold m a c
bind = flip concatMap
-- Note : concatMap and Monad instance for unfolds have performance comparable
-- to Stream . In fact , concatMap is slower than Stream , that may be some
-- optimization issue though .
--
-- Monad allows an unfold to depend on the output of a previous unfold .
-- However , it is probably easier to use streams in such situations .
--
-- | Example :
--
-- > > > : {
-- u = do
-- x < - Unfold.enumerateFromToIntegral 4
-- y < - Unfold.enumerateFromToIntegral x
-- return ( x , y )
-- :}
-- > > > Stream.fold Fold.toList
-- [ ( 1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4 ) ]
--
instance = > Monad ( Unfold m a ) where
{ - # INLINE return #
-- Note: concatMap and Monad instance for unfolds have performance comparable
-- to Stream. In fact, concatMap is slower than Stream, that may be some
-- optimization issue though.
--
-- Monad allows an unfold to depend on the output of a previous unfold.
-- However, it is probably easier to use streams in such situations.
--
-- | Example:
--
-- >>> :{
-- u = do
-- x <- Unfold.enumerateFromToIntegral 4
-- y <- Unfold.enumerateFromToIntegral x
-- return (x, y)
-- :}
-- >>> Stream.fold Fold.toList $ Stream.unfold u 1
-- [(1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4)]
--
instance Monad m => Monad (Unfold m a) where
{-# INLINE return #-}
return = pure
{-# INLINE (>>=) #-}
(>>=) = flip concatMap
{ - # INLINE ( > > ) # - }
-- (>>) = (*>)
-}
-------------------------------------------------------------------------------
-- Category
-------------------------------------------------------------------------------
-- | Lift a monadic function into an unfold. The unfold generates a singleton
-- stream.
--
# INLINE functionM #
functionM :: Applicative m => (a -> m b) -> Unfold m a b
functionM f = Unfold step inject
where
inject x = pure $ Just x
# INLINE_LATE step #
step (Just x) = (`Yield` Nothing) <$> f x
step Nothing = pure Stop
-- | Lift a pure function into an unfold. The unfold generates a singleton
-- stream.
--
-- > function f = functionM $ return . f
--
# INLINE function #
function :: Applicative m => (a -> b) -> Unfold m a b
function f = functionM $ pure Prelude.. f
-- | Identity unfold. The unfold generates a singleton stream having the input
-- as the only element.
--
-- > identity = function Prelude.id
--
-- /Pre-release/
# INLINE identity #
identity :: Applicative m => Unfold m a a
identity = function Prelude.id
# ANN type Fuse #
data ConcatState s1 s2 = ConcatOuter s1 | ConcatInner s1 s2
| Apply the first unfold to each output element of the second unfold and
-- flatten the output in a single stream.
--
-- >>> many u = Unfold.many2 (Unfold.lmap snd u)
--
# INLINE_NORMAL many #
many :: Monad m => Unfold m b c -> Unfold m a b -> Unfold m a c
-- many u1 = many2 (lmap snd u1)
many (Unfold step2 inject2) (Unfold step1 inject1) = Unfold step inject
where
inject x = do
s <- inject1 x
return $ ConcatOuter s
# INLINE_LATE step #
step (ConcatOuter st) = do
r <- step1 st
case r of
Yield x s -> do
innerSt <- inject2 x
return $ Skip (ConcatInner s innerSt)
Skip s -> return $ Skip (ConcatOuter s)
Stop -> return Stop
step (ConcatInner ost ist) = do
r <- step2 ist
return $ case r of
Yield x s -> Yield x (ConcatInner ost s)
Skip s -> Skip (ConcatInner ost s)
Stop -> Skip (ConcatOuter ost)
-- XXX There are multiple possible ways to combine the unfolds , " many " appends
-- them , we could also have other variants of " many " e.g. manyInterleave .
-- Should we even have a category instance or just use these functions
-- directly ?
--
instance = > Category ( Unfold m ) where
{ - # INLINE i d #
-- XXX There are multiple possible ways to combine the unfolds, "many" appends
-- them, we could also have other variants of "many" e.g. manyInterleave.
-- Should we even have a category instance or just use these functions
-- directly?
--
instance Monad m => Category (Unfold m) where
{-# INLINE id #-}
id = identity
{-# INLINE (.) #-}
(.) = many
-}
-------------------------------------------------------------------------------
-- Zipping
-------------------------------------------------------------------------------
| Distribute the input to two unfolds and then zip the outputs to a single
-- stream using a monadic zip function.
--
-- Stops as soon as any of the unfolds stops.
--
-- /Pre-release/
# INLINE_NORMAL zipWithM #
zipWithM :: Monad m
=> (b -> c -> m d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
zipWithM f (Unfold step1 inject1) (Unfold step2 inject2) = Unfold step inject
where
inject x = do
s1 <- inject1 x
s2 <- inject2 x
return (s1, s2, Nothing)
# INLINE_LATE step #
step (s1, s2, Nothing) = do
r <- step1 s1
return $
case r of
Yield x s -> Skip (s, s2, Just x)
Skip s -> Skip (s, s2, Nothing)
Stop -> Stop
step (s1, s2, Just x) = do
r <- step2 s2
case r of
Yield y s -> do
z <- f x y
return $ Yield z (s1, s, Nothing)
Skip s -> return $ Skip (s1, s, Just x)
Stop -> return Stop
-- | Like 'zipWithM' but with a pure zip function.
--
> > > square = fmap ( \x - > x * x ) Unfold.fromList
> > > cube = fmap ( \x - > x * x * x ) Unfold.fromList
-- >>> u = Unfold.zipWith (,) square cube
> > > Unfold.fold Fold.toList u [ 1 .. 5 ]
-- [(1,1),(4,8),(9,27),(16,64),(25,125)]
--
> zipWith f = zipWithM ( \a b - > return $ f a b )
--
# INLINE zipWith #
zipWith :: Monad m
=> (b -> c -> d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
zipWith f = zipWithM (\a b -> return (f a b))
-------------------------------------------------------------------------------
Arrow
-------------------------------------------------------------------------------
-- XXX There are multiple ways of combining the outputs of two unfolds , we
-- could zip , merge , append and more . What is the preferred way for Arrow
-- instance ? Should we even have an arrow instance or just use these functions
-- directly ?
--
-- | ' * * * ' is a zip like operation , in fact it is the same as @Unfold.zipWith
-- ( , ) @ , ' & & & ' is a tee like operation i.e. distributes the input to both the
-- unfolds and then zips the output .
--
{ - # ANN module " HLint : ignore Use zip " #
-- XXX There are multiple ways of combining the outputs of two unfolds, we
-- could zip, merge, append and more. What is the preferred way for Arrow
-- instance? Should we even have an arrow instance or just use these functions
-- directly?
--
-- | '***' is a zip like operation, in fact it is the same as @Unfold.zipWith
-- (,)@, '&&&' is a tee like operation i.e. distributes the input to both the
-- unfolds and then zips the output.
--
{-# ANN module "HLint: ignore Use zip" #-}
instance Monad m => Arrow (Unfold m) where
# INLINE arr #
arr = function
{-# INLINE (***) #-}
u1 *** u2 = zipWith (,) (lmap fst u1) (lmap snd u2)
-}
------------------------------------------------------------------------------
-- Interleaving
------------------------------------------------------------------------------
-- We can possibly have an "interleave" operation to interleave the streams
from two seeds :
--
-- interleave :: Unfold m x a -> Unfold m x a -> Unfold m (x, x) a
--
-- Alternatively, we can use a signature like zipWith:
-- interleave :: Unfold m x a -> Unfold m x a -> Unfold m x a
--
We can implement this in terms of manyInterleave , but that may
-- not be as efficient as a custom implementation.
--
-- Similarly we can also have other binary combining ops like append, mergeBy.
-- We already have zipWith.
--
data ManyInterleaveState o i =
ManyInterleaveOuter o [i]
| ManyInterleaveInner o [i]
| ManyInterleaveInnerL [i] [i]
| ManyInterleaveInnerR [i] [i]
| ' Streamly . Internal . Data . Stream.unfoldManyInterleave ' for
-- documentation and notes.
--
-- This is almost identical to unfoldManyInterleave in StreamD module.
--
-- The 'many' combinator is in fact 'manyAppend' to be more explicit in naming.
--
-- /Internal/
{-# INLINE_NORMAL manyInterleave #-}
manyInterleave :: Monad m => Unfold m a b -> Unfold m c a -> Unfold m c b
manyInterleave (Unfold istep iinject) (Unfold ostep oinject) =
Unfold step inject
where
inject x = do
ost <- oinject x
return (ManyInterleaveOuter ost [])
# INLINE_LATE step #
step (ManyInterleaveOuter o ls) = do
r <- ostep o
case r of
Yield a o' -> do
i <- iinject a
i `seq` return (Skip (ManyInterleaveInner o' (i : ls)))
Skip o' -> return $ Skip (ManyInterleaveOuter o' ls)
Stop -> return $ Skip (ManyInterleaveInnerL ls [])
step (ManyInterleaveInner _ []) = undefined
step (ManyInterleaveInner o (st:ls)) = do
r <- istep st
return $ case r of
Yield x s -> Yield x (ManyInterleaveOuter o (s:ls))
Skip s -> Skip (ManyInterleaveInner o (s:ls))
Stop -> Skip (ManyInterleaveOuter o ls)
step (ManyInterleaveInnerL [] []) = return Stop
step (ManyInterleaveInnerL [] rs) =
return $ Skip (ManyInterleaveInnerR [] rs)
step (ManyInterleaveInnerL (st:ls) rs) = do
r <- istep st
return $ case r of
Yield x s -> Yield x (ManyInterleaveInnerL ls (s:rs))
Skip s -> Skip (ManyInterleaveInnerL (s:ls) rs)
Stop -> Skip (ManyInterleaveInnerL ls rs)
step (ManyInterleaveInnerR [] []) = return Stop
step (ManyInterleaveInnerR ls []) =
return $ Skip (ManyInterleaveInnerL ls [])
step (ManyInterleaveInnerR ls (st:rs)) = do
r <- istep st
return $ case r of
Yield x s -> Yield x (ManyInterleaveInnerR (s:ls) rs)
Skip s -> Skip (ManyInterleaveInnerR ls (s:rs))
Stop -> Skip (ManyInterleaveInnerR ls rs)
| null | https://raw.githubusercontent.com/composewell/streamly/1f9dbb8d8abd706d7f4058ccd67472ba86938b0c/core/src/Streamly/Internal/Data/Unfold/Type.hs | haskell | |
License : BSD3
Maintainer :
Stability : experimental
To run the examples in this module:
* Basic Constructors
* From Values
* From Containers
* Transformations
* Trimming
* Nesting
, manyInterleave2
Applicative
$setup
----------------------------------------------------------------------------
Monadic Unfolds
----------------------------------------------------------------------------
The order of arguments allows 'Category' and 'Arrow' instances but precludes
An unfold is akin to a reader. It is the streaming equivalent of a reader.
The argument @a@ is the environment of the reader. That's the reason the
default unfolds in various modules are called "read".
seed of type 'a' in 'Monad' @m@.
| @Unfold step inject@
----------------------------------------------------------------------------
Basic constructors
----------------------------------------------------------------------------
| Make an unfold from @step@ and @inject@ functions.
/Pre-release/
| Make an unfold from a step function.
See also: 'unfoldrM'
/Pre-release/
The type 'Step' is isomorphic to 'Maybe'. Ideally unfoldrM should be the
unfold step functions.
| Build a stream by unfolding a /monadic/ step function starting from a seed.
The step function returns the next element in the stream and the next seed
value. When it is done it returns 'Nothing' and the stream ends.
| Like 'unfoldrM' but uses a pure step function.
>>> :{
f [] = Nothing
f (x:xs) = Just (x, xs)
:}
[1,2,3]
----------------------------------------------------------------------------
Map input
----------------------------------------------------------------------------
| Map a function on the input argument of the 'Unfold'.
@
lmap f = Unfold.many (Unfold.function f)
@
| Map an action on the input argument of the 'Unfold'.
@
lmapM f = Unfold.many (Unfold.functionM f)
@
| Supply the seed to an unfold closing the input end of the unfold.
@
both a = Unfold.lmap (Prelude.const a)
@
/Pre-release/
# INLINE_NORMAL both #
as a seed.
@
first a = Unfold.lmap (a, )
@
/Pre-release/
# INLINE_NORMAL first #
as a seed.
@
@
/Pre-release/
----------------------------------------------------------------------------
Filter input
----------------------------------------------------------------------------
# INLINE_NORMAL takeWhileMWithInput #
| Same as 'takeWhile' but with a monadic predicate.
# INLINE_NORMAL takeWhileM #
XXX Check if the compiler simplifies the following to the same as the custom
takeWhileM f = takeWhileMWithInput (\_ b -> f b)
| End the stream generated by the 'Unfold' as soon as the predicate fails
on an element.
----------------------------------------------------------------------------
Functor
----------------------------------------------------------------------------
# INLINE_NORMAL mapM2 #
| Apply a monadic function to each element of the stream and replace it
with the output of the resulting action.
>>> mapM f = Unfold.mapM2 (const f)
mapM f = mapM2 (const f)
XXX We can also introduce a withInput combinator which will output the input
seed along with the output as a tuple.
|
Note that the seed may mutate (e.g. if the seed is a Handle or IORef) as
stream is generated from it, so we need to be careful when reusing the seed
while the stream is being generated from it.
# INLINE_NORMAL map2 #
map2 f = mapM2 (\a b -> pure (f a b))
>>> map f = Unfold.map2 (const f)
/Pre-release/
# INLINE_NORMAL map #
----------------------------------------------------------------------------
Applicative
----------------------------------------------------------------------------
XXX Shouldn't this be Unfold m (m a) a ?
| The unfold discards its input and generates a function stream using the
supplied monadic action.
/Pre-release/
| Discards the unfold input and always returns the argument of 'fromPure'.
> fromPure = fromEffect . pure
/Pre-release/
rewrite rules to rewrite list enumerations to unfold enumerations.
| Convert a list of pure values to a 'Stream'
/Unimplemented/
# INLINE_NORMAL crossApplySnd #
Monad m =>
/Unimplemented/
# INLINE_NORMAL crossApplyFst #
Monad m =>
# ANN type Many2State Fuse #
# INLINE_NORMAL many2 #
| Create a cross product (vector product or cartesian product) of the
>>> f1 f u = Unfold.mapM2 (\(_, c) b -> f b c) (Unfold.lmap fst u)
>>> crossWithM f u = Unfold.many2 (f1 f u)
/Pre-release/
# INLINE_NORMAL crossWithM #
crossWithM f u1 u2 = many2 (mapM2 (\(_, b) c -> f b c) (lmap fst u2)) u1
| Like 'crossWithM' but uses a pure combining function.
>>> Unfold.fold Fold.toList u ([1,2,3], [4,5,6])
[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
| See 'crossWith'.
Definition:
>>> cross = Unfold.crossWith (,)
To create a cross product of the streams generated from a tuple we can
write:
>>> :{
cross u1 u2 = Unfold.cross (Unfold.lmap fst u1) (Unfold.lmap snd u2)
:}
/Pre-release/
# INLINE_NORMAL cross #
XXX Applicative makes sense for unfolds, but monad does not. Use streams for
monad.
| Example :
> > > rlist = Unfold.lmap fst Unfold.fromList
> > > llist = Unfold.lmap snd Unfold.fromList
> > > Stream.fold Fold.toList ( ( , ) < $ > rlist < * > llist ) ( [ 1,2],[3,4 ] )
[ ( ) ]
| Example:
>>> rlist = Unfold.lmap fst Unfold.fromList
>>> llist = Unfold.lmap snd Unfold.fromList
>>> Stream.fold Fold.toList $ Stream.unfold ((,) <$> rlist <*> llist) ([1,2],[3,4])
[(1,3),(1,4),(2,3),(2,4)]
# INLINE pure #
# INLINE (<*>) #
(*>) = apSequence
(<*) = apDiscardSnd
----------------------------------------------------------------------------
----------------------------------------------------------------------------
XXX This is experimental. We should rather use streams if concatMap like
functionality is needed. This is no more efficient than streams.
| Map an unfold generating action to each element of an unfold and
flatten the results into a single stream.
# INLINE_NORMAL concatMapM #
Note : concatMap and Monad instance for unfolds have performance comparable
to Stream . In fact , concatMap is slower than Stream , that may be some
optimization issue though .
Monad allows an unfold to depend on the output of a previous unfold .
However , it is probably easier to use streams in such situations .
| Example :
> > > : {
u = do
x < - Unfold.enumerateFromToIntegral 4
y < - Unfold.enumerateFromToIntegral x
return ( x , y )
:}
> > > Stream.fold Fold.toList
[ ( 1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4 ) ]
Note: concatMap and Monad instance for unfolds have performance comparable
to Stream. In fact, concatMap is slower than Stream, that may be some
optimization issue though.
Monad allows an unfold to depend on the output of a previous unfold.
However, it is probably easier to use streams in such situations.
| Example:
>>> :{
u = do
x <- Unfold.enumerateFromToIntegral 4
y <- Unfold.enumerateFromToIntegral x
return (x, y)
:}
>>> Stream.fold Fold.toList $ Stream.unfold u 1
[(1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4)]
# INLINE return #
# INLINE (>>=) #
(>>) = (*>)
-----------------------------------------------------------------------------
Category
-----------------------------------------------------------------------------
| Lift a monadic function into an unfold. The unfold generates a singleton
stream.
| Lift a pure function into an unfold. The unfold generates a singleton
stream.
> function f = functionM $ return . f
| Identity unfold. The unfold generates a singleton stream having the input
as the only element.
> identity = function Prelude.id
/Pre-release/
flatten the output in a single stream.
>>> many u = Unfold.many2 (Unfold.lmap snd u)
many u1 = many2 (lmap snd u1)
XXX There are multiple possible ways to combine the unfolds , " many " appends
them , we could also have other variants of " many " e.g. manyInterleave .
Should we even have a category instance or just use these functions
directly ?
XXX There are multiple possible ways to combine the unfolds, "many" appends
them, we could also have other variants of "many" e.g. manyInterleave.
Should we even have a category instance or just use these functions
directly?
# INLINE id #
# INLINE (.) #
-----------------------------------------------------------------------------
Zipping
-----------------------------------------------------------------------------
stream using a monadic zip function.
Stops as soon as any of the unfolds stops.
/Pre-release/
| Like 'zipWithM' but with a pure zip function.
>>> u = Unfold.zipWith (,) square cube
[(1,1),(4,8),(9,27),(16,64),(25,125)]
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
XXX There are multiple ways of combining the outputs of two unfolds , we
could zip , merge , append and more . What is the preferred way for Arrow
instance ? Should we even have an arrow instance or just use these functions
directly ?
| ' * * * ' is a zip like operation , in fact it is the same as @Unfold.zipWith
( , ) @ , ' & & & ' is a tee like operation i.e. distributes the input to both the
unfolds and then zips the output .
XXX There are multiple ways of combining the outputs of two unfolds, we
could zip, merge, append and more. What is the preferred way for Arrow
instance? Should we even have an arrow instance or just use these functions
directly?
| '***' is a zip like operation, in fact it is the same as @Unfold.zipWith
(,)@, '&&&' is a tee like operation i.e. distributes the input to both the
unfolds and then zips the output.
# ANN module "HLint: ignore Use zip" #
# INLINE (***) #
----------------------------------------------------------------------------
Interleaving
----------------------------------------------------------------------------
We can possibly have an "interleave" operation to interleave the streams
interleave :: Unfold m x a -> Unfold m x a -> Unfold m (x, x) a
Alternatively, we can use a signature like zipWith:
interleave :: Unfold m x a -> Unfold m x a -> Unfold m x a
not be as efficient as a custom implementation.
Similarly we can also have other binary combining ops like append, mergeBy.
We already have zipWith.
documentation and notes.
This is almost identical to unfoldManyInterleave in StreamD module.
The 'many' combinator is in fact 'manyAppend' to be more explicit in naming.
/Internal/
# INLINE_NORMAL manyInterleave # | Module : Streamly . Internal . Data . Unfold . Type
Copyright : ( c ) 2019 Composewell Technologies
Portability : GHC
> > > import qualified Streamly . Data . Stream as Stream
> > > import qualified Streamly . Data . Fold as Fold
> > > import qualified Streamly . Internal . Data . Unfold as Unfold
module Streamly.Internal.Data.Unfold.Type
( Unfold (..)
, mkUnfoldM
, mkUnfoldrM
, unfoldrM
, unfoldr
, functionM
, function
, identity
, fromEffect
, fromPure
, fromList
, lmap
, lmapM
, map
, map2
, mapM
, mapM2
, both
, first
, second
, takeWhileMWithInput
, takeWhileM
, takeWhile
, ConcatState (..)
, many
, many2
, manyInterleave
, crossApplySnd
, crossApplyFst
, crossWithM
, crossWith
, cross
, crossApply
Monad
, concatMapM
, concatMap
, bind
, zipWithM
, zipWith
)
where
#include "inline.hs"
import Control . Arrow ( Arrow ( .. ) )
import Control . Category ( Category ( .. ) )
import Control.Monad ((>=>))
import Data.Void (Void)
import Fusion.Plugin.Types (Fuse(..))
import Streamly.Internal.Data.Tuple.Strict (Tuple'(..))
import Streamly.Internal.Data.Stream.StreamD.Step (Step(..))
import Prelude hiding (map, mapM, concatMap, zipWith, takeWhile)
> > > import qualified Streamly . Data . Stream as Stream
> > > import qualified Streamly . Data . Fold as Fold
> > > import qualified Streamly . Internal . Data . Unfold as Unfold
contravariant and contra - applicative .
| An @Unfold m a b@ is a generator of a stream of values of type @b@ from a
data Unfold m a b =
forall s. Unfold (s -> m (Step s b)) (a -> m s)
# INLINE mkUnfoldM #
mkUnfoldM :: (s -> m (Step s b)) -> (a -> m s) -> Unfold m a b
mkUnfoldM = Unfold
# INLINE mkUnfoldrM #
mkUnfoldrM :: Applicative m => (a -> m (Step a b)) -> Unfold m a b
mkUnfoldrM step = Unfold step pure
same as mkUnfoldrM , this is for compatibility with traditional Maybe based
# INLINE unfoldrM #
unfoldrM :: Applicative m => (a -> m (Maybe (b, a))) -> Unfold m a b
unfoldrM next = Unfold step pure
where
# INLINE_LATE step #
step st =
(\case
Just (x, s) -> Yield x s
Nothing -> Stop) <$> next st
> > > Unfold.fold Fold.toList ( Unfold.unfoldr f ) [ 1,2,3 ]
# INLINE unfoldr #
unfoldr :: Applicative m => (a -> Maybe (b, a)) -> Unfold m a b
unfoldr step = unfoldrM (pure . step)
> > > u = Unfold.lmap ( fmap ( +1 ) ) Unfold.fromList
> > > Unfold.fold Fold.toList u [ 1 .. 5 ]
[ 2,3,4,5,6 ]
# INLINE_NORMAL lmap #
lmap :: (a -> c) -> Unfold m c b -> Unfold m a b
lmap f (Unfold ustep uinject) = Unfold ustep (uinject Prelude.. f)
# INLINE_NORMAL lmapM #
lmapM :: Monad m => (a -> m c) -> Unfold m c b -> Unfold m a b
lmapM f (Unfold ustep uinject) = Unfold ustep (f >=> uinject)
both :: a -> Unfold m a b -> Unfold m Void b
both a = lmap (Prelude.const a)
| Supply the first component of the tuple to an unfold that accepts a tuple
as a seed resulting in a fold that accepts the second component of the tuple
first :: a -> Unfold m (a, b) c -> Unfold m b c
first a = lmap (a, )
| Supply the second component of the tuple to an unfold that accepts a tuple
as a seed resulting in a fold that accepts the first component of the tuple
second b = Unfold.lmap ( , b )
# INLINE_NORMAL second #
second :: b -> Unfold m (a, b) c -> Unfold m a c
second b = lmap (, b)
takeWhileMWithInput :: Monad m =>
(a -> b -> m Bool) -> Unfold m a b -> Unfold m a b
takeWhileMWithInput f (Unfold step1 inject1) = Unfold step inject
where
inject a = do
s <- inject1 a
return $ Tuple' a s
# INLINE_LATE step #
step (Tuple' a st) = do
r <- step1 st
case r of
Yield x s -> do
b <- f a x
return $ if b then Yield x (Tuple' a s) else Stop
Skip s -> return $ Skip (Tuple' a s)
Stop -> return Stop
takeWhileM :: Monad m => (b -> m Bool) -> Unfold m a b -> Unfold m a b
implementation below ( the Tuple ' should help eliminate the unused param ):
takeWhileM f (Unfold step1 inject1) = Unfold step inject1
where
# INLINE_LATE step #
step st = do
r <- step1 st
case r of
Yield x s -> do
b <- f x
return $ if b then Yield x s else Stop
Skip s -> return $ Skip s
Stop -> return Stop
# INLINE takeWhile #
takeWhile :: Monad m => (b -> Bool) -> Unfold m a b -> Unfold m a b
takeWhile f = takeWhileM (return . f)
mapM2 :: Monad m => (a -> b -> m c) -> Unfold m a b -> Unfold m a c
mapM2 f (Unfold ustep uinject) = Unfold step inject
where
inject a = do
r <- uinject a
return (a, r)
# INLINE_LATE step #
step (inp, st) = do
r <- ustep st
case r of
Yield x s -> f inp x >>= \a -> return $ Yield a (inp, s)
Skip s -> return $ Skip (inp, s)
Stop -> return Stop
# INLINE_NORMAL mapM #
mapM :: Monad m => (b -> m c) -> Unfold m a b -> Unfold m a c
mapM f (Unfold ustep uinject) = Unfold step uinject
where
# INLINE_LATE step #
step st = do
r <- ustep st
case r of
Yield x s -> f x >>= \a -> return $ Yield a s
Skip s -> return $ Skip s
Stop -> return Stop
> > > map2 f = Unfold.mapM2 ( \a b - > pure ( f a b ) )
map2 :: Functor m => (a -> b -> c) -> Unfold m a b -> Unfold m a c
map2 f (Unfold ustep uinject) = Unfold step (\a -> (a,) <$> uinject a)
where
func a r =
case r of
Yield x s -> Yield (f a x) (a, s)
Skip s -> Skip (a, s)
Stop -> Stop
# INLINE_LATE step #
step (a, st) = fmap (func a) (ustep st)
| Map a function on the output of the unfold ( the type ) .
map :: Functor m => (b -> c) -> Unfold m a b -> Unfold m a c
map f = map2 ( const f )
map f (Unfold ustep uinject) = Unfold step uinject
where
# INLINE_LATE step #
step st = fmap (fmap f) (ustep st)
| Maps a function on the output of the unfold ( the type ) .
instance Functor m => Functor (Unfold m a) where
# INLINE fmap #
fmap = map
# INLINE fromEffect #
fromEffect :: Applicative m => m b -> Unfold m a b
fromEffect m = Unfold step inject
where
inject _ = pure False
step False = (`Yield` True) <$> m
step True = pure Stop
XXX Should n't this be Unfold m a a ? Which is identity . Should this function
even exist for . Should we have applicative / Monad for unfolds ?
fromPure :: Applicative m => b -> Unfold m a b
fromPure = fromEffect Prelude.. pure
XXX Check if " unfold ( fromList [ 1 .. 10 ] ) " fuses , if it does n't we can use
# INLINE_LATE fromList #
fromList :: Applicative m => Unfold m [a] a
fromList = Unfold step pure
where
# INLINE_LATE step #
step (x:xs) = pure $ Yield x xs
step [] = pure Stop
| Outer product discarding the first element .
Unfold m a b -> Unfold m a c -> Unfold m a c
crossApplySnd (Unfold _step1 _inject1) (Unfold _step2 _inject2) = undefined
| Outer product discarding the second element .
Unfold m a b -> Unfold m a c -> Unfold m a b
crossApplyFst (Unfold _step1 _inject1) (Unfold _step2 _inject2) = undefined
data Many2State x s1 s2 = Many2Outer x s1 | Many2Inner x s1 s2
many2 :: Monad m => Unfold m (a, b) c -> Unfold m a b -> Unfold m a c
many2 (Unfold step2 inject2) (Unfold step1 inject1) = Unfold step inject
where
inject a = do
s <- inject1 a
return $ Many2Outer a s
# INLINE_LATE step #
step (Many2Outer a st) = do
r <- step1 st
case r of
Yield b s -> do
innerSt <- inject2 (a, b)
return $ Skip (Many2Inner a s innerSt)
Skip s -> return $ Skip (Many2Outer a s)
Stop -> return Stop
step (Many2Inner a ost ist) = do
r <- step2 ist
return $ case r of
Yield x s -> Yield x (Many2Inner a ost s)
Skip s -> Skip (Many2Inner a ost s)
Stop -> Skip (Many2Outer a ost)
data Cross a s1 b s2 = CrossOuter a s1 | CrossInner a s1 b s2
output streams of two unfolds using a monadic combining function .
crossWithM :: Monad m =>
(b -> c -> m d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
crossWithM f (Unfold step1 inject1) (Unfold step2 inject2) = Unfold step inject
where
inject a = do
s1 <- inject1 a
return $ CrossOuter a s1
# INLINE_LATE step #
step (CrossOuter a s1) = do
r <- step1 s1
case r of
Yield b s -> do
s2 <- inject2 a
return $ Skip (CrossInner a s b s2)
Skip s -> return $ Skip (CrossOuter a s)
Stop -> return Stop
step (CrossInner a s1 b s2) = do
r <- step2 s2
case r of
Yield c s -> f b c >>= \d -> return $ Yield d (CrossInner a s1 b s)
Skip s -> return $ Skip (CrossInner a s1 b s)
Stop -> return $ Skip (CrossOuter a s1)
> crossWith f = crossWithM ( \b c - > return $ f b c )
> > > u1 = Unfold.lmap fst Unfold.fromList
> > > u2 = Unfold.lmap snd Unfold.fromList
> > > u = Unfold.crossWith ( , ) u1 u2
# INLINE crossWith #
crossWith :: Monad m =>
(b -> c -> d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
crossWith f = crossWithM (\b c -> return $ f b c)
cross : : = > Unfold m a b - > Unfold m c d - > Unfold m ( a , c ) ( b , d )
cross :: Monad m => Unfold m a b -> Unfold m a c -> Unfold m a (b, c)
cross = crossWith (,)
crossApply :: Monad m => Unfold m a (b -> c) -> Unfold m a b -> Unfold m a c
crossApply u1 u2 = fmap (\(a, b) -> a b) (cross u1 u2)
instance = > Applicative ( Unfold m a ) where
{ - # INLINE pure #
instance Monad m => Applicative (Unfold m a) where
pure = fromPure
(<*>) = apply
{ - # INLINE ( * > ) # - }
{ - # INLINE ( < * ) # - }
-}
Monad
data ConcatMapState m b s1 x =
ConcatMapOuter x s1
| forall s2. ConcatMapInner x s1 s2 (s2 -> m (Step s2 b))
concatMapM :: Monad m
=> (b -> m (Unfold m a c)) -> Unfold m a b -> Unfold m a c
concatMapM f (Unfold step1 inject1) = Unfold step inject
where
inject x = do
s <- inject1 x
return $ ConcatMapOuter x s
# INLINE_LATE step #
step (ConcatMapOuter seed st) = do
r <- step1 st
case r of
Yield x s -> do
Unfold step2 inject2 <- f x
innerSt <- inject2 seed
return $ Skip (ConcatMapInner seed s innerSt step2)
Skip s -> return $ Skip (ConcatMapOuter seed s)
Stop -> return Stop
step (ConcatMapInner seed ost ist istep) = do
r <- istep ist
return $ case r of
Yield x s -> Yield x (ConcatMapInner seed ost s istep)
Skip s -> Skip (ConcatMapInner seed ost s istep)
Stop -> Skip (ConcatMapOuter seed ost)
# INLINE concatMap #
concatMap :: Monad m => (b -> Unfold m a c) -> Unfold m a b -> Unfold m a c
concatMap f = concatMapM (return Prelude.. f)
infixl 1 `bind`
# INLINE bind #
bind :: Monad m => Unfold m a b -> (b -> Unfold m a c) -> Unfold m a c
bind = flip concatMap
instance = > Monad ( Unfold m a ) where
{ - # INLINE return #
instance Monad m => Monad (Unfold m a) where
return = pure
(>>=) = flip concatMap
{ - # INLINE ( > > ) # - }
-}
# INLINE functionM #
functionM :: Applicative m => (a -> m b) -> Unfold m a b
functionM f = Unfold step inject
where
inject x = pure $ Just x
# INLINE_LATE step #
step (Just x) = (`Yield` Nothing) <$> f x
step Nothing = pure Stop
# INLINE function #
function :: Applicative m => (a -> b) -> Unfold m a b
function f = functionM $ pure Prelude.. f
# INLINE identity #
identity :: Applicative m => Unfold m a a
identity = function Prelude.id
# ANN type Fuse #
data ConcatState s1 s2 = ConcatOuter s1 | ConcatInner s1 s2
| Apply the first unfold to each output element of the second unfold and
# INLINE_NORMAL many #
many :: Monad m => Unfold m b c -> Unfold m a b -> Unfold m a c
many (Unfold step2 inject2) (Unfold step1 inject1) = Unfold step inject
where
inject x = do
s <- inject1 x
return $ ConcatOuter s
# INLINE_LATE step #
step (ConcatOuter st) = do
r <- step1 st
case r of
Yield x s -> do
innerSt <- inject2 x
return $ Skip (ConcatInner s innerSt)
Skip s -> return $ Skip (ConcatOuter s)
Stop -> return Stop
step (ConcatInner ost ist) = do
r <- step2 ist
return $ case r of
Yield x s -> Yield x (ConcatInner ost s)
Skip s -> Skip (ConcatInner ost s)
Stop -> Skip (ConcatOuter ost)
instance = > Category ( Unfold m ) where
{ - # INLINE i d #
instance Monad m => Category (Unfold m) where
id = identity
(.) = many
-}
| Distribute the input to two unfolds and then zip the outputs to a single
# INLINE_NORMAL zipWithM #
zipWithM :: Monad m
=> (b -> c -> m d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
zipWithM f (Unfold step1 inject1) (Unfold step2 inject2) = Unfold step inject
where
inject x = do
s1 <- inject1 x
s2 <- inject2 x
return (s1, s2, Nothing)
# INLINE_LATE step #
step (s1, s2, Nothing) = do
r <- step1 s1
return $
case r of
Yield x s -> Skip (s, s2, Just x)
Skip s -> Skip (s, s2, Nothing)
Stop -> Stop
step (s1, s2, Just x) = do
r <- step2 s2
case r of
Yield y s -> do
z <- f x y
return $ Yield z (s1, s, Nothing)
Skip s -> return $ Skip (s1, s, Just x)
Stop -> return Stop
> > > square = fmap ( \x - > x * x ) Unfold.fromList
> > > cube = fmap ( \x - > x * x * x ) Unfold.fromList
> > > Unfold.fold Fold.toList u [ 1 .. 5 ]
> zipWith f = zipWithM ( \a b - > return $ f a b )
# INLINE zipWith #
zipWith :: Monad m
=> (b -> c -> d) -> Unfold m a b -> Unfold m a c -> Unfold m a d
zipWith f = zipWithM (\a b -> return (f a b))
Arrow
{ - # ANN module " HLint : ignore Use zip " #
instance Monad m => Arrow (Unfold m) where
# INLINE arr #
arr = function
u1 *** u2 = zipWith (,) (lmap fst u1) (lmap snd u2)
-}
from two seeds :
We can implement this in terms of manyInterleave , but that may
data ManyInterleaveState o i =
ManyInterleaveOuter o [i]
| ManyInterleaveInner o [i]
| ManyInterleaveInnerL [i] [i]
| ManyInterleaveInnerR [i] [i]
| ' Streamly . Internal . Data . Stream.unfoldManyInterleave ' for
manyInterleave :: Monad m => Unfold m a b -> Unfold m c a -> Unfold m c b
manyInterleave (Unfold istep iinject) (Unfold ostep oinject) =
Unfold step inject
where
inject x = do
ost <- oinject x
return (ManyInterleaveOuter ost [])
# INLINE_LATE step #
step (ManyInterleaveOuter o ls) = do
r <- ostep o
case r of
Yield a o' -> do
i <- iinject a
i `seq` return (Skip (ManyInterleaveInner o' (i : ls)))
Skip o' -> return $ Skip (ManyInterleaveOuter o' ls)
Stop -> return $ Skip (ManyInterleaveInnerL ls [])
step (ManyInterleaveInner _ []) = undefined
step (ManyInterleaveInner o (st:ls)) = do
r <- istep st
return $ case r of
Yield x s -> Yield x (ManyInterleaveOuter o (s:ls))
Skip s -> Skip (ManyInterleaveInner o (s:ls))
Stop -> Skip (ManyInterleaveOuter o ls)
step (ManyInterleaveInnerL [] []) = return Stop
step (ManyInterleaveInnerL [] rs) =
return $ Skip (ManyInterleaveInnerR [] rs)
step (ManyInterleaveInnerL (st:ls) rs) = do
r <- istep st
return $ case r of
Yield x s -> Yield x (ManyInterleaveInnerL ls (s:rs))
Skip s -> Skip (ManyInterleaveInnerL (s:ls) rs)
Stop -> Skip (ManyInterleaveInnerL ls rs)
step (ManyInterleaveInnerR [] []) = return Stop
step (ManyInterleaveInnerR ls []) =
return $ Skip (ManyInterleaveInnerL ls [])
step (ManyInterleaveInnerR ls (st:rs)) = do
r <- istep st
return $ case r of
Yield x s -> Yield x (ManyInterleaveInnerR (s:ls) rs)
Skip s -> Skip (ManyInterleaveInnerR ls (s:rs))
Stop -> Skip (ManyInterleaveInnerR ls rs)
|
cfc995ae4ee97efc7b49a07b2b0e6a185b3b210454de6b5ff82ce580d60e1315 | aleator/Simple-SVM | PlotOneClass.hs | # LANGUAGE ForeignFunctionInterface , BangPatterns , ScopedTypeVariables , TupleSections ,
RecordWildCards , NoMonomorphismRestriction #
RecordWildCards, NoMonomorphismRestriction #-}
module Main where
import AI.SVM.Simple
import qualified Data.Vector.Storable as V
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Backend.Cairo
import System.Random.MWC
import Control.Applicative
import Control.Monad
scaledN g = (+0.5) . (/10) <$> normal g
main = do
pts ::[(Double,Double)]
<- withSystemRandom $ \g -> zip <$> replicateM 30 (scaledN g :: IO Double)
<*> replicateM 30 (scaledN g :: IO Double)
let (msg, svm2) = trainOneClass 0.01 (RBF 1) pts
putStrLn msg
let plot =
foldl (atop) (circle # scale 0.025)
[circle # scale 0.022 # translate (x,y) # fc green
| (x,y) <- pts ]
`atop`
foldl (atop) (circle # scale 0.025)
[circle # scale 0.012 # translate (x,y) # fc (color svm2 (x,y))
| x <- [0,0.025..1], y <- [0,0.025..1]]
fst $ renderDia Cairo (CairoOptions ("test.png") (PNG (400,400))) (plot # lineWidth 0.002)
where
color svm pt = case inSet svm pt of
In -> red
Out -> black
between a x b = a <= x && x <= b
| null | https://raw.githubusercontent.com/aleator/Simple-SVM/591b86e645e04ac8e7b73246e9a6b573840fb251/Examples/PlotOneClass.hs | haskell | # LANGUAGE ForeignFunctionInterface , BangPatterns , ScopedTypeVariables , TupleSections ,
RecordWildCards , NoMonomorphismRestriction #
RecordWildCards, NoMonomorphismRestriction #-}
module Main where
import AI.SVM.Simple
import qualified Data.Vector.Storable as V
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Backend.Cairo
import System.Random.MWC
import Control.Applicative
import Control.Monad
scaledN g = (+0.5) . (/10) <$> normal g
main = do
pts ::[(Double,Double)]
<- withSystemRandom $ \g -> zip <$> replicateM 30 (scaledN g :: IO Double)
<*> replicateM 30 (scaledN g :: IO Double)
let (msg, svm2) = trainOneClass 0.01 (RBF 1) pts
putStrLn msg
let plot =
foldl (atop) (circle # scale 0.025)
[circle # scale 0.022 # translate (x,y) # fc green
| (x,y) <- pts ]
`atop`
foldl (atop) (circle # scale 0.025)
[circle # scale 0.012 # translate (x,y) # fc (color svm2 (x,y))
| x <- [0,0.025..1], y <- [0,0.025..1]]
fst $ renderDia Cairo (CairoOptions ("test.png") (PNG (400,400))) (plot # lineWidth 0.002)
where
color svm pt = case inSet svm pt of
In -> red
Out -> black
between a x b = a <= x && x <= b
|
|
2192bdfa1cf209e6955d2d5c20e6c6c85fb5c7b6f67c52b41efac6f621c49edf | OlafChitil/hat | DirectoryBuiltinTypes.hs | module Hat.DirectoryBuiltinTypes
(Permissions(..), greadable, hreadable, gwritable,
hwritable, gexecutable, hexecutable, gsearchable,
hsearchable, aPermissions, aexecutable, areadable,
asearchable, awritable)
where
import qualified Prelude
import qualified Hat.Hat as T
import qualified Hat.PreludeBasic
import qualified Hat.PreludeBuiltinTypes
import Hat.Prelude
data Permissions = Permissions{breadable, bwritable,
bexecutable, bsearchable :: T.R Bool}
instance T.WrapVal Permissions where
wrapVal pwrapVal
kwrapVal@(Permissions (T.R _ z1wrapVal)
(T.R _ z2wrapVal) (T.R _ z3wrapVal)
(T.R _ z4wrapVal))
p
= T.R kwrapVal
(T.mkValueApp4 p pwrapVal aPermissions z1wrapVal
z2wrapVal
z3wrapVal
z4wrapVal)
greadable preadable p
= T.ufun1 areadable preadable p hreadable
hreadable (T.R z1readable _) p
= T.projection T.mkNoSrcPos p (breadable z1readable)
gwritable pwritable p
= T.ufun1 awritable pwritable p hwritable
hwritable (T.R z1writable _) p
= T.projection T.mkNoSrcPos p (bwritable z1writable)
gexecutable pexecutable p
= T.ufun1 aexecutable pexecutable p hexecutable
hexecutable (T.R z1executable _) p
= T.projection T.mkNoSrcPos p
(bexecutable z1executable)
gsearchable psearchable p
= T.ufun1 asearchable psearchable p hsearchable
hsearchable (T.R z1searchable _) p
= T.projection T.mkNoSrcPos p
(bsearchable z1searchable)
aPermissions
= T.mkConstructorWFields tDirectoryBuiltinTypes 30020
30030
3
(4)
"Permissions"
((:) areadable
((:) awritable
((:) aexecutable ((:) asearchable []))))
aexecutable
= T.mkVariable tDirectoryBuiltinTypes 50002 50011 3
(1)
"executable"
Prelude.False
areadable
= T.mkVariable tDirectoryBuiltinTypes 40002 40009 3
(1)
"readable"
Prelude.False
asearchable
= T.mkVariable tDirectoryBuiltinTypes 50014 50023 3
(1)
"searchable"
Prelude.False
awritable
= T.mkVariable tDirectoryBuiltinTypes 40014 40021 3
(1)
"writable"
Prelude.False
p = T.mkRoot
tDirectoryBuiltinTypes
= T.mkModule "DirectoryBuiltinTypes"
"DirectoryBuiltinTypes.hs"
Prelude.False | null | https://raw.githubusercontent.com/OlafChitil/hat/8840a480c076f9f01e58ce24b346850169498be2/Hat/DirectoryBuiltinTypes.hs | haskell | module Hat.DirectoryBuiltinTypes
(Permissions(..), greadable, hreadable, gwritable,
hwritable, gexecutable, hexecutable, gsearchable,
hsearchable, aPermissions, aexecutable, areadable,
asearchable, awritable)
where
import qualified Prelude
import qualified Hat.Hat as T
import qualified Hat.PreludeBasic
import qualified Hat.PreludeBuiltinTypes
import Hat.Prelude
data Permissions = Permissions{breadable, bwritable,
bexecutable, bsearchable :: T.R Bool}
instance T.WrapVal Permissions where
wrapVal pwrapVal
kwrapVal@(Permissions (T.R _ z1wrapVal)
(T.R _ z2wrapVal) (T.R _ z3wrapVal)
(T.R _ z4wrapVal))
p
= T.R kwrapVal
(T.mkValueApp4 p pwrapVal aPermissions z1wrapVal
z2wrapVal
z3wrapVal
z4wrapVal)
greadable preadable p
= T.ufun1 areadable preadable p hreadable
hreadable (T.R z1readable _) p
= T.projection T.mkNoSrcPos p (breadable z1readable)
gwritable pwritable p
= T.ufun1 awritable pwritable p hwritable
hwritable (T.R z1writable _) p
= T.projection T.mkNoSrcPos p (bwritable z1writable)
gexecutable pexecutable p
= T.ufun1 aexecutable pexecutable p hexecutable
hexecutable (T.R z1executable _) p
= T.projection T.mkNoSrcPos p
(bexecutable z1executable)
gsearchable psearchable p
= T.ufun1 asearchable psearchable p hsearchable
hsearchable (T.R z1searchable _) p
= T.projection T.mkNoSrcPos p
(bsearchable z1searchable)
aPermissions
= T.mkConstructorWFields tDirectoryBuiltinTypes 30020
30030
3
(4)
"Permissions"
((:) areadable
((:) awritable
((:) aexecutable ((:) asearchable []))))
aexecutable
= T.mkVariable tDirectoryBuiltinTypes 50002 50011 3
(1)
"executable"
Prelude.False
areadable
= T.mkVariable tDirectoryBuiltinTypes 40002 40009 3
(1)
"readable"
Prelude.False
asearchable
= T.mkVariable tDirectoryBuiltinTypes 50014 50023 3
(1)
"searchable"
Prelude.False
awritable
= T.mkVariable tDirectoryBuiltinTypes 40014 40021 3
(1)
"writable"
Prelude.False
p = T.mkRoot
tDirectoryBuiltinTypes
= T.mkModule "DirectoryBuiltinTypes"
"DirectoryBuiltinTypes.hs"
Prelude.False |
|
638bc6771b9c333ab727d12672c1b98ca901592fbbb3bde2a90f69e0c9c638dd | weblocks-framework/weblocks | widget.lisp | (in-package :weblocks)
(export '(widget-presentation get-widget-form-value-from-request))
(defclass widget-presentation (form-presentation)
((widget-init :initarg :widget-init :accessor widget-presentation-widget)
(widget-set-value :initform nil :initarg :set-value)
(current-widget :initform nil)))
(defmethod render-view-field-value (value (presentation widget-presentation) field view widget obj &rest args &key intermediate-values field-info)
(let ((attributized-slot-name (if field-info
(attributize-view-field-name field-info)
(attributize-name (view-field-slot-name field))))
(field-widget (setf
(slot-value presentation 'current-widget)
(or (get (view-field-slot-name field) widget)
(let ((field-widget
(funcall (slot-value presentation 'widget-init)
:value value
:presentation presentation
:field field
:view view
:form widget
:object obj)))
(funcall (slot-value presentation 'widget-set-value)
:value value
:widget field-widget
:type :init-value)
(setf (get (view-field-slot-name field) widget) field-widget))))))
(render-widget field-widget)))
(defmethod request-parameter-for-presentation (name (presentation widget-presentation))
(let ((value (get-widget-form-value-from-request (slot-value presentation 'current-widget))))
(funcall (slot-value presentation 'widget-set-value)
:value value
:widget (slot-value presentation 'current-widget)
:type :set-value)
value))
(defgeneric get-widget-form-value-from-request (widget)
(:documentation "Should parse and return request value for widget. Used for widgets rendered inside of widget-presentation")
(:method ((widget t))
nil))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/src/views/types/presentations/widget.lisp | lisp | (in-package :weblocks)
(export '(widget-presentation get-widget-form-value-from-request))
(defclass widget-presentation (form-presentation)
((widget-init :initarg :widget-init :accessor widget-presentation-widget)
(widget-set-value :initform nil :initarg :set-value)
(current-widget :initform nil)))
(defmethod render-view-field-value (value (presentation widget-presentation) field view widget obj &rest args &key intermediate-values field-info)
(let ((attributized-slot-name (if field-info
(attributize-view-field-name field-info)
(attributize-name (view-field-slot-name field))))
(field-widget (setf
(slot-value presentation 'current-widget)
(or (get (view-field-slot-name field) widget)
(let ((field-widget
(funcall (slot-value presentation 'widget-init)
:value value
:presentation presentation
:field field
:view view
:form widget
:object obj)))
(funcall (slot-value presentation 'widget-set-value)
:value value
:widget field-widget
:type :init-value)
(setf (get (view-field-slot-name field) widget) field-widget))))))
(render-widget field-widget)))
(defmethod request-parameter-for-presentation (name (presentation widget-presentation))
(let ((value (get-widget-form-value-from-request (slot-value presentation 'current-widget))))
(funcall (slot-value presentation 'widget-set-value)
:value value
:widget (slot-value presentation 'current-widget)
:type :set-value)
value))
(defgeneric get-widget-form-value-from-request (widget)
(:documentation "Should parse and return request value for widget. Used for widgets rendered inside of widget-presentation")
(:method ((widget t))
nil))
|
|
4095c64a1176cc644db004d9da2edb000194e8b3768319e0c65afc8809eec4d1 | taffybar/taffybar | Battery.hs | {-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
Module : System . . Information . Battery
Copyright : ( c )
-- License : BSD3-style (see LICENSE)
--
Maintainer :
-- Stability : unstable
-- Portability : unportable
--
-- This module provides functions for querying battery information using the
UPower dbus , as well as a " BroadcastChan " system for allowing multiple
readers to receive ' BatteryState ' updates without duplicating requests .
-----------------------------------------------------------------------------
module System.Taffybar.Information.Battery
( BatteryInfo(..)
, BatteryState(..)
, BatteryTechnology(..)
, BatteryType(..)
, module System.Taffybar.Information.Battery
) where
import BroadcastChan
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Reader
import DBus
import DBus.Client
import DBus.Internal.Types (Serial(..))
import qualified DBus.TH as DBus
import Data.Int
import Data.List
import Data.Map ( Map )
import qualified Data.Map as M
import Data.Maybe
import Data.Text ( Text )
import Data.Word
import System.Log.Logger
import System.Taffybar.Context
import System.Taffybar.DBus.Client.Params
import System.Taffybar.DBus.Client.UPower
import System.Taffybar.DBus.Client.UPowerDevice
import System.Taffybar.Util
batteryLogPath :: String
batteryLogPath = "System.Taffybar.Information.Battery"
batteryLog
:: MonadIO m
=> Priority -> String -> m ()
batteryLog priority = liftIO . logM batteryLogPath priority
batteryLogF
:: (MonadIO m, Show t)
=> Priority -> String -> t -> m ()
batteryLogF = logPrintF batteryLogPath
-- | The prefix of name of battery devices path. UPower generates the object
path as " battery " + " _ " + basename of the object .
batteryPrefix :: String
batteryPrefix = formatObjectPath uPowerBaseObjectPath ++ "/devices/battery_"
-- | Determine if a power source is a battery.
isBattery :: ObjectPath -> Bool
isBattery = isPrefixOf batteryPrefix . formatObjectPath
-- | A helper to read the variant contents of a dict with a default
-- value.
readDict :: (IsVariant a) => Map Text Variant -> Text -> a -> a
readDict dict key dflt = fromMaybe dflt $ do
variant <- M.lookup key dict
fromVariant variant
-- | Read the variant contents of a dict which is of an unknown integral type.
readDictIntegral :: Map Text Variant -> Text -> Int32 -> Int
readDictIntegral dict key dflt = fromMaybe (fromIntegral dflt) $ do
v <- M.lookup key dict
case variantType v of
TypeWord8 -> return $ fromIntegral (f v :: Word8)
TypeWord16 -> return $ fromIntegral (f v :: Word16)
TypeWord32 -> return $ fromIntegral (f v :: Word32)
TypeWord64 -> return $ fromIntegral (f v :: Word64)
TypeInt16 -> return $ fromIntegral (f v :: Int16)
TypeInt32 -> return $ fromIntegral (f v :: Int32)
TypeInt64 -> return $ fromIntegral (f v :: Int64)
_ -> Nothing
where
f :: (Num a, IsVariant a) => Variant -> a
f = fromMaybe (fromIntegral dflt) . fromVariant
XXX : Remove this once it is exposed in haskell - dbus
dummyMethodError :: MethodError
dummyMethodError = methodError (Serial 1) $ errorName_ "org.ClientTypeMismatch"
-- | Query the UPower daemon about information on a specific battery.
-- If some fields are not actually present, they may have bogus values
-- here. Don't bet anything critical on it.
getBatteryInfo :: ObjectPath -> TaffyIO (Either MethodError BatteryInfo)
getBatteryInfo battPath = asks systemDBusClient >>= \client -> lift $ runExceptT $ do
reply <- ExceptT $ getAllProperties client $
(methodCall battPath uPowerDeviceInterfaceName "FakeMethod")
{ methodCallDestination = Just uPowerBusName }
dict <- ExceptT $ return $ maybeToEither dummyMethodError $
listToMaybe (methodReturnBody reply) >>= fromVariant
return $ infoMapToBatteryInfo dict
infoMapToBatteryInfo :: Map Text Variant -> BatteryInfo
infoMapToBatteryInfo dict =
BatteryInfo
{ batteryNativePath = readDict dict "NativePath" ""
, batteryVendor = readDict dict "Vendor" ""
, batteryModel = readDict dict "Model" ""
, batterySerial = readDict dict "Serial" ""
, batteryType = toEnum $ fromIntegral $ readDictIntegral dict "Type" 0
, batteryPowerSupply = readDict dict "PowerSupply" False
, batteryHasHistory = readDict dict "HasHistory" False
, batteryHasStatistics = readDict dict "HasStatistics" False
, batteryOnline = readDict dict "Online" False
, batteryEnergy = readDict dict "Energy" 0.0
, batteryEnergyEmpty = readDict dict "EnergyEmpty" 0.0
, batteryEnergyFull = readDict dict "EnergyFull" 0.0
, batteryEnergyFullDesign = readDict dict "EnergyFullDesign" 0.0
, batteryEnergyRate = readDict dict "EnergyRate" 0.0
, batteryVoltage = readDict dict "Voltage" 0.0
, batteryTimeToEmpty = readDict dict "TimeToEmpty" 0
, batteryTimeToFull = readDict dict "TimeToFull" 0
, batteryPercentage = readDict dict "Percentage" 0.0
, batteryIsPresent = readDict dict "IsPresent" False
, batteryState = toEnum $ readDictIntegral dict "State" 0
, batteryIsRechargeable = readDict dict "IsRechargable" True
, batteryCapacity = readDict dict "Capacity" 0.0
, batteryTechnology =
toEnum $ fromIntegral $ readDictIntegral dict "Technology" 0
, batteryUpdateTime = readDict dict "UpdateTime" 0
, batteryLuminosity = readDict dict "Luminosity" 0.0
, batteryTemperature = readDict dict "Temperature" 0.0
, batteryWarningLevel = readDict dict "WarningLevel" 0
, batteryBatteryLevel = readDict dict "BatteryLevel" 0
, batteryIconName = readDict dict "IconName" ""
}
getBatteryPaths :: TaffyIO (Either MethodError [ObjectPath])
getBatteryPaths = do
client <- asks systemDBusClient
liftIO $ runExceptT $ do
paths <- ExceptT $ enumerateDevices client
return $ filter isBattery paths
newtype DisplayBatteryChanVar =
DisplayBatteryChanVar (BroadcastChan In BatteryInfo, MVar BatteryInfo)
getDisplayBatteryInfo :: TaffyIO BatteryInfo
getDisplayBatteryInfo = do
DisplayBatteryChanVar (_, theVar) <- getDisplayBatteryChanVar
lift $ readMVar theVar
defaultMonitorDisplayBatteryProperties :: [String]
defaultMonitorDisplayBatteryProperties = [ "IconName", "State", "Percentage" ]
-- | Start the monitoring of the display battery, and setup the associated
-- channel and mvar for the current state.
setupDisplayBatteryChanVar :: [String] -> TaffyIO DisplayBatteryChanVar
setupDisplayBatteryChanVar properties = getStateDefault $
DisplayBatteryChanVar <$> monitorDisplayBattery properties
getDisplayBatteryChanVar :: TaffyIO DisplayBatteryChanVar
getDisplayBatteryChanVar =
setupDisplayBatteryChanVar defaultMonitorDisplayBatteryProperties
getDisplayBatteryChan :: TaffyIO (BroadcastChan In BatteryInfo)
getDisplayBatteryChan = do
DisplayBatteryChanVar (chan, _) <- getDisplayBatteryChanVar
return chan
updateBatteryInfo
:: BroadcastChan In BatteryInfo
-> MVar BatteryInfo
-> ObjectPath
-> TaffyIO ()
updateBatteryInfo chan var path =
getBatteryInfo path >>= lift . either warnOfFailure doWrites
where
doWrites info =
batteryLogF DEBUG "Writing info %s" info >>
swapMVar var info >> void (writeBChan chan info)
warnOfFailure = batteryLogF WARNING "Failed to update battery info %s"
registerForAnyUPowerPropertiesChanged
:: (Signal -> String -> Map String Variant -> [String] -> IO ())
-> ReaderT Context IO SignalHandler
registerForAnyUPowerPropertiesChanged = registerForUPowerPropertyChanges []
registerForUPowerPropertyChanges
:: [String]
-> (Signal -> String -> Map String Variant -> [String] -> IO ())
-> ReaderT Context IO SignalHandler
registerForUPowerPropertyChanges properties signalHandler = do
client <- asks systemDBusClient
lift $ DBus.registerForPropertiesChanged
client
matchAny { matchInterface = Just uPowerDeviceInterfaceName }
handleIfPropertyMatches
where handleIfPropertyMatches rawSignal n propertiesMap l =
let propertyPresent prop = isJust $ M.lookup prop propertiesMap
in when (any propertyPresent properties || null properties) $
signalHandler rawSignal n propertiesMap l
| Monitor the DisplayDevice for changes , writing a new " BatteryInfo " object
to returned " MVar " and " " objects
monitorDisplayBattery ::
[String] -> TaffyIO (BroadcastChan In BatteryInfo, MVar BatteryInfo)
monitorDisplayBattery propertiesToMonitor = do
lift $ batteryLog DEBUG "Starting Battery Monitor"
client <- asks systemDBusClient
infoVar <- lift $ newMVar $ infoMapToBatteryInfo M.empty
chan <- newBroadcastChan
taffyFork $ do
ctx <- ask
let warnOfFailedGetDevice err =
batteryLogF WARNING "Failure getting DisplayBattery: %s" err >>
return "/org/freedesktop/UPower/devices/DisplayDevice"
displayPath <- lift $ getDisplayDevice client >>=
either warnOfFailedGetDevice return
let doUpdate = updateBatteryInfo chan infoVar displayPath
signalCallback _ _ changedProps _ =
do
batteryLogF DEBUG "Battery changed properties: %s" changedProps
runReaderT doUpdate ctx
_ <- registerForUPowerPropertyChanges propertiesToMonitor signalCallback
doUpdate
return ()
return (chan, infoVar)
| Call " refreshAllBatteries " whenever the BatteryInfo for the DisplayDevice
-- is updated. This handles cases where there is a race between the signal that
-- something is updated and the update actually being visible. See
-- for more details.
refreshBatteriesOnPropChange :: TaffyIO ()
refreshBatteriesOnPropChange = ask >>= \ctx ->
let updateIfRealChange _ _ changedProps _ =
flip runReaderT ctx $
when (any ((`notElem` ["UpdateTime", "Voltage"]) . fst) $
M.toList changedProps) $
lift (threadDelay 1000000) >> refreshAllBatteries
in void $ registerForAnyUPowerPropertiesChanged updateIfRealChange
| Request a refresh of all UPower batteries . This is only needed if UPower 's
-- refresh mechanism is not working properly.
refreshAllBatteries :: TaffyIO ()
refreshAllBatteries = do
client <- asks systemDBusClient
let doRefresh path =
batteryLogF DEBUG "Refreshing battery: %s" path >> refresh client path
eerror <- runExceptT $ ExceptT getBatteryPaths >>= liftIO . mapM doRefresh
let logRefreshError = batteryLogF ERROR "Failed to refresh battery: %s"
logGetPathsError = batteryLogF ERROR "Failed to get battery paths %s"
void $ either logGetPathsError (mapM_ $ either logRefreshError return) eerror
| null | https://raw.githubusercontent.com/taffybar/taffybar/9e18037d1f707291de1301929209053472170b60/src/System/Taffybar/Information/Battery.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
|
License : BSD3-style (see LICENSE)
Stability : unstable
Portability : unportable
This module provides functions for querying battery information using the
---------------------------------------------------------------------------
| The prefix of name of battery devices path. UPower generates the object
| Determine if a power source is a battery.
| A helper to read the variant contents of a dict with a default
value.
| Read the variant contents of a dict which is of an unknown integral type.
| Query the UPower daemon about information on a specific battery.
If some fields are not actually present, they may have bogus values
here. Don't bet anything critical on it.
| Start the monitoring of the display battery, and setup the associated
channel and mvar for the current state.
is updated. This handles cases where there is a race between the signal that
something is updated and the update actually being visible. See
for more details.
refresh mechanism is not working properly. | Module : System . . Information . Battery
Copyright : ( c )
Maintainer :
UPower dbus , as well as a " BroadcastChan " system for allowing multiple
readers to receive ' BatteryState ' updates without duplicating requests .
module System.Taffybar.Information.Battery
( BatteryInfo(..)
, BatteryState(..)
, BatteryTechnology(..)
, BatteryType(..)
, module System.Taffybar.Information.Battery
) where
import BroadcastChan
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Reader
import DBus
import DBus.Client
import DBus.Internal.Types (Serial(..))
import qualified DBus.TH as DBus
import Data.Int
import Data.List
import Data.Map ( Map )
import qualified Data.Map as M
import Data.Maybe
import Data.Text ( Text )
import Data.Word
import System.Log.Logger
import System.Taffybar.Context
import System.Taffybar.DBus.Client.Params
import System.Taffybar.DBus.Client.UPower
import System.Taffybar.DBus.Client.UPowerDevice
import System.Taffybar.Util
batteryLogPath :: String
batteryLogPath = "System.Taffybar.Information.Battery"
batteryLog
:: MonadIO m
=> Priority -> String -> m ()
batteryLog priority = liftIO . logM batteryLogPath priority
batteryLogF
:: (MonadIO m, Show t)
=> Priority -> String -> t -> m ()
batteryLogF = logPrintF batteryLogPath
path as " battery " + " _ " + basename of the object .
batteryPrefix :: String
batteryPrefix = formatObjectPath uPowerBaseObjectPath ++ "/devices/battery_"
isBattery :: ObjectPath -> Bool
isBattery = isPrefixOf batteryPrefix . formatObjectPath
readDict :: (IsVariant a) => Map Text Variant -> Text -> a -> a
readDict dict key dflt = fromMaybe dflt $ do
variant <- M.lookup key dict
fromVariant variant
readDictIntegral :: Map Text Variant -> Text -> Int32 -> Int
readDictIntegral dict key dflt = fromMaybe (fromIntegral dflt) $ do
v <- M.lookup key dict
case variantType v of
TypeWord8 -> return $ fromIntegral (f v :: Word8)
TypeWord16 -> return $ fromIntegral (f v :: Word16)
TypeWord32 -> return $ fromIntegral (f v :: Word32)
TypeWord64 -> return $ fromIntegral (f v :: Word64)
TypeInt16 -> return $ fromIntegral (f v :: Int16)
TypeInt32 -> return $ fromIntegral (f v :: Int32)
TypeInt64 -> return $ fromIntegral (f v :: Int64)
_ -> Nothing
where
f :: (Num a, IsVariant a) => Variant -> a
f = fromMaybe (fromIntegral dflt) . fromVariant
XXX : Remove this once it is exposed in haskell - dbus
dummyMethodError :: MethodError
dummyMethodError = methodError (Serial 1) $ errorName_ "org.ClientTypeMismatch"
getBatteryInfo :: ObjectPath -> TaffyIO (Either MethodError BatteryInfo)
getBatteryInfo battPath = asks systemDBusClient >>= \client -> lift $ runExceptT $ do
reply <- ExceptT $ getAllProperties client $
(methodCall battPath uPowerDeviceInterfaceName "FakeMethod")
{ methodCallDestination = Just uPowerBusName }
dict <- ExceptT $ return $ maybeToEither dummyMethodError $
listToMaybe (methodReturnBody reply) >>= fromVariant
return $ infoMapToBatteryInfo dict
infoMapToBatteryInfo :: Map Text Variant -> BatteryInfo
infoMapToBatteryInfo dict =
BatteryInfo
{ batteryNativePath = readDict dict "NativePath" ""
, batteryVendor = readDict dict "Vendor" ""
, batteryModel = readDict dict "Model" ""
, batterySerial = readDict dict "Serial" ""
, batteryType = toEnum $ fromIntegral $ readDictIntegral dict "Type" 0
, batteryPowerSupply = readDict dict "PowerSupply" False
, batteryHasHistory = readDict dict "HasHistory" False
, batteryHasStatistics = readDict dict "HasStatistics" False
, batteryOnline = readDict dict "Online" False
, batteryEnergy = readDict dict "Energy" 0.0
, batteryEnergyEmpty = readDict dict "EnergyEmpty" 0.0
, batteryEnergyFull = readDict dict "EnergyFull" 0.0
, batteryEnergyFullDesign = readDict dict "EnergyFullDesign" 0.0
, batteryEnergyRate = readDict dict "EnergyRate" 0.0
, batteryVoltage = readDict dict "Voltage" 0.0
, batteryTimeToEmpty = readDict dict "TimeToEmpty" 0
, batteryTimeToFull = readDict dict "TimeToFull" 0
, batteryPercentage = readDict dict "Percentage" 0.0
, batteryIsPresent = readDict dict "IsPresent" False
, batteryState = toEnum $ readDictIntegral dict "State" 0
, batteryIsRechargeable = readDict dict "IsRechargable" True
, batteryCapacity = readDict dict "Capacity" 0.0
, batteryTechnology =
toEnum $ fromIntegral $ readDictIntegral dict "Technology" 0
, batteryUpdateTime = readDict dict "UpdateTime" 0
, batteryLuminosity = readDict dict "Luminosity" 0.0
, batteryTemperature = readDict dict "Temperature" 0.0
, batteryWarningLevel = readDict dict "WarningLevel" 0
, batteryBatteryLevel = readDict dict "BatteryLevel" 0
, batteryIconName = readDict dict "IconName" ""
}
getBatteryPaths :: TaffyIO (Either MethodError [ObjectPath])
getBatteryPaths = do
client <- asks systemDBusClient
liftIO $ runExceptT $ do
paths <- ExceptT $ enumerateDevices client
return $ filter isBattery paths
newtype DisplayBatteryChanVar =
DisplayBatteryChanVar (BroadcastChan In BatteryInfo, MVar BatteryInfo)
getDisplayBatteryInfo :: TaffyIO BatteryInfo
getDisplayBatteryInfo = do
DisplayBatteryChanVar (_, theVar) <- getDisplayBatteryChanVar
lift $ readMVar theVar
defaultMonitorDisplayBatteryProperties :: [String]
defaultMonitorDisplayBatteryProperties = [ "IconName", "State", "Percentage" ]
setupDisplayBatteryChanVar :: [String] -> TaffyIO DisplayBatteryChanVar
setupDisplayBatteryChanVar properties = getStateDefault $
DisplayBatteryChanVar <$> monitorDisplayBattery properties
getDisplayBatteryChanVar :: TaffyIO DisplayBatteryChanVar
getDisplayBatteryChanVar =
setupDisplayBatteryChanVar defaultMonitorDisplayBatteryProperties
getDisplayBatteryChan :: TaffyIO (BroadcastChan In BatteryInfo)
getDisplayBatteryChan = do
DisplayBatteryChanVar (chan, _) <- getDisplayBatteryChanVar
return chan
updateBatteryInfo
:: BroadcastChan In BatteryInfo
-> MVar BatteryInfo
-> ObjectPath
-> TaffyIO ()
updateBatteryInfo chan var path =
getBatteryInfo path >>= lift . either warnOfFailure doWrites
where
doWrites info =
batteryLogF DEBUG "Writing info %s" info >>
swapMVar var info >> void (writeBChan chan info)
warnOfFailure = batteryLogF WARNING "Failed to update battery info %s"
registerForAnyUPowerPropertiesChanged
:: (Signal -> String -> Map String Variant -> [String] -> IO ())
-> ReaderT Context IO SignalHandler
registerForAnyUPowerPropertiesChanged = registerForUPowerPropertyChanges []
registerForUPowerPropertyChanges
:: [String]
-> (Signal -> String -> Map String Variant -> [String] -> IO ())
-> ReaderT Context IO SignalHandler
registerForUPowerPropertyChanges properties signalHandler = do
client <- asks systemDBusClient
lift $ DBus.registerForPropertiesChanged
client
matchAny { matchInterface = Just uPowerDeviceInterfaceName }
handleIfPropertyMatches
where handleIfPropertyMatches rawSignal n propertiesMap l =
let propertyPresent prop = isJust $ M.lookup prop propertiesMap
in when (any propertyPresent properties || null properties) $
signalHandler rawSignal n propertiesMap l
| Monitor the DisplayDevice for changes , writing a new " BatteryInfo " object
to returned " MVar " and " " objects
monitorDisplayBattery ::
[String] -> TaffyIO (BroadcastChan In BatteryInfo, MVar BatteryInfo)
monitorDisplayBattery propertiesToMonitor = do
lift $ batteryLog DEBUG "Starting Battery Monitor"
client <- asks systemDBusClient
infoVar <- lift $ newMVar $ infoMapToBatteryInfo M.empty
chan <- newBroadcastChan
taffyFork $ do
ctx <- ask
let warnOfFailedGetDevice err =
batteryLogF WARNING "Failure getting DisplayBattery: %s" err >>
return "/org/freedesktop/UPower/devices/DisplayDevice"
displayPath <- lift $ getDisplayDevice client >>=
either warnOfFailedGetDevice return
let doUpdate = updateBatteryInfo chan infoVar displayPath
signalCallback _ _ changedProps _ =
do
batteryLogF DEBUG "Battery changed properties: %s" changedProps
runReaderT doUpdate ctx
_ <- registerForUPowerPropertyChanges propertiesToMonitor signalCallback
doUpdate
return ()
return (chan, infoVar)
| Call " refreshAllBatteries " whenever the BatteryInfo for the DisplayDevice
refreshBatteriesOnPropChange :: TaffyIO ()
refreshBatteriesOnPropChange = ask >>= \ctx ->
let updateIfRealChange _ _ changedProps _ =
flip runReaderT ctx $
when (any ((`notElem` ["UpdateTime", "Voltage"]) . fst) $
M.toList changedProps) $
lift (threadDelay 1000000) >> refreshAllBatteries
in void $ registerForAnyUPowerPropertiesChanged updateIfRealChange
| Request a refresh of all UPower batteries . This is only needed if UPower 's
refreshAllBatteries :: TaffyIO ()
refreshAllBatteries = do
client <- asks systemDBusClient
let doRefresh path =
batteryLogF DEBUG "Refreshing battery: %s" path >> refresh client path
eerror <- runExceptT $ ExceptT getBatteryPaths >>= liftIO . mapM doRefresh
let logRefreshError = batteryLogF ERROR "Failed to refresh battery: %s"
logGetPathsError = batteryLogF ERROR "Failed to get battery paths %s"
void $ either logGetPathsError (mapM_ $ either logRefreshError return) eerror
|
0043268e428281c148caecc9784ef98b7b7f45f1ac2347aaee046e893c31ee62 | francescoc/erlangprogramming | dist.erl | %% Code from
%% Erlang Programming
and
O'Reilly , 2008
%% /
/
( c ) and
-module(dist).
-export([t/1]).
t(From) -> From ! node().
| null | https://raw.githubusercontent.com/francescoc/erlangprogramming/b4c39cbebe6599f23eb9d1a052316baf75e40a47/chapter11/dist.erl | erlang | Code from
Erlang Programming
/ | and
O'Reilly , 2008
/
( c ) and
-module(dist).
-export([t/1]).
t(From) -> From ! node().
|
6ffe5ddf996a63fb5c3f8569d65bc9efc2774889e1015fd3a9bd7a0c02fbab5e | timbod7/haskell-chart | example1.hs | import Graphics.Rendering.Chart
import Data.Colour
import Data.Colour.Names
import Data.Default.Class
import Graphics.Rendering.Chart.Backend.Cairo
import Control.Lens
setLinesBlue :: PlotLines a b -> PlotLines a b
setLinesBlue = plot_lines_style . line_color .~ opaque blue
chart = toRenderable layout
where
am :: Double -> Double
am x = (sin (x*3.14159/45) + 1) / 2 * (sin (x*3.14159/5))
sinusoid1 = plot_lines_values .~ [[ (x,(am x)) | x <- [0,(0.5)..400]]]
$ plot_lines_style . line_color .~ opaque blue
$ plot_lines_title .~ "am"
$ def
sinusoid2 = plot_points_style .~ filledCircles 2 (opaque green)
$ plot_points_values .~ [ (x,(am x)) | x <- [0,7..400]]
$ plot_points_title .~ "am points"
$ def
layout = layout_title .~ "Amplitude Modulation"
$ layout_plots .~ [toPlot sinusoid1,
toPlot sinusoid2]
$ def
main = renderableToFile def "example1_big.png" chart
| null | https://raw.githubusercontent.com/timbod7/haskell-chart/8c5a823652ea1b4ec2adbced4a92a8161065ead6/wiki-examples/example1.hs | haskell | import Graphics.Rendering.Chart
import Data.Colour
import Data.Colour.Names
import Data.Default.Class
import Graphics.Rendering.Chart.Backend.Cairo
import Control.Lens
setLinesBlue :: PlotLines a b -> PlotLines a b
setLinesBlue = plot_lines_style . line_color .~ opaque blue
chart = toRenderable layout
where
am :: Double -> Double
am x = (sin (x*3.14159/45) + 1) / 2 * (sin (x*3.14159/5))
sinusoid1 = plot_lines_values .~ [[ (x,(am x)) | x <- [0,(0.5)..400]]]
$ plot_lines_style . line_color .~ opaque blue
$ plot_lines_title .~ "am"
$ def
sinusoid2 = plot_points_style .~ filledCircles 2 (opaque green)
$ plot_points_values .~ [ (x,(am x)) | x <- [0,7..400]]
$ plot_points_title .~ "am points"
$ def
layout = layout_title .~ "Amplitude Modulation"
$ layout_plots .~ [toPlot sinusoid1,
toPlot sinusoid2]
$ def
main = renderableToFile def "example1_big.png" chart
|
|
a81b39a877187f17baef1df3f3d16ae6b21cfc2f70c17bae755e74daaea8250c | valmirjunior0088/curios | Module.hs | module WebAssembly.Syntax.Module
( magic
, version
, CustomSec (..)
, customSecId
, TypeSec (..)
, typeSecId
, ImportDesc (..)
, Import (..)
, ImportSec (..)
, importSecId
, FuncSec (..)
, funcSecId
, Table (..)
, TableSec (..)
, tableSecId
, Mem (..)
, MemSec (..)
, memSecId
, Global (..)
, GlobalSec (..)
, globalSecId
, ExportDesc (..)
, Export (..)
, ExportSec (..)
, exportSecId
, Start (..)
, StartSec (..)
, startSecId
, ElemKind (..)
, Elem (..)
, ElemSec (..)
, elemSecId
, Locals (..)
, Func (..)
, Code (..)
, CodeSec (..)
, codeSecId
, Data (..)
, DataSec (..)
, dataSecId
, DataCountSec (..)
, dataCountSecId
, Module (..)
, emptyModule
)
where
import WebAssembly.Syntax.Conventions (TypeIdx, FuncIdx, TableIdx, MemIdx, GlobalIdx, Vec, Name)
import WebAssembly.Syntax.Types (ValType, FuncType, TableType, MemType, GlobalType)
import WebAssembly.Syntax.Instructions (Expr)
import WebAssembly.Syntax.LLVM (RelocEntry, SymInfo)
import Data.Word (Word8, Word32)
import GHC.Generics (Generic)
magic :: String
magic = "\0asm"
version :: Word32
version = 1
data CustomSec =
CustomSec Name [Word8]
deriving (Show)
customSecId :: Word8
customSecId = 0
newtype TypeSec =
TypeSec (Vec FuncType)
deriving (Show)
typeSecId :: Word8
typeSecId = 1
data ImportDesc =
ImportFunc TypeIdx |
ImportTable TableType |
ImportMem MemType |
ImportGlobal GlobalType
deriving (Show)
data Import =
Import Name Name ImportDesc
deriving (Show)
newtype ImportSec =
ImportSec (Vec Import)
deriving (Show)
importSecId :: Word8
importSecId = 2
newtype FuncSec =
FuncSec (Vec TypeIdx)
deriving (Show)
funcSecId :: Word8
funcSecId = 3
newtype Table =
Table TableType
deriving (Show)
newtype TableSec =
TableSec (Vec Table)
deriving (Show)
tableSecId :: Word8
tableSecId = 4
newtype Mem =
Mem MemType
deriving (Show)
newtype MemSec =
MemSec (Vec Mem)
deriving (Show)
memSecId :: Word8
memSecId = 5
data Global =
Global GlobalType Expr
deriving (Show)
newtype GlobalSec =
GlobalSec (Vec Global)
deriving (Show)
globalSecId :: Word8
globalSecId = 6
data ExportDesc =
ExportFunc FuncIdx |
ExportTable TableIdx |
ExportMem MemIdx |
ExportGlobal GlobalIdx
deriving (Show)
data Export =
Export Name ExportDesc
deriving (Show)
newtype ExportSec =
ExportSec (Vec Export)
deriving (Show)
exportSecId :: Word8
exportSecId = 7
newtype Start =
Start FuncIdx
deriving (Show)
newtype StartSec =
StartSec Start
deriving (Show)
startSecId :: Word8
startSecId = 8
data ElemKind =
ElemFuncRef
deriving (Show)
data Elem =
Elem TableIdx Expr ElemKind (Vec FuncIdx)
deriving (Show)
newtype ElemSec =
ElemSec (Vec Elem)
deriving (Show)
elemSecId :: Word8
elemSecId = 9
data Locals =
Locals Word32 ValType
deriving (Show)
data Func =
Func (Vec Locals) Expr
deriving (Show)
newtype Code =
Code Func
deriving (Show)
newtype CodeSec =
CodeSec (Vec Code)
deriving (Show)
codeSecId :: Word8
codeSecId = 10
data Data =
Data Expr (Vec Word8) [RelocEntry]
deriving (Show)
newtype DataSec =
DataSec (Vec Data)
deriving (Show)
dataSecId :: Word8
dataSecId = 11
newtype DataCountSec =
DataCountSec Word32
deriving (Show)
dataCountSecId :: Word8
dataCountSecId = 12
data Module = Module
{ typeSec :: [FuncType]
, importSec :: [Import]
, funcSec :: [TypeIdx]
, tableSec :: [Table]
, memSec :: [Mem]
, globalSec :: [Global]
, exportSec :: [Export]
, startSec :: Maybe FuncIdx
, elemSec :: [Elem]
, codeSec :: [Code]
, dataSec :: [Data]
, linkingSec :: [SymInfo]
}
deriving (Show, Generic)
emptyModule :: Module
emptyModule = Module
{ typeSec = []
, importSec = []
, funcSec = []
, tableSec = []
, memSec = []
, globalSec = []
, exportSec = []
, startSec = Nothing
, elemSec = []
, codeSec = []
, dataSec = []
, linkingSec = []
}
| null | https://raw.githubusercontent.com/valmirjunior0088/curios/391bebe67d5e7a4c3d51c758da9ba96b38c11705/src/WebAssembly/Syntax/Module.hs | haskell | module WebAssembly.Syntax.Module
( magic
, version
, CustomSec (..)
, customSecId
, TypeSec (..)
, typeSecId
, ImportDesc (..)
, Import (..)
, ImportSec (..)
, importSecId
, FuncSec (..)
, funcSecId
, Table (..)
, TableSec (..)
, tableSecId
, Mem (..)
, MemSec (..)
, memSecId
, Global (..)
, GlobalSec (..)
, globalSecId
, ExportDesc (..)
, Export (..)
, ExportSec (..)
, exportSecId
, Start (..)
, StartSec (..)
, startSecId
, ElemKind (..)
, Elem (..)
, ElemSec (..)
, elemSecId
, Locals (..)
, Func (..)
, Code (..)
, CodeSec (..)
, codeSecId
, Data (..)
, DataSec (..)
, dataSecId
, DataCountSec (..)
, dataCountSecId
, Module (..)
, emptyModule
)
where
import WebAssembly.Syntax.Conventions (TypeIdx, FuncIdx, TableIdx, MemIdx, GlobalIdx, Vec, Name)
import WebAssembly.Syntax.Types (ValType, FuncType, TableType, MemType, GlobalType)
import WebAssembly.Syntax.Instructions (Expr)
import WebAssembly.Syntax.LLVM (RelocEntry, SymInfo)
import Data.Word (Word8, Word32)
import GHC.Generics (Generic)
magic :: String
magic = "\0asm"
version :: Word32
version = 1
data CustomSec =
CustomSec Name [Word8]
deriving (Show)
customSecId :: Word8
customSecId = 0
newtype TypeSec =
TypeSec (Vec FuncType)
deriving (Show)
typeSecId :: Word8
typeSecId = 1
data ImportDesc =
ImportFunc TypeIdx |
ImportTable TableType |
ImportMem MemType |
ImportGlobal GlobalType
deriving (Show)
data Import =
Import Name Name ImportDesc
deriving (Show)
newtype ImportSec =
ImportSec (Vec Import)
deriving (Show)
importSecId :: Word8
importSecId = 2
newtype FuncSec =
FuncSec (Vec TypeIdx)
deriving (Show)
funcSecId :: Word8
funcSecId = 3
newtype Table =
Table TableType
deriving (Show)
newtype TableSec =
TableSec (Vec Table)
deriving (Show)
tableSecId :: Word8
tableSecId = 4
newtype Mem =
Mem MemType
deriving (Show)
newtype MemSec =
MemSec (Vec Mem)
deriving (Show)
memSecId :: Word8
memSecId = 5
data Global =
Global GlobalType Expr
deriving (Show)
newtype GlobalSec =
GlobalSec (Vec Global)
deriving (Show)
globalSecId :: Word8
globalSecId = 6
data ExportDesc =
ExportFunc FuncIdx |
ExportTable TableIdx |
ExportMem MemIdx |
ExportGlobal GlobalIdx
deriving (Show)
data Export =
Export Name ExportDesc
deriving (Show)
newtype ExportSec =
ExportSec (Vec Export)
deriving (Show)
exportSecId :: Word8
exportSecId = 7
newtype Start =
Start FuncIdx
deriving (Show)
newtype StartSec =
StartSec Start
deriving (Show)
startSecId :: Word8
startSecId = 8
data ElemKind =
ElemFuncRef
deriving (Show)
data Elem =
Elem TableIdx Expr ElemKind (Vec FuncIdx)
deriving (Show)
newtype ElemSec =
ElemSec (Vec Elem)
deriving (Show)
elemSecId :: Word8
elemSecId = 9
data Locals =
Locals Word32 ValType
deriving (Show)
data Func =
Func (Vec Locals) Expr
deriving (Show)
newtype Code =
Code Func
deriving (Show)
newtype CodeSec =
CodeSec (Vec Code)
deriving (Show)
codeSecId :: Word8
codeSecId = 10
data Data =
Data Expr (Vec Word8) [RelocEntry]
deriving (Show)
newtype DataSec =
DataSec (Vec Data)
deriving (Show)
dataSecId :: Word8
dataSecId = 11
newtype DataCountSec =
DataCountSec Word32
deriving (Show)
dataCountSecId :: Word8
dataCountSecId = 12
data Module = Module
{ typeSec :: [FuncType]
, importSec :: [Import]
, funcSec :: [TypeIdx]
, tableSec :: [Table]
, memSec :: [Mem]
, globalSec :: [Global]
, exportSec :: [Export]
, startSec :: Maybe FuncIdx
, elemSec :: [Elem]
, codeSec :: [Code]
, dataSec :: [Data]
, linkingSec :: [SymInfo]
}
deriving (Show, Generic)
emptyModule :: Module
emptyModule = Module
{ typeSec = []
, importSec = []
, funcSec = []
, tableSec = []
, memSec = []
, globalSec = []
, exportSec = []
, startSec = Nothing
, elemSec = []
, codeSec = []
, dataSec = []
, linkingSec = []
}
|
|
ebb741407200f95f0045b8a93c06b8e42900971afaf396fd7fa373db93770d17 | antono/guix-debian | mc.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 < >
;;;
;;; 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 (gnu packages mc)
#:use-module (guix packages)
#:use-module (guix licenses)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (gnu packages aspell)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages glib)
#:use-module (gnu packages ssh)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages check)
#:use-module (gnu packages file)
#:use-module (gnu packages perl))
(define-public mc
(package
(name "mc")
(version "4.8.11")
(source
(origin
(method url-fetch)
(uri (string-append "-commander.org/mc-"
version ".tar.xz"))
(sha256
(base32
"0flrw5pq2mg2d39bh6dllndhpcfppjza6g70p4ry2wcx9y2flxqq"))
(patches (list (search-patch "mc-fix-ncurses-build.patch")))))
(build-system gnu-build-system)
(native-inputs `(("pkg-config" ,pkg-config)
("file" ,file)
("perl" ,perl)))
(inputs `(("aspell" ,aspell)
("ncurses" ,ncurses)
("libssh2" ,libssh2)
("glib" ,glib)
("check" ,check)))
(arguments
`(#:configure-flags
'("--with-screen=ncurses" "--enable-aspell")
#:phases
(alist-cons-before
'configure 'patch-configure
(lambda _
(substitute* "configure"
(("/usr/bin/file") (which "file"))))
%standard-phases)))
(home-page "-commander.org")
(synopsis "Graphical file manager")
(description
"GNU Midnight Commander is a command-line file manager laid out in a
common two-pane format. In addition to standard file management tasks such as
copying and moving, Midnight Commander also supports viewing the contents of
RPM package files and other archives and managing files on other computers via
FTP or FISH. It also includes a powerful text editor for opening text
files.")
(license gpl2)))
| null | https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/mc.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.
| Copyright © 2014 < >
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 (gnu packages mc)
#:use-module (guix packages)
#:use-module (guix licenses)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (gnu packages aspell)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages glib)
#:use-module (gnu packages ssh)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages check)
#:use-module (gnu packages file)
#:use-module (gnu packages perl))
(define-public mc
(package
(name "mc")
(version "4.8.11")
(source
(origin
(method url-fetch)
(uri (string-append "-commander.org/mc-"
version ".tar.xz"))
(sha256
(base32
"0flrw5pq2mg2d39bh6dllndhpcfppjza6g70p4ry2wcx9y2flxqq"))
(patches (list (search-patch "mc-fix-ncurses-build.patch")))))
(build-system gnu-build-system)
(native-inputs `(("pkg-config" ,pkg-config)
("file" ,file)
("perl" ,perl)))
(inputs `(("aspell" ,aspell)
("ncurses" ,ncurses)
("libssh2" ,libssh2)
("glib" ,glib)
("check" ,check)))
(arguments
`(#:configure-flags
'("--with-screen=ncurses" "--enable-aspell")
#:phases
(alist-cons-before
'configure 'patch-configure
(lambda _
(substitute* "configure"
(("/usr/bin/file") (which "file"))))
%standard-phases)))
(home-page "-commander.org")
(synopsis "Graphical file manager")
(description
"GNU Midnight Commander is a command-line file manager laid out in a
common two-pane format. In addition to standard file management tasks such as
copying and moving, Midnight Commander also supports viewing the contents of
RPM package files and other archives and managing files on other computers via
FTP or FISH. It also includes a powerful text editor for opening text
files.")
(license gpl2)))
|
b1d168a06a98bc7b8748c416282b729f8f60d5ff8fbf836745a40fb3856f64e3 | cartazio/tlaps | m_flatten.mli |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
open M_t;;
val flatten :
modctx -> mule -> Util.Coll.Ss.t -> (mule_ Property.wrapped * Util.Coll.Ss.t)
;;
| null | https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/module/m_flatten.mli | ocaml |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
open M_t;;
val flatten :
modctx -> mule -> Util.Coll.Ss.t -> (mule_ Property.wrapped * Util.Coll.Ss.t)
;;
|
|
eddefacdf8d4f5bb4b85288484680d301445f458a8b5c3b31babd10e2a6996b7 | exercism/common-lisp | example.lisp | (defpackage :space-age
(:use :common-lisp))
(in-package :space-age)
(defvar +earth-period+ 31557600)
(defvar +planets-and-periods+
`((:mercury ,(* 0.2408467 +earth-period+))
(:venus ,(* 0.61519726 +earth-period+))
(:earth ,(* 1 +earth-period+))
(:mars ,(* 1.8808158 +earth-period+))
(:jupiter ,(* 11.862615 +earth-period+))
(:saturn ,(* 29.447498 +earth-period+))
(:uranus ,(* 84.016846 +earth-period+))
(:neptune ,(* 164.79132 +earth-period+))))
(dolist (planet-info +planets-and-periods+)
(let ((name (first planet-info))
(period (second planet-info)))
(let ((symbol (intern (string-upcase
(concatenate 'string
"on-"
(string name))))))
(setf (symbol-function symbol)
#'(lambda (seconds) (/ seconds period)))
(export symbol))))
| null | https://raw.githubusercontent.com/exercism/common-lisp/0bb38d1b126f7dc90d86f04c41479d4eaf35df74/exercises/practice/space-age/.meta/example.lisp | lisp | (defpackage :space-age
(:use :common-lisp))
(in-package :space-age)
(defvar +earth-period+ 31557600)
(defvar +planets-and-periods+
`((:mercury ,(* 0.2408467 +earth-period+))
(:venus ,(* 0.61519726 +earth-period+))
(:earth ,(* 1 +earth-period+))
(:mars ,(* 1.8808158 +earth-period+))
(:jupiter ,(* 11.862615 +earth-period+))
(:saturn ,(* 29.447498 +earth-period+))
(:uranus ,(* 84.016846 +earth-period+))
(:neptune ,(* 164.79132 +earth-period+))))
(dolist (planet-info +planets-and-periods+)
(let ((name (first planet-info))
(period (second planet-info)))
(let ((symbol (intern (string-upcase
(concatenate 'string
"on-"
(string name))))))
(setf (symbol-function symbol)
#'(lambda (seconds) (/ seconds period)))
(export symbol))))
|
|
8a501a606f8621853918fce924cdccb2406e72daf218aa15e57026cd455a30ea | racket/gui | info.rkt | #lang info
(define version '(400))
(define install-collection "installer.rkt")
(define copy-man-pages '("mred.1"))
(define release-note-files
'(("GRacket and racket/gui" "HISTORY.txt"
0
(("Porting from v5.0.x to v5.1" "Draw_and_GUI_5_1.txt")
("Porting to v1xxx" "MrEd_100.txt")
("Porting to v1xxx" "MrEd_100_Framework.txt")))))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mred/info.rkt | racket | #lang info
(define version '(400))
(define install-collection "installer.rkt")
(define copy-man-pages '("mred.1"))
(define release-note-files
'(("GRacket and racket/gui" "HISTORY.txt"
0
(("Porting from v5.0.x to v5.1" "Draw_and_GUI_5_1.txt")
("Porting to v1xxx" "MrEd_100.txt")
("Porting to v1xxx" "MrEd_100_Framework.txt")))))
|
|
6d0f13e4da2cf84f2602bde29189ae242cd379afc6a5dea3a074654977a6e50f | facebook/duckling | Rules.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
module Duckling.AmountOfMoney.EN.Rules
( rules
) where
import Data.Maybe
import Data.String
import Prelude
import qualified Data.Text as Text
import Duckling.AmountOfMoney.Helpers
import Duckling.AmountOfMoney.Types (Currency(..), AmountOfMoneyData (..))
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers (isNatural, isPositive)
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.AmountOfMoney.Types as TAmountOfMoney
import qualified Duckling.Numeral.Types as TNumeral
ruleUnitAmount :: Rule
ruleUnitAmount = Rule
{ name = "<unit> <amount>"
, pattern =
[ Predicate isCurrencyOnly
, Predicate isPositive
]
, prod = \case
(Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.currency = c}:
Token Numeral NumeralData{TNumeral.value = v}:
_) -> Just . Token AmountOfMoney . withValue v $ currencyOnly c
_ -> Nothing
}
rulePounds :: Rule
rulePounds = Rule
{ name = "£"
, pattern =
[ regex "pounds?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly Pound
}
ruleOtherPounds :: Rule
ruleOtherPounds = Rule
{ name = "other pounds"
, pattern =
[ regex "(egyptian|lebanese) ?pounds?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"egyptian" -> Just . Token AmountOfMoney $ currencyOnly EGP
"lebanese" -> Just . Token AmountOfMoney $ currencyOnly LBP
_ -> Nothing
_ -> Nothing
}
ruleEgpAbrreviation :: Rule
ruleEgpAbrreviation = Rule
{ name = "livre égyptienne"
, pattern =
[ regex "[lL].?[eE].?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly EGP
}
ruleEgpArabizi :: Rule
ruleEgpArabizi = Rule
{ name = "geneh"
, pattern =
[ regex "[Gg][eiy]*n[eiy]*h(at)?( m[aiey]?sr[eiy]+a?)?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly EGP
}
ruleRiyals :: Rule
ruleRiyals = Rule
{ name = "riyals"
, pattern =
[ regex "(qatari|saudi) ?riyals?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"qatari" -> Just . Token AmountOfMoney $ currencyOnly QAR
"saudi" -> Just . Token AmountOfMoney $ currencyOnly SAR
_ -> Nothing
_ -> Nothing
}
ruleDinars :: Rule
ruleDinars = Rule
{ name = "dinars"
, pattern =
[ regex "(kuwaiti) ?dinars?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"kuwaiti" -> Just . Token AmountOfMoney $ currencyOnly KWD
_ -> Nothing
_ -> Nothing
}
ruleDirham :: Rule
ruleDirham = Rule
{ name = "dirham"
, pattern =
[ regex "dirhams?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly AED
}
ruleRinggit :: Rule
ruleRinggit = Rule
{ name = "ringgit"
, pattern =
[ regex "(malaysian? )?ringgits?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly MYR
}
ruleHryvnia :: Rule
ruleHryvnia = Rule
{ name = "hryvnia"
, pattern =
[ regex "hryvnia" -- TODO: complete
]
, prod = \_ -> Just $ Token AmountOfMoney $ currencyOnly UAH
}
ruleCent :: Rule
ruleCent = Rule
{ name = "cent"
, pattern =
[ regex "cents?|penn(y|ies)|pence|sens?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly Cent
}
ruleKopiyka :: Rule
ruleKopiyka = Rule
{ name = "kopiyka"
, pattern =
[ regex "kopiy(ok|kas?)"
]
, prod = \_ -> Just $ Token AmountOfMoney $ currencyOnly Cent
}
ruleBucks :: Rule
ruleBucks = Rule
{ name = "bucks"
, pattern =
[ regex "bucks?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly Unnamed
}
ruleACurrency :: Rule
ruleACurrency = Rule
{ name = "a <currency>"
, pattern =
[ regex "an?"
, Predicate isCurrencyOnly
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney fd:
_) -> Just . Token AmountOfMoney $ fd {TAmountOfMoney.value = Just 1}
_ -> Nothing
}
ruleAbsorbA :: Rule
ruleAbsorbA = Rule
{ name = "a <amount-of-money>"
, pattern =
[ regex "an?"
, Predicate isSimpleAmountOfMoney
]
, prod = \case
(_:Token AmountOfMoney fd:_) -> Just $ Token AmountOfMoney fd
_ -> Nothing
}
ruleADollarCoin :: Rule
ruleADollarCoin = Rule
{ name = "a <dollar coin>"
, pattern =
[ regex "an?"
, Predicate isDollarCoin
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney fd:
_) -> Just . Token AmountOfMoney $ fd
_ -> Nothing
}
ruleNumDollarCoins :: Rule
ruleNumDollarCoins = Rule
{ name = "X <dollar coins>"
, pattern =
[ Predicate isNatural
, Predicate isDollarCoin
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = c}:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just d,
TAmountOfMoney.currency = cur}:
_) -> Just . Token AmountOfMoney $ withValue (c * d) $ currencyOnly cur
_ -> Nothing
}
ruleIntersectAndXCents :: Rule
ruleIntersectAndXCents = Rule
{ name = "intersect (and X cents)"
, pattern =
[ Predicate isWithoutCents
, regex "and"
, Predicate isCents
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
ruleIntersect :: Rule
ruleIntersect = Rule
{ name = "intersect"
, pattern =
[ Predicate isWithoutCents
, Predicate isNatural
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
Token Numeral NumeralData{TNumeral.value = c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
ruleIntersectAndNumeral :: Rule
ruleIntersectAndNumeral = Rule
{ name = "intersect (and number)"
, pattern =
[ Predicate isWithoutCents
, regex "and"
, Predicate isNatural
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
_:
Token Numeral NumeralData{TNumeral.value = c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
ruleIntersectXCents :: Rule
ruleIntersectXCents = Rule
{ name = "intersect (X cents)"
, pattern =
[ Predicate isWithoutCents
, Predicate isCents
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
rulePrecision :: Rule
rulePrecision = Rule
{ name = "about|exactly <amount-of-money>"
, pattern =
[ regex "exactly|precisely|about|approx(\\.|imately)?|close to|near( to)?|around|almost"
, Predicate isMoneyWithValue
]
, prod = \tokens -> case tokens of
(_:token:_) -> Just token
_ -> Nothing
}
ruleIntervalBetweenNumeral :: Rule
ruleIntervalBetweenNumeral = Rule
{ name = "between|from <numeral> to|and <amount-of-money>"
, pattern =
[ regex "between|from"
, Predicate isPositive
, regex "to|and"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token Numeral NumeralData{TNumeral.value = from}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) | from < to ->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c
_ -> Nothing
}
ruleIntervalBetween :: Rule
ruleIntervalBetween = Rule
{ name = "between|from <amount-of-money> to|and <amount-of-money>"
, pattern =
[ regex "between|from"
, Predicate isSimpleAmountOfMoney
, regex "to|and"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just from,
TAmountOfMoney.currency = c1}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c2}:
_) | from < to && c1 == c2 ->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c1
_ -> Nothing
}
ruleIntervalNumeralDash :: Rule
ruleIntervalNumeralDash = Rule
{ name = "<numeral> - <amount-of-money>"
, pattern =
[ Predicate isNatural
, regex "-"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = from}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) | from < to->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c
_ -> Nothing
}
ruleIntervalDash :: Rule
ruleIntervalDash = Rule
{ name = "<amount-of-money> - <amount-of-money>"
, pattern =
[ Predicate isSimpleAmountOfMoney
, regex "-"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just from,
TAmountOfMoney.currency = c1}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c2}:
_) | from < to && c1 == c2 ->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c1
_ -> Nothing
}
ruleIntervalMax :: Rule
ruleIntervalMax = Rule
{ name = "under/less/lower/no more than <amount-of-money>"
, pattern =
[ regex "under|at most|(less|lower|not? more) than"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) -> Just . Token AmountOfMoney . withMax to $ currencyOnly c
_ -> Nothing
}
ruleIntervalMin :: Rule
ruleIntervalMin = Rule
{ name = "over/above/at least/more than <amount-of-money>"
, pattern =
[ regex "over|above|at least|(more|not? less) than"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) -> Just . Token AmountOfMoney . withMin to $ currencyOnly c
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleUnitAmount
, ruleACurrency
, ruleAbsorbA
, ruleBucks
, ruleCent
, ruleADollarCoin
, ruleNumDollarCoins
, ruleDinars
, ruleDirham
, ruleHryvnia
, ruleIntersect
, ruleIntersectAndNumeral
, ruleIntersectAndXCents
, ruleIntersectXCents
, ruleIntervalBetweenNumeral
, ruleIntervalBetween
, ruleIntervalMax
, ruleIntervalMin
, ruleIntervalNumeralDash
, ruleIntervalDash
, ruleKopiyka
, ruleOtherPounds
, ruleEgpAbrreviation
, ruleEgpArabizi
, rulePounds
, rulePrecision
, ruleRinggit
, ruleRiyals
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/AmountOfMoney/EN/Rules.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
TODO: complete | Copyright ( c ) 2016 - present , Facebook , Inc.
# LANGUAGE LambdaCase #
module Duckling.AmountOfMoney.EN.Rules
( rules
) where
import Data.Maybe
import Data.String
import Prelude
import qualified Data.Text as Text
import Duckling.AmountOfMoney.Helpers
import Duckling.AmountOfMoney.Types (Currency(..), AmountOfMoneyData (..))
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers (isNatural, isPositive)
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.AmountOfMoney.Types as TAmountOfMoney
import qualified Duckling.Numeral.Types as TNumeral
ruleUnitAmount :: Rule
ruleUnitAmount = Rule
{ name = "<unit> <amount>"
, pattern =
[ Predicate isCurrencyOnly
, Predicate isPositive
]
, prod = \case
(Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.currency = c}:
Token Numeral NumeralData{TNumeral.value = v}:
_) -> Just . Token AmountOfMoney . withValue v $ currencyOnly c
_ -> Nothing
}
rulePounds :: Rule
rulePounds = Rule
{ name = "£"
, pattern =
[ regex "pounds?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly Pound
}
ruleOtherPounds :: Rule
ruleOtherPounds = Rule
{ name = "other pounds"
, pattern =
[ regex "(egyptian|lebanese) ?pounds?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"egyptian" -> Just . Token AmountOfMoney $ currencyOnly EGP
"lebanese" -> Just . Token AmountOfMoney $ currencyOnly LBP
_ -> Nothing
_ -> Nothing
}
ruleEgpAbrreviation :: Rule
ruleEgpAbrreviation = Rule
{ name = "livre égyptienne"
, pattern =
[ regex "[lL].?[eE].?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly EGP
}
ruleEgpArabizi :: Rule
ruleEgpArabizi = Rule
{ name = "geneh"
, pattern =
[ regex "[Gg][eiy]*n[eiy]*h(at)?( m[aiey]?sr[eiy]+a?)?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly EGP
}
ruleRiyals :: Rule
ruleRiyals = Rule
{ name = "riyals"
, pattern =
[ regex "(qatari|saudi) ?riyals?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"qatari" -> Just . Token AmountOfMoney $ currencyOnly QAR
"saudi" -> Just . Token AmountOfMoney $ currencyOnly SAR
_ -> Nothing
_ -> Nothing
}
ruleDinars :: Rule
ruleDinars = Rule
{ name = "dinars"
, pattern =
[ regex "(kuwaiti) ?dinars?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"kuwaiti" -> Just . Token AmountOfMoney $ currencyOnly KWD
_ -> Nothing
_ -> Nothing
}
ruleDirham :: Rule
ruleDirham = Rule
{ name = "dirham"
, pattern =
[ regex "dirhams?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly AED
}
ruleRinggit :: Rule
ruleRinggit = Rule
{ name = "ringgit"
, pattern =
[ regex "(malaysian? )?ringgits?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly MYR
}
ruleHryvnia :: Rule
ruleHryvnia = Rule
{ name = "hryvnia"
, pattern =
]
, prod = \_ -> Just $ Token AmountOfMoney $ currencyOnly UAH
}
ruleCent :: Rule
ruleCent = Rule
{ name = "cent"
, pattern =
[ regex "cents?|penn(y|ies)|pence|sens?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly Cent
}
ruleKopiyka :: Rule
ruleKopiyka = Rule
{ name = "kopiyka"
, pattern =
[ regex "kopiy(ok|kas?)"
]
, prod = \_ -> Just $ Token AmountOfMoney $ currencyOnly Cent
}
ruleBucks :: Rule
ruleBucks = Rule
{ name = "bucks"
, pattern =
[ regex "bucks?"
]
, prod = \_ -> Just . Token AmountOfMoney $ currencyOnly Unnamed
}
ruleACurrency :: Rule
ruleACurrency = Rule
{ name = "a <currency>"
, pattern =
[ regex "an?"
, Predicate isCurrencyOnly
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney fd:
_) -> Just . Token AmountOfMoney $ fd {TAmountOfMoney.value = Just 1}
_ -> Nothing
}
ruleAbsorbA :: Rule
ruleAbsorbA = Rule
{ name = "a <amount-of-money>"
, pattern =
[ regex "an?"
, Predicate isSimpleAmountOfMoney
]
, prod = \case
(_:Token AmountOfMoney fd:_) -> Just $ Token AmountOfMoney fd
_ -> Nothing
}
ruleADollarCoin :: Rule
ruleADollarCoin = Rule
{ name = "a <dollar coin>"
, pattern =
[ regex "an?"
, Predicate isDollarCoin
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney fd:
_) -> Just . Token AmountOfMoney $ fd
_ -> Nothing
}
ruleNumDollarCoins :: Rule
ruleNumDollarCoins = Rule
{ name = "X <dollar coins>"
, pattern =
[ Predicate isNatural
, Predicate isDollarCoin
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = c}:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just d,
TAmountOfMoney.currency = cur}:
_) -> Just . Token AmountOfMoney $ withValue (c * d) $ currencyOnly cur
_ -> Nothing
}
ruleIntersectAndXCents :: Rule
ruleIntersectAndXCents = Rule
{ name = "intersect (and X cents)"
, pattern =
[ Predicate isWithoutCents
, regex "and"
, Predicate isCents
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
ruleIntersect :: Rule
ruleIntersect = Rule
{ name = "intersect"
, pattern =
[ Predicate isWithoutCents
, Predicate isNatural
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
Token Numeral NumeralData{TNumeral.value = c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
ruleIntersectAndNumeral :: Rule
ruleIntersectAndNumeral = Rule
{ name = "intersect (and number)"
, pattern =
[ Predicate isWithoutCents
, regex "and"
, Predicate isNatural
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
_:
Token Numeral NumeralData{TNumeral.value = c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
ruleIntersectXCents :: Rule
ruleIntersectXCents = Rule
{ name = "intersect (X cents)"
, pattern =
[ Predicate isWithoutCents
, Predicate isCents
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney fd:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just c}:
_) -> Just . Token AmountOfMoney $ withCents c fd
_ -> Nothing
}
rulePrecision :: Rule
rulePrecision = Rule
{ name = "about|exactly <amount-of-money>"
, pattern =
[ regex "exactly|precisely|about|approx(\\.|imately)?|close to|near( to)?|around|almost"
, Predicate isMoneyWithValue
]
, prod = \tokens -> case tokens of
(_:token:_) -> Just token
_ -> Nothing
}
ruleIntervalBetweenNumeral :: Rule
ruleIntervalBetweenNumeral = Rule
{ name = "between|from <numeral> to|and <amount-of-money>"
, pattern =
[ regex "between|from"
, Predicate isPositive
, regex "to|and"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token Numeral NumeralData{TNumeral.value = from}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) | from < to ->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c
_ -> Nothing
}
ruleIntervalBetween :: Rule
ruleIntervalBetween = Rule
{ name = "between|from <amount-of-money> to|and <amount-of-money>"
, pattern =
[ regex "between|from"
, Predicate isSimpleAmountOfMoney
, regex "to|and"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just from,
TAmountOfMoney.currency = c1}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c2}:
_) | from < to && c1 == c2 ->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c1
_ -> Nothing
}
ruleIntervalNumeralDash :: Rule
ruleIntervalNumeralDash = Rule
{ name = "<numeral> - <amount-of-money>"
, pattern =
[ Predicate isNatural
, regex "-"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = from}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) | from < to->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c
_ -> Nothing
}
ruleIntervalDash :: Rule
ruleIntervalDash = Rule
{ name = "<amount-of-money> - <amount-of-money>"
, pattern =
[ Predicate isSimpleAmountOfMoney
, regex "-"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just from,
TAmountOfMoney.currency = c1}:
_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c2}:
_) | from < to && c1 == c2 ->
Just . Token AmountOfMoney . withInterval (from, to) $ currencyOnly c1
_ -> Nothing
}
ruleIntervalMax :: Rule
ruleIntervalMax = Rule
{ name = "under/less/lower/no more than <amount-of-money>"
, pattern =
[ regex "under|at most|(less|lower|not? more) than"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) -> Just . Token AmountOfMoney . withMax to $ currencyOnly c
_ -> Nothing
}
ruleIntervalMin :: Rule
ruleIntervalMin = Rule
{ name = "over/above/at least/more than <amount-of-money>"
, pattern =
[ regex "over|above|at least|(more|not? less) than"
, Predicate isSimpleAmountOfMoney
]
, prod = \tokens -> case tokens of
(_:
Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to,
TAmountOfMoney.currency = c}:
_) -> Just . Token AmountOfMoney . withMin to $ currencyOnly c
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleUnitAmount
, ruleACurrency
, ruleAbsorbA
, ruleBucks
, ruleCent
, ruleADollarCoin
, ruleNumDollarCoins
, ruleDinars
, ruleDirham
, ruleHryvnia
, ruleIntersect
, ruleIntersectAndNumeral
, ruleIntersectAndXCents
, ruleIntersectXCents
, ruleIntervalBetweenNumeral
, ruleIntervalBetween
, ruleIntervalMax
, ruleIntervalMin
, ruleIntervalNumeralDash
, ruleIntervalDash
, ruleKopiyka
, ruleOtherPounds
, ruleEgpAbrreviation
, ruleEgpArabizi
, rulePounds
, rulePrecision
, ruleRinggit
, ruleRiyals
]
|
663036ab155e1583b35fa1ff5bc61272b44ac9ca06744fbcb440980aa6257a94 | finkel-lang/finkel | bind-pat.hs | Just x = lookup k vs -- Haskell
| null | https://raw.githubusercontent.com/finkel-lang/finkel/c3c7729d5228bd7e0cf76e8ff05fe2f79a0ec0a2/doc/include/language-syntax/decl/bind-pat.hs | haskell | Haskell | |
37c0342c49b431d217cbbc31cfcb38c489a8dead591d44c5868a93a3dad09789 | ocaml-flambda/flambda-backend | to_cmm_expr.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
(* *)
(* Copyright 2019--2019 OCamlPro SAS *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
[@@@ocaml.warning "+a-30-40-41-42"]
open! Flambda.Import
module Env = To_cmm_env
module Ece = Effects_and_coeffects
module K = Flambda_kind
module C = struct
include Cmm_helpers
include Cmm_builtins
include To_cmm_shared
end
(* Note about flushing of environments: this module treats the delayed bindings
in [To_cmm_env] environments (see to_cmm_env.mli for more information) in a
linear manner. Flushes are inserted to preserve this property. This ensures
in particular that effectful bindings get placed exactly once and that other
bindings are not duplicated. *)
Bind a Cmm variable to the result of translating a [ Simple ] into Cmm .
let bind_var_to_simple ~dbg env res v ~num_normal_occurrences_of_bound_vars s =
match Simple.must_be_var s with
| Some (alias_of, _coercion) ->
Env.add_alias env res ~var:v ~num_normal_occurrences_of_bound_vars ~alias_of
| None ->
let To_cmm_env.
{ env;
res;
expr =
{ cmm = defining_expr;
free_vars = free_vars_of_defining_expr;
effs = effects_and_coeffects_of_defining_expr
}
} =
C.simple ~dbg env res s
in
let env, res =
Env.bind_variable env res v ~effects_and_coeffects_of_defining_expr
~defining_expr ~free_vars_of_defining_expr
~num_normal_occurrences_of_bound_vars
in
env, res
(* Helpers for the translation of [Apply] expressions. *)
let translate_apply0 env res apply =
let callee_simple = Apply.callee apply in
let args = Apply.args apply in
let dbg = Apply.dbg apply in
CR mshinwell : When we fix the problem that [ prim_effects ] and
[ prim_coeffects ] are ignored for C calls , we need to take into account the
effects / coeffects values currently ignored on the following two lines . At
the moment they can be ignored as we always deem all calls to have
arbitrary effects and coeffects .
[prim_coeffects] are ignored for C calls, we need to take into account the
effects/coeffects values currently ignored on the following two lines. At
the moment they can be ignored as we always deem all calls to have
arbitrary effects and coeffects. *)
let To_cmm_env.
{ env;
res;
expr = { cmm = callee; free_vars = callee_free_vars; effs = _ }
} =
C.simple ~dbg env res callee_simple
in
let args, args_free_vars, env, res, _ = C.simple_list ~dbg env res args in
let free_vars = Backend_var.Set.union callee_free_vars args_free_vars in
let fail_if_probe apply =
match Apply.probe_name apply with
| None -> ()
| Some _ ->
Misc.fatal_errorf
"[Apply] terms with a [probe_name] (i.e. that call a tracing probe) \
must always be direct applications of an OCaml function:@ %a"
Apply.print apply
in
let pos =
match Apply.position apply with
| Normal ->
(* We always use [Rc_normal] since the [Lambda_to_flambda] pass has
already taken care of the placement of region begin/end primitives. *)
Lambda.Rc_normal
| Nontail -> Lambda.Rc_nontail
in
let args_arity =
Apply.args_arity apply |> Flambda_arity.With_subkinds.to_arity
|> Flambda_arity.to_list
in
let return_arity =
Apply.return_arity apply |> Flambda_arity.With_subkinds.to_arity
in
let args_ty = List.map C.machtype_of_kind args_arity in
let return_ty = C.machtype_of_return_arity return_arity in
match Apply.call_kind apply with
| Function { function_call = Direct code_id; alloc_mode = _ } -> (
let code_metadata = Env.get_code_metadata env code_id in
let params_arity = Code_metadata.params_arity code_metadata in
if not (C.check_arity params_arity args)
then Misc.fatal_errorf "Wrong arity for direct call";
let args =
if Code_metadata.is_my_closure_used code_metadata
then args @ [callee]
else args
in
let code_linkage_name = Code_id.linkage_name code_id in
match Apply.probe_name apply with
| None ->
( C.direct_call ~dbg return_ty pos
(C.symbol_from_linkage_name ~dbg code_linkage_name)
args,
free_vars,
env,
res,
Ece.all )
| Some name ->
( C.probe ~dbg ~name
~handler_code_linkage_name:(Linkage_name.to_string code_linkage_name)
~args
|> C.return_unit dbg,
free_vars,
env,
res,
Ece.all ))
| Function { function_call = Indirect_unknown_arity; alloc_mode } ->
fail_if_probe apply;
( C.indirect_call ~dbg return_ty pos
(Alloc_mode.For_types.to_lambda alloc_mode)
callee args_ty args,
free_vars,
env,
res,
Ece.all )
| Function { function_call = Indirect_known_arity; alloc_mode } ->
fail_if_probe apply;
if not (C.check_arity (Apply.args_arity apply) args)
then
Misc.fatal_errorf
"To_cmm expects indirect_known_arity calls to be full applications in \
order to translate them"
else
( C.indirect_full_call ~dbg return_ty pos
(Alloc_mode.For_types.to_lambda alloc_mode)
callee args_ty args,
free_vars,
env,
res,
Ece.all )
| Call_kind.C_call { alloc; is_c_builtin } ->
fail_if_probe apply;
let callee =
match Simple.must_be_symbol callee_simple with
| Some (sym, _) -> Symbol.linkage_name sym |> Linkage_name.to_string
| None ->
Misc.fatal_errorf "Expected a function symbol instead of:@ %a"
Simple.print callee_simple
in
let returns = Apply.returns apply in
let wrap =
match Flambda_arity.to_list return_arity with
(* Returned int32 values need to be sign_extended because it's not clear
whether C code that returns an int32 returns one that is sign extended
or not. There is no need to wrap other return arities. Note that
extcalls of arity 0 are allowed (these never return). *)
| [] -> fun _dbg cmm -> cmm
| [kind] -> (
match kind with
| Naked_number Naked_int32 -> C.sign_extend_32
| Naked_number
(Naked_float | Naked_immediate | Naked_int64 | Naked_nativeint)
| Value | Rec_info | Region ->
fun _dbg cmm -> cmm)
| _ ->
(* CR gbury: update when unboxed tuples are used *)
Misc.fatal_errorf
"C functions are currently limited to a single return value"
in
let ty_args =
List.map C.exttype_of_kind
(Flambda_arity.to_list
(Flambda_arity.With_subkinds.to_arity (Apply.args_arity apply)))
in
( wrap dbg
(C.extcall ~dbg ~alloc ~is_c_builtin ~returns ~ty_args callee return_ty
args),
free_vars,
env,
res,
Ece.all )
| Call_kind.Method { kind; obj; alloc_mode } ->
fail_if_probe apply;
let To_cmm_env.
{ env;
res;
expr = { cmm = obj; free_vars = obj_free_vars; effs = _ }
} =
C.simple ~dbg env res obj
in
let free_vars = Backend_var.Set.union free_vars obj_free_vars in
let kind = Call_kind.Method_kind.to_lambda kind in
let alloc_mode = Alloc_mode.For_types.to_lambda alloc_mode in
( C.send kind callee obj args args_ty return_ty (pos, alloc_mode) dbg,
free_vars,
env,
res,
Ece.all )
(* Function calls that have an exn continuation with extra arguments must be
wrapped with assignments for the mutable variables used to pass the extra
arguments. *)
CR mshinwell : Add first - class support in Cmm for the concept of an exception
handler with extra arguments .
handler with extra arguments. *)
let translate_apply env res apply =
let call, free_vars, env, res, effs = translate_apply0 env res apply in
let dbg = Apply.dbg apply in
let k_exn = Apply.exn_continuation apply in
let mut_vars =
Exn_continuation.exn_handler k_exn |> Env.get_exn_extra_args env
in
let extra_args = Exn_continuation.extra_args k_exn in
if List.compare_lengths extra_args mut_vars = 0
then
Note wrt evaluation order : this is correct for the same reason as
` To_cmm_shared.simple_list ` , namely the first simple translated ( and
potentially inlined / substituted ) is evaluted last .
`To_cmm_shared.simple_list`, namely the first simple translated (and
potentially inlined/substituted) is evaluted last. *)
let aux (call, env, res, free_vars) (arg, _k) v =
let To_cmm_env.
{ env;
res;
expr = { cmm = arg; free_vars = arg_free_vars; effs = _ }
} =
C.simple ~dbg env res arg
in
let free_vars = Backend_var.Set.union free_vars arg_free_vars in
C.sequence (C.assign v arg) call, env, res, free_vars
in
let call, env, res, free_vars =
List.fold_left2 aux (call, env, res, free_vars) extra_args mut_vars
in
call, free_vars, env, res, effs
else
Misc.fatal_errorf
"Length of [extra_args] in exception continuation %a@ does not match \
those in the environment (%a)@ for application expression:@ %a"
Exn_continuation.print k_exn
(Format.pp_print_list ~pp_sep:Format.pp_print_space Ident.print)
mut_vars Apply.print apply
(* Helpers for translating [Apply_cont] expressions *)
Exception continuations always receive the exception value in their first
argument . Additionally , they may have extra arguments that are passed to the
handler via mutable variables ( expected to be spilled to the stack ) .
argument. Additionally, they may have extra arguments that are passed to the
handler via mutable variables (expected to be spilled to the stack). *)
let translate_raise env res apply exn_handler args =
match args with
| exn :: extra ->
let raise_kind =
match Apply_cont.trap_action apply with
| Some (Pop { raise_kind; _ }) ->
Trap_action.Raise_kind.option_to_lambda raise_kind
| Some (Push _) | None ->
Misc.fatal_errorf
"Apply_cont calls an exception handler without a Pop trap action:@ %a"
Apply_cont.print apply
in
let dbg = Apply_cont.debuginfo apply in
let To_cmm_env.
{ env;
res;
expr = { cmm = exn; free_vars = exn_free_vars; effs = _ }
} =
C.simple ~dbg env res exn
in
let extra, extra_free_vars, env, res, _ =
C.simple_list ~dbg env res extra
in
let free_vars = Backend_var.Set.union exn_free_vars extra_free_vars in
let mut_vars = Env.get_exn_extra_args env exn_handler in
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm =
List.fold_left2
(fun expr arg v -> C.sequence (C.assign v arg) expr)
(C.raise_prim raise_kind exn dbg)
extra mut_vars
in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
| [] ->
Misc.fatal_errorf "Exception continuation %a has no arguments:@ \n%a"
Continuation.print exn_handler Apply_cont.print apply
let translate_jump_to_continuation env res apply types cont args =
if List.compare_lengths types args = 0
then
let trap_actions =
match Apply_cont.trap_action apply with
| None -> []
| Some (Pop _) -> [Cmm.Pop]
| Some (Push { exn_handler }) ->
let cont = Env.get_cmm_continuation env exn_handler in
[Cmm.Push cont]
in
let dbg = Apply_cont.debuginfo apply in
let args, free_vars, env, res, _ = C.simple_list ~dbg env res args in
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap (C.cexit cont args trap_actions) free_vars in
cmm, free_vars, res
else
Misc.fatal_errorf "Types (%a) do not match arguments of@ %a"
(Format.pp_print_list ~pp_sep:Format.pp_print_space Printcmm.machtype)
types Apply_cont.print apply
(* A call to the return continuation of the current block simply is the return
value for the current block being translated. *)
let translate_jump_to_return_continuation env res apply return_cont args =
match args with
| [return_value] -> (
let dbg = Apply_cont.debuginfo apply in
let To_cmm_env.
{ env; res; expr = { cmm = return_value; free_vars; effs = _ } } =
C.simple ~dbg env res return_value
in
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
match Apply_cont.trap_action apply with
| None ->
let cmm, free_vars = wrap return_value free_vars in
cmm, free_vars, res
| Some (Pop _) ->
let cmm, free_vars =
wrap (C.trap_return return_value [Cmm.Pop]) free_vars
in
cmm, free_vars, res
| Some (Push _) ->
Misc.fatal_errorf
"Return continuation %a should not be applied with a Push trap action"
Continuation.print return_cont)
| _ ->
(* CR gbury: add support using unboxed tuples *)
Misc.fatal_errorf
"Return continuation %a should be applied to a single argument in@\n\
%a@\n\
Multiple return values from functions are not yet supported"
Continuation.print return_cont Apply_cont.print apply
Invalid expressions
let invalid env res ~message =
let wrap, _empty_env, res =
Env.flush_delayed_lets ~mode:Branching_point env res
in
let cmm_invalid, res = C.invalid res ~message in
let cmm, free_vars = wrap cmm_invalid Backend_var.Set.empty in
cmm, free_vars, res
(* The main set of translation functions for expressions *)
let rec expr env res e : Cmm.expression * Backend_var.Set.t * To_cmm_result.t =
match Expr.descr e with
| Let e' -> let_expr env res e'
| Let_cont e' -> let_cont env res e'
| Apply e' -> apply_expr env res e'
| Apply_cont e' -> apply_cont env res e'
| Switch e' -> switch env res e'
| Invalid { message } -> invalid env res ~message
and let_prim env res ~num_normal_occurrences_of_bound_vars v p dbg body =
let v = Bound_var.var v in
let effects_and_coeffects_of_prim =
Flambda_primitive.effects_and_coeffects p
in
let inline =
To_cmm_effects.classify_let_binding v ~num_normal_occurrences_of_bound_vars
~effects_and_coeffects_of_defining_expr:effects_and_coeffects_of_prim
in
let simple_case (inline : Env.simple Env.inline) =
let defining_expr, extra, env, res, args_effs =
To_cmm_primitive.prim_simple env res dbg p
in
let effects_and_coeffects_of_defining_expr =
Ece.join args_effs effects_and_coeffects_of_prim
in
let env, res =
Env.bind_variable_to_primitive ?extra env res v ~inline
~effects_and_coeffects_of_defining_expr ~defining_expr
in
expr env res body
in
let complex_case (inline : Env.complex Env.inline) =
let defining_expr, env, res, args_effs =
To_cmm_primitive.prim_complex env res dbg p
in
let effects_and_coeffects_of_defining_expr =
Ece.join args_effs effects_and_coeffects_of_prim
in
let env, res =
Env.bind_variable_to_primitive env res v ~inline
~effects_and_coeffects_of_defining_expr ~defining_expr
in
expr env res body
in
match inline with
(* It can be useful to translate a dropped expression because it allows to
inline (and thus remove from the env) the arguments in it. *)
| Drop_defining_expr | Regular -> simple_case Do_not_inline
| May_inline_once -> simple_case May_inline_once
| Must_inline_once -> complex_case Must_inline_once
| Must_inline_and_duplicate -> complex_case Must_inline_and_duplicate
and let_expr0 env res let_expr (bound_pattern : Bound_pattern.t)
~num_normal_occurrences_of_bound_vars ~body =
match[@warning "-4"] bound_pattern, Let.defining_expr let_expr with
| Singleton v, Simple s ->
let v = Bound_var.var v in
(* CR mshinwell: Try to get a proper [dbg] here (although the majority of
these bindings should have been substituted out). *)
let dbg = Debuginfo.none in
let env, res =
bind_var_to_simple ~dbg env res v ~num_normal_occurrences_of_bound_vars s
in
expr env res body
| Singleton _, Prim (p, _)
when (not (Flambda_features.stack_allocation_enabled ()))
&& Flambda_primitive.is_begin_or_end_region p ->
expr env res body
| Singleton v, Prim ((Unary (End_region, _) as p), dbg) ->
CR gbury : this is a hack to prevent moving of expressions past an
End_region . We have to do this manually because we currently have effects
and coeffects that are not precise enough . Particularly , an immutable
load of a locally allocated block is considered as pure , and thus can be
moved past an end_region . Here we also need to flush everything ,
including must_inline bindings , particularly projections that may project
from locally allocated closures ( and that must not be moved past an
end_region ) .
End_region. We have to do this manually because we currently have effects
and coeffects that are not precise enough. Particularly, an immutable
load of a locally allocated block is considered as pure, and thus can be
moved past an end_region. Here we also need to flush everything,
including must_inline bindings, particularly projections that may project
from locally allocated closures (and that must not be moved past an
end_region). *)
let wrap, env, res =
Env.flush_delayed_lets ~mode:Flush_everything env res
in
let cmm, free_vars, res =
let_prim env res ~num_normal_occurrences_of_bound_vars v p dbg body
in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
| Singleton v, Prim (p, dbg) ->
let_prim env res ~num_normal_occurrences_of_bound_vars v p dbg body
| Set_of_closures bound_vars, Set_of_closures soc ->
To_cmm_set_of_closures.let_dynamic_set_of_closures env res ~body ~bound_vars
~num_normal_occurrences_of_bound_vars soc ~translate_expr:expr
| Static bound_static, Static_consts consts -> (
let env, res, update_opt =
To_cmm_static.static_consts env res
~params_and_body:
(To_cmm_set_of_closures.params_and_body ~translate_expr:expr)
bound_static consts
in
match update_opt with
| None -> expr env res body
| Some { cmm; free_vars; effs = _ } ->
let wrap, env, res =
Env.flush_delayed_lets ~mode:Branching_point env res
in
let body, body_free_vars, res = expr env res body in
let free_vars = Backend_var.Set.union free_vars body_free_vars in
let cmm, free_vars = wrap (C.sequence cmm body) free_vars in
cmm, free_vars, res)
| Singleton _, Rec_info _ -> expr env res body
| Singleton _, (Set_of_closures _ | Static_consts _)
| Set_of_closures _, (Simple _ | Prim _ | Static_consts _ | Rec_info _)
| Static _, (Simple _ | Prim _ | Set_of_closures _ | Rec_info _) ->
Misc.fatal_errorf "Mismatch between pattern and defining expression:@ %a"
Let.print let_expr
and let_expr env res let_expr =
Let.pattern_match' let_expr
~f:(fun bound_pattern ~num_normal_occurrences_of_bound_vars ~body ->
match Bound_pattern.name_mode bound_pattern with
| Normal ->
let_expr0 env res let_expr bound_pattern
~num_normal_occurrences_of_bound_vars ~body
| Phantom -> expr env res body
| In_types ->
Misc.fatal_errorf "Cannot bind In_types variables in terms:@ %a"
Let.print let_expr)
and let_cont env res (let_cont : Flambda.Let_cont.t) =
match let_cont with
| Non_recursive { handler; num_free_occurrences; is_applied_with_traps } ->
Non_recursive_let_cont_handler.pattern_match handler ~f:(fun k ~body ->
let handler = Non_recursive_let_cont_handler.handler handler in
match
To_cmm_effects.classify_continuation_handler k handler
~num_free_occurrences ~is_applied_with_traps
with
| May_inline -> let_cont_inlined env res k handler body
| Regular -> let_cont_not_inlined env res k handler body)
| Recursive handlers ->
Recursive_let_cont_handlers.pattern_match handlers
~f:(fun ~invariant_params ~body conts ->
if Continuation_handlers.contains_exn_handler conts
then
Misc.fatal_errorf
"Recursive continuation bindings cannot involve exception \
handlers:@ %a"
Let_cont.print let_cont;
let_cont_rec env res invariant_params conts body)
(* The bound continuation [k] will be inlined. *)
and let_cont_inlined env res k handler body =
Continuation_handler.pattern_match' handler
~f:(fun handler_params ~num_normal_occurrences_of_params ~handler ->
let env =
Env.add_inline_cont env k ~handler_params
~handler_params_occurrences:num_normal_occurrences_of_params
~handler_body:handler
in
expr env res body)
and let_cont_not_inlined env res k handler body =
(* The environment must be flushed to ensure that expressions are not
duplicated into both the body and the handler. *)
(* CR gbury: "split" the environment according to which variables the handler
and the body uses, to allow for inlining to proceed within each
expression. *)
let wrap, env, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let is_exn_handler = Continuation_handler.is_exn_handler handler in
let vars, arity, handler, free_vars_of_handler, res =
continuation_handler env res handler
in
let catch_id, env =
Env.add_jump_cont env k ~param_types:(List.map snd vars)
in
let cmm, free_vars, res =
(* Exception continuations are translated specially -- these will be reached
via the raising of exceptions, whereas other continuations are reached
using a normal jump. *)
if is_exn_handler
then
let_cont_exn_handler env res k body vars handler free_vars_of_handler
~catch_id arity
else
CR mshinwell : fix debuginfo
let body, free_vars_of_body, res = expr env res body in
let free_vars =
Backend_var.Set.union free_vars_of_body
(C.remove_vars_with_machtype free_vars_of_handler vars)
in
( C.create_ccatch ~rec_flag:false ~body
~handlers:[C.handler ~dbg catch_id vars handler],
free_vars,
res )
in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
Exception continuations are translated using delayed Ctrywith blocks . The
exception handler parts of these blocks are identified by the [ catch_id]s .
Additionally , exception continuations can have extra args , which are passed
through the try - with using mutable Cmm variables . Thus the exception handler
must first read the contents of those extra args ( eagerly , in order to
minmize the lifetime of the mutable variables ) .
exception handler parts of these blocks are identified by the [catch_id]s.
Additionally, exception continuations can have extra args, which are passed
through the try-with using mutable Cmm variables. Thus the exception handler
must first read the contents of those extra args (eagerly, in order to
minmize the lifetime of the mutable variables). *)
and let_cont_exn_handler env res k body vars handler free_vars_of_handler
~catch_id arity =
let exn_var, extra_params =
match vars with
| (v, _) :: rest -> v, rest
| [] ->
(* See comment on [translate_raise], above. *)
Misc.fatal_errorf
"Exception continuation %a should have at least one argument"
Continuation.print k
in
let env_body, mut_vars = Env.add_exn_handler env k arity in
let handler =
(* Wrap the exn handler with reads of the mutable variables *)
List.fold_left2
(fun handler (mut_var, _) (extra_param, _) ->
(* We introduce these mutable cmm variables at very precise points, and
without going through the delayed let-bindings of the [env], so we do
not consider them when computing the [free_vars]. *)
C.letin extra_param ~defining_expr:(C.var mut_var) ~body:handler)
handler mut_vars extra_params
in
let body, free_vars_of_body, res = expr env_body res body in
let free_vars =
Backend_var.Set.union free_vars_of_body
(C.remove_vars_with_machtype free_vars_of_handler vars)
in
CR mshinwell : fix debuginfo
let trywith =
C.trywith ~dbg ~kind:(Delayed catch_id) ~body ~exn_var ~handler ()
in
Define and initialize the mutable Cmm variables for extra args
let cmm =
List.fold_left
(fun cmm (mut_var, (kind : K.t)) ->
(* CR mshinwell: Fix [provenance] *)
let mut_var =
Backend_var.With_provenance.create ?provenance:None mut_var
in
let dummy_value =
match kind with
| Value -> C.int ~dbg 1
| Naked_number Naked_float -> C.float ~dbg 0.
| Naked_number
(Naked_immediate | Naked_int32 | Naked_int64 | Naked_nativeint) ->
C.int ~dbg 0
| Region | Rec_info ->
Misc.fatal_errorf "No dummy value available for kind %a" K.print
kind
in
C.letin_mut mut_var (C.machtype_of_kind kind) dummy_value cmm)
trywith mut_vars
in
cmm, free_vars, res
and let_cont_rec env res invariant_params conts body =
Flush the env now to avoid inlining something inside of a recursive
continuation ( aka a loop ) , as it would increase the number of times the
computation is performed ( even if there is only one syntactic
occurrence )
continuation (aka a loop), as it would increase the number of times the
computation is performed (even if there is only one syntactic
occurrence) *)
(* CR-someday mshinwell: As discussed, the tradeoff here is not clear, since
flushing might increase register pressure. *)
let wrap, env, res = Env.flush_delayed_lets ~mode:Entering_loop env res in
(* Compute the environment for Ccatch ids *)
let conts_to_handlers = Continuation_handlers.to_map conts in
let env =
Continuation.Map.fold
(fun k handler acc ->
let continuation_arg_tys =
Continuation_handler.pattern_match' handler
~f:(fun params ~num_normal_occurrences_of_params:_ ~handler:_ ->
List.map C.machtype_of_kinded_parameter
(Bound_parameters.to_list
(Bound_parameters.append invariant_params params)))
in
snd (Env.add_jump_cont acc k ~param_types:continuation_arg_tys))
conts_to_handlers env
in
(* Generate variables for the invariant params *)
let env, invariant_vars = C.bound_parameters env invariant_params in
(* Translate each continuation handler *)
let conts_to_handlers, res =
Continuation.Map.fold
(fun k handler (conts_to_handlers, res) ->
let vars, _arity, handler, free_vars_of_handler, res =
continuation_handler env res handler
in
( Continuation.Map.add k
(invariant_vars @ vars, handler, free_vars_of_handler)
conts_to_handlers,
res ))
conts_to_handlers
(Continuation.Map.empty, res)
in
CR mshinwell : fix debuginfo
let body, free_vars_of_body, res = expr env res body in
Setup the Cmm handlers for the Ccatch
let handlers, free_vars =
Continuation.Map.fold
(fun k (vars, handler, free_vars_of_handler) (handlers, free_vars) ->
let free_vars =
Backend_var.Set.union free_vars
(C.remove_vars_with_machtype free_vars_of_handler vars)
in
let id = Env.get_cmm_continuation env k in
C.handler ~dbg id vars handler :: handlers, free_vars)
conts_to_handlers ([], free_vars_of_body)
in
let cmm = C.create_ccatch ~rec_flag:true ~body ~handlers in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
and continuation_handler env res handler =
Continuation_handler.pattern_match' handler
~f:(fun params ~num_normal_occurrences_of_params:_ ~handler ->
let arity = Bound_parameters.arity params in
let env, vars = C.bound_parameters env params in
let expr, free_vars_of_handler, res = expr env res handler in
vars, arity, expr, free_vars_of_handler, res)
and apply_expr env res apply =
let call, free_vars, env, res, effs = translate_apply env res apply in
With respect to flushing the environment we have three cases :
1 . The call never returns or jumps to another function
2 . The call jumps to somewhere else in the current function , but there is
more than one incoming control flow edge to that point
3 . The call jumps to somewhere else in the current function and is the only
thing that jumps to that point . In this case we will inline the return
continuation of the [ Apply ] .
In case 1 we ca n't affect the code generation at the jump target : there is
no option but to flush now .
In case 2 we also flush to ensure that effectful bindings are not pushed
past join points and that no binding is duplicated .
In case 3 we can avoid flushing the environment due to the linearity of the
control flow . We know that flushing will eventually happen by virtue of the
recursive call to [ expr ] .
1. The call never returns or jumps to another function
2. The call jumps to somewhere else in the current function, but there is
more than one incoming control flow edge to that point
3. The call jumps to somewhere else in the current function and is the only
thing that jumps to that point. In this case we will inline the return
continuation of the [Apply].
In case 1 we can't affect the code generation at the jump target: there is
no option but to flush now.
In case 2 we also flush to ensure that effectful bindings are not pushed
past join points and that no binding is duplicated.
In case 3 we can avoid flushing the environment due to the linearity of the
control flow. We know that flushing will eventually happen by virtue of the
recursive call to [expr]. *)
match Apply.continuation apply with
| Never_returns ->
(* Case 1 *)
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap call free_vars in
cmm, free_vars, res
| Return k when Continuation.equal (Env.return_continuation env) k ->
(* Case 1 *)
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap call free_vars in
cmm, free_vars, res
| Return k -> (
let[@inline always] unsupported () =
(* CR gbury: add support using unboxed tuples *)
Misc.fatal_errorf
"Return continuation %a should be applied to a single argument in@\n\
%a@\n\
Multiple return values from functions are not yet supported"
Continuation.print k Apply.print apply
in
match Env.get_continuation env k with
| Jump { param_types = []; cont = _ } -> unsupported ()
| Jump { param_types = [_]; cont } ->
(* Case 2 *)
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap (C.cexit cont [call] []) free_vars in
cmm, free_vars, res
| Inline { handler_params; handler_body = body; handler_params_occurrences }
-> (
(* Case 3 *)
let handler_params = Bound_parameters.to_list handler_params in
match handler_params with
| [] -> unsupported ()
| [param] ->
let var = Bound_parameter.var param in
let env, res =
Env.bind_variable env res var
~effects_and_coeffects_of_defining_expr:effs ~defining_expr:call
~free_vars_of_defining_expr:free_vars
~num_normal_occurrences_of_bound_vars:handler_params_occurrences
in
expr env res body
| _ :: _ -> unsupported ())
| Jump _ -> unsupported ())
and apply_cont env res apply_cont =
let k = Apply_cont.continuation apply_cont in
let args = Apply_cont.args apply_cont in
if Env.is_exn_handler env k
then translate_raise env res apply_cont k args
else if Continuation.equal (Env.return_continuation env) k
then translate_jump_to_return_continuation env res apply_cont k args
else
match Env.get_continuation env k with
| Jump { param_types; cont } ->
translate_jump_to_continuation env res apply_cont param_types cont args
| Inline { handler_params; handler_body; handler_params_occurrences } ->
if Option.is_some (Apply_cont.trap_action apply_cont)
then
Misc.fatal_errorf "This [Apply_cont] should not have a trap action:@ %a"
Apply_cont.print apply_cont;
(* Inlining a continuation call simply needs to bind the arguments to the
variables that the continuation's handler expects. *)
let handler_params = Bound_parameters.to_list handler_params in
if List.compare_lengths args handler_params = 0
then
let env, res =
List.fold_left2
(fun (env, res) param ->
bind_var_to_simple
~dbg:(Apply_cont.debuginfo apply_cont)
env res
(Bound_parameter.var param)
~num_normal_occurrences_of_bound_vars:handler_params_occurrences)
(env, res) handler_params args
in
expr env res handler_body
else
Misc.fatal_errorf
"Continuation %a in@\n%a@\nExpected %d arguments but got %a."
Continuation.print k Apply_cont.print apply_cont
(List.length handler_params)
Apply_cont.print apply_cont
and switch env res switch =
let scrutinee = Switch.scrutinee switch in
let dbg = Switch.condition_dbg switch in
let To_cmm_env.
{ env;
res;
expr =
{ cmm = untagged_scrutinee_cmm;
free_vars = scrutinee_free_vars;
effs = _
}
} =
C.simple ~dbg env res scrutinee
in
let arms = Switch.arms switch in
For binary switches , which can be translated to an if - then - else , it can be
interesting for the scrutinee to be tagged ( particularly for switches
coming from a source level if - then - else on booleans ) as that way the
translation can use 2 instructions instead of 3 .
However , this is only useful to do if the tagged expression is smaller then
the untagged one ( which is not always true due to arithmetic
simplifications performed by Cmm_helpers ) .
Additionally for switches with more than 2 arms , not untagging and
adjusting the switch to work on tagged integers might be worse . The
discriminants of the arms might not be successive machine integers anymore ,
thus preventing the use of a table . Alternatively it might not be worth it
given the already high number of instructions needed for big switches ( but
this might be debatable for small switches with 3 to 5 arms ) .
interesting for the scrutinee to be tagged (particularly for switches
coming from a source level if-then-else on booleans) as that way the
translation can use 2 instructions instead of 3.
However, this is only useful to do if the tagged expression is smaller then
the untagged one (which is not always true due to arithmetic
simplifications performed by Cmm_helpers).
Additionally for switches with more than 2 arms, not untagging and
adjusting the switch to work on tagged integers might be worse. The
discriminants of the arms might not be successive machine integers anymore,
thus preventing the use of a table. Alternatively it might not be worth it
given the already high number of instructions needed for big switches (but
this might be debatable for small switches with 3 to 5 arms). *)
let scrutinee, must_tag_discriminant =
match Targetint_31_63.Map.cardinal arms with
| 2 -> (
match Env.extra_info env scrutinee with
| None -> untagged_scrutinee_cmm, false
| Some (Untag tagged_scrutinee_cmm) ->
let size_untagged =
Option.value
(C.cmm_arith_size untagged_scrutinee_cmm)
~default:max_int
in
let size_tagged =
Option.value (C.cmm_arith_size tagged_scrutinee_cmm) ~default:max_int
in
if size_tagged < size_untagged
then tagged_scrutinee_cmm, true
else untagged_scrutinee_cmm, false)
| _ -> untagged_scrutinee_cmm, false
in
let wrap, env, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let prepare_discriminant ~must_tag d =
let targetint_d = Targetint_31_63.to_targetint d in
Targetint_32_64.to_int_checked
(if must_tag then C.tag_targetint targetint_d else targetint_d)
in
let make_arm ~must_tag_discriminant env res (d, action) =
let d = prepare_discriminant ~must_tag:must_tag_discriminant d in
let cmm_action, action_free_vars, res = apply_cont env res action in
(d, cmm_action, action_free_vars, Apply_cont.debuginfo action), res
in
match Targetint_31_63.Map.cardinal arms with
(* Binary case: if-then-else *)
| 2 -> (
let aux = make_arm ~must_tag_discriminant env in
let first_arm, res = aux res (Targetint_31_63.Map.min_binding arms) in
let second_arm, res = aux res (Targetint_31_63.Map.max_binding arms) in
match first_arm, second_arm with
These switches are actually if - then - elses . On such switches ,
transl_switch_clambda will introduce a let - binding of the scrutinee
before creating an if - then - else , introducing an indirection that might
prevent some optimizations performed by Selectgen / Emit when the condition
is inlined in the if - then - else . Instead we use [ C.ite ] .
transl_switch_clambda will introduce a let-binding of the scrutinee
before creating an if-then-else, introducing an indirection that might
prevent some optimizations performed by Selectgen/Emit when the condition
is inlined in the if-then-else. Instead we use [C.ite]. *)
| (0, else_, else_free_vars, else_dbg), (_, then_, then_free_vars, then_dbg)
| (_, then_, then_free_vars, then_dbg), (0, else_, else_free_vars, else_dbg)
->
let free_vars =
Backend_var.Set.union scrutinee_free_vars
(Backend_var.Set.union else_free_vars then_free_vars)
in
let cmm, free_vars =
wrap (C.ite ~dbg scrutinee ~then_dbg ~then_ ~else_dbg ~else_) free_vars
in
cmm, free_vars, res
Similar case to the previous but none of the arms match 0 , so we have to
generate an equality test , and make sure it is inside the condition to
ensure Selectgen and Emit can take advantage of it .
generate an equality test, and make sure it is inside the condition to
ensure Selectgen and Emit can take advantage of it. *)
| ( (x, if_x, if_x_free_vars, if_x_dbg),
(_, if_not, if_not_free_vars, if_not_dbg) ) ->
let free_vars =
Backend_var.Set.union scrutinee_free_vars
(Backend_var.Set.union if_x_free_vars if_not_free_vars)
in
let expr =
C.ite ~dbg
(C.eq ~dbg (C.int ~dbg x) scrutinee)
~then_dbg:if_x_dbg ~then_:if_x ~else_dbg:if_not_dbg ~else_:if_not
in
let cmm, free_vars = wrap expr free_vars in
cmm, free_vars, res)
(* General case *)
| n ->
(* transl_switch_clambda expects an [index] array such that index.(d) is the
index in [cases] of the expression to execute when [e] matches [d]. *)
let max_d, _ = Targetint_31_63.Map.max_binding arms in
let m = prepare_discriminant ~must_tag:must_tag_discriminant max_d in
let unreachable, res = C.invalid res ~message:"unreachable switch case" in
let cases = Array.make (n + 1) unreachable in
let index = Array.make (m + 1) n in
let _, res, free_vars =
Targetint_31_63.Map.fold
(fun discriminant action (i, res, free_vars) ->
let (d, cmm_action, action_free_vars, _dbg), res =
make_arm ~must_tag_discriminant env res (discriminant, action)
in
let free_vars = Backend_var.Set.union free_vars action_free_vars in
cases.(i) <- cmm_action;
index.(d) <- i;
i + 1, res, free_vars)
arms
(0, res, scrutinee_free_vars)
in
(* CR-someday poechsel: Put a more precise value kind here *)
let expr =
C.transl_switch_clambda dbg (Vval Pgenval) scrutinee index cases
in
let cmm, free_vars = wrap expr free_vars in
cmm, free_vars, res
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/527c173ab2d4943c372256b769e17bee98ccfc62/middle_end/flambda2/to_cmm/to_cmm_expr.ml | ocaml | ************************************************************************
OCaml
Copyright 2019--2019 OCamlPro SAS
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Note about flushing of environments: this module treats the delayed bindings
in [To_cmm_env] environments (see to_cmm_env.mli for more information) in a
linear manner. Flushes are inserted to preserve this property. This ensures
in particular that effectful bindings get placed exactly once and that other
bindings are not duplicated.
Helpers for the translation of [Apply] expressions.
We always use [Rc_normal] since the [Lambda_to_flambda] pass has
already taken care of the placement of region begin/end primitives.
Returned int32 values need to be sign_extended because it's not clear
whether C code that returns an int32 returns one that is sign extended
or not. There is no need to wrap other return arities. Note that
extcalls of arity 0 are allowed (these never return).
CR gbury: update when unboxed tuples are used
Function calls that have an exn continuation with extra arguments must be
wrapped with assignments for the mutable variables used to pass the extra
arguments.
Helpers for translating [Apply_cont] expressions
A call to the return continuation of the current block simply is the return
value for the current block being translated.
CR gbury: add support using unboxed tuples
The main set of translation functions for expressions
It can be useful to translate a dropped expression because it allows to
inline (and thus remove from the env) the arguments in it.
CR mshinwell: Try to get a proper [dbg] here (although the majority of
these bindings should have been substituted out).
The bound continuation [k] will be inlined.
The environment must be flushed to ensure that expressions are not
duplicated into both the body and the handler.
CR gbury: "split" the environment according to which variables the handler
and the body uses, to allow for inlining to proceed within each
expression.
Exception continuations are translated specially -- these will be reached
via the raising of exceptions, whereas other continuations are reached
using a normal jump.
See comment on [translate_raise], above.
Wrap the exn handler with reads of the mutable variables
We introduce these mutable cmm variables at very precise points, and
without going through the delayed let-bindings of the [env], so we do
not consider them when computing the [free_vars].
CR mshinwell: Fix [provenance]
CR-someday mshinwell: As discussed, the tradeoff here is not clear, since
flushing might increase register pressure.
Compute the environment for Ccatch ids
Generate variables for the invariant params
Translate each continuation handler
Case 1
Case 1
CR gbury: add support using unboxed tuples
Case 2
Case 3
Inlining a continuation call simply needs to bind the arguments to the
variables that the continuation's handler expects.
Binary case: if-then-else
General case
transl_switch_clambda expects an [index] array such that index.(d) is the
index in [cases] of the expression to execute when [e] matches [d].
CR-someday poechsel: Put a more precise value kind here | , OCamlPro
the GNU Lesser General Public License version 2.1 , with the
[@@@ocaml.warning "+a-30-40-41-42"]
open! Flambda.Import
module Env = To_cmm_env
module Ece = Effects_and_coeffects
module K = Flambda_kind
module C = struct
include Cmm_helpers
include Cmm_builtins
include To_cmm_shared
end
Bind a Cmm variable to the result of translating a [ Simple ] into Cmm .
let bind_var_to_simple ~dbg env res v ~num_normal_occurrences_of_bound_vars s =
match Simple.must_be_var s with
| Some (alias_of, _coercion) ->
Env.add_alias env res ~var:v ~num_normal_occurrences_of_bound_vars ~alias_of
| None ->
let To_cmm_env.
{ env;
res;
expr =
{ cmm = defining_expr;
free_vars = free_vars_of_defining_expr;
effs = effects_and_coeffects_of_defining_expr
}
} =
C.simple ~dbg env res s
in
let env, res =
Env.bind_variable env res v ~effects_and_coeffects_of_defining_expr
~defining_expr ~free_vars_of_defining_expr
~num_normal_occurrences_of_bound_vars
in
env, res
let translate_apply0 env res apply =
let callee_simple = Apply.callee apply in
let args = Apply.args apply in
let dbg = Apply.dbg apply in
CR mshinwell : When we fix the problem that [ prim_effects ] and
[ prim_coeffects ] are ignored for C calls , we need to take into account the
effects / coeffects values currently ignored on the following two lines . At
the moment they can be ignored as we always deem all calls to have
arbitrary effects and coeffects .
[prim_coeffects] are ignored for C calls, we need to take into account the
effects/coeffects values currently ignored on the following two lines. At
the moment they can be ignored as we always deem all calls to have
arbitrary effects and coeffects. *)
let To_cmm_env.
{ env;
res;
expr = { cmm = callee; free_vars = callee_free_vars; effs = _ }
} =
C.simple ~dbg env res callee_simple
in
let args, args_free_vars, env, res, _ = C.simple_list ~dbg env res args in
let free_vars = Backend_var.Set.union callee_free_vars args_free_vars in
let fail_if_probe apply =
match Apply.probe_name apply with
| None -> ()
| Some _ ->
Misc.fatal_errorf
"[Apply] terms with a [probe_name] (i.e. that call a tracing probe) \
must always be direct applications of an OCaml function:@ %a"
Apply.print apply
in
let pos =
match Apply.position apply with
| Normal ->
Lambda.Rc_normal
| Nontail -> Lambda.Rc_nontail
in
let args_arity =
Apply.args_arity apply |> Flambda_arity.With_subkinds.to_arity
|> Flambda_arity.to_list
in
let return_arity =
Apply.return_arity apply |> Flambda_arity.With_subkinds.to_arity
in
let args_ty = List.map C.machtype_of_kind args_arity in
let return_ty = C.machtype_of_return_arity return_arity in
match Apply.call_kind apply with
| Function { function_call = Direct code_id; alloc_mode = _ } -> (
let code_metadata = Env.get_code_metadata env code_id in
let params_arity = Code_metadata.params_arity code_metadata in
if not (C.check_arity params_arity args)
then Misc.fatal_errorf "Wrong arity for direct call";
let args =
if Code_metadata.is_my_closure_used code_metadata
then args @ [callee]
else args
in
let code_linkage_name = Code_id.linkage_name code_id in
match Apply.probe_name apply with
| None ->
( C.direct_call ~dbg return_ty pos
(C.symbol_from_linkage_name ~dbg code_linkage_name)
args,
free_vars,
env,
res,
Ece.all )
| Some name ->
( C.probe ~dbg ~name
~handler_code_linkage_name:(Linkage_name.to_string code_linkage_name)
~args
|> C.return_unit dbg,
free_vars,
env,
res,
Ece.all ))
| Function { function_call = Indirect_unknown_arity; alloc_mode } ->
fail_if_probe apply;
( C.indirect_call ~dbg return_ty pos
(Alloc_mode.For_types.to_lambda alloc_mode)
callee args_ty args,
free_vars,
env,
res,
Ece.all )
| Function { function_call = Indirect_known_arity; alloc_mode } ->
fail_if_probe apply;
if not (C.check_arity (Apply.args_arity apply) args)
then
Misc.fatal_errorf
"To_cmm expects indirect_known_arity calls to be full applications in \
order to translate them"
else
( C.indirect_full_call ~dbg return_ty pos
(Alloc_mode.For_types.to_lambda alloc_mode)
callee args_ty args,
free_vars,
env,
res,
Ece.all )
| Call_kind.C_call { alloc; is_c_builtin } ->
fail_if_probe apply;
let callee =
match Simple.must_be_symbol callee_simple with
| Some (sym, _) -> Symbol.linkage_name sym |> Linkage_name.to_string
| None ->
Misc.fatal_errorf "Expected a function symbol instead of:@ %a"
Simple.print callee_simple
in
let returns = Apply.returns apply in
let wrap =
match Flambda_arity.to_list return_arity with
| [] -> fun _dbg cmm -> cmm
| [kind] -> (
match kind with
| Naked_number Naked_int32 -> C.sign_extend_32
| Naked_number
(Naked_float | Naked_immediate | Naked_int64 | Naked_nativeint)
| Value | Rec_info | Region ->
fun _dbg cmm -> cmm)
| _ ->
Misc.fatal_errorf
"C functions are currently limited to a single return value"
in
let ty_args =
List.map C.exttype_of_kind
(Flambda_arity.to_list
(Flambda_arity.With_subkinds.to_arity (Apply.args_arity apply)))
in
( wrap dbg
(C.extcall ~dbg ~alloc ~is_c_builtin ~returns ~ty_args callee return_ty
args),
free_vars,
env,
res,
Ece.all )
| Call_kind.Method { kind; obj; alloc_mode } ->
fail_if_probe apply;
let To_cmm_env.
{ env;
res;
expr = { cmm = obj; free_vars = obj_free_vars; effs = _ }
} =
C.simple ~dbg env res obj
in
let free_vars = Backend_var.Set.union free_vars obj_free_vars in
let kind = Call_kind.Method_kind.to_lambda kind in
let alloc_mode = Alloc_mode.For_types.to_lambda alloc_mode in
( C.send kind callee obj args args_ty return_ty (pos, alloc_mode) dbg,
free_vars,
env,
res,
Ece.all )
CR mshinwell : Add first - class support in Cmm for the concept of an exception
handler with extra arguments .
handler with extra arguments. *)
let translate_apply env res apply =
let call, free_vars, env, res, effs = translate_apply0 env res apply in
let dbg = Apply.dbg apply in
let k_exn = Apply.exn_continuation apply in
let mut_vars =
Exn_continuation.exn_handler k_exn |> Env.get_exn_extra_args env
in
let extra_args = Exn_continuation.extra_args k_exn in
if List.compare_lengths extra_args mut_vars = 0
then
Note wrt evaluation order : this is correct for the same reason as
` To_cmm_shared.simple_list ` , namely the first simple translated ( and
potentially inlined / substituted ) is evaluted last .
`To_cmm_shared.simple_list`, namely the first simple translated (and
potentially inlined/substituted) is evaluted last. *)
let aux (call, env, res, free_vars) (arg, _k) v =
let To_cmm_env.
{ env;
res;
expr = { cmm = arg; free_vars = arg_free_vars; effs = _ }
} =
C.simple ~dbg env res arg
in
let free_vars = Backend_var.Set.union free_vars arg_free_vars in
C.sequence (C.assign v arg) call, env, res, free_vars
in
let call, env, res, free_vars =
List.fold_left2 aux (call, env, res, free_vars) extra_args mut_vars
in
call, free_vars, env, res, effs
else
Misc.fatal_errorf
"Length of [extra_args] in exception continuation %a@ does not match \
those in the environment (%a)@ for application expression:@ %a"
Exn_continuation.print k_exn
(Format.pp_print_list ~pp_sep:Format.pp_print_space Ident.print)
mut_vars Apply.print apply
Exception continuations always receive the exception value in their first
argument . Additionally , they may have extra arguments that are passed to the
handler via mutable variables ( expected to be spilled to the stack ) .
argument. Additionally, they may have extra arguments that are passed to the
handler via mutable variables (expected to be spilled to the stack). *)
let translate_raise env res apply exn_handler args =
match args with
| exn :: extra ->
let raise_kind =
match Apply_cont.trap_action apply with
| Some (Pop { raise_kind; _ }) ->
Trap_action.Raise_kind.option_to_lambda raise_kind
| Some (Push _) | None ->
Misc.fatal_errorf
"Apply_cont calls an exception handler without a Pop trap action:@ %a"
Apply_cont.print apply
in
let dbg = Apply_cont.debuginfo apply in
let To_cmm_env.
{ env;
res;
expr = { cmm = exn; free_vars = exn_free_vars; effs = _ }
} =
C.simple ~dbg env res exn
in
let extra, extra_free_vars, env, res, _ =
C.simple_list ~dbg env res extra
in
let free_vars = Backend_var.Set.union exn_free_vars extra_free_vars in
let mut_vars = Env.get_exn_extra_args env exn_handler in
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm =
List.fold_left2
(fun expr arg v -> C.sequence (C.assign v arg) expr)
(C.raise_prim raise_kind exn dbg)
extra mut_vars
in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
| [] ->
Misc.fatal_errorf "Exception continuation %a has no arguments:@ \n%a"
Continuation.print exn_handler Apply_cont.print apply
let translate_jump_to_continuation env res apply types cont args =
if List.compare_lengths types args = 0
then
let trap_actions =
match Apply_cont.trap_action apply with
| None -> []
| Some (Pop _) -> [Cmm.Pop]
| Some (Push { exn_handler }) ->
let cont = Env.get_cmm_continuation env exn_handler in
[Cmm.Push cont]
in
let dbg = Apply_cont.debuginfo apply in
let args, free_vars, env, res, _ = C.simple_list ~dbg env res args in
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap (C.cexit cont args trap_actions) free_vars in
cmm, free_vars, res
else
Misc.fatal_errorf "Types (%a) do not match arguments of@ %a"
(Format.pp_print_list ~pp_sep:Format.pp_print_space Printcmm.machtype)
types Apply_cont.print apply
let translate_jump_to_return_continuation env res apply return_cont args =
match args with
| [return_value] -> (
let dbg = Apply_cont.debuginfo apply in
let To_cmm_env.
{ env; res; expr = { cmm = return_value; free_vars; effs = _ } } =
C.simple ~dbg env res return_value
in
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
match Apply_cont.trap_action apply with
| None ->
let cmm, free_vars = wrap return_value free_vars in
cmm, free_vars, res
| Some (Pop _) ->
let cmm, free_vars =
wrap (C.trap_return return_value [Cmm.Pop]) free_vars
in
cmm, free_vars, res
| Some (Push _) ->
Misc.fatal_errorf
"Return continuation %a should not be applied with a Push trap action"
Continuation.print return_cont)
| _ ->
Misc.fatal_errorf
"Return continuation %a should be applied to a single argument in@\n\
%a@\n\
Multiple return values from functions are not yet supported"
Continuation.print return_cont Apply_cont.print apply
Invalid expressions
let invalid env res ~message =
let wrap, _empty_env, res =
Env.flush_delayed_lets ~mode:Branching_point env res
in
let cmm_invalid, res = C.invalid res ~message in
let cmm, free_vars = wrap cmm_invalid Backend_var.Set.empty in
cmm, free_vars, res
let rec expr env res e : Cmm.expression * Backend_var.Set.t * To_cmm_result.t =
match Expr.descr e with
| Let e' -> let_expr env res e'
| Let_cont e' -> let_cont env res e'
| Apply e' -> apply_expr env res e'
| Apply_cont e' -> apply_cont env res e'
| Switch e' -> switch env res e'
| Invalid { message } -> invalid env res ~message
and let_prim env res ~num_normal_occurrences_of_bound_vars v p dbg body =
let v = Bound_var.var v in
let effects_and_coeffects_of_prim =
Flambda_primitive.effects_and_coeffects p
in
let inline =
To_cmm_effects.classify_let_binding v ~num_normal_occurrences_of_bound_vars
~effects_and_coeffects_of_defining_expr:effects_and_coeffects_of_prim
in
let simple_case (inline : Env.simple Env.inline) =
let defining_expr, extra, env, res, args_effs =
To_cmm_primitive.prim_simple env res dbg p
in
let effects_and_coeffects_of_defining_expr =
Ece.join args_effs effects_and_coeffects_of_prim
in
let env, res =
Env.bind_variable_to_primitive ?extra env res v ~inline
~effects_and_coeffects_of_defining_expr ~defining_expr
in
expr env res body
in
let complex_case (inline : Env.complex Env.inline) =
let defining_expr, env, res, args_effs =
To_cmm_primitive.prim_complex env res dbg p
in
let effects_and_coeffects_of_defining_expr =
Ece.join args_effs effects_and_coeffects_of_prim
in
let env, res =
Env.bind_variable_to_primitive env res v ~inline
~effects_and_coeffects_of_defining_expr ~defining_expr
in
expr env res body
in
match inline with
| Drop_defining_expr | Regular -> simple_case Do_not_inline
| May_inline_once -> simple_case May_inline_once
| Must_inline_once -> complex_case Must_inline_once
| Must_inline_and_duplicate -> complex_case Must_inline_and_duplicate
and let_expr0 env res let_expr (bound_pattern : Bound_pattern.t)
~num_normal_occurrences_of_bound_vars ~body =
match[@warning "-4"] bound_pattern, Let.defining_expr let_expr with
| Singleton v, Simple s ->
let v = Bound_var.var v in
let dbg = Debuginfo.none in
let env, res =
bind_var_to_simple ~dbg env res v ~num_normal_occurrences_of_bound_vars s
in
expr env res body
| Singleton _, Prim (p, _)
when (not (Flambda_features.stack_allocation_enabled ()))
&& Flambda_primitive.is_begin_or_end_region p ->
expr env res body
| Singleton v, Prim ((Unary (End_region, _) as p), dbg) ->
CR gbury : this is a hack to prevent moving of expressions past an
End_region . We have to do this manually because we currently have effects
and coeffects that are not precise enough . Particularly , an immutable
load of a locally allocated block is considered as pure , and thus can be
moved past an end_region . Here we also need to flush everything ,
including must_inline bindings , particularly projections that may project
from locally allocated closures ( and that must not be moved past an
end_region ) .
End_region. We have to do this manually because we currently have effects
and coeffects that are not precise enough. Particularly, an immutable
load of a locally allocated block is considered as pure, and thus can be
moved past an end_region. Here we also need to flush everything,
including must_inline bindings, particularly projections that may project
from locally allocated closures (and that must not be moved past an
end_region). *)
let wrap, env, res =
Env.flush_delayed_lets ~mode:Flush_everything env res
in
let cmm, free_vars, res =
let_prim env res ~num_normal_occurrences_of_bound_vars v p dbg body
in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
| Singleton v, Prim (p, dbg) ->
let_prim env res ~num_normal_occurrences_of_bound_vars v p dbg body
| Set_of_closures bound_vars, Set_of_closures soc ->
To_cmm_set_of_closures.let_dynamic_set_of_closures env res ~body ~bound_vars
~num_normal_occurrences_of_bound_vars soc ~translate_expr:expr
| Static bound_static, Static_consts consts -> (
let env, res, update_opt =
To_cmm_static.static_consts env res
~params_and_body:
(To_cmm_set_of_closures.params_and_body ~translate_expr:expr)
bound_static consts
in
match update_opt with
| None -> expr env res body
| Some { cmm; free_vars; effs = _ } ->
let wrap, env, res =
Env.flush_delayed_lets ~mode:Branching_point env res
in
let body, body_free_vars, res = expr env res body in
let free_vars = Backend_var.Set.union free_vars body_free_vars in
let cmm, free_vars = wrap (C.sequence cmm body) free_vars in
cmm, free_vars, res)
| Singleton _, Rec_info _ -> expr env res body
| Singleton _, (Set_of_closures _ | Static_consts _)
| Set_of_closures _, (Simple _ | Prim _ | Static_consts _ | Rec_info _)
| Static _, (Simple _ | Prim _ | Set_of_closures _ | Rec_info _) ->
Misc.fatal_errorf "Mismatch between pattern and defining expression:@ %a"
Let.print let_expr
and let_expr env res let_expr =
Let.pattern_match' let_expr
~f:(fun bound_pattern ~num_normal_occurrences_of_bound_vars ~body ->
match Bound_pattern.name_mode bound_pattern with
| Normal ->
let_expr0 env res let_expr bound_pattern
~num_normal_occurrences_of_bound_vars ~body
| Phantom -> expr env res body
| In_types ->
Misc.fatal_errorf "Cannot bind In_types variables in terms:@ %a"
Let.print let_expr)
and let_cont env res (let_cont : Flambda.Let_cont.t) =
match let_cont with
| Non_recursive { handler; num_free_occurrences; is_applied_with_traps } ->
Non_recursive_let_cont_handler.pattern_match handler ~f:(fun k ~body ->
let handler = Non_recursive_let_cont_handler.handler handler in
match
To_cmm_effects.classify_continuation_handler k handler
~num_free_occurrences ~is_applied_with_traps
with
| May_inline -> let_cont_inlined env res k handler body
| Regular -> let_cont_not_inlined env res k handler body)
| Recursive handlers ->
Recursive_let_cont_handlers.pattern_match handlers
~f:(fun ~invariant_params ~body conts ->
if Continuation_handlers.contains_exn_handler conts
then
Misc.fatal_errorf
"Recursive continuation bindings cannot involve exception \
handlers:@ %a"
Let_cont.print let_cont;
let_cont_rec env res invariant_params conts body)
and let_cont_inlined env res k handler body =
Continuation_handler.pattern_match' handler
~f:(fun handler_params ~num_normal_occurrences_of_params ~handler ->
let env =
Env.add_inline_cont env k ~handler_params
~handler_params_occurrences:num_normal_occurrences_of_params
~handler_body:handler
in
expr env res body)
and let_cont_not_inlined env res k handler body =
let wrap, env, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let is_exn_handler = Continuation_handler.is_exn_handler handler in
let vars, arity, handler, free_vars_of_handler, res =
continuation_handler env res handler
in
let catch_id, env =
Env.add_jump_cont env k ~param_types:(List.map snd vars)
in
let cmm, free_vars, res =
if is_exn_handler
then
let_cont_exn_handler env res k body vars handler free_vars_of_handler
~catch_id arity
else
CR mshinwell : fix debuginfo
let body, free_vars_of_body, res = expr env res body in
let free_vars =
Backend_var.Set.union free_vars_of_body
(C.remove_vars_with_machtype free_vars_of_handler vars)
in
( C.create_ccatch ~rec_flag:false ~body
~handlers:[C.handler ~dbg catch_id vars handler],
free_vars,
res )
in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
Exception continuations are translated using delayed Ctrywith blocks . The
exception handler parts of these blocks are identified by the [ catch_id]s .
Additionally , exception continuations can have extra args , which are passed
through the try - with using mutable Cmm variables . Thus the exception handler
must first read the contents of those extra args ( eagerly , in order to
minmize the lifetime of the mutable variables ) .
exception handler parts of these blocks are identified by the [catch_id]s.
Additionally, exception continuations can have extra args, which are passed
through the try-with using mutable Cmm variables. Thus the exception handler
must first read the contents of those extra args (eagerly, in order to
minmize the lifetime of the mutable variables). *)
and let_cont_exn_handler env res k body vars handler free_vars_of_handler
~catch_id arity =
let exn_var, extra_params =
match vars with
| (v, _) :: rest -> v, rest
| [] ->
Misc.fatal_errorf
"Exception continuation %a should have at least one argument"
Continuation.print k
in
let env_body, mut_vars = Env.add_exn_handler env k arity in
let handler =
List.fold_left2
(fun handler (mut_var, _) (extra_param, _) ->
C.letin extra_param ~defining_expr:(C.var mut_var) ~body:handler)
handler mut_vars extra_params
in
let body, free_vars_of_body, res = expr env_body res body in
let free_vars =
Backend_var.Set.union free_vars_of_body
(C.remove_vars_with_machtype free_vars_of_handler vars)
in
CR mshinwell : fix debuginfo
let trywith =
C.trywith ~dbg ~kind:(Delayed catch_id) ~body ~exn_var ~handler ()
in
Define and initialize the mutable Cmm variables for extra args
let cmm =
List.fold_left
(fun cmm (mut_var, (kind : K.t)) ->
let mut_var =
Backend_var.With_provenance.create ?provenance:None mut_var
in
let dummy_value =
match kind with
| Value -> C.int ~dbg 1
| Naked_number Naked_float -> C.float ~dbg 0.
| Naked_number
(Naked_immediate | Naked_int32 | Naked_int64 | Naked_nativeint) ->
C.int ~dbg 0
| Region | Rec_info ->
Misc.fatal_errorf "No dummy value available for kind %a" K.print
kind
in
C.letin_mut mut_var (C.machtype_of_kind kind) dummy_value cmm)
trywith mut_vars
in
cmm, free_vars, res
and let_cont_rec env res invariant_params conts body =
Flush the env now to avoid inlining something inside of a recursive
continuation ( aka a loop ) , as it would increase the number of times the
computation is performed ( even if there is only one syntactic
occurrence )
continuation (aka a loop), as it would increase the number of times the
computation is performed (even if there is only one syntactic
occurrence) *)
let wrap, env, res = Env.flush_delayed_lets ~mode:Entering_loop env res in
let conts_to_handlers = Continuation_handlers.to_map conts in
let env =
Continuation.Map.fold
(fun k handler acc ->
let continuation_arg_tys =
Continuation_handler.pattern_match' handler
~f:(fun params ~num_normal_occurrences_of_params:_ ~handler:_ ->
List.map C.machtype_of_kinded_parameter
(Bound_parameters.to_list
(Bound_parameters.append invariant_params params)))
in
snd (Env.add_jump_cont acc k ~param_types:continuation_arg_tys))
conts_to_handlers env
in
let env, invariant_vars = C.bound_parameters env invariant_params in
let conts_to_handlers, res =
Continuation.Map.fold
(fun k handler (conts_to_handlers, res) ->
let vars, _arity, handler, free_vars_of_handler, res =
continuation_handler env res handler
in
( Continuation.Map.add k
(invariant_vars @ vars, handler, free_vars_of_handler)
conts_to_handlers,
res ))
conts_to_handlers
(Continuation.Map.empty, res)
in
CR mshinwell : fix debuginfo
let body, free_vars_of_body, res = expr env res body in
Setup the Cmm handlers for the Ccatch
let handlers, free_vars =
Continuation.Map.fold
(fun k (vars, handler, free_vars_of_handler) (handlers, free_vars) ->
let free_vars =
Backend_var.Set.union free_vars
(C.remove_vars_with_machtype free_vars_of_handler vars)
in
let id = Env.get_cmm_continuation env k in
C.handler ~dbg id vars handler :: handlers, free_vars)
conts_to_handlers ([], free_vars_of_body)
in
let cmm = C.create_ccatch ~rec_flag:true ~body ~handlers in
let cmm, free_vars = wrap cmm free_vars in
cmm, free_vars, res
and continuation_handler env res handler =
Continuation_handler.pattern_match' handler
~f:(fun params ~num_normal_occurrences_of_params:_ ~handler ->
let arity = Bound_parameters.arity params in
let env, vars = C.bound_parameters env params in
let expr, free_vars_of_handler, res = expr env res handler in
vars, arity, expr, free_vars_of_handler, res)
and apply_expr env res apply =
let call, free_vars, env, res, effs = translate_apply env res apply in
With respect to flushing the environment we have three cases :
1 . The call never returns or jumps to another function
2 . The call jumps to somewhere else in the current function , but there is
more than one incoming control flow edge to that point
3 . The call jumps to somewhere else in the current function and is the only
thing that jumps to that point . In this case we will inline the return
continuation of the [ Apply ] .
In case 1 we ca n't affect the code generation at the jump target : there is
no option but to flush now .
In case 2 we also flush to ensure that effectful bindings are not pushed
past join points and that no binding is duplicated .
In case 3 we can avoid flushing the environment due to the linearity of the
control flow . We know that flushing will eventually happen by virtue of the
recursive call to [ expr ] .
1. The call never returns or jumps to another function
2. The call jumps to somewhere else in the current function, but there is
more than one incoming control flow edge to that point
3. The call jumps to somewhere else in the current function and is the only
thing that jumps to that point. In this case we will inline the return
continuation of the [Apply].
In case 1 we can't affect the code generation at the jump target: there is
no option but to flush now.
In case 2 we also flush to ensure that effectful bindings are not pushed
past join points and that no binding is duplicated.
In case 3 we can avoid flushing the environment due to the linearity of the
control flow. We know that flushing will eventually happen by virtue of the
recursive call to [expr]. *)
match Apply.continuation apply with
| Never_returns ->
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap call free_vars in
cmm, free_vars, res
| Return k when Continuation.equal (Env.return_continuation env) k ->
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap call free_vars in
cmm, free_vars, res
| Return k -> (
let[@inline always] unsupported () =
Misc.fatal_errorf
"Return continuation %a should be applied to a single argument in@\n\
%a@\n\
Multiple return values from functions are not yet supported"
Continuation.print k Apply.print apply
in
match Env.get_continuation env k with
| Jump { param_types = []; cont = _ } -> unsupported ()
| Jump { param_types = [_]; cont } ->
let wrap, _, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let cmm, free_vars = wrap (C.cexit cont [call] []) free_vars in
cmm, free_vars, res
| Inline { handler_params; handler_body = body; handler_params_occurrences }
-> (
let handler_params = Bound_parameters.to_list handler_params in
match handler_params with
| [] -> unsupported ()
| [param] ->
let var = Bound_parameter.var param in
let env, res =
Env.bind_variable env res var
~effects_and_coeffects_of_defining_expr:effs ~defining_expr:call
~free_vars_of_defining_expr:free_vars
~num_normal_occurrences_of_bound_vars:handler_params_occurrences
in
expr env res body
| _ :: _ -> unsupported ())
| Jump _ -> unsupported ())
and apply_cont env res apply_cont =
let k = Apply_cont.continuation apply_cont in
let args = Apply_cont.args apply_cont in
if Env.is_exn_handler env k
then translate_raise env res apply_cont k args
else if Continuation.equal (Env.return_continuation env) k
then translate_jump_to_return_continuation env res apply_cont k args
else
match Env.get_continuation env k with
| Jump { param_types; cont } ->
translate_jump_to_continuation env res apply_cont param_types cont args
| Inline { handler_params; handler_body; handler_params_occurrences } ->
if Option.is_some (Apply_cont.trap_action apply_cont)
then
Misc.fatal_errorf "This [Apply_cont] should not have a trap action:@ %a"
Apply_cont.print apply_cont;
let handler_params = Bound_parameters.to_list handler_params in
if List.compare_lengths args handler_params = 0
then
let env, res =
List.fold_left2
(fun (env, res) param ->
bind_var_to_simple
~dbg:(Apply_cont.debuginfo apply_cont)
env res
(Bound_parameter.var param)
~num_normal_occurrences_of_bound_vars:handler_params_occurrences)
(env, res) handler_params args
in
expr env res handler_body
else
Misc.fatal_errorf
"Continuation %a in@\n%a@\nExpected %d arguments but got %a."
Continuation.print k Apply_cont.print apply_cont
(List.length handler_params)
Apply_cont.print apply_cont
and switch env res switch =
let scrutinee = Switch.scrutinee switch in
let dbg = Switch.condition_dbg switch in
let To_cmm_env.
{ env;
res;
expr =
{ cmm = untagged_scrutinee_cmm;
free_vars = scrutinee_free_vars;
effs = _
}
} =
C.simple ~dbg env res scrutinee
in
let arms = Switch.arms switch in
For binary switches , which can be translated to an if - then - else , it can be
interesting for the scrutinee to be tagged ( particularly for switches
coming from a source level if - then - else on booleans ) as that way the
translation can use 2 instructions instead of 3 .
However , this is only useful to do if the tagged expression is smaller then
the untagged one ( which is not always true due to arithmetic
simplifications performed by Cmm_helpers ) .
Additionally for switches with more than 2 arms , not untagging and
adjusting the switch to work on tagged integers might be worse . The
discriminants of the arms might not be successive machine integers anymore ,
thus preventing the use of a table . Alternatively it might not be worth it
given the already high number of instructions needed for big switches ( but
this might be debatable for small switches with 3 to 5 arms ) .
interesting for the scrutinee to be tagged (particularly for switches
coming from a source level if-then-else on booleans) as that way the
translation can use 2 instructions instead of 3.
However, this is only useful to do if the tagged expression is smaller then
the untagged one (which is not always true due to arithmetic
simplifications performed by Cmm_helpers).
Additionally for switches with more than 2 arms, not untagging and
adjusting the switch to work on tagged integers might be worse. The
discriminants of the arms might not be successive machine integers anymore,
thus preventing the use of a table. Alternatively it might not be worth it
given the already high number of instructions needed for big switches (but
this might be debatable for small switches with 3 to 5 arms). *)
let scrutinee, must_tag_discriminant =
match Targetint_31_63.Map.cardinal arms with
| 2 -> (
match Env.extra_info env scrutinee with
| None -> untagged_scrutinee_cmm, false
| Some (Untag tagged_scrutinee_cmm) ->
let size_untagged =
Option.value
(C.cmm_arith_size untagged_scrutinee_cmm)
~default:max_int
in
let size_tagged =
Option.value (C.cmm_arith_size tagged_scrutinee_cmm) ~default:max_int
in
if size_tagged < size_untagged
then tagged_scrutinee_cmm, true
else untagged_scrutinee_cmm, false)
| _ -> untagged_scrutinee_cmm, false
in
let wrap, env, res = Env.flush_delayed_lets ~mode:Branching_point env res in
let prepare_discriminant ~must_tag d =
let targetint_d = Targetint_31_63.to_targetint d in
Targetint_32_64.to_int_checked
(if must_tag then C.tag_targetint targetint_d else targetint_d)
in
let make_arm ~must_tag_discriminant env res (d, action) =
let d = prepare_discriminant ~must_tag:must_tag_discriminant d in
let cmm_action, action_free_vars, res = apply_cont env res action in
(d, cmm_action, action_free_vars, Apply_cont.debuginfo action), res
in
match Targetint_31_63.Map.cardinal arms with
| 2 -> (
let aux = make_arm ~must_tag_discriminant env in
let first_arm, res = aux res (Targetint_31_63.Map.min_binding arms) in
let second_arm, res = aux res (Targetint_31_63.Map.max_binding arms) in
match first_arm, second_arm with
These switches are actually if - then - elses . On such switches ,
transl_switch_clambda will introduce a let - binding of the scrutinee
before creating an if - then - else , introducing an indirection that might
prevent some optimizations performed by Selectgen / Emit when the condition
is inlined in the if - then - else . Instead we use [ C.ite ] .
transl_switch_clambda will introduce a let-binding of the scrutinee
before creating an if-then-else, introducing an indirection that might
prevent some optimizations performed by Selectgen/Emit when the condition
is inlined in the if-then-else. Instead we use [C.ite]. *)
| (0, else_, else_free_vars, else_dbg), (_, then_, then_free_vars, then_dbg)
| (_, then_, then_free_vars, then_dbg), (0, else_, else_free_vars, else_dbg)
->
let free_vars =
Backend_var.Set.union scrutinee_free_vars
(Backend_var.Set.union else_free_vars then_free_vars)
in
let cmm, free_vars =
wrap (C.ite ~dbg scrutinee ~then_dbg ~then_ ~else_dbg ~else_) free_vars
in
cmm, free_vars, res
Similar case to the previous but none of the arms match 0 , so we have to
generate an equality test , and make sure it is inside the condition to
ensure Selectgen and Emit can take advantage of it .
generate an equality test, and make sure it is inside the condition to
ensure Selectgen and Emit can take advantage of it. *)
| ( (x, if_x, if_x_free_vars, if_x_dbg),
(_, if_not, if_not_free_vars, if_not_dbg) ) ->
let free_vars =
Backend_var.Set.union scrutinee_free_vars
(Backend_var.Set.union if_x_free_vars if_not_free_vars)
in
let expr =
C.ite ~dbg
(C.eq ~dbg (C.int ~dbg x) scrutinee)
~then_dbg:if_x_dbg ~then_:if_x ~else_dbg:if_not_dbg ~else_:if_not
in
let cmm, free_vars = wrap expr free_vars in
cmm, free_vars, res)
| n ->
let max_d, _ = Targetint_31_63.Map.max_binding arms in
let m = prepare_discriminant ~must_tag:must_tag_discriminant max_d in
let unreachable, res = C.invalid res ~message:"unreachable switch case" in
let cases = Array.make (n + 1) unreachable in
let index = Array.make (m + 1) n in
let _, res, free_vars =
Targetint_31_63.Map.fold
(fun discriminant action (i, res, free_vars) ->
let (d, cmm_action, action_free_vars, _dbg), res =
make_arm ~must_tag_discriminant env res (discriminant, action)
in
let free_vars = Backend_var.Set.union free_vars action_free_vars in
cases.(i) <- cmm_action;
index.(d) <- i;
i + 1, res, free_vars)
arms
(0, res, scrutinee_free_vars)
in
let expr =
C.transl_switch_clambda dbg (Vval Pgenval) scrutinee index cases
in
let cmm, free_vars = wrap expr free_vars in
cmm, free_vars, res
|
732ac725a3505d137b622ad27971411de4b0be443aabb22b0872ebb7d2faead3 | ygmpkk/house | Unicode.hs | {-# OPTIONS -optc-DSTANDALONE #-}
{-# OPTIONS -#include "config.h" #-}
# LINE 1 " Unicode.hsc " #
{-# OPTIONS -fno-implicit-prelude #-}
# LINE 2 " Unicode.hsc " #
-----------------------------------------------------------------------------
-- |
Module :
Copyright : ( c ) The University of Glasgow , 2003
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC extensions )
--
-- Implementations for the character predicates (isLower, isUpper, etc.)
-- and the conversions (toUpper, toLower). The implementation uses
-- libunicode on Unix systems if that is available.
--
-----------------------------------------------------------------------------
module GHC.Unicode (
isAscii, isLatin1, isControl,
isAsciiUpper, isAsciiLower,
isPrint, isSpace, isUpper,
isLower, isAlpha, isDigit,
isOctDigit, isHexDigit, isAlphaNum,
toUpper, toLower,
) where
import GHC.Base
import GHC.Real (fromIntegral)
import GHC.Int
import GHC.Word
import GHC.Num (fromInteger)
# LINE 34 " Unicode.hsc " #
| Selects the first 128 characters of the Unicode character set ,
-- corresponding to the ASCII character set.
isAscii :: Char -> Bool
isAscii c = c < '\x80'
| Selects the first 256 characters of the Unicode character set ,
-- corresponding to the ISO 8859-1 (Latin-1) character set.
isLatin1 :: Char -> Bool
isLatin1 c = c <= '\xff'
isAsciiUpper, isAsciiLower :: Char -> Bool
isAsciiLower c = c >= 'a' && c <= 'z'
isAsciiUpper c = c >= 'A' && c <= 'Z'
-- | Selects control characters, which are the non-printing characters of
the Latin-1 subset of Unicode .
isControl :: Char -> Bool
| Selects printable Unicode characters
-- (letters, numbers, marks, punctuation, symbols and spaces).
isPrint :: Char -> Bool
-- | Selects white-space characters in the Latin-1 range.
( In Unicode terms , this includes spaces and some control characters . )
isSpace :: Char -> Bool
-- isSpace includes non-breaking space
-- Done with explicit equalities both for efficiency, and to avoid a tiresome
recursion with GHC.List elem
isSpace c = c == ' ' ||
c == '\t' ||
c == '\n' ||
c == '\r' ||
c == '\f' ||
c == '\v' ||
c == '\xa0'
-- | Selects alphabetic Unicode characters (letters) that are not lower-case.
( In Unicode terms , this includes letters in upper and title cases ,
-- as well as modifier letters and other letters.)
isUpper :: Char -> Bool
-- | Selects lower-case alphabetic Unicode characters (letters).
isLower :: Char -> Bool
-- | Selects alphabetic Unicode characters (letters).
isAlpha :: Char -> Bool
-- | Selects alphabetic or numeric digit Unicode characters.
--
-- Note that numeric digits outside the ASCII range are selected by this
-- function but not by 'isDigit'. Such digits may be part of identifiers
-- but are not used by the printer and reader to represent numbers.
isAlphaNum :: Char -> Bool
-- | Selects ASCII digits, i.e. @\'0\'@..@\'9\'@.
isDigit :: Char -> Bool
-- | Selects ASCII octal digits, i.e. @\'0\'@..@\'7\'@.
isOctDigit :: Char -> Bool
isOctDigit c = c >= '0' && c <= '7'
-- | Selects ASCII hexadecimal digits,
i.e. @\'0\'@ .. @\'9\'@ , @\'a\'@ .. @\'f\'@ , @\'A\'@ .. @\'F\'@.
isHexDigit :: Char -> Bool
isHexDigit c = isDigit c || c >= 'A' && c <= 'F' ||
c >= 'a' && c <= 'f'
-- | Convert a letter to the corresponding upper-case letter, leaving any
other character unchanged . Any letter which has an upper - case
-- equivalent is transformed.
toUpper :: Char -> Char
-- | Convert a letter to the corresponding lower-case letter, leaving any
other character unchanged . Any letter which has a lower - case
-- equivalent is transformed.
toLower :: Char -> Char
-- -----------------------------------------------------------------------------
-- Win32 implementation
# LINE 175 " Unicode.hsc " #
isControl c = c < ' ' || c >= '\DEL' && c <= '\x9f'
isPrint c = not (isControl c)
-- The upper case ISO characters have the multiplication sign dumped
-- randomly in the middle of the range. Go figure.
isUpper c = c >= 'A' && c <= 'Z' ||
c >= '\xC0' && c <= '\xD6' ||
c >= '\xD8' && c <= '\xDE'
-- The lower case ISO characters have the division sign dumped
-- randomly in the middle of the range. Go figure.
isLower c = c >= 'a' && c <= 'z' ||
c >= '\xDF' && c <= '\xF6' ||
c >= '\xF8' && c <= '\xFF'
isAlpha c = isLower c || isUpper c
isDigit c = c >= '0' && c <= '9'
isAlphaNum c = isAlpha c || isDigit c
-- Case-changing operations
toUpper c@(C# c#)
| isAsciiLower c = C# (chr# (ord# c# -# 32#))
| isAscii c = c
-- fall-through to the slower stuff.
| isLower c && c /= '\xDF' && c /= '\xFF'
= unsafeChr (ord c `minusInt` ord 'a' `plusInt` ord 'A')
| otherwise
= c
toLower c@(C# c#)
| isAsciiUpper c = C# (chr# (ord# c# +# 32#))
| isAscii c = c
| isUpper c = unsafeChr (ord c `minusInt` ord 'A' `plusInt` ord 'a')
| otherwise = c
# LINE 213 " Unicode.hsc " #
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/base/GHC/Unicode.hs | haskell | # OPTIONS -optc-DSTANDALONE #
# OPTIONS -#include "config.h" #
# OPTIONS -fno-implicit-prelude #
---------------------------------------------------------------------------
|
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
Implementations for the character predicates (isLower, isUpper, etc.)
and the conversions (toUpper, toLower). The implementation uses
libunicode on Unix systems if that is available.
---------------------------------------------------------------------------
corresponding to the ASCII character set.
corresponding to the ISO 8859-1 (Latin-1) character set.
| Selects control characters, which are the non-printing characters of
(letters, numbers, marks, punctuation, symbols and spaces).
| Selects white-space characters in the Latin-1 range.
isSpace includes non-breaking space
Done with explicit equalities both for efficiency, and to avoid a tiresome
| Selects alphabetic Unicode characters (letters) that are not lower-case.
as well as modifier letters and other letters.)
| Selects lower-case alphabetic Unicode characters (letters).
| Selects alphabetic Unicode characters (letters).
| Selects alphabetic or numeric digit Unicode characters.
Note that numeric digits outside the ASCII range are selected by this
function but not by 'isDigit'. Such digits may be part of identifiers
but are not used by the printer and reader to represent numbers.
| Selects ASCII digits, i.e. @\'0\'@..@\'9\'@.
| Selects ASCII octal digits, i.e. @\'0\'@..@\'7\'@.
| Selects ASCII hexadecimal digits,
| Convert a letter to the corresponding upper-case letter, leaving any
equivalent is transformed.
| Convert a letter to the corresponding lower-case letter, leaving any
equivalent is transformed.
-----------------------------------------------------------------------------
Win32 implementation
The upper case ISO characters have the multiplication sign dumped
randomly in the middle of the range. Go figure.
The lower case ISO characters have the division sign dumped
randomly in the middle of the range. Go figure.
Case-changing operations
fall-through to the slower stuff. | # LINE 1 " Unicode.hsc " #
# LINE 2 " Unicode.hsc " #
Module :
Copyright : ( c ) The University of Glasgow , 2003
Portability : non - portable ( GHC extensions )
module GHC.Unicode (
isAscii, isLatin1, isControl,
isAsciiUpper, isAsciiLower,
isPrint, isSpace, isUpper,
isLower, isAlpha, isDigit,
isOctDigit, isHexDigit, isAlphaNum,
toUpper, toLower,
) where
import GHC.Base
import GHC.Real (fromIntegral)
import GHC.Int
import GHC.Word
import GHC.Num (fromInteger)
# LINE 34 " Unicode.hsc " #
| Selects the first 128 characters of the Unicode character set ,
isAscii :: Char -> Bool
isAscii c = c < '\x80'
| Selects the first 256 characters of the Unicode character set ,
isLatin1 :: Char -> Bool
isLatin1 c = c <= '\xff'
isAsciiUpper, isAsciiLower :: Char -> Bool
isAsciiLower c = c >= 'a' && c <= 'z'
isAsciiUpper c = c >= 'A' && c <= 'Z'
the Latin-1 subset of Unicode .
isControl :: Char -> Bool
| Selects printable Unicode characters
isPrint :: Char -> Bool
( In Unicode terms , this includes spaces and some control characters . )
isSpace :: Char -> Bool
recursion with GHC.List elem
isSpace c = c == ' ' ||
c == '\t' ||
c == '\n' ||
c == '\r' ||
c == '\f' ||
c == '\v' ||
c == '\xa0'
( In Unicode terms , this includes letters in upper and title cases ,
isUpper :: Char -> Bool
isLower :: Char -> Bool
isAlpha :: Char -> Bool
isAlphaNum :: Char -> Bool
isDigit :: Char -> Bool
isOctDigit :: Char -> Bool
isOctDigit c = c >= '0' && c <= '7'
i.e. @\'0\'@ .. @\'9\'@ , @\'a\'@ .. @\'f\'@ , @\'A\'@ .. @\'F\'@.
isHexDigit :: Char -> Bool
isHexDigit c = isDigit c || c >= 'A' && c <= 'F' ||
c >= 'a' && c <= 'f'
other character unchanged . Any letter which has an upper - case
toUpper :: Char -> Char
other character unchanged . Any letter which has a lower - case
toLower :: Char -> Char
# LINE 175 " Unicode.hsc " #
isControl c = c < ' ' || c >= '\DEL' && c <= '\x9f'
isPrint c = not (isControl c)
isUpper c = c >= 'A' && c <= 'Z' ||
c >= '\xC0' && c <= '\xD6' ||
c >= '\xD8' && c <= '\xDE'
isLower c = c >= 'a' && c <= 'z' ||
c >= '\xDF' && c <= '\xF6' ||
c >= '\xF8' && c <= '\xFF'
isAlpha c = isLower c || isUpper c
isDigit c = c >= '0' && c <= '9'
isAlphaNum c = isAlpha c || isDigit c
toUpper c@(C# c#)
| isAsciiLower c = C# (chr# (ord# c# -# 32#))
| isAscii c = c
| isLower c && c /= '\xDF' && c /= '\xFF'
= unsafeChr (ord c `minusInt` ord 'a' `plusInt` ord 'A')
| otherwise
= c
toLower c@(C# c#)
| isAsciiUpper c = C# (chr# (ord# c# +# 32#))
| isAscii c = c
| isUpper c = unsafeChr (ord c `minusInt` ord 'A' `plusInt` ord 'a')
| otherwise = c
# LINE 213 " Unicode.hsc " #
|
97fb2f9e716803f15624e6e7ad4021ecccc2b683d63179ece03e637e53a04e61 | onedata/op-worker | file_popularity_test_SUITE.erl | %%%-------------------------------------------------------------------
@author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%%--------------------------------------------------------------------
%%% @doc
%%% This module contains tests of file_popularity_view.
%%% The view is queried using view_traverse mechanism.
%%% @end
%%%-------------------------------------------------------------------
-module(file_popularity_test_SUITE).
-author("Jakub Kudzia").
-behaviour(view_traverse).
-include("global_definitions.hrl").
-include("lfm_test_utils.hrl").
-include("modules/fslogic/acl.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/file_popularity/file_popularity_view.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include_lib("ctool/include/logging.hrl").
-include_lib("ctool/include/test/test_utils.hrl").
-include_lib("ctool/include/test/assertions.hrl").
-include_lib("ctool/include/errors.hrl").
%% API
-export([all/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2,
end_per_testcase/2]).
-export([
query_should_return_error_when_file_popularity_is_disabled/1,
query_should_return_empty_list_when_file_popularity_is_enabled/1,
query_should_return_empty_list_when_file_has_not_been_opened/1,
query_should_return_file_when_file_has_been_opened/1,
query_should_return_files_sorted_by_increasing_last_open_timestamp/1,
query_should_return_files_sorted_by_increasing_avg_open_count_per_day/1,
file_should_have_correct_popularity_value/1,
file_should_have_correct_popularity_value2/1,
file_should_have_correct_popularity_value3/1,
avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default/1,
avg_open_count_per_day_parameter_should_be_bounded_by_custom_value/1,
changing_max_avg_open_count_per_day_limit_should_reindex_the_file/1,
changing_last_open_weight_should_reindex_the_file/1,
changing_avg_open_count_weight_should_reindex_the_file/1,
time_warp_test/1
]).
%% view_traverse callbacks
-export([process_row/3, task_finished/1]).
%% view_processing_module API
-export([init/0, stop/0, run/2]).
%% exported for RPC
-export([start_collector/1, collector_loop/1]).
all() -> [
query_should_return_error_when_file_popularity_is_disabled,
query_should_return_empty_list_when_file_popularity_is_enabled,
query_should_return_empty_list_when_file_has_not_been_opened,
query_should_return_file_when_file_has_been_opened,
file_should_have_correct_popularity_value,
file_should_have_correct_popularity_value2,
file_should_have_correct_popularity_value3,
avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default,
avg_open_count_per_day_parameter_should_be_bounded_by_custom_value,
changing_max_avg_open_count_per_day_limit_should_reindex_the_file,
changing_last_open_weight_should_reindex_the_file,
changing_avg_open_count_weight_should_reindex_the_file,
query_should_return_files_sorted_by_increasing_avg_open_count_per_day,
query_should_return_files_sorted_by_increasing_last_open_timestamp,
time_warp_test
].
-define(SPACE_ID, <<"space1">>).
-define(VIEW_PROCESSING_MODULE, ?MODULE).
-define(FILE_PATH(FileName), filename:join(["/", ?SPACE_ID, FileName])).
-define(USER1, <<"user1">>).
-define(SESSION(Worker, Config), ?SESS_ID(?USER1, Worker, Config)).
-define(ATTEMPTS, 10).
% name for process responsible for collecting traverse results
-define(COLLECTOR, collector).
% messages used to communicate with ?COLLECTOR process
-define(FINISHED, finished).
-define(COLLECTED_RESULTS(Rows), {collected_results, Rows}).
-define(ROW(FileId, Popularity, RowNum), {row, FileId, Popularity, RowNum}).
%%%===================================================================
%%% API
%%%===================================================================
query_should_return_error_when_file_popularity_is_disabled(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
?assertMatch({error, not_found}, query(W, ?SPACE_ID, #{})).
query_should_return_empty_list_when_file_popularity_is_enabled(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
?assertMatch([], query(W, ?SPACE_ID, #{})).
query_should_return_empty_list_when_file_has_not_been_opened(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
{ok, _} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
?assertMatch([], query(W, ?SPACE_ID, #{})).
query_should_return_file_when_file_has_been_opened(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, H} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G), read),
ok = lfm_proxy:close(W, H),
{ok, FileId} = file_id:guid_to_objectid(G),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
file_should_have_correct_popularity_value(Config) ->
file_should_have_correct_popularity_value_base(Config, 1.123, 0).
file_should_have_correct_popularity_value2(Config) ->
file_should_have_correct_popularity_value_base(Config, 0, 9.987).
file_should_have_correct_popularity_value3(Config) ->
file_should_have_correct_popularity_value_base(Config, 1.123, 9.987).
avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
2 files should have the same probability value , despite having different avg_open_count
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
DefaultMaxOpenCount = 100,
avg_open_count = 100
avg_open_count = 101
% all files will have the same timestamp as the time is frozen
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
open_and_close_file(W, ?SESSION(W, Config), G1, OpenCountPerMonth1),
open_and_close_file(W, ?SESSION(W, Config), G2, OpenCountPerMonth2),
?assertMatch([{_, _Popularity}, {_, _Popularity}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
avg_open_count_per_day_parameter_should_be_bounded_by_custom_value(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
2 files should have the same probability value , despite having different avg_open_count
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
LastOpenWeight = 1.0,
AvgOpenCountPerDayWeight = 20.0,
MaxOpenCount = 10,
avg_open_count = 100
avg_open_count = 200
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
open_and_close_file(W, ?SESSION(W, Config), G1, OpenCountPerMonth1),
open_and_close_file(W, ?SESSION(W, Config), G2, OpenCountPerMonth2),
?assertMatch([{_, _Popularity}, {_, _Popularity}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
changing_max_avg_open_count_per_day_limit_should_reindex_the_file(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
LastOpenWeight = 1.0,
AvgOpenCountPerDayWeight = 20.0,
MaxOpenCount = 10,
MaxOpenCount2 = 20,
avg_open_count = 15
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, FileId} = file_id:guid_to_objectid(G),
open_and_close_file(W, ?SESSION(W, Config), G, OpenCountPerMonth),
[{_, Popularity}] = ?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS),
ok = configure_file_popularity(W, ?SPACE_ID, undefined, undefined, undefined, MaxOpenCount2),
?assertNotMatch([{_, Popularity}], query(W, ?SPACE_ID, #{})),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{})).
changing_last_open_weight_should_reindex_the_file(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
LastOpenWeight = 1.0,
LastOpenWeight2 = 2.0,
AvgOpenCountPerDayWeight = 20.0,
MaxOpenCount = 10,
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, FileId} = file_id:guid_to_objectid(G),
open_and_close_file(W, ?SESSION(W, Config), G, 1),
[{_, Popularity}] = ?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS),
ok = configure_file_popularity(W, ?SPACE_ID, undefined, LastOpenWeight2, undefined, undefined),
?assertNotMatch([{_, Popularity}], query(W, ?SPACE_ID, #{})),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{})).
changing_avg_open_count_weight_should_reindex_the_file(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
LastOpenWeight = 1.0,
AvgOpenCountPerDayWeight = 20.0,
AvgOpenCountPerDayWeight2 = 40.0,
MaxOpenCount = 10,
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, FileId} = file_id:guid_to_objectid(G),
open_and_close_file(W, ?SESSION(W, Config), G, 1),
[{_, Popularity}] = ?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS),
ok = configure_file_popularity(W, ?SPACE_ID, undefined, undefined, AvgOpenCountPerDayWeight2, undefined),
?assertNotMatch([{_, Popularity}], query(W, ?SPACE_ID, #{})),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{})).
query_should_return_files_sorted_by_increasing_avg_open_count_per_day(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FileName3 = <<"file3">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
FilePath3 = ?FILE_PATH(FileName3),
% all files will have the same timestamp as the time is frozen
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
{ok, H} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G1), read),
ok = lfm_proxy:close(W, H),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
{ok, H2} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G2), read),
ok = lfm_proxy:close(W, H2),
{ok, H22} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G2), read),
ok = lfm_proxy:close(W, H22),
{ok, G3} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath3),
{ok, H3} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G3), read),
ok = lfm_proxy:close(W, H3),
{ok, H32} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G3), read),
ok = lfm_proxy:close(W, H32),
{ok, H33} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G3), read),
ok = lfm_proxy:close(W, H33),
{ok, FileId1} = file_id:guid_to_objectid(G1),
{ok, FileId2} = file_id:guid_to_objectid(G2),
{ok, FileId3} = file_id:guid_to_objectid(G3),
?assertMatch([{FileId1, _}, {FileId2, _}, {FileId3, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
query_should_return_files_sorted_by_increasing_last_open_timestamp(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FileName3 = <<"file3">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
FilePath3 = ?FILE_PATH(FileName3),
simulate each next file being opened one hour after the previous one
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
3 hours before query
ok = lfm_proxy:close(W, H1),
time_test_utils:simulate_seconds_passing(3600),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
2 hours before query
ok = lfm_proxy:close(W, H2),
time_test_utils:simulate_seconds_passing(3600),
{ok, G3} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath3),
1 hour before query
ok = lfm_proxy:close(W, H3),
time_test_utils:simulate_seconds_passing(3600),
{ok, FileId1} = file_id:guid_to_objectid(G1),
{ok, FileId2} = file_id:guid_to_objectid(G2),
{ok, FileId3} = file_id:guid_to_objectid(G3),
?assertMatch([{FileId1, _}, {FileId2, _}, {FileId3, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
time_warp_test(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FileName3 = <<"file3">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
FilePath3 = ?FILE_PATH(FileName3),
simulate each next file being opened one hour BEFORE the previous one ( due to a time warp )
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
1 hour before query
ok = lfm_proxy:close(W, H1),
time_test_utils:simulate_seconds_passing(-3600),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
2 hours before query
ok = lfm_proxy:close(W, H2),
time_test_utils:simulate_seconds_passing(-3600),
{ok, G3} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath3),
3 hour before query
ok = lfm_proxy:close(W, H3),
time_test_utils:simulate_seconds_passing(-3600),
{ok, FileId1} = file_id:guid_to_objectid(G1),
{ok, FileId2} = file_id:guid_to_objectid(G2),
{ok, FileId3} = file_id:guid_to_objectid(G3),
% Files should be sorted by increasing timestamp of last open
% Due to time warps, file that was created as last one has the smallest timestamp so the files
% should be sorted in reverse order than they were created
?assertMatch([{FileId3, _}, {FileId2, _}, {FileId1, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
%%%===================================================================
%%% Test base functions
%%%===================================================================
file_should_have_correct_popularity_value_base(Config, LastOpenW, AvgOpenW) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenW, AvgOpenW),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
FrozenTimestamp = time_test_utils:get_frozen_time_hours(),
AvgOpen = 1 / 30,
Popularity = popularity(FrozenTimestamp, LastOpenW, AvgOpen, AvgOpenW),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
open_and_close_file(W, ?SESSION(W, Config), G),
{ok, FileId} = file_id:guid_to_objectid(G),
?assertMatch([{FileId, Popularity}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
%%%===================================================================
SetUp and TearDown functions
%%%===================================================================
init_per_suite(Config) ->
Posthook = fun(NewConfig) ->
application:start(ssl),
application:ensure_all_started(hackney),
initializer:create_test_users_and_spaces(?TEST_FILE(NewConfig, "env_desc.json"), NewConfig)
end,
[{?ENV_UP_POSTHOOK, Posthook}, {?LOAD_MODULES, [initializer, ?MODULE]} | Config].
init_per_testcase(Case, Config) when
Case == avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default;
Case == query_should_return_files_sorted_by_increasing_avg_open_count_per_day;
Case == query_should_return_files_sorted_by_increasing_last_open_timestamp;
Case == file_should_have_correct_popularity_value;
Case == file_should_have_correct_popularity_value2;
Case == file_should_have_correct_popularity_value3;
Case == time_warp_test
->
time_test_utils:freeze_time(Config),
init_per_testcase(default, Config);
init_per_testcase(_Case, Config) ->
[W | _] = ?config(op_worker_nodes, Config),
init_pool(W),
lfm_proxy:init(Config).
end_per_testcase(Case, Config) when
Case == avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default;
Case == query_should_return_files_sorted_by_increasing_avg_open_count_per_day;
Case == query_should_return_files_sorted_by_increasing_last_open_timestamp;
Case == file_should_have_correct_popularity_value;
Case == file_should_have_correct_popularity_value2;
Case == file_should_have_correct_popularity_value3;
Case == time_warp_test
->
time_test_utils:unfreeze_time(Config),
end_per_testcase(default, Config);
end_per_testcase(_Case, Config) ->
[W | _] = ?config(op_worker_nodes, Config),
disable_file_popularity(W, ?SPACE_ID),
ensure_collector_stopped(W),
test_utils:mock_unload(W, file_popularity),
lfm_test_utils:clean_space(W, ?SPACE_ID, ?ATTEMPTS),
lfm_proxy:teardown(Config).
end_per_suite(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
stop_pool(W),
initializer:clean_test_users_and_spaces_no_validate(Config),
application:stop(hackney),
application:stop(ssl).
%%%===================================================================
%%% view_traverse callbacks
%%%===================================================================
process_row(Row, _Info, RowNum) ->
Popularity = maps:get(<<"key">>, Row),
FileId = maps:get(<<"value">>, Row),
?COLLECTOR ! ?ROW(FileId, Popularity, RowNum),
ok.
task_finished(_TaskId) ->
whereis(?COLLECTOR) ! ?FINISHED.
%%%===================================================================
%%% view processing module API function
%%%===================================================================
init() ->
view_traverse:init(?VIEW_PROCESSING_MODULE).
stop() ->
view_traverse:stop(?VIEW_PROCESSING_MODULE).
run(SpaceId, Opts) ->
view_traverse:run(?VIEW_PROCESSING_MODULE, ?FILE_POPULARITY_VIEW(SpaceId), Opts).
%%%===================================================================
%%% Functions exported for RPC
%%%===================================================================
start_collector(TestMasterPid) ->
register(?COLLECTOR, spawn(?MODULE, collector_loop, [TestMasterPid])).
collector_loop(TestMaster) ->
collector_loop(TestMaster, #{}).
%%%===================================================================
Internal functions
%%%===================================================================
init_pool(Worker) ->
rpc:call(Worker, ?MODULE, init, []).
stop_pool(Worker) ->
rpc:call(Worker, ?MODULE, stop, []).
run(Worker, SpaceId, Opts) ->
rpc:call(Worker, ?MODULE, run, [SpaceId, Opts]).
start_collector_remote(Worker) ->
true = rpc:call(Worker, ?MODULE, start_collector, [self()]).
collector_loop(TestMaster, RowsMap) ->
receive
?FINISHED ->
TestMaster ! ?COLLECTED_RESULTS([ {FileId, PopValue} || {_RN, {FileId, PopValue}} <- lists:sort(maps:to_list(RowsMap))]);
?ROW(FileId, Popularity, RowNum) ->
collector_loop(TestMaster, RowsMap#{RowNum => {FileId, Popularity}})
end.
query(Worker, SpaceId, Opts) ->
start_collector_remote(Worker),
case run(Worker, SpaceId, Opts) of
{ok, _} ->
receive ?COLLECTED_RESULTS(Rows) -> Rows end;
Error = {error, _} ->
Error
end.
ensure_collector_stopped(Worker) ->
case whereis(Worker, ?COLLECTOR) of
undefined -> ok;
CollectorPid -> exit(CollectorPid, kill)
end.
enable_file_popularity(Worker, SpaceId) ->
rpc:call(Worker, file_popularity_api, enable, [SpaceId]).
configure_file_popularity(Worker, SpaceId, Enabled, LastOpenWeight, AvgOpenCountPerDayWeight) ->
rpc:call(Worker, file_popularity_api, configure, [SpaceId, filter_undefined_values(#{
enabled => Enabled,
last_open_hour_weight => LastOpenWeight,
avg_open_count_per_day_weight => AvgOpenCountPerDayWeight
})]).
configure_file_popularity(Worker, SpaceId, Enabled, LastOpenWeight, AvgOpenCountPerDayWeight, MaxAvgOpenCountPerDay) ->
rpc:call(Worker, file_popularity_api, configure, [SpaceId, filter_undefined_values(#{
enabled => Enabled,
last_open_hour_weight => LastOpenWeight,
avg_open_count_per_day_weight => AvgOpenCountPerDayWeight,
max_avg_open_count_per_day => MaxAvgOpenCountPerDay
})]).
disable_file_popularity(Worker, SpaceId) ->
rpc:call(Worker, file_popularity_api, disable, [SpaceId]).
open_and_close_file(Worker, SessId, Guid, Times) ->
lists:foreach(fun(_) ->
open_and_close_file(Worker, SessId, Guid)
end, lists:seq(1, Times)).
open_and_close_file(Worker, SessId, Guid) ->
{ok, H} = lfm_proxy:open(Worker, SessId, ?FILE_REF(Guid), read),
ok = lfm_proxy:close(Worker, H).
popularity(LastOpen, LastOpenW, AvgOpen, AvgOpenW) ->
LastOpen * LastOpenW + AvgOpen * AvgOpenW.
filter_undefined_values(Map) ->
maps:filter(fun
(_, undefined) -> false;
(_, _) -> true
end, Map).
whereis(Node, Name) ->
rpc:call(Node, erlang, whereis, [Name]). | null | https://raw.githubusercontent.com/onedata/op-worker/b0e4045090b180f28c79d40b9b334d7411ec3ca5/test_distributed/file_popularity_test_SUITE.erl | erlang | -------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This module contains tests of file_popularity_view.
The view is queried using view_traverse mechanism.
@end
-------------------------------------------------------------------
API
view_traverse callbacks
view_processing_module API
exported for RPC
name for process responsible for collecting traverse results
messages used to communicate with ?COLLECTOR process
===================================================================
API
===================================================================
all files will have the same timestamp as the time is frozen
all files will have the same timestamp as the time is frozen
Files should be sorted by increasing timestamp of last open
Due to time warps, file that was created as last one has the smallest timestamp so the files
should be sorted in reverse order than they were created
===================================================================
Test base functions
===================================================================
===================================================================
===================================================================
===================================================================
view_traverse callbacks
===================================================================
===================================================================
view processing module API function
===================================================================
===================================================================
Functions exported for RPC
===================================================================
===================================================================
=================================================================== | @author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(file_popularity_test_SUITE).
-author("Jakub Kudzia").
-behaviour(view_traverse).
-include("global_definitions.hrl").
-include("lfm_test_utils.hrl").
-include("modules/fslogic/acl.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/file_popularity/file_popularity_view.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include_lib("ctool/include/logging.hrl").
-include_lib("ctool/include/test/test_utils.hrl").
-include_lib("ctool/include/test/assertions.hrl").
-include_lib("ctool/include/errors.hrl").
-export([all/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2,
end_per_testcase/2]).
-export([
query_should_return_error_when_file_popularity_is_disabled/1,
query_should_return_empty_list_when_file_popularity_is_enabled/1,
query_should_return_empty_list_when_file_has_not_been_opened/1,
query_should_return_file_when_file_has_been_opened/1,
query_should_return_files_sorted_by_increasing_last_open_timestamp/1,
query_should_return_files_sorted_by_increasing_avg_open_count_per_day/1,
file_should_have_correct_popularity_value/1,
file_should_have_correct_popularity_value2/1,
file_should_have_correct_popularity_value3/1,
avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default/1,
avg_open_count_per_day_parameter_should_be_bounded_by_custom_value/1,
changing_max_avg_open_count_per_day_limit_should_reindex_the_file/1,
changing_last_open_weight_should_reindex_the_file/1,
changing_avg_open_count_weight_should_reindex_the_file/1,
time_warp_test/1
]).
-export([process_row/3, task_finished/1]).
-export([init/0, stop/0, run/2]).
-export([start_collector/1, collector_loop/1]).
all() -> [
query_should_return_error_when_file_popularity_is_disabled,
query_should_return_empty_list_when_file_popularity_is_enabled,
query_should_return_empty_list_when_file_has_not_been_opened,
query_should_return_file_when_file_has_been_opened,
file_should_have_correct_popularity_value,
file_should_have_correct_popularity_value2,
file_should_have_correct_popularity_value3,
avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default,
avg_open_count_per_day_parameter_should_be_bounded_by_custom_value,
changing_max_avg_open_count_per_day_limit_should_reindex_the_file,
changing_last_open_weight_should_reindex_the_file,
changing_avg_open_count_weight_should_reindex_the_file,
query_should_return_files_sorted_by_increasing_avg_open_count_per_day,
query_should_return_files_sorted_by_increasing_last_open_timestamp,
time_warp_test
].
-define(SPACE_ID, <<"space1">>).
-define(VIEW_PROCESSING_MODULE, ?MODULE).
-define(FILE_PATH(FileName), filename:join(["/", ?SPACE_ID, FileName])).
-define(USER1, <<"user1">>).
-define(SESSION(Worker, Config), ?SESS_ID(?USER1, Worker, Config)).
-define(ATTEMPTS, 10).
-define(COLLECTOR, collector).
-define(FINISHED, finished).
-define(COLLECTED_RESULTS(Rows), {collected_results, Rows}).
-define(ROW(FileId, Popularity, RowNum), {row, FileId, Popularity, RowNum}).
query_should_return_error_when_file_popularity_is_disabled(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
?assertMatch({error, not_found}, query(W, ?SPACE_ID, #{})).
query_should_return_empty_list_when_file_popularity_is_enabled(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
?assertMatch([], query(W, ?SPACE_ID, #{})).
query_should_return_empty_list_when_file_has_not_been_opened(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
{ok, _} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
?assertMatch([], query(W, ?SPACE_ID, #{})).
query_should_return_file_when_file_has_been_opened(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, H} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G), read),
ok = lfm_proxy:close(W, H),
{ok, FileId} = file_id:guid_to_objectid(G),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
file_should_have_correct_popularity_value(Config) ->
file_should_have_correct_popularity_value_base(Config, 1.123, 0).
file_should_have_correct_popularity_value2(Config) ->
file_should_have_correct_popularity_value_base(Config, 0, 9.987).
file_should_have_correct_popularity_value3(Config) ->
file_should_have_correct_popularity_value_base(Config, 1.123, 9.987).
avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
2 files should have the same probability value , despite having different avg_open_count
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
DefaultMaxOpenCount = 100,
avg_open_count = 100
avg_open_count = 101
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
open_and_close_file(W, ?SESSION(W, Config), G1, OpenCountPerMonth1),
open_and_close_file(W, ?SESSION(W, Config), G2, OpenCountPerMonth2),
?assertMatch([{_, _Popularity}, {_, _Popularity}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
avg_open_count_per_day_parameter_should_be_bounded_by_custom_value(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
2 files should have the same probability value , despite having different avg_open_count
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
LastOpenWeight = 1.0,
AvgOpenCountPerDayWeight = 20.0,
MaxOpenCount = 10,
avg_open_count = 100
avg_open_count = 200
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
open_and_close_file(W, ?SESSION(W, Config), G1, OpenCountPerMonth1),
open_and_close_file(W, ?SESSION(W, Config), G2, OpenCountPerMonth2),
?assertMatch([{_, _Popularity}, {_, _Popularity}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
changing_max_avg_open_count_per_day_limit_should_reindex_the_file(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
LastOpenWeight = 1.0,
AvgOpenCountPerDayWeight = 20.0,
MaxOpenCount = 10,
MaxOpenCount2 = 20,
avg_open_count = 15
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, FileId} = file_id:guid_to_objectid(G),
open_and_close_file(W, ?SESSION(W, Config), G, OpenCountPerMonth),
[{_, Popularity}] = ?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS),
ok = configure_file_popularity(W, ?SPACE_ID, undefined, undefined, undefined, MaxOpenCount2),
?assertNotMatch([{_, Popularity}], query(W, ?SPACE_ID, #{})),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{})).
changing_last_open_weight_should_reindex_the_file(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
LastOpenWeight = 1.0,
LastOpenWeight2 = 2.0,
AvgOpenCountPerDayWeight = 20.0,
MaxOpenCount = 10,
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, FileId} = file_id:guid_to_objectid(G),
open_and_close_file(W, ?SESSION(W, Config), G, 1),
[{_, Popularity}] = ?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS),
ok = configure_file_popularity(W, ?SPACE_ID, undefined, LastOpenWeight2, undefined, undefined),
?assertNotMatch([{_, Popularity}], query(W, ?SPACE_ID, #{})),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{})).
changing_avg_open_count_weight_should_reindex_the_file(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
LastOpenWeight = 1.0,
AvgOpenCountPerDayWeight = 20.0,
AvgOpenCountPerDayWeight2 = 40.0,
MaxOpenCount = 10,
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenWeight, AvgOpenCountPerDayWeight, MaxOpenCount),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
{ok, FileId} = file_id:guid_to_objectid(G),
open_and_close_file(W, ?SESSION(W, Config), G, 1),
[{_, Popularity}] = ?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS),
ok = configure_file_popularity(W, ?SPACE_ID, undefined, undefined, AvgOpenCountPerDayWeight2, undefined),
?assertNotMatch([{_, Popularity}], query(W, ?SPACE_ID, #{})),
?assertMatch([{FileId, _}], query(W, ?SPACE_ID, #{})).
query_should_return_files_sorted_by_increasing_avg_open_count_per_day(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FileName3 = <<"file3">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
FilePath3 = ?FILE_PATH(FileName3),
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
{ok, H} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G1), read),
ok = lfm_proxy:close(W, H),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
{ok, H2} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G2), read),
ok = lfm_proxy:close(W, H2),
{ok, H22} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G2), read),
ok = lfm_proxy:close(W, H22),
{ok, G3} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath3),
{ok, H3} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G3), read),
ok = lfm_proxy:close(W, H3),
{ok, H32} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G3), read),
ok = lfm_proxy:close(W, H32),
{ok, H33} = lfm_proxy:open(W, ?SESSION(W, Config), ?FILE_REF(G3), read),
ok = lfm_proxy:close(W, H33),
{ok, FileId1} = file_id:guid_to_objectid(G1),
{ok, FileId2} = file_id:guid_to_objectid(G2),
{ok, FileId3} = file_id:guid_to_objectid(G3),
?assertMatch([{FileId1, _}, {FileId2, _}, {FileId3, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
query_should_return_files_sorted_by_increasing_last_open_timestamp(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FileName3 = <<"file3">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
FilePath3 = ?FILE_PATH(FileName3),
simulate each next file being opened one hour after the previous one
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
3 hours before query
ok = lfm_proxy:close(W, H1),
time_test_utils:simulate_seconds_passing(3600),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
2 hours before query
ok = lfm_proxy:close(W, H2),
time_test_utils:simulate_seconds_passing(3600),
{ok, G3} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath3),
1 hour before query
ok = lfm_proxy:close(W, H3),
time_test_utils:simulate_seconds_passing(3600),
{ok, FileId1} = file_id:guid_to_objectid(G1),
{ok, FileId2} = file_id:guid_to_objectid(G2),
{ok, FileId3} = file_id:guid_to_objectid(G3),
?assertMatch([{FileId1, _}, {FileId2, _}, {FileId3, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
time_warp_test(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = enable_file_popularity(W, ?SPACE_ID),
FileName1 = <<"file1">>,
FileName2 = <<"file2">>,
FileName3 = <<"file3">>,
FilePath1 = ?FILE_PATH(FileName1),
FilePath2 = ?FILE_PATH(FileName2),
FilePath3 = ?FILE_PATH(FileName3),
simulate each next file being opened one hour BEFORE the previous one ( due to a time warp )
{ok, G1} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath1),
1 hour before query
ok = lfm_proxy:close(W, H1),
time_test_utils:simulate_seconds_passing(-3600),
{ok, G2} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath2),
2 hours before query
ok = lfm_proxy:close(W, H2),
time_test_utils:simulate_seconds_passing(-3600),
{ok, G3} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath3),
3 hour before query
ok = lfm_proxy:close(W, H3),
time_test_utils:simulate_seconds_passing(-3600),
{ok, FileId1} = file_id:guid_to_objectid(G1),
{ok, FileId2} = file_id:guid_to_objectid(G2),
{ok, FileId3} = file_id:guid_to_objectid(G3),
?assertMatch([{FileId3, _}, {FileId2, _}, {FileId1, _}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
file_should_have_correct_popularity_value_base(Config, LastOpenW, AvgOpenW) ->
[W | _] = ?config(op_worker_nodes, Config),
ok = configure_file_popularity(W, ?SPACE_ID, true, LastOpenW, AvgOpenW),
FileName = <<"file">>,
FilePath = ?FILE_PATH(FileName),
FrozenTimestamp = time_test_utils:get_frozen_time_hours(),
AvgOpen = 1 / 30,
Popularity = popularity(FrozenTimestamp, LastOpenW, AvgOpen, AvgOpenW),
{ok, G} = lfm_proxy:create(W, ?SESSION(W, Config), FilePath),
open_and_close_file(W, ?SESSION(W, Config), G),
{ok, FileId} = file_id:guid_to_objectid(G),
?assertMatch([{FileId, Popularity}], query(W, ?SPACE_ID, #{}), ?ATTEMPTS).
SetUp and TearDown functions
init_per_suite(Config) ->
Posthook = fun(NewConfig) ->
application:start(ssl),
application:ensure_all_started(hackney),
initializer:create_test_users_and_spaces(?TEST_FILE(NewConfig, "env_desc.json"), NewConfig)
end,
[{?ENV_UP_POSTHOOK, Posthook}, {?LOAD_MODULES, [initializer, ?MODULE]} | Config].
init_per_testcase(Case, Config) when
Case == avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default;
Case == query_should_return_files_sorted_by_increasing_avg_open_count_per_day;
Case == query_should_return_files_sorted_by_increasing_last_open_timestamp;
Case == file_should_have_correct_popularity_value;
Case == file_should_have_correct_popularity_value2;
Case == file_should_have_correct_popularity_value3;
Case == time_warp_test
->
time_test_utils:freeze_time(Config),
init_per_testcase(default, Config);
init_per_testcase(_Case, Config) ->
[W | _] = ?config(op_worker_nodes, Config),
init_pool(W),
lfm_proxy:init(Config).
end_per_testcase(Case, Config) when
Case == avg_open_count_per_day_parameter_should_be_bounded_by_100_by_default;
Case == query_should_return_files_sorted_by_increasing_avg_open_count_per_day;
Case == query_should_return_files_sorted_by_increasing_last_open_timestamp;
Case == file_should_have_correct_popularity_value;
Case == file_should_have_correct_popularity_value2;
Case == file_should_have_correct_popularity_value3;
Case == time_warp_test
->
time_test_utils:unfreeze_time(Config),
end_per_testcase(default, Config);
end_per_testcase(_Case, Config) ->
[W | _] = ?config(op_worker_nodes, Config),
disable_file_popularity(W, ?SPACE_ID),
ensure_collector_stopped(W),
test_utils:mock_unload(W, file_popularity),
lfm_test_utils:clean_space(W, ?SPACE_ID, ?ATTEMPTS),
lfm_proxy:teardown(Config).
end_per_suite(Config) ->
[W | _] = ?config(op_worker_nodes, Config),
stop_pool(W),
initializer:clean_test_users_and_spaces_no_validate(Config),
application:stop(hackney),
application:stop(ssl).
process_row(Row, _Info, RowNum) ->
Popularity = maps:get(<<"key">>, Row),
FileId = maps:get(<<"value">>, Row),
?COLLECTOR ! ?ROW(FileId, Popularity, RowNum),
ok.
task_finished(_TaskId) ->
whereis(?COLLECTOR) ! ?FINISHED.
init() ->
view_traverse:init(?VIEW_PROCESSING_MODULE).
stop() ->
view_traverse:stop(?VIEW_PROCESSING_MODULE).
run(SpaceId, Opts) ->
view_traverse:run(?VIEW_PROCESSING_MODULE, ?FILE_POPULARITY_VIEW(SpaceId), Opts).
start_collector(TestMasterPid) ->
register(?COLLECTOR, spawn(?MODULE, collector_loop, [TestMasterPid])).
collector_loop(TestMaster) ->
collector_loop(TestMaster, #{}).
Internal functions
init_pool(Worker) ->
rpc:call(Worker, ?MODULE, init, []).
stop_pool(Worker) ->
rpc:call(Worker, ?MODULE, stop, []).
run(Worker, SpaceId, Opts) ->
rpc:call(Worker, ?MODULE, run, [SpaceId, Opts]).
start_collector_remote(Worker) ->
true = rpc:call(Worker, ?MODULE, start_collector, [self()]).
collector_loop(TestMaster, RowsMap) ->
receive
?FINISHED ->
TestMaster ! ?COLLECTED_RESULTS([ {FileId, PopValue} || {_RN, {FileId, PopValue}} <- lists:sort(maps:to_list(RowsMap))]);
?ROW(FileId, Popularity, RowNum) ->
collector_loop(TestMaster, RowsMap#{RowNum => {FileId, Popularity}})
end.
query(Worker, SpaceId, Opts) ->
start_collector_remote(Worker),
case run(Worker, SpaceId, Opts) of
{ok, _} ->
receive ?COLLECTED_RESULTS(Rows) -> Rows end;
Error = {error, _} ->
Error
end.
ensure_collector_stopped(Worker) ->
case whereis(Worker, ?COLLECTOR) of
undefined -> ok;
CollectorPid -> exit(CollectorPid, kill)
end.
enable_file_popularity(Worker, SpaceId) ->
rpc:call(Worker, file_popularity_api, enable, [SpaceId]).
configure_file_popularity(Worker, SpaceId, Enabled, LastOpenWeight, AvgOpenCountPerDayWeight) ->
rpc:call(Worker, file_popularity_api, configure, [SpaceId, filter_undefined_values(#{
enabled => Enabled,
last_open_hour_weight => LastOpenWeight,
avg_open_count_per_day_weight => AvgOpenCountPerDayWeight
})]).
configure_file_popularity(Worker, SpaceId, Enabled, LastOpenWeight, AvgOpenCountPerDayWeight, MaxAvgOpenCountPerDay) ->
rpc:call(Worker, file_popularity_api, configure, [SpaceId, filter_undefined_values(#{
enabled => Enabled,
last_open_hour_weight => LastOpenWeight,
avg_open_count_per_day_weight => AvgOpenCountPerDayWeight,
max_avg_open_count_per_day => MaxAvgOpenCountPerDay
})]).
disable_file_popularity(Worker, SpaceId) ->
rpc:call(Worker, file_popularity_api, disable, [SpaceId]).
open_and_close_file(Worker, SessId, Guid, Times) ->
lists:foreach(fun(_) ->
open_and_close_file(Worker, SessId, Guid)
end, lists:seq(1, Times)).
open_and_close_file(Worker, SessId, Guid) ->
{ok, H} = lfm_proxy:open(Worker, SessId, ?FILE_REF(Guid), read),
ok = lfm_proxy:close(Worker, H).
popularity(LastOpen, LastOpenW, AvgOpen, AvgOpenW) ->
LastOpen * LastOpenW + AvgOpen * AvgOpenW.
filter_undefined_values(Map) ->
maps:filter(fun
(_, undefined) -> false;
(_, _) -> true
end, Map).
whereis(Node, Name) ->
rpc:call(Node, erlang, whereis, [Name]). |
2f6d9d08e9ed2beceda8642150d0b973573c0851c8a0b2bc1def6406b6d49236 | mstksg/uncertain | Hople.hs | {-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE NoImplicitPrelude #
{-# OPTIONS_HADDOCK hide #-}
{-# OPTIONS_HADDOCK prune #-}
-- |
-- Module : Data.Hople
Copyright : ( c ) 2016
-- License : BSD3
--
Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- Homogeneous strict tuples used for implementing 'liftU2', etc.
module Data.Hople
( H1(..)
, H2(..)
, H3(..)
, H4(..)
, H5(..)
, curryH1, curryH2, curryH3, curryH4, curryH5
, uncurryH1, uncurryH2, uncurryH3, uncurryH4, uncurryH5
)
where
import Prelude.Compat
data H1 a = H1 !a
deriving (Functor, Foldable, Traversable, Show)
data H2 a = H2 !a !a
deriving (Functor, Foldable, Traversable, Show)
data H3 a = H3 !a !a !a
deriving (Functor, Foldable, Traversable, Show)
data H4 a = H4 !a !a !a !a
deriving (Functor, Foldable, Traversable, Show)
data H5 a = H5 !a !a !a !a !a
deriving (Functor, Foldable, Traversable, Show)
curryH1 :: (H1 a -> a) -> a -> a
curryH1 f x = f (H1 x)
# INLINE curryH1 #
curryH2 :: (H2 a -> a) -> a -> a -> a
curryH2 f x y = f (H2 x y)
# INLINE curryH2 #
curryH3 :: (H3 a -> a) -> a -> a -> a -> a
curryH3 f x y z = f (H3 x y z)
# INLINE curryH3 #
curryH4 :: (H4 a -> a) -> a -> a -> a -> a -> a
curryH4 f x y z a = f (H4 x y z a)
# INLINE curryH4 #
curryH5 :: (H5 a -> a) -> a -> a -> a -> a -> a -> a
curryH5 f x y z a b = f (H5 x y z a b)
# INLINE curryH5 #
uncurryH1 :: (a -> a) -> H1 a -> a
uncurryH1 f (H1 x) = f x
# INLINE uncurryH1 #
uncurryH2 :: (a -> a -> a) -> H2 a -> a
uncurryH2 f (H2 x y) = f x y
# INLINE uncurryH2 #
uncurryH3 :: (a -> a -> a -> a) -> H3 a -> a
uncurryH3 f (H3 x y z) = f x y z
# INLINE uncurryH3 #
uncurryH4 :: (a -> a -> a -> a -> a) -> H4 a -> a
uncurryH4 f (H4 x y z a) = f x y z a
# INLINE uncurryH4 #
uncurryH5 :: (a -> a -> a -> a -> a -> a) -> H5 a -> a
uncurryH5 f (H5 x y z a b) = f x y z a b
# INLINE uncurryH5 #
| null | https://raw.githubusercontent.com/mstksg/uncertain/d68fc14bbe311f4a50df75a7e878343de6170bf0/src/Data/Hople.hs | haskell | # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveTraversable #
# OPTIONS_HADDOCK hide #
# OPTIONS_HADDOCK prune #
|
Module : Data.Hople
License : BSD3
Stability : experimental
Portability : non-portable
Homogeneous strict tuples used for implementing 'liftU2', etc. | # LANGUAGE NoImplicitPrelude #
Copyright : ( c ) 2016
Maintainer :
module Data.Hople
( H1(..)
, H2(..)
, H3(..)
, H4(..)
, H5(..)
, curryH1, curryH2, curryH3, curryH4, curryH5
, uncurryH1, uncurryH2, uncurryH3, uncurryH4, uncurryH5
)
where
import Prelude.Compat
data H1 a = H1 !a
deriving (Functor, Foldable, Traversable, Show)
data H2 a = H2 !a !a
deriving (Functor, Foldable, Traversable, Show)
data H3 a = H3 !a !a !a
deriving (Functor, Foldable, Traversable, Show)
data H4 a = H4 !a !a !a !a
deriving (Functor, Foldable, Traversable, Show)
data H5 a = H5 !a !a !a !a !a
deriving (Functor, Foldable, Traversable, Show)
curryH1 :: (H1 a -> a) -> a -> a
curryH1 f x = f (H1 x)
# INLINE curryH1 #
curryH2 :: (H2 a -> a) -> a -> a -> a
curryH2 f x y = f (H2 x y)
# INLINE curryH2 #
curryH3 :: (H3 a -> a) -> a -> a -> a -> a
curryH3 f x y z = f (H3 x y z)
# INLINE curryH3 #
curryH4 :: (H4 a -> a) -> a -> a -> a -> a -> a
curryH4 f x y z a = f (H4 x y z a)
# INLINE curryH4 #
curryH5 :: (H5 a -> a) -> a -> a -> a -> a -> a -> a
curryH5 f x y z a b = f (H5 x y z a b)
# INLINE curryH5 #
uncurryH1 :: (a -> a) -> H1 a -> a
uncurryH1 f (H1 x) = f x
# INLINE uncurryH1 #
uncurryH2 :: (a -> a -> a) -> H2 a -> a
uncurryH2 f (H2 x y) = f x y
# INLINE uncurryH2 #
uncurryH3 :: (a -> a -> a -> a) -> H3 a -> a
uncurryH3 f (H3 x y z) = f x y z
# INLINE uncurryH3 #
uncurryH4 :: (a -> a -> a -> a -> a) -> H4 a -> a
uncurryH4 f (H4 x y z a) = f x y z a
# INLINE uncurryH4 #
uncurryH5 :: (a -> a -> a -> a -> a -> a) -> H5 a -> a
uncurryH5 f (H5 x y z a b) = f x y z a b
# INLINE uncurryH5 #
|
58f1a6189531cde4ecbc9778d5e7c31ace0a933272a10acfed1f9973889e97e5 | ntestoc3/burp-clj | proxy.clj | (ns burp-clj.proxy
(:require [burp-clj.helper :as helper])
(:import [burp IProxyListener]))
(defn make-proxy-proc [proc-fn]
(reify IProxyListener
(processProxyMessage [this is-req msg]
(proc-fn is-req msg))))
| null | https://raw.githubusercontent.com/ntestoc3/burp-clj/436802d34fb77e183cf513ba767e3310d96f6946/src/burp_clj/proxy.clj | clojure | (ns burp-clj.proxy
(:require [burp-clj.helper :as helper])
(:import [burp IProxyListener]))
(defn make-proxy-proc [proc-fn]
(reify IProxyListener
(processProxyMessage [this is-req msg]
(proc-fn is-req msg))))
|
|
c3867561180c8a5a1c31f789ac04123856c41779ec950f1b4dd002ef925881e9 | piotr-yuxuan/closeable-map | project.clj | (defproject piotr-yuxuan/closeable-map (-> "./resources/closeable-map.version" slurp .trim)
:description "Application state management made simple: a Clojure map that implements java.io.Closeable."
:url "-yuxuan/closeable-map"
:license {:name "European Union Public License 1.2 or later"
:url "-text-eupl-12"
:distribution :repo}
:scm {:name "git"
:url "-yuxuan/closeable-map"}
:pom-addition [:developers [:developer
[:name "胡雨軒 Петр"]
[:url "-yuxuan"]]]
:dependencies [[potemkin/potemkin "0.4.6"]]
:aot :all
:profiles {:github {:github/topics ["map" "clojure" "state-management" "component"
"state" "mount" "integrant" "closeable"
"with-open" "clojure-maps" "system"]
:github/private? false}
:provided {:dependencies [[org.clojure/clojure "1.12.0-alpha1"]]}
:dev {:global-vars {*warn-on-reflection* true}}
:jar {:jvm-opts ["-Dclojure.compiler.disable-locals-clearing=false"
"-Dclojure.compiler.direct-linking=true"]}
:kaocha [:test {:dependencies [[lambdaisland/kaocha "1.80.1274"]]}]}
:deploy-repositories [["clojars" {:sign-releases false
:url ""
:username :env/WALTER_CLOJARS_USERNAME
:password :env/WALTER_CLOJARS_PASSWORD}]
["github" {:sign-releases false
:url "-yuxuan/closeable-map"
:username :env/GITHUB_ACTOR
:password :env/WALTER_GITHUB_PASSWORD}]])
| null | https://raw.githubusercontent.com/piotr-yuxuan/closeable-map/ee7e2f04b36ed73c25864d854b2c771ef3157c52/project.clj | clojure | (defproject piotr-yuxuan/closeable-map (-> "./resources/closeable-map.version" slurp .trim)
:description "Application state management made simple: a Clojure map that implements java.io.Closeable."
:url "-yuxuan/closeable-map"
:license {:name "European Union Public License 1.2 or later"
:url "-text-eupl-12"
:distribution :repo}
:scm {:name "git"
:url "-yuxuan/closeable-map"}
:pom-addition [:developers [:developer
[:name "胡雨軒 Петр"]
[:url "-yuxuan"]]]
:dependencies [[potemkin/potemkin "0.4.6"]]
:aot :all
:profiles {:github {:github/topics ["map" "clojure" "state-management" "component"
"state" "mount" "integrant" "closeable"
"with-open" "clojure-maps" "system"]
:github/private? false}
:provided {:dependencies [[org.clojure/clojure "1.12.0-alpha1"]]}
:dev {:global-vars {*warn-on-reflection* true}}
:jar {:jvm-opts ["-Dclojure.compiler.disable-locals-clearing=false"
"-Dclojure.compiler.direct-linking=true"]}
:kaocha [:test {:dependencies [[lambdaisland/kaocha "1.80.1274"]]}]}
:deploy-repositories [["clojars" {:sign-releases false
:url ""
:username :env/WALTER_CLOJARS_USERNAME
:password :env/WALTER_CLOJARS_PASSWORD}]
["github" {:sign-releases false
:url "-yuxuan/closeable-map"
:username :env/GITHUB_ACTOR
:password :env/WALTER_GITHUB_PASSWORD}]])
|
|
dfd8ecf7e818af4a544ffc5ece30c6a439b0602d881b4016c8df29e4f22d3ee3 | multimodalrouting/osm-fulcro | components.cljs | (ns app.ui.framework7.components
(:require
[app.ui.framework7.factory-helpers :as h]
["framework7-react/components/accordion-content" :default AccordionContent]
["framework7-react/components/accordion-item" :default AccordionItem]
["framework7-react/components/accordion-toggle" :default AccordionToggle]
["framework7-react/components/accordion" :default Accordion]
["framework7-react/components/actions-button" :default ActionsButton]
["framework7-react/components/actions-group" :default ActionsGroup]
["framework7-react/components/actions-label" :default ActionsLabel]
["framework7-react/components/actions" :default Actions]
["framework7-react/components/app" :default App]
["framework7-react/components/appbar" :default Appbar]
["framework7-react/components/badge" :default Badge]
["framework7-react/components/block-footer" :default BlockFooter]
["framework7-react/components/block-header" :default BlockHeader]
["framework7-react/components/block-title" :default BlockTitle]
["framework7-react/components/block" :default Block]
["framework7-react/components/button" :default Button]
["framework7-react/components/card-content" :default CardContent]
["framework7-react/components/card-footer" :default CardFooter]
["framework7-react/components/card-header" :default CardHeader]
["framework7-react/components/card" :default Card]
["framework7-react/components/checkbox" :default Checkbox]
["framework7-react/components/chip" :default Chip]
["framework7-react/components/col" :default Col]
["framework7-react/components/fab-button" :default FabButton]
["framework7-react/components/fab-buttons" :default FabButtons]
["framework7-react/components/fab" :default Fab]
["framework7-react/components/gauge" :default Gauge]
["framework7-react/components/icon" :default Icon]
["framework7-react/components/input" :default Input]
["framework7-react/components/link" :default Link]
["framework7-react/components/list-button" :default ListButton]
["framework7-react/components/list-group" :default ListGroup]
["framework7-react/components/list-index" :default ListIndex]
["framework7-react/components/list-input" :default ListInput]
["framework7-react/components/list-item-cell" :default ListItemCell]
["framework7-react/components/list-item-content" :default ListItemContent]
["framework7-react/components/list-item-row" :default ListItemRow]
["framework7-react/components/list-item" :default ListItem]
["framework7-react/components/list" :default List]
["framework7-react/components/login-screen-title" :default LoginScreenTitle]
["framework7-react/components/login-screen" :default LoginScreen]
["framework7-react/components/menu-dropdown-item" :default MenuDropdownItem]
["framework7-react/components/menu-dropdown" :default MenuDropdown]
["framework7-react/components/menu-item" :default MenuItem]
["framework7-react/components/menu" :default Menu]
["framework7-react/components/message" :default Message]
["framework7-react/components/messagebar-attachment" :default MessagebarAttachment]
["framework7-react/components/messagebar-attachments" :default MessagebarAttachments]
["framework7-react/components/messagebar-sheet-image" :default MessagebarSheetImage]
["framework7-react/components/messagebar-sheet-item" :default MessagebarSheetItem]
["framework7-react/components/messagebar-sheet" :default MessagebarSheet]
["framework7-react/components/messagebar" :default Messagebar]
["framework7-react/components/messages-title" :default MessagesTitle]
["framework7-react/components/messages" :default Messages]
["framework7-react/components/nav-left" :default NavLeft]
["framework7-react/components/nav-right" :default NavRight]
["framework7-react/components/nav-title-large" :default NavTitleLarge]
["framework7-react/components/nav-title" :default NavTitle]
["framework7-react/components/navbar" :default Navbar]
["framework7-react/components/page-content" :default PageContent]
["framework7-react/components/page" :default Page]
["framework7-react/components/panel" :default Panel]
["framework7-react/components/photo-browser" :default PhotoBrowser]
["framework7-react/components/popover" :default Popover]
["framework7-react/components/popup" :default Popup]
["framework7-react/components/preloader" :default Preloader]
["framework7-react/components/progressbar" :default Progressbar]
["framework7-react/components/radio" :default Radio]
["framework7-react/components/range" :default Range]
["framework7-react/components/routable-modals" :default RoutableModals]
["framework7-react/components/row" :default Row]
["framework7-react/components/searchbar" :default Searchbar]
["framework7-react/components/segmented" :default Segmented]
["framework7-react/components/sheet" :default Sheet]
["framework7-react/components/skeleton-block" :default SkeletonBlock]
["framework7-react/components/skeleton-text" :default SkeletonText]
["framework7-react/components/stepper" :default Stepper]
["framework7-react/components/subnavbar" :default Subnavbar]
["framework7-react/components/swipeout-actions" :default SwipeoutActions]
["framework7-react/components/swipeout-button" :default SwipeoutButton]
["framework7-react/components/swiper-slide" :default SwiperSlide]
["framework7-react/components/swiper" :default Swiper]
["framework7-react/components/tab" :default Tab]
["framework7-react/components/tabs" :default Tabs]
["framework7-react/components/toggle" :default Toggle]
["framework7-react/components/toolbar" :default Toolbar]
["framework7-react/components/treeview-item" :default TreeviewItem]
["framework7-react/components/treeview" :default Treeview]
["framework7-react/components/view" :default View]
["framework7-react/components/views" :default Views]
))
(def f7-accordion-content (h/factory-apply AccordionContent))
(def f7-accordion-item (h/factory-apply AccordionItem))
(def f7-accordion-toggle (h/factory-apply AccordionToggle))
(def f7-accordion (h/factory-apply Accordion))
(def f7-actions-button (h/factory-apply ActionsButton))
(def f7-actions-group (h/factory-apply ActionsGroup))
(def f7-actions-label (h/factory-apply ActionsLabel))
(def f7-actions (h/factory-apply Actions))
(def f7-app (h/factory-apply App))
(def f7-appbar (h/factory-apply Appbar))
(def f7-badge (h/factory-apply Badge))
(def f7-block-footer (h/factory-apply BlockFooter))
(def f7-block-header (h/factory-apply BlockHeader))
(def f7-block-title (h/factory-apply BlockTitle))
(def f7-block (h/factory-apply Block))
(def f7-button (h/factory-apply Button))
(def f7-card-content (h/factory-apply CardContent))
(def f7-card-footer (h/factory-apply CardFooter))
(def f7-card-header (h/factory-apply CardHeader))
(def f7-card (h/factory-apply Card))
(def f7-checkbox (h/factory-apply Checkbox))
(def f7-chip (h/factory-apply Chip))
(def f7-col (h/factory-apply Col))
(def f7-fab-button (h/factory-apply FabButton))
(def f7-fab-buttons (h/factory-apply FabButtons))
(def f7-fab (h/factory-apply Fab))
(def f7-gauge (h/factory-apply Gauge))
(def f7-icon (h/factory-apply Icon))
(def f7-input (h/factory-apply Input))
(def f7-link (h/factory-apply Link))
(def f7-list-button (h/factory-apply ListButton))
(def f7-list-group (h/factory-apply ListGroup))
(def f7-list-index (h/factory-apply ListIndex))
(def f7-list-input (h/factory-apply ListInput))
(def f7-list-item-cell (h/factory-apply ListItemCell))
(def f7-list-item-content (h/factory-apply ListItemContent))
(def f7-list-item-row (h/factory-apply ListItemRow))
(def f7-list-item (h/factory-apply ListItem))
(def f7-list (h/factory-apply List))
(def f7-login-screen-title (h/factory-apply LoginScreenTitle))
(def f7-login-screen (h/factory-apply LoginScreen))
(def f7-menu-dropdown-item (h/factory-apply MenuDropdownItem))
(def f7-menu-dropdown (h/factory-apply MenuDropdown))
(def f7-menu-item (h/factory-apply MenuItem))
(def f7-menu (h/factory-apply Menu))
(def f7-message (h/factory-apply Message))
(def f7-messagebar-attachment (h/factory-apply MessagebarAttachment))
(def f7-messagebar-attachments (h/factory-apply MessagebarAttachments))
(def f7-messagebar-sheet-image (h/factory-apply MessagebarSheetImage))
(def f7-messagebar-sheet-item (h/factory-apply MessagebarSheetItem))
(def f7-messagebar-sheet (h/factory-apply MessagebarSheet))
(def f7-messagebar (h/factory-apply Messagebar))
(def f7-messages-title (h/factory-apply MessagesTitle))
(def f7-messages (h/factory-apply Messages))
(def f7-nav-left (h/factory-apply NavLeft))
(def f7-nav-right (h/factory-apply NavRight))
(def f7-nav-title-large (h/factory-apply NavTitleLarge))
(def f7-nav-title (h/factory-apply NavTitle))
(def f7-navbar (h/factory-apply Navbar))
(def f7-page-content (h/factory-apply PageContent))
(def f7-page (h/factory-apply Page))
(def f7-panel (h/factory-apply Panel))
(def f7-photo-browser (h/factory-apply PhotoBrowser))
(def f7-popover (h/factory-apply Popover))
(def f7-popup (h/factory-apply Popup))
(def f7-preloader (h/factory-apply Preloader))
(def f7-progressbar (h/factory-apply Progressbar))
(def f7-radio (h/factory-apply Radio))
(def f7-range (h/factory-apply Range))
(def f7-routable-modals (h/factory-apply RoutableModals))
(def f7-row (h/factory-apply Row))
(def f7-searchbar (h/factory-apply Searchbar))
(def f7-segmented (h/factory-apply Segmented))
(def f7-sheet (h/factory-apply Sheet))
(def f7-skeleton-block (h/factory-apply SkeletonBlock))
(def f7-skeleton-text (h/factory-apply SkeletonText))
(def f7-stepper (h/factory-apply Stepper))
(def f7-subnavbar (h/factory-apply Subnavbar))
(def f7-swipeout-actions (h/factory-apply SwipeoutActions))
(def f7-swipeout-button (h/factory-apply SwipeoutButton))
(def f7-swiper-slide (h/factory-apply SwiperSlide))
(def f7-swiper (h/factory-apply Swiper))
(def f7-tab (h/factory-apply Tab))
(def f7-tabs (h/factory-apply Tabs))
(def f7-toggle (h/factory-apply Toggle))
(def f7-toolbar (h/factory-apply Toolbar))
(def f7-treeview-item (h/factory-apply TreeviewItem))
(def f7-treeview (h/factory-apply Treeview))
(def f7-view (h/factory-apply View))
(def f7-views (h/factory-apply Views))
| null | https://raw.githubusercontent.com/multimodalrouting/osm-fulcro/dedbf40686a18238349603021687694e5a4c31b6/src/main/app/ui/framework7/components.cljs | clojure | (ns app.ui.framework7.components
(:require
[app.ui.framework7.factory-helpers :as h]
["framework7-react/components/accordion-content" :default AccordionContent]
["framework7-react/components/accordion-item" :default AccordionItem]
["framework7-react/components/accordion-toggle" :default AccordionToggle]
["framework7-react/components/accordion" :default Accordion]
["framework7-react/components/actions-button" :default ActionsButton]
["framework7-react/components/actions-group" :default ActionsGroup]
["framework7-react/components/actions-label" :default ActionsLabel]
["framework7-react/components/actions" :default Actions]
["framework7-react/components/app" :default App]
["framework7-react/components/appbar" :default Appbar]
["framework7-react/components/badge" :default Badge]
["framework7-react/components/block-footer" :default BlockFooter]
["framework7-react/components/block-header" :default BlockHeader]
["framework7-react/components/block-title" :default BlockTitle]
["framework7-react/components/block" :default Block]
["framework7-react/components/button" :default Button]
["framework7-react/components/card-content" :default CardContent]
["framework7-react/components/card-footer" :default CardFooter]
["framework7-react/components/card-header" :default CardHeader]
["framework7-react/components/card" :default Card]
["framework7-react/components/checkbox" :default Checkbox]
["framework7-react/components/chip" :default Chip]
["framework7-react/components/col" :default Col]
["framework7-react/components/fab-button" :default FabButton]
["framework7-react/components/fab-buttons" :default FabButtons]
["framework7-react/components/fab" :default Fab]
["framework7-react/components/gauge" :default Gauge]
["framework7-react/components/icon" :default Icon]
["framework7-react/components/input" :default Input]
["framework7-react/components/link" :default Link]
["framework7-react/components/list-button" :default ListButton]
["framework7-react/components/list-group" :default ListGroup]
["framework7-react/components/list-index" :default ListIndex]
["framework7-react/components/list-input" :default ListInput]
["framework7-react/components/list-item-cell" :default ListItemCell]
["framework7-react/components/list-item-content" :default ListItemContent]
["framework7-react/components/list-item-row" :default ListItemRow]
["framework7-react/components/list-item" :default ListItem]
["framework7-react/components/list" :default List]
["framework7-react/components/login-screen-title" :default LoginScreenTitle]
["framework7-react/components/login-screen" :default LoginScreen]
["framework7-react/components/menu-dropdown-item" :default MenuDropdownItem]
["framework7-react/components/menu-dropdown" :default MenuDropdown]
["framework7-react/components/menu-item" :default MenuItem]
["framework7-react/components/menu" :default Menu]
["framework7-react/components/message" :default Message]
["framework7-react/components/messagebar-attachment" :default MessagebarAttachment]
["framework7-react/components/messagebar-attachments" :default MessagebarAttachments]
["framework7-react/components/messagebar-sheet-image" :default MessagebarSheetImage]
["framework7-react/components/messagebar-sheet-item" :default MessagebarSheetItem]
["framework7-react/components/messagebar-sheet" :default MessagebarSheet]
["framework7-react/components/messagebar" :default Messagebar]
["framework7-react/components/messages-title" :default MessagesTitle]
["framework7-react/components/messages" :default Messages]
["framework7-react/components/nav-left" :default NavLeft]
["framework7-react/components/nav-right" :default NavRight]
["framework7-react/components/nav-title-large" :default NavTitleLarge]
["framework7-react/components/nav-title" :default NavTitle]
["framework7-react/components/navbar" :default Navbar]
["framework7-react/components/page-content" :default PageContent]
["framework7-react/components/page" :default Page]
["framework7-react/components/panel" :default Panel]
["framework7-react/components/photo-browser" :default PhotoBrowser]
["framework7-react/components/popover" :default Popover]
["framework7-react/components/popup" :default Popup]
["framework7-react/components/preloader" :default Preloader]
["framework7-react/components/progressbar" :default Progressbar]
["framework7-react/components/radio" :default Radio]
["framework7-react/components/range" :default Range]
["framework7-react/components/routable-modals" :default RoutableModals]
["framework7-react/components/row" :default Row]
["framework7-react/components/searchbar" :default Searchbar]
["framework7-react/components/segmented" :default Segmented]
["framework7-react/components/sheet" :default Sheet]
["framework7-react/components/skeleton-block" :default SkeletonBlock]
["framework7-react/components/skeleton-text" :default SkeletonText]
["framework7-react/components/stepper" :default Stepper]
["framework7-react/components/subnavbar" :default Subnavbar]
["framework7-react/components/swipeout-actions" :default SwipeoutActions]
["framework7-react/components/swipeout-button" :default SwipeoutButton]
["framework7-react/components/swiper-slide" :default SwiperSlide]
["framework7-react/components/swiper" :default Swiper]
["framework7-react/components/tab" :default Tab]
["framework7-react/components/tabs" :default Tabs]
["framework7-react/components/toggle" :default Toggle]
["framework7-react/components/toolbar" :default Toolbar]
["framework7-react/components/treeview-item" :default TreeviewItem]
["framework7-react/components/treeview" :default Treeview]
["framework7-react/components/view" :default View]
["framework7-react/components/views" :default Views]
))
(def f7-accordion-content (h/factory-apply AccordionContent))
(def f7-accordion-item (h/factory-apply AccordionItem))
(def f7-accordion-toggle (h/factory-apply AccordionToggle))
(def f7-accordion (h/factory-apply Accordion))
(def f7-actions-button (h/factory-apply ActionsButton))
(def f7-actions-group (h/factory-apply ActionsGroup))
(def f7-actions-label (h/factory-apply ActionsLabel))
(def f7-actions (h/factory-apply Actions))
(def f7-app (h/factory-apply App))
(def f7-appbar (h/factory-apply Appbar))
(def f7-badge (h/factory-apply Badge))
(def f7-block-footer (h/factory-apply BlockFooter))
(def f7-block-header (h/factory-apply BlockHeader))
(def f7-block-title (h/factory-apply BlockTitle))
(def f7-block (h/factory-apply Block))
(def f7-button (h/factory-apply Button))
(def f7-card-content (h/factory-apply CardContent))
(def f7-card-footer (h/factory-apply CardFooter))
(def f7-card-header (h/factory-apply CardHeader))
(def f7-card (h/factory-apply Card))
(def f7-checkbox (h/factory-apply Checkbox))
(def f7-chip (h/factory-apply Chip))
(def f7-col (h/factory-apply Col))
(def f7-fab-button (h/factory-apply FabButton))
(def f7-fab-buttons (h/factory-apply FabButtons))
(def f7-fab (h/factory-apply Fab))
(def f7-gauge (h/factory-apply Gauge))
(def f7-icon (h/factory-apply Icon))
(def f7-input (h/factory-apply Input))
(def f7-link (h/factory-apply Link))
(def f7-list-button (h/factory-apply ListButton))
(def f7-list-group (h/factory-apply ListGroup))
(def f7-list-index (h/factory-apply ListIndex))
(def f7-list-input (h/factory-apply ListInput))
(def f7-list-item-cell (h/factory-apply ListItemCell))
(def f7-list-item-content (h/factory-apply ListItemContent))
(def f7-list-item-row (h/factory-apply ListItemRow))
(def f7-list-item (h/factory-apply ListItem))
(def f7-list (h/factory-apply List))
(def f7-login-screen-title (h/factory-apply LoginScreenTitle))
(def f7-login-screen (h/factory-apply LoginScreen))
(def f7-menu-dropdown-item (h/factory-apply MenuDropdownItem))
(def f7-menu-dropdown (h/factory-apply MenuDropdown))
(def f7-menu-item (h/factory-apply MenuItem))
(def f7-menu (h/factory-apply Menu))
(def f7-message (h/factory-apply Message))
(def f7-messagebar-attachment (h/factory-apply MessagebarAttachment))
(def f7-messagebar-attachments (h/factory-apply MessagebarAttachments))
(def f7-messagebar-sheet-image (h/factory-apply MessagebarSheetImage))
(def f7-messagebar-sheet-item (h/factory-apply MessagebarSheetItem))
(def f7-messagebar-sheet (h/factory-apply MessagebarSheet))
(def f7-messagebar (h/factory-apply Messagebar))
(def f7-messages-title (h/factory-apply MessagesTitle))
(def f7-messages (h/factory-apply Messages))
(def f7-nav-left (h/factory-apply NavLeft))
(def f7-nav-right (h/factory-apply NavRight))
(def f7-nav-title-large (h/factory-apply NavTitleLarge))
(def f7-nav-title (h/factory-apply NavTitle))
(def f7-navbar (h/factory-apply Navbar))
(def f7-page-content (h/factory-apply PageContent))
(def f7-page (h/factory-apply Page))
(def f7-panel (h/factory-apply Panel))
(def f7-photo-browser (h/factory-apply PhotoBrowser))
(def f7-popover (h/factory-apply Popover))
(def f7-popup (h/factory-apply Popup))
(def f7-preloader (h/factory-apply Preloader))
(def f7-progressbar (h/factory-apply Progressbar))
(def f7-radio (h/factory-apply Radio))
(def f7-range (h/factory-apply Range))
(def f7-routable-modals (h/factory-apply RoutableModals))
(def f7-row (h/factory-apply Row))
(def f7-searchbar (h/factory-apply Searchbar))
(def f7-segmented (h/factory-apply Segmented))
(def f7-sheet (h/factory-apply Sheet))
(def f7-skeleton-block (h/factory-apply SkeletonBlock))
(def f7-skeleton-text (h/factory-apply SkeletonText))
(def f7-stepper (h/factory-apply Stepper))
(def f7-subnavbar (h/factory-apply Subnavbar))
(def f7-swipeout-actions (h/factory-apply SwipeoutActions))
(def f7-swipeout-button (h/factory-apply SwipeoutButton))
(def f7-swiper-slide (h/factory-apply SwiperSlide))
(def f7-swiper (h/factory-apply Swiper))
(def f7-tab (h/factory-apply Tab))
(def f7-tabs (h/factory-apply Tabs))
(def f7-toggle (h/factory-apply Toggle))
(def f7-toolbar (h/factory-apply Toolbar))
(def f7-treeview-item (h/factory-apply TreeviewItem))
(def f7-treeview (h/factory-apply Treeview))
(def f7-view (h/factory-apply View))
(def f7-views (h/factory-apply Views))
|
|
e64ee978bdf87b030ac1f0aa26cc99cc2309d6a5c40f5a081aa7ed618d1091d7 | ProjectMAC/propagators | core-test.scm | ;;; ----------------------------------------------------------------------
Copyright 2009 - 2010 .
;;; ----------------------------------------------------------------------
This file is part of Propagator Network Prototype .
;;;
Propagator Network Prototype 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.
;;;
Propagator Network Prototype 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 Propagator Network Prototype . If not , see
;;; </>.
;;; ----------------------------------------------------------------------
(in-test-group
core
(define-test (temperature1)
(interaction
(initialize-scheduler)
(define-cell f)
(define-cell c)
(p:fahrenheit->celsius f c)
(add-content f 77)
(run)
(content c)
(produces 25)
))
(define-test (temperature2)
(interaction
(initialize-scheduler)
(define-cell f)
(define-cell c)
(c:fahrenheit-celsius f c)
(add-content c 25)
(run)
(content f)
(produces 77)
(define-cell k)
(c:celsius-kelvin c k)
(run)
(content k)
(produces 298.15)
))
(define-test (barometer-fall-time)
(interaction
(initialize-scheduler)
(define-cell fall-time)
(define-cell building-height)
(c:fall-duration fall-time building-height)
(add-content fall-time (make-interval 2.9 3.1))
(run)
(content building-height)
(produces #(interval 41.163 47.243))
))
(define-test (barometer)
(interaction
(initialize-scheduler)
(define-cell barometer-height)
(define-cell barometer-shadow)
(define-cell building-height)
(define-cell building-shadow)
(c:similar-triangles barometer-shadow barometer-height
building-shadow building-height)
(add-content building-shadow (make-interval 54.9 55.1))
(add-content barometer-height (make-interval 0.3 0.32))
(add-content barometer-shadow (make-interval 0.36 0.37))
(run)
(content building-height)
(produces #(interval 44.514 48.978))
(define-cell fall-time)
(c:fall-duration fall-time building-height)
(add-content fall-time (make-interval 2.9 3.1))
(run)
(content building-height)
(produces #(interval 44.514 47.243))
(content barometer-height)
(produces #(interval .3 .31839))
Refining the ( make - interval 0.3 0.32 ) we put in originally
(content fall-time)
(produces #(interval 3.0091 3.1))
Refining ( make - interval 2.9 3.1 )
(add-content building-height (make-interval 45 45))
(run)
(content barometer-height)
(produces #(interval .3 .30328))
(content barometer-shadow)
(produces #(interval .366 .37))
(content building-shadow)
(produces #(interval 54.9 55.1))
(content fall-time)
(produces #(interval 3.0255 3.0322))
))
(define-test (barometer-reverse-fall-time)
(interaction
(initialize-scheduler)
(define-cell fall-time)
(define-cell building-height)
(c:fall-duration fall-time building-height)
(add-content fall-time (make-interval 2.9 3.1))
(run)
(content building-height)
(produces #(interval 41.163 47.243))
(add-content building-height 45)
(run)
(content fall-time)
(produces #(interval 3.0255 3.0322))
))
(define-each-check
(= 4 (let-cell (x 4) (run) (content x)))
(= 5 (let-cells ((x (e:constant 2))
(y 3))
(let-cell (z (e:+ x y))
(run)
(content z))))
(= 7 (let-cells* ((x 3)
(y (e:+ x 4)))
(run)
(content y)))
(= 1 (let-cell ((answer (ce:+ 2 %% 3)))
(run)
(content answer)))
(= 7 (let-cells-rec ((z (e:+ x y))
(x (e:- z y))
(y (e:- z x)))
(c:id x 4)
(c:id y 3)
(run)
(content z)))
(= 4 (let-cells-rec ((z (e:+ x y))
(x (e:- z y))
(y (e:- z x)))
(c:id z 7)
(c:id y 3)
(run)
(content x)))
(= 3 (let-cells-rec ((z (e:+ x y))
(x (e:- z y))
(y (e:- z x)))
(c:id x 4)
(c:id z 7)
(run)
(content y)))
)
(define-test (serpent)
(initialize-scheduler)
(let-cell-rec (ones (e:cons 1 ones))
(run)
(check (eqv? 1 (content (e:car ones))))
(check (eqv? 1 (content (e:car (e:cdr ones)))))
(check (eqv? 1 (content (e:car (e:cdr (e:cdr ones)))))))
)
(define-test (monotonic-intervals)
(interaction
(initialize-scheduler)
(define-cell range1 (make-interval -5 5))
(define-cell range2 (make-interval -5 5))
(define-cell less? (e:< range1 range2))
(define-cell same? (e:= range1 range2))
(define-cell more? (e:> range1 range2))
(run)
(add-content range1 (make-interval 3 5))
(add-content range2 (make-interval 1 2))
(run)
(content less?)
(produces #f)
(content same?)
(produces #f)
(content more?)
(produces #t)
))
(define-test (divisible-intervals)
(check (contradictory? (generic-/ (make-interval 3 4) 0)))
(check (contradictory? (generic-/ (make-interval 3 4) (make-interval 0 0))))
)
)
| null | https://raw.githubusercontent.com/ProjectMAC/propagators/add671f009e62441e77735a88980b6b21fad7a79/core/test/core-test.scm | scheme | ----------------------------------------------------------------------
----------------------------------------------------------------------
you can
redistribute it and/or modify it under the terms of the GNU
any later version.
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.
</>.
---------------------------------------------------------------------- | Copyright 2009 - 2010 .
This file is part of Propagator Network Prototype .
General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
Propagator Network Prototype is distributed in the hope that it
You should have received a copy of the GNU General Public License
along with Propagator Network Prototype . If not , see
(in-test-group
core
(define-test (temperature1)
(interaction
(initialize-scheduler)
(define-cell f)
(define-cell c)
(p:fahrenheit->celsius f c)
(add-content f 77)
(run)
(content c)
(produces 25)
))
(define-test (temperature2)
(interaction
(initialize-scheduler)
(define-cell f)
(define-cell c)
(c:fahrenheit-celsius f c)
(add-content c 25)
(run)
(content f)
(produces 77)
(define-cell k)
(c:celsius-kelvin c k)
(run)
(content k)
(produces 298.15)
))
(define-test (barometer-fall-time)
(interaction
(initialize-scheduler)
(define-cell fall-time)
(define-cell building-height)
(c:fall-duration fall-time building-height)
(add-content fall-time (make-interval 2.9 3.1))
(run)
(content building-height)
(produces #(interval 41.163 47.243))
))
(define-test (barometer)
(interaction
(initialize-scheduler)
(define-cell barometer-height)
(define-cell barometer-shadow)
(define-cell building-height)
(define-cell building-shadow)
(c:similar-triangles barometer-shadow barometer-height
building-shadow building-height)
(add-content building-shadow (make-interval 54.9 55.1))
(add-content barometer-height (make-interval 0.3 0.32))
(add-content barometer-shadow (make-interval 0.36 0.37))
(run)
(content building-height)
(produces #(interval 44.514 48.978))
(define-cell fall-time)
(c:fall-duration fall-time building-height)
(add-content fall-time (make-interval 2.9 3.1))
(run)
(content building-height)
(produces #(interval 44.514 47.243))
(content barometer-height)
(produces #(interval .3 .31839))
Refining the ( make - interval 0.3 0.32 ) we put in originally
(content fall-time)
(produces #(interval 3.0091 3.1))
Refining ( make - interval 2.9 3.1 )
(add-content building-height (make-interval 45 45))
(run)
(content barometer-height)
(produces #(interval .3 .30328))
(content barometer-shadow)
(produces #(interval .366 .37))
(content building-shadow)
(produces #(interval 54.9 55.1))
(content fall-time)
(produces #(interval 3.0255 3.0322))
))
(define-test (barometer-reverse-fall-time)
(interaction
(initialize-scheduler)
(define-cell fall-time)
(define-cell building-height)
(c:fall-duration fall-time building-height)
(add-content fall-time (make-interval 2.9 3.1))
(run)
(content building-height)
(produces #(interval 41.163 47.243))
(add-content building-height 45)
(run)
(content fall-time)
(produces #(interval 3.0255 3.0322))
))
(define-each-check
(= 4 (let-cell (x 4) (run) (content x)))
(= 5 (let-cells ((x (e:constant 2))
(y 3))
(let-cell (z (e:+ x y))
(run)
(content z))))
(= 7 (let-cells* ((x 3)
(y (e:+ x 4)))
(run)
(content y)))
(= 1 (let-cell ((answer (ce:+ 2 %% 3)))
(run)
(content answer)))
(= 7 (let-cells-rec ((z (e:+ x y))
(x (e:- z y))
(y (e:- z x)))
(c:id x 4)
(c:id y 3)
(run)
(content z)))
(= 4 (let-cells-rec ((z (e:+ x y))
(x (e:- z y))
(y (e:- z x)))
(c:id z 7)
(c:id y 3)
(run)
(content x)))
(= 3 (let-cells-rec ((z (e:+ x y))
(x (e:- z y))
(y (e:- z x)))
(c:id x 4)
(c:id z 7)
(run)
(content y)))
)
(define-test (serpent)
(initialize-scheduler)
(let-cell-rec (ones (e:cons 1 ones))
(run)
(check (eqv? 1 (content (e:car ones))))
(check (eqv? 1 (content (e:car (e:cdr ones)))))
(check (eqv? 1 (content (e:car (e:cdr (e:cdr ones)))))))
)
(define-test (monotonic-intervals)
(interaction
(initialize-scheduler)
(define-cell range1 (make-interval -5 5))
(define-cell range2 (make-interval -5 5))
(define-cell less? (e:< range1 range2))
(define-cell same? (e:= range1 range2))
(define-cell more? (e:> range1 range2))
(run)
(add-content range1 (make-interval 3 5))
(add-content range2 (make-interval 1 2))
(run)
(content less?)
(produces #f)
(content same?)
(produces #f)
(content more?)
(produces #t)
))
(define-test (divisible-intervals)
(check (contradictory? (generic-/ (make-interval 3 4) 0)))
(check (contradictory? (generic-/ (make-interval 3 4) (make-interval 0 0))))
)
)
|
3a4154dcc456877ba11afab62981ece47875f1155d5375a906149e804835928d | kepler16/next.cljs | build.clj | (ns build
(:require [clojure.tools.build.api :as b]
[org.corfield.build :as bb]))
(def global-opts
{:repository "github-kepler"
:lib 'kepler16/next.cljs})
(defn release-prepare [opts]
(->> opts
(merge global-opts)
(bb/clean)
(bb/jar)))
(defn release-publish [opts]
(->> opts
(merge global-opts)
(bb/deploy)))
| null | https://raw.githubusercontent.com/kepler16/next.cljs/99b2c934c8c8b66f7f6085e64be45f616f4ba779/build.clj | clojure | (ns build
(:require [clojure.tools.build.api :as b]
[org.corfield.build :as bb]))
(def global-opts
{:repository "github-kepler"
:lib 'kepler16/next.cljs})
(defn release-prepare [opts]
(->> opts
(merge global-opts)
(bb/clean)
(bb/jar)))
(defn release-publish [opts]
(->> opts
(merge global-opts)
(bb/deploy)))
|
|
04e4f3d6e3430a710dde4ef6f312717d713cc60df0df60563acacd1e48a51334 | nitrogen/nitrogen | action.erl | %% -*- mode: nitrogen -*-
%% vim: ts=4 sw=4 et
-module (action_[[[NAME]]]).
-include_lib ("nitrogen_core/include/wf.hrl").
-include("records.hrl").
-export([
render_action/1
]).
%% move the following record definition to site/include/records.hrl
-record([[[NAME]]], {?ACTION_BASE(action_[[[NAME]]]),
attr1 :: any(),
attr2 :: any()
}).
-spec render_action(#[[[NAME]]]{}) -> actions().
render_action(_Record = #[[[NAME]]]{}) ->
"alert('Hello, from [[[NAME]]]!');".
| null | https://raw.githubusercontent.com/nitrogen/nitrogen/7b39d2976c2b77e1b92bc026e14068d1e1017c73/rel/overlay/common/site/.prototypes/action.erl | erlang | -*- mode: nitrogen -*-
vim: ts=4 sw=4 et
move the following record definition to site/include/records.hrl | -module (action_[[[NAME]]]).
-include_lib ("nitrogen_core/include/wf.hrl").
-include("records.hrl").
-export([
render_action/1
]).
-record([[[NAME]]], {?ACTION_BASE(action_[[[NAME]]]),
attr1 :: any(),
attr2 :: any()
}).
-spec render_action(#[[[NAME]]]{}) -> actions().
render_action(_Record = #[[[NAME]]]{}) ->
"alert('Hello, from [[[NAME]]]!');".
|
86842f5612583f30565d75ba9e711990599f55825e1259b4c2124d6f9f6ac5e2 | waymonad/waymonad | Box.hs |
waymonad A wayland compositor in the spirit of xmonad
Copyright ( C ) 2017
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
Reach us at
waymonad A wayland compositor in the spirit of xmonad
Copyright (C) 2017 Markus Ongyerth
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Reach us at
-}
{-# LANGUAGE OverloadedStrings, ApplicativeDo #-}
module Config.Box
where
import Config.Schema
import qualified Graphics.Wayland.WlRoots.Box as R
data Point a = Point
{ pointX :: a
, pointY :: a
} deriving (Eq, Show)
instance Spec a => Spec (Point a) where
valuesSpec = sectionsSpec "point" $ do
x <- reqSection "x" "The x position of the point"
y <- reqSection "y" "The y position of the point"
pure $ Point x y
asRootsPoint :: Integral a => Point a -> R.Point
asRootsPoint (Point x y) = R.Point (fromIntegral x) (fromIntegral y)
| null | https://raw.githubusercontent.com/waymonad/waymonad/18ab493710dd54c330fb4d122ed35bc3a59585df/src/Config/Box.hs | haskell | # LANGUAGE OverloadedStrings, ApplicativeDo # |
waymonad A wayland compositor in the spirit of xmonad
Copyright ( C ) 2017
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
Reach us at
waymonad A wayland compositor in the spirit of xmonad
Copyright (C) 2017 Markus Ongyerth
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Reach us at
-}
module Config.Box
where
import Config.Schema
import qualified Graphics.Wayland.WlRoots.Box as R
data Point a = Point
{ pointX :: a
, pointY :: a
} deriving (Eq, Show)
instance Spec a => Spec (Point a) where
valuesSpec = sectionsSpec "point" $ do
x <- reqSection "x" "The x position of the point"
y <- reqSection "y" "The y position of the point"
pure $ Point x y
asRootsPoint :: Integral a => Point a -> R.Point
asRootsPoint (Point x y) = R.Point (fromIntegral x) (fromIntegral y)
|
dfaba0188c51f484874e40cfb760269d0e8ba5809db0a1d0f86246af2117d623 | facebook/flow | operator_precedence_test.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
open Ast_builder
open Layout_test_utils
open Layout_generator_test_utils
module S = Ast_builder.Statements
module E = Ast_builder.Expressions
module L = Layout_builder
let opts = Js_layout_generator.default_opts
let (x, y, z) = (E.identifier "x", E.identifier "y", E.identifier "z")
let x40 = E.identifier (String.make 40 'x')
let str = E.literal (Literals.string "a")
let ( && ) a b = E.logical_and a b
let ( || ) a b = E.logical_or a b
let ( + ) a b = E.binary ~op:Flow_ast.Expression.Binary.Plus a b
let ( - ) a b = E.binary ~op:Flow_ast.Expression.Binary.Minus a b
let tests =
[
( "and_with_and_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x && y) && z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x && y);
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x&&y&&z" layout;
assert_output ~ctxt ~pretty:true "x && y && z" layout;
let layout = Js_layout_generator.expression ~opts ((x40 && x40) && x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
layout
);
( "and_with_and_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && y && z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "&&";
indent (fused [pretty_line; wrap_in_parens (expression (y && z))]);
]
)
)
layout;
assert_output ~ctxt "x&&(y&&z)" layout;
assert_output ~ctxt ~pretty:true "x && (y && z)" layout;
let layout = Js_layout_generator.expression ~opts (x40 && x40 && x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
)
layout
);
( "or_with_and_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x && y) || z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x && y);
pretty_space;
atom "||";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x&&y||z" layout;
assert_output ~ctxt ~pretty:true "x && y || z" layout;
let layout = Js_layout_generator.expression ~opts ((x40 && x40) || x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
layout
);
( "and_with_or_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && (y || z)) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "&&";
indent (fused [pretty_line; wrap_in_parens (expression (y || z))]);
]
)
)
layout;
assert_output ~ctxt "x&&(y||z)" layout;
assert_output ~ctxt ~pretty:true "x && (y || z)" layout;
let layout = Js_layout_generator.expression ~opts (x40 && (x40 || x40)) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
)
layout
);
( "or_with_or_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x || y) || z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x || y);
pretty_space;
atom "||";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x||y||z" layout;
assert_output ~ctxt ~pretty:true "x || y || z" layout;
let layout = Js_layout_generator.expression ~opts ((x40 || x40) || x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
layout
);
( "or_with_or_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x || y || z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "||";
indent (fused [pretty_line; wrap_in_parens (expression (y || z))]);
]
)
)
layout;
assert_output ~ctxt "x||(y||z)" layout;
assert_output ~ctxt ~pretty:true "x || (y || z)" layout
);
( "and_with_or_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x || y) && z) in
assert_layout
~ctxt
L.(
loc
(group
[
wrap_in_parens (expression (x || y));
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "(x||y)&&z" layout;
assert_output ~ctxt ~pretty:true "(x || y) && z" layout
);
( "or_with_and_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x || (y && z)) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "||";
indent (fused [pretty_line; expression (y && z)]);
]
)
)
layout;
assert_output ~ctxt "x||y&&z" layout;
assert_output ~ctxt ~pretty:true "x || y && z" layout
);
( "plus_with_plus_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + y + z) in
assert_layout
~ctxt
L.(loc (fused [expression (x + y); pretty_space; atom "+"; pretty_space; expression z]))
layout;
assert_output ~ctxt "x+y+z" layout;
assert_output ~ctxt ~pretty:true "x + y + z" layout
);
( "plus_with_plus_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + (y + z)) in
assert_layout
~ctxt
L.(
loc
(fused
[
expression x;
pretty_space;
atom "+";
pretty_space;
wrap_in_parens (expression (y + z));
]
)
)
layout;
assert_output ~ctxt "x+(y+z)" layout;
assert_output ~ctxt ~pretty:true "x + (y + z)" layout
);
( "minus_with_plus_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + y - z) in
assert_layout
~ctxt
L.(loc (fused [expression (x + y); pretty_space; atom "-"; pretty_space; expression z]))
layout;
assert_output ~ctxt "x+y-z" layout;
assert_output ~ctxt ~pretty:true "x + y - z" layout
);
( "plus_with_minus_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + (y - z)) in
assert_layout
~ctxt
L.(
loc
(fused
[
expression x;
pretty_space;
atom "+";
pretty_space;
wrap_in_parens (expression (y - z));
]
)
)
layout;
assert_output ~ctxt "x+(y-z)" layout;
assert_output ~ctxt ~pretty:true "x + (y - z)" layout
);
( "and_with_plus_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x + y) && z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x + y);
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x+y&&z" layout;
assert_output ~ctxt ~pretty:true "x + y && z" layout
);
( "plus_with_and_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + (y && z)) in
assert_layout
~ctxt
L.(
loc
(fused
[
expression x;
pretty_space;
atom "+";
pretty_space;
wrap_in_parens (expression (y && z));
]
)
)
layout;
assert_output ~ctxt "x+(y&&z)" layout;
assert_output ~ctxt ~pretty:true "x + (y && z)" layout
);
( "plus_with_and_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x && y) + z) in
assert_layout
~ctxt
L.(
loc
(fused
[
wrap_in_parens (expression (x && y));
pretty_space;
atom "+";
pretty_space;
expression z;
]
)
)
layout;
assert_output ~ctxt "(x&&y)+z" layout;
assert_output ~ctxt ~pretty:true "(x && y) + z" layout
);
( "and_with_plus_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && (y + z)) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "&&";
indent (fused [pretty_line; expression (y + z)]);
]
)
)
layout;
assert_output ~ctxt "x&&y+z" layout;
assert_output ~ctxt ~pretty:true "x && y + z" layout
);
( "and_literal_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (str && x) in
assert_layout
~ctxt
L.(
loc
(group
[expression str; pretty_space; atom "&&"; indent (fused [pretty_line; expression x])]
)
)
layout;
assert_output ~ctxt "\"a\"&&x" layout;
assert_output ~ctxt ~pretty:true "\"a\" && x" layout
);
( "and_literal_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && str) in
assert_layout
~ctxt
L.(
loc
(group
[expression x; pretty_space; atom "&&"; indent (fused [pretty_line; expression str])]
)
)
layout;
assert_output ~ctxt "x&&\"a\"" layout;
assert_output ~ctxt ~pretty:true "x && \"a\"" layout
);
( "function" >:: fun ctxt ->
let fn = (Loc.none, Flow_ast.Expression.Function (Functions.make ~id:None ())) in
let layout = Js_layout_generator.expression ~opts (fn && x) in
assert_layout
~ctxt
L.(
loc
(group
[expression fn; pretty_space; atom "&&"; indent (fused [pretty_line; expression x])]
)
)
layout;
assert_output ~ctxt "function(){}&&x" layout;
assert_output ~ctxt ~pretty:true "function() {} && x" layout;
let layout = Js_layout_generator.expression ~opts (x && fn) in
assert_layout
~ctxt
L.(
loc
(group
[expression x; pretty_space; atom "&&"; indent (fused [pretty_line; expression fn])]
)
)
layout;
assert_output ~ctxt "x&&function(){}" layout;
assert_output ~ctxt ~pretty:true "x && function() {}" layout
);
( "sequence" >:: fun ctxt ->
let seq = E.sequence [x; y] in
let layout = Js_layout_generator.expression ~opts (seq && z) in
assert_layout
~ctxt
L.(
loc
(group
[
wrap_in_parens (expression seq);
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "(x,y)&&z" layout;
assert_output ~ctxt ~pretty:true "(x, y) && z" layout;
let layout = Js_layout_generator.expression ~opts (z && seq) in
assert_layout
~ctxt
L.(
loc
(group
[
expression z;
pretty_space;
atom "&&";
indent (fused [pretty_line; wrap_in_parens (expression seq)]);
]
)
)
layout;
assert_output ~ctxt "z&&(x,y)" layout;
assert_output ~ctxt ~pretty:true "z && (x, y)" layout;
let layout = Js_layout_generator.expression ~opts (E.sequence [z; seq]) in
assert_layout
~ctxt
L.(loc (group [loc (id "z"); atom ","; pretty_line; wrap_in_parens (expression seq)]))
layout;
assert_output ~ctxt "z,(x,y)" layout;
assert_output ~ctxt ~pretty:true "z, (x, y)" layout;
let layout = Js_layout_generator.expression ~opts (E.sequence [seq; z]) in
assert_layout
~ctxt
L.(loc (group [wrap_in_parens (expression seq); atom ","; pretty_line; loc (id "z")]))
layout;
assert_output ~ctxt "(x,y),z" layout;
assert_output ~ctxt ~pretty:true "(x, y), z" layout
);
]
| null | https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/parser_utils/output/__tests__/js_layout_generator/operator_precedence_test.ml | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
open Ast_builder
open Layout_test_utils
open Layout_generator_test_utils
module S = Ast_builder.Statements
module E = Ast_builder.Expressions
module L = Layout_builder
let opts = Js_layout_generator.default_opts
let (x, y, z) = (E.identifier "x", E.identifier "y", E.identifier "z")
let x40 = E.identifier (String.make 40 'x')
let str = E.literal (Literals.string "a")
let ( && ) a b = E.logical_and a b
let ( || ) a b = E.logical_or a b
let ( + ) a b = E.binary ~op:Flow_ast.Expression.Binary.Plus a b
let ( - ) a b = E.binary ~op:Flow_ast.Expression.Binary.Minus a b
let tests =
[
( "and_with_and_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x && y) && z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x && y);
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x&&y&&z" layout;
assert_output ~ctxt ~pretty:true "x && y && z" layout;
let layout = Js_layout_generator.expression ~opts ((x40 && x40) && x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
layout
);
( "and_with_and_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && y && z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "&&";
indent (fused [pretty_line; wrap_in_parens (expression (y && z))]);
]
)
)
layout;
assert_output ~ctxt "x&&(y&&z)" layout;
assert_output ~ctxt ~pretty:true "x && (y && z)" layout;
let layout = Js_layout_generator.expression ~opts (x40 && x40 && x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
)
layout
);
( "or_with_and_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x && y) || z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x && y);
pretty_space;
atom "||";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x&&y||z" layout;
assert_output ~ctxt ~pretty:true "x && y || z" layout;
let layout = Js_layout_generator.expression ~opts ((x40 && x40) || x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
layout
);
( "and_with_or_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && (y || z)) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "&&";
indent (fused [pretty_line; wrap_in_parens (expression (y || z))]);
]
)
)
layout;
assert_output ~ctxt "x&&(y||z)" layout;
assert_output ~ctxt ~pretty:true "x && (y || z)" layout;
let layout = Js_layout_generator.expression ~opts (x40 && (x40 || x40)) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&&(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &&\n"
^ " (xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)"
)
layout
);
( "or_with_or_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x || y) || z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x || y);
pretty_space;
atom "||";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x||y||z" layout;
assert_output ~ctxt ~pretty:true "x || y || z" layout;
let layout = Js_layout_generator.expression ~opts ((x40 || x40) || x40) in
assert_output
~ctxt
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
layout;
assert_output
~ctxt
~pretty:true
("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ||\n"
^ " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
layout
);
( "or_with_or_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x || y || z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "||";
indent (fused [pretty_line; wrap_in_parens (expression (y || z))]);
]
)
)
layout;
assert_output ~ctxt "x||(y||z)" layout;
assert_output ~ctxt ~pretty:true "x || (y || z)" layout
);
( "and_with_or_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x || y) && z) in
assert_layout
~ctxt
L.(
loc
(group
[
wrap_in_parens (expression (x || y));
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "(x||y)&&z" layout;
assert_output ~ctxt ~pretty:true "(x || y) && z" layout
);
( "or_with_and_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x || (y && z)) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "||";
indent (fused [pretty_line; expression (y && z)]);
]
)
)
layout;
assert_output ~ctxt "x||y&&z" layout;
assert_output ~ctxt ~pretty:true "x || y && z" layout
);
( "plus_with_plus_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + y + z) in
assert_layout
~ctxt
L.(loc (fused [expression (x + y); pretty_space; atom "+"; pretty_space; expression z]))
layout;
assert_output ~ctxt "x+y+z" layout;
assert_output ~ctxt ~pretty:true "x + y + z" layout
);
( "plus_with_plus_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + (y + z)) in
assert_layout
~ctxt
L.(
loc
(fused
[
expression x;
pretty_space;
atom "+";
pretty_space;
wrap_in_parens (expression (y + z));
]
)
)
layout;
assert_output ~ctxt "x+(y+z)" layout;
assert_output ~ctxt ~pretty:true "x + (y + z)" layout
);
( "minus_with_plus_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + y - z) in
assert_layout
~ctxt
L.(loc (fused [expression (x + y); pretty_space; atom "-"; pretty_space; expression z]))
layout;
assert_output ~ctxt "x+y-z" layout;
assert_output ~ctxt ~pretty:true "x + y - z" layout
);
( "plus_with_minus_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + (y - z)) in
assert_layout
~ctxt
L.(
loc
(fused
[
expression x;
pretty_space;
atom "+";
pretty_space;
wrap_in_parens (expression (y - z));
]
)
)
layout;
assert_output ~ctxt "x+(y-z)" layout;
assert_output ~ctxt ~pretty:true "x + (y - z)" layout
);
( "and_with_plus_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x + y) && z) in
assert_layout
~ctxt
L.(
loc
(group
[
expression (x + y);
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "x+y&&z" layout;
assert_output ~ctxt ~pretty:true "x + y && z" layout
);
( "plus_with_and_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x + (y && z)) in
assert_layout
~ctxt
L.(
loc
(fused
[
expression x;
pretty_space;
atom "+";
pretty_space;
wrap_in_parens (expression (y && z));
]
)
)
layout;
assert_output ~ctxt "x+(y&&z)" layout;
assert_output ~ctxt ~pretty:true "x + (y && z)" layout
);
( "plus_with_and_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts ((x && y) + z) in
assert_layout
~ctxt
L.(
loc
(fused
[
wrap_in_parens (expression (x && y));
pretty_space;
atom "+";
pretty_space;
expression z;
]
)
)
layout;
assert_output ~ctxt "(x&&y)+z" layout;
assert_output ~ctxt ~pretty:true "(x && y) + z" layout
);
( "and_with_plus_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && (y + z)) in
assert_layout
~ctxt
L.(
loc
(group
[
expression x;
pretty_space;
atom "&&";
indent (fused [pretty_line; expression (y + z)]);
]
)
)
layout;
assert_output ~ctxt "x&&y+z" layout;
assert_output ~ctxt ~pretty:true "x && y + z" layout
);
( "and_literal_lhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (str && x) in
assert_layout
~ctxt
L.(
loc
(group
[expression str; pretty_space; atom "&&"; indent (fused [pretty_line; expression x])]
)
)
layout;
assert_output ~ctxt "\"a\"&&x" layout;
assert_output ~ctxt ~pretty:true "\"a\" && x" layout
);
( "and_literal_rhs" >:: fun ctxt ->
let layout = Js_layout_generator.expression ~opts (x && str) in
assert_layout
~ctxt
L.(
loc
(group
[expression x; pretty_space; atom "&&"; indent (fused [pretty_line; expression str])]
)
)
layout;
assert_output ~ctxt "x&&\"a\"" layout;
assert_output ~ctxt ~pretty:true "x && \"a\"" layout
);
( "function" >:: fun ctxt ->
let fn = (Loc.none, Flow_ast.Expression.Function (Functions.make ~id:None ())) in
let layout = Js_layout_generator.expression ~opts (fn && x) in
assert_layout
~ctxt
L.(
loc
(group
[expression fn; pretty_space; atom "&&"; indent (fused [pretty_line; expression x])]
)
)
layout;
assert_output ~ctxt "function(){}&&x" layout;
assert_output ~ctxt ~pretty:true "function() {} && x" layout;
let layout = Js_layout_generator.expression ~opts (x && fn) in
assert_layout
~ctxt
L.(
loc
(group
[expression x; pretty_space; atom "&&"; indent (fused [pretty_line; expression fn])]
)
)
layout;
assert_output ~ctxt "x&&function(){}" layout;
assert_output ~ctxt ~pretty:true "x && function() {}" layout
);
( "sequence" >:: fun ctxt ->
let seq = E.sequence [x; y] in
let layout = Js_layout_generator.expression ~opts (seq && z) in
assert_layout
~ctxt
L.(
loc
(group
[
wrap_in_parens (expression seq);
pretty_space;
atom "&&";
indent (fused [pretty_line; expression z]);
]
)
)
layout;
assert_output ~ctxt "(x,y)&&z" layout;
assert_output ~ctxt ~pretty:true "(x, y) && z" layout;
let layout = Js_layout_generator.expression ~opts (z && seq) in
assert_layout
~ctxt
L.(
loc
(group
[
expression z;
pretty_space;
atom "&&";
indent (fused [pretty_line; wrap_in_parens (expression seq)]);
]
)
)
layout;
assert_output ~ctxt "z&&(x,y)" layout;
assert_output ~ctxt ~pretty:true "z && (x, y)" layout;
let layout = Js_layout_generator.expression ~opts (E.sequence [z; seq]) in
assert_layout
~ctxt
L.(loc (group [loc (id "z"); atom ","; pretty_line; wrap_in_parens (expression seq)]))
layout;
assert_output ~ctxt "z,(x,y)" layout;
assert_output ~ctxt ~pretty:true "z, (x, y)" layout;
let layout = Js_layout_generator.expression ~opts (E.sequence [seq; z]) in
assert_layout
~ctxt
L.(loc (group [wrap_in_parens (expression seq); atom ","; pretty_line; loc (id "z")]))
layout;
assert_output ~ctxt "(x,y),z" layout;
assert_output ~ctxt ~pretty:true "(x, y), z" layout
);
]
|
|
c74b145898fbebfe4c3b13a334ad4433fccfbb268ff3e812c65336b14b7935bc | ultralisp/ultralisp | metadata.lisp | (defpackage #:ultralisp/metadata
(:use #:cl)
(:import-from #:alexandria
#:make-keyword)
(:import-from #:arrows
#:->)
(:import-from #:dexador)
(:import-from #:jonathan)
(:import-from #:function-cache
#:defcached)
(:export
#:read-metadata
#:metadata
#:get-source
#:get-urn
#:get-description))
(in-package #:ultralisp/metadata)
(defclass metadata ()
((source :type keyword
:initarg :source
:documentation "Project source type: :github, :git, :bitbucket, :http, etc."
:reader get-source)
(urn :type string
:initarg :urn
:documentation "A string containing information to download sources. Format depends on a source slot's content."
:reader get-urn)))
(defun make-metadata (source urn)
(make-instance 'metadata
:source (make-keyword source)
:urn urn))
(defmethod print-object ((obj metadata) stream)
(print-unreadable-object (obj stream :type t)
(format stream "~A ~S"
(get-source obj)
(get-urn obj))))
(defun read-metadata (path)
(when (probe-file path)
(with-open-file (input path)
(loop for form = (read input nil nil)
for metadata = (when form
(when (not (= (length form)
2))
(error "Form ~A should countain two items, like \"(:github \"40ants/defmain\")\"."
form))
(apply #'make-metadata form))
while metadata
collect metadata))))
(defcached %github-get-description (project-urn)
(-> (format nil "/~A"
project-urn)
(dex:get)
(jonathan:parse)
(getf :|description|)))
(defun get-description (metadata)
(check-type metadata metadata)
(%github-get-description (get-urn metadata)))
| null | https://raw.githubusercontent.com/ultralisp/ultralisp/37bd5d92b2cf751cd03ced69bac785bf4bcb6c15/src/metadata.lisp | lisp | (defpackage #:ultralisp/metadata
(:use #:cl)
(:import-from #:alexandria
#:make-keyword)
(:import-from #:arrows
#:->)
(:import-from #:dexador)
(:import-from #:jonathan)
(:import-from #:function-cache
#:defcached)
(:export
#:read-metadata
#:metadata
#:get-source
#:get-urn
#:get-description))
(in-package #:ultralisp/metadata)
(defclass metadata ()
((source :type keyword
:initarg :source
:documentation "Project source type: :github, :git, :bitbucket, :http, etc."
:reader get-source)
(urn :type string
:initarg :urn
:documentation "A string containing information to download sources. Format depends on a source slot's content."
:reader get-urn)))
(defun make-metadata (source urn)
(make-instance 'metadata
:source (make-keyword source)
:urn urn))
(defmethod print-object ((obj metadata) stream)
(print-unreadable-object (obj stream :type t)
(format stream "~A ~S"
(get-source obj)
(get-urn obj))))
(defun read-metadata (path)
(when (probe-file path)
(with-open-file (input path)
(loop for form = (read input nil nil)
for metadata = (when form
(when (not (= (length form)
2))
(error "Form ~A should countain two items, like \"(:github \"40ants/defmain\")\"."
form))
(apply #'make-metadata form))
while metadata
collect metadata))))
(defcached %github-get-description (project-urn)
(-> (format nil "/~A"
project-urn)
(dex:get)
(jonathan:parse)
(getf :|description|)))
(defun get-description (metadata)
(check-type metadata metadata)
(%github-get-description (get-urn metadata)))
|
|
adc0218aefb565987618a7dca9f0c104268d151d6d594871c29b6267d2989f75 | ocaml-ppx/ppx | poly_env.mli | type env
val create : vars:string list -> args:Astlib.Grammar.targ list -> env
val uninstantiated : string list -> env
val empty_env : env
val env_is_empty : env -> bool
val args : env -> Astlib.Grammar.targ list
val subst_ty : Astlib.Grammar.ty -> env:env -> Astlib.Grammar.ty
val subst_decl : Astlib.Grammar.decl -> env:env -> Astlib.Grammar.decl
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/ast/cinaps/poly_env.mli | ocaml | type env
val create : vars:string list -> args:Astlib.Grammar.targ list -> env
val uninstantiated : string list -> env
val empty_env : env
val env_is_empty : env -> bool
val args : env -> Astlib.Grammar.targ list
val subst_ty : Astlib.Grammar.ty -> env:env -> Astlib.Grammar.ty
val subst_decl : Astlib.Grammar.decl -> env:env -> Astlib.Grammar.decl
|
|
8207ac9d00ea65cc3b40875826799028a12dcf667f502284c0e68d0dcee44b32 | godfat/sandbox | hash.hs | output 2
module TestHash where
import GHC.Int
import Data.HashTable as HashTable
import Data.Maybe as Maybe
hash :: IO (HashTable Int32 Int32)
hash = new (==) id
main = do
h <- hash
insert h 1 2
v <- HashTable.lookup h 1
putStrLn $ show $ Maybe.fromJust v
| null | https://raw.githubusercontent.com/godfat/sandbox/eb6294238f92543339adfdfb4ba88586ba0e82b8/haskell/hash.hs | haskell | output 2
module TestHash where
import GHC.Int
import Data.HashTable as HashTable
import Data.Maybe as Maybe
hash :: IO (HashTable Int32 Int32)
hash = new (==) id
main = do
h <- hash
insert h 1 2
v <- HashTable.lookup h 1
putStrLn $ show $ Maybe.fromJust v
|
|
ac81a1e8c27398db3fae892ec1e98c42f5d8d31d7870275609fb72efab12662c | berke/aurochs | peg.ml | (* Peg *)
open Pffpsf
(*** types *)
type char_set =
| One of char
| Many of char list
| Range of char * char
type match_options =
| Exact
| Case_insensitive
type 'a pe =
| Epsilon
| Position
| Tokenize of 'a pe
| Ascribe of string * 'a pe
| Constant of string
| A of string (* Atom *)
| Ax of string * match_options
| C of char_set Boolean.t
Nonterminal
| S of 'a pe list (* Sequence *)
| Build of string * 'a pe list
| Or of 'a pe list (* Ordered alternative *)
| And of 'a pe
| Not of 'a pe
| Opt of 'a pe (* Option *)
Star
| Plus of 'a pe
| BOF
| EOF
type proto_tree =
| Empty_
| Node_ of string * proto_tree list
| Attribute_ of string * string
| Token_ of string
| Pseudo_ of proto_tree list
type value =
| V_Substring of int * int
| V_Constant of string
type ('node, 'attribute) poly_positioned_tree =
| P_Node of int * int * 'node * (value * 'attribute) list * ('node, 'attribute) poly_positioned_tree list (* Node (name, attributes_list, children *)
| P_Token of int * int
type ('node, 'attribute) poly_tree =
| Node of 'node * ('attribute * string) list * ('node, 'attribute) poly_tree list (* Node (name, attributes_list, children *)
| Token of string
let rec iter_over_poly_tree_nodes f = function
| Node(nd, _, xl) -> f nd; List.iter (iter_over_poly_tree_nodes f) xl
| Token _ -> ()
let rec iter_over_poly_tree_attributes f = function
| Node(_, al, xl) -> List.iter (fun (a, _) -> f a) al; List.iter (iter_over_poly_tree_attributes f) xl
| Token _ -> ()
type tree = (string, string) poly_tree
type 'a result =
| Failure
| Success of 'a
| Busy
exception Fail
exception Not_implemented
exception Error of string
(* ***)
let sub u i j = String.sub u i (j - i)
(*** rec *)
let rec relativize u = function
| P_Node(_, _, n, al, xl) ->
Node(n,
List.map
(fun (v, a) ->
match v with
| V_Substring(i, j) -> (a, if j < i then string_of_int i else sub u i j)
| V_Constant u -> (a, u)
)
al,
List.map (relativize u) xl)
| P_Token(i, j) -> Token(sub u i j)
(* ***)
* * iter_over_n
let rec iter_over_n f = function
| N x -> f x
| Epsilon|EOF|BOF|Position|A _|Ax _|C _|Constant _ -> ()
| Tokenize x|Ascribe(_,x)|And x|Not x|Opt x|Star x|Plus x -> iter_over_n f x
| S xl|Build(_, xl)|Or xl -> List.iter (iter_over_n f) xl
(* ***)
(*** map_over_n *)
let rec map_over_n f = function
| N x -> N(f x)
| Constant u -> Constant u
| Epsilon -> Epsilon
| Position -> Position
| EOF -> EOF
| BOF -> BOF
| A u -> A u
| Ax(u, o) -> Ax(u, o)
| C c -> C c
| Tokenize x -> Tokenize(map_over_n f x)
| Ascribe(n, x) -> Ascribe(n, map_over_n f x)
| And x -> And(map_over_n f x)
| Not x -> Not(map_over_n f x)
| Opt x -> Opt(map_over_n f x)
| Star x -> Star(map_over_n f x)
| Plus x -> Plus(map_over_n f x)
| S xl -> S(List.map (map_over_n f) xl)
| Build(n, xl) -> Build(n, List.map (map_over_n f) xl)
| Or xl -> Or(List.map (map_over_n f) xl)
(* ***)
(*** iter_over_builds *)
let rec iter_over_builds f = function
| N _ | Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> ()
| And x | Not x | Opt x | Star x | Plus x | Tokenize x | Ascribe(_, x) -> iter_over_builds f x
| Build(n, xl) -> f n; List.iter (iter_over_builds f) xl
| S xl | Or xl -> List.iter (iter_over_builds f) xl
(* ***)
(*** iter_over_attributes *)
let rec iter_over_attributes f = function
| N _ | Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> ()
| And x | Not x | Opt x | Star x | Plus x | Tokenize x -> iter_over_attributes f x
| Ascribe(a, x) -> f a; iter_over_attributes f x
| Build(_, xl) | S xl | Or xl -> List.iter (iter_over_attributes f) xl
(* ***)
module SS = Set.Make(String)
module SM = Map.Make(String)
type trool =
| Unknown
| True
| False
let ( ||| ) a b = match (a, b) with
| (Unknown, x)|(x, Unknown) -> x
| (True,_)|(_,True) -> True
| (_,_) -> False
let print_trool oc = function
| True -> fp oc "true"
| False -> fp oc "false"
| Unknown -> fp oc "unknown"
(*** rec *)
MUST BE CANONIFIED
let compute_active_terminals peg =
(* Compute produceability graph *)
let genitors = ref SM.empty in
(* x may generate y *)
let is_genitor y x =
let children =
try
SM.find x !genitors
with
| Not_found -> SS.empty
in
genitors := SM.add x (SS.add y children) !genitors
in
List.iter
begin fun (n, x) ->
let rec loop = function
| N n' -> is_genitor n n'
| Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> ()
| And x | Not x | Opt x | Star x | Plus x | Tokenize x | Ascribe(_, x) -> loop x
| Build(_, xl) | S xl | Or xl -> List.iter loop xl
in
loop x
end
peg;
(* Compute reachability *)
let actives = ref SS.empty in
let rec mark busy n =
if SS.mem n busy then
() (* Already being marked *)
else
begin
actives := SS.add n !actives;
let g =
try
SM.find n !genitors
with
| Not_found -> SS.empty
in
let busy' = SS.add n busy in
SS.iter
begin fun n' ->
if not (SS.mem n' busy) && not (SS.mem n' !actives) then
mark busy' n'
end
g
end
in
let rec active_root = function
| N n' -> false
| Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> false
| And x | Not x | Opt x | Star x | Plus x -> active_root x
| Tokenize _ | Ascribe(_, _) | Build(_, _)-> true
| S xl | Or xl -> List.exists active_root xl
in
List.iter (fun (n, x) -> if active_root x then mark SS.empty n) peg;
!actives
(* ***)
let fp = Printf.fprintf
let sf = Printf.sprintf
(*** print_indent *)
let print_indent oc d =
for i = 1 to d do
fp oc " "
done
(* ***)
(*** print_escaping *)
let print_escaping oc u =
let m = String.length u in
for i = 0 to m - 1 do
match u.[i] with
| '"' -> fp oc """
| '<' -> fp oc "<"
| '>' -> fp oc ">"
| c -> output_char oc c
done
(* ***)
(*** print_tree, print_tree_list *)
let print_string oc x = fp oc "%s" x
let has_two = function
| _ :: _ :: _ -> true
| _ -> false
let rec print_poly_tree ?(terse=false) ?(depth=0) ?(short=false) ~print_node ~print_attribute () oc t =
let terse_head n al l =
fp oc "%a%a" print_indent depth print_node n;
if al <> [] then
begin
fp oc "(";
let x = ref false in
List.iter
begin fun (name, value) ->
if !x then fp oc " " else x := true;
fp oc "%a=\"%a\"" print_attribute name print_escaping value
end
al;
fp oc ")"
end;
if has_two l then fp oc "{\n" else fp oc "\n"
in
match t with
| Node(n, al, (_::_ as l)) ->
if terse then
terse_head n al l
else
begin
if short then fp oc "<%a" print_node n else fp oc "%a<%a" print_indent depth print_node n;
List.iter
begin fun (name, value) ->
fp oc " %a=\"%a\"" print_attribute name print_escaping value
end
al;
if short then fp oc ">" else fp oc ">\n";
end;
print_poly_tree_list ~terse ~depth:(depth + 1) ~short ~print_node ~print_attribute () oc l;
if terse then
if has_two l then
fp oc "%a}\n" print_indent depth
else
()
else
if short then
fp oc "</%a>" print_node n
else
fp oc "%a</%a>\n" print_indent depth print_node n
| Node(n, al, []) ->
if terse then
terse_head n al []
else
begin
if short then
fp oc "<%a" print_node n
else
fp oc "%a<%a" print_indent depth print_node n;
List.iter
begin fun (name, value) ->
fp oc " %a=\"%a\"" print_attribute name print_escaping value
end
al;
if short then fp oc "/>" else fp oc "/>\n"
end
| Token u ->
if short then
print_escaping oc u
else
fp oc "%a%a\n" print_indent depth print_escaping u
and print_poly_tree_list ?terse ?(depth=0) ?(short=false) ~print_node ~print_attribute () oc l =
List.iter
begin fun t ->
print_poly_tree ?terse ~depth ~short ~print_node ~print_attribute () oc t
end
l
let print_tree ?terse ?depth ?short () oc t = print_poly_tree ?terse ?depth ?short ~print_node:print_string ~print_attribute:print_string () oc t
let print_tree_list ?terse ?depth ?short () oc l = print_poly_tree_list ?terse ?depth ?short ~print_node:print_string ~print_attribute:print_string () oc l
(* ***)
(*** collect *)
exception Bad_tree
let collect t =
let rec do_collector n attributes children = function
| [] -> (attributes, children)
| x :: rest ->
match x with
| Node_(n', l') ->
let (attributes', children') = do_collector n' [] [] l' in
do_collector n attributes (Node(n', List.rev attributes', List.rev children') :: children) rest
| Token_ u -> do_collector n attributes ((Token u) :: children) rest
| Empty_ -> do_collector n attributes children rest
| Attribute_(name, value) -> do_collector n ((name, value) :: attributes) children rest
| Pseudo_ l ->
let (attributes', children') = do_collector n attributes children l in
do_collector n attributes' children' rest
and do_tree = function
| Empty_ -> Node("*Empty", [], [])
| Attribute_(n, v) -> Node("*Attribute", [n,v], [])
| Pseudo_ l -> Node("*Pseudo", [], List.map do_tree l)
| Node_(n, children) ->
let (attributes, children') = do_collector n [] [] children in
Node(n, List.rev attributes, List.rev children')
| Token_ u -> Token u
in
do_tree t
(* ***)
(*** is_factor *)
let is_factor v u i =
let m = String.length u
and n = String.length v
in
0 <= i && i < m && n <= m - i &&
let rec loop j =
j = n or
u.[i + j] = v.[j] && loop (j + 1)
in
loop 0
(* ***)
(*** extract_token, extract_token_from_list *)
let rec extract_token = function
| (Node_(_, l)|Pseudo_ l) -> extract_token_from_list l
| Token_ u -> u
| _ -> raise Fail
and extract_token_from_list = function
| [] -> raise Fail
| x :: rest ->
match x with
| Token_ u -> u
| (Pseudo_ l|Node_(_, l)) ->
begin
try
extract_token_from_list l
with
| Fail -> extract_token_from_list rest
end
| _ -> extract_token_from_list rest
(* ***)
(*** process *)
let process resolve peg u =
let m = String.length u in
let cache = Hashtbl.create 1009 in
let rec loop i pe =
if Hashtbl.mem cache (i, pe) then
begin
match Hashtbl.find cache (i, pe) with
| Failure -> raise Fail
| Busy -> raise Fail
| Success x -> x
end
else
begin
Hashtbl.replace cache (i, pe) Busy;
let y =
try
Success(
match pe with
| Epsilon | Position -> (i, Empty_)
| BOF ->
if i = 0 then
(i, Empty_)
else
raise Fail
| EOF ->
if i = m then
(i, Empty_)
else
raise Fail
| Tokenize pe ->
let (j, s) = loop i pe in
(j, Token_(String.sub u i (j - i)))
| Ascribe(n, Position) ->
(i, Attribute_(n, Printf.sprintf "%d" i))
| Constant _ -> (i, Empty_)
| Ascribe(n, Constant u) -> (i, Attribute_(n, u))
| Ascribe(n, pe) ->
if false then
begin
let (j, s) = loop i pe in
let v = extract_token s in
(j, Attribute_(n, v))
end
else
begin
let (j, _) = loop i pe in
(j, Attribute_(n, String.sub u i (j - i)))
end
| C f ->
if i < m &&
begin
let c = u.[i] in
Boolean.eval
begin function
| One d -> c = d
| Many dl -> List.mem c dl
| Range(d1,d2) -> d1 <= c && c <= d2
end
f
end
then
(i + 1, Empty_)
else
raise Fail
| Ax(v, Case_insensitive) ->
let n = String.length v in
if is_factor (String.lowercase v) (String.lowercase u) i then
(i + n, Empty_)
else
raise Fail
| Ax(v, Exact) | A v ->
let n = String.length v in
if is_factor v u i then
(i + n, Empty_)
else
raise Fail
| N n -> loop i (resolve n)
| S l ->
let (i, sl) =
List.fold_left
begin fun (i, sl) pe ->
let (i, s) = loop i pe in
(i, s :: sl)
end
(i, [])
l
in
(i, Pseudo_(List.rev sl))
| Build(n, l) ->
let (i, sl) =
List.fold_left
begin fun (i, sl) pe ->
let (i, s) = loop i pe in
(i, s :: sl)
end
(i, [])
l
in
(i, Node_(n, List.rev sl))
| Or l ->
begin
let rec scan = function
| [] -> raise Fail
| pe :: rest ->
try
loop i pe
with
| Fail -> scan rest
in
scan l
end
| And pe ->
let _ = loop i pe in
(i, Empty_)
| Not pe ->
begin
if
try
let _ = loop i pe in
true
with
| Fail -> false
then
raise Fail
else
(i, Empty_)
end
| Opt pe ->
begin
try
loop i pe
with
| Fail -> (i, Empty_)
end
| Star pe ->
begin
let rec scan i sl =
try
let (i', s) = loop i pe in
if i = i' then
(i, sl)
else
scan i' (s :: sl)
with
| Fail -> (i, sl)
in
let (i, sl) = scan i [] in
(i, Pseudo_(List.rev sl))
end
| Plus pe ->
begin
let rec scan i sl =
try
let (i', s) = loop i pe in
if i = i' then
(i, sl)
else
scan i' (s :: sl)
with
| Fail -> (i, sl)
in
let (i, s) = loop i pe in
let (i, sl) = scan i [s] in
(i, Pseudo_(List.rev sl))
end
)
with
| Fail -> Failure
in
Hashtbl.add cache (i, pe) y;
match y with
| Failure|Busy -> raise Fail
| Success x -> x
end
in
loop 0 peg, cache
(* ***)
(*** descent *)
let descent resolve peg u =
let ((i, s), cache) = process resolve peg u in
let success = i = String.length u in
if success then
(true, i, collect s)
else
begin
let max_i = ref 0 in
Hashtbl.iter
begin fun (i, _) y ->
match y with
| Success(i, _) -> max_i := max i !max_i
| _ -> ()
end
cache;
Printf.eprintf "Parse error at character %d.\n%!" !max_i;
(false, i, collect s)
end
(* ***)
| null | https://raw.githubusercontent.com/berke/aurochs/637bdc0d4682772837f9e44112212e7f20ab96ff/peg/peg.ml | ocaml | Peg
** types
Atom
Sequence
Ordered alternative
Option
Node (name, attributes_list, children
Node (name, attributes_list, children
**
** rec
**
**
** map_over_n
**
** iter_over_builds
**
** iter_over_attributes
**
** rec
Compute produceability graph
x may generate y
Compute reachability
Already being marked
**
** print_indent
**
** print_escaping
**
** print_tree, print_tree_list
**
** collect
**
** is_factor
**
** extract_token, extract_token_from_list
**
** process
**
** descent
** |
open Pffpsf
type char_set =
| One of char
| Many of char list
| Range of char * char
type match_options =
| Exact
| Case_insensitive
type 'a pe =
| Epsilon
| Position
| Tokenize of 'a pe
| Ascribe of string * 'a pe
| Constant of string
| Ax of string * match_options
| C of char_set Boolean.t
Nonterminal
| Build of string * 'a pe list
| And of 'a pe
| Not of 'a pe
Star
| Plus of 'a pe
| BOF
| EOF
type proto_tree =
| Empty_
| Node_ of string * proto_tree list
| Attribute_ of string * string
| Token_ of string
| Pseudo_ of proto_tree list
type value =
| V_Substring of int * int
| V_Constant of string
type ('node, 'attribute) poly_positioned_tree =
| P_Token of int * int
type ('node, 'attribute) poly_tree =
| Token of string
let rec iter_over_poly_tree_nodes f = function
| Node(nd, _, xl) -> f nd; List.iter (iter_over_poly_tree_nodes f) xl
| Token _ -> ()
let rec iter_over_poly_tree_attributes f = function
| Node(_, al, xl) -> List.iter (fun (a, _) -> f a) al; List.iter (iter_over_poly_tree_attributes f) xl
| Token _ -> ()
type tree = (string, string) poly_tree
type 'a result =
| Failure
| Success of 'a
| Busy
exception Fail
exception Not_implemented
exception Error of string
let sub u i j = String.sub u i (j - i)
let rec relativize u = function
| P_Node(_, _, n, al, xl) ->
Node(n,
List.map
(fun (v, a) ->
match v with
| V_Substring(i, j) -> (a, if j < i then string_of_int i else sub u i j)
| V_Constant u -> (a, u)
)
al,
List.map (relativize u) xl)
| P_Token(i, j) -> Token(sub u i j)
* * iter_over_n
let rec iter_over_n f = function
| N x -> f x
| Epsilon|EOF|BOF|Position|A _|Ax _|C _|Constant _ -> ()
| Tokenize x|Ascribe(_,x)|And x|Not x|Opt x|Star x|Plus x -> iter_over_n f x
| S xl|Build(_, xl)|Or xl -> List.iter (iter_over_n f) xl
let rec map_over_n f = function
| N x -> N(f x)
| Constant u -> Constant u
| Epsilon -> Epsilon
| Position -> Position
| EOF -> EOF
| BOF -> BOF
| A u -> A u
| Ax(u, o) -> Ax(u, o)
| C c -> C c
| Tokenize x -> Tokenize(map_over_n f x)
| Ascribe(n, x) -> Ascribe(n, map_over_n f x)
| And x -> And(map_over_n f x)
| Not x -> Not(map_over_n f x)
| Opt x -> Opt(map_over_n f x)
| Star x -> Star(map_over_n f x)
| Plus x -> Plus(map_over_n f x)
| S xl -> S(List.map (map_over_n f) xl)
| Build(n, xl) -> Build(n, List.map (map_over_n f) xl)
| Or xl -> Or(List.map (map_over_n f) xl)
let rec iter_over_builds f = function
| N _ | Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> ()
| And x | Not x | Opt x | Star x | Plus x | Tokenize x | Ascribe(_, x) -> iter_over_builds f x
| Build(n, xl) -> f n; List.iter (iter_over_builds f) xl
| S xl | Or xl -> List.iter (iter_over_builds f) xl
let rec iter_over_attributes f = function
| N _ | Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> ()
| And x | Not x | Opt x | Star x | Plus x | Tokenize x -> iter_over_attributes f x
| Ascribe(a, x) -> f a; iter_over_attributes f x
| Build(_, xl) | S xl | Or xl -> List.iter (iter_over_attributes f) xl
module SS = Set.Make(String)
module SM = Map.Make(String)
type trool =
| Unknown
| True
| False
let ( ||| ) a b = match (a, b) with
| (Unknown, x)|(x, Unknown) -> x
| (True,_)|(_,True) -> True
| (_,_) -> False
let print_trool oc = function
| True -> fp oc "true"
| False -> fp oc "false"
| Unknown -> fp oc "unknown"
MUST BE CANONIFIED
let compute_active_terminals peg =
let genitors = ref SM.empty in
let is_genitor y x =
let children =
try
SM.find x !genitors
with
| Not_found -> SS.empty
in
genitors := SM.add x (SS.add y children) !genitors
in
List.iter
begin fun (n, x) ->
let rec loop = function
| N n' -> is_genitor n n'
| Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> ()
| And x | Not x | Opt x | Star x | Plus x | Tokenize x | Ascribe(_, x) -> loop x
| Build(_, xl) | S xl | Or xl -> List.iter loop xl
in
loop x
end
peg;
let actives = ref SS.empty in
let rec mark busy n =
if SS.mem n busy then
else
begin
actives := SS.add n !actives;
let g =
try
SM.find n !genitors
with
| Not_found -> SS.empty
in
let busy' = SS.add n busy in
SS.iter
begin fun n' ->
if not (SS.mem n' busy) && not (SS.mem n' !actives) then
mark busy' n'
end
g
end
in
let rec active_root = function
| N n' -> false
| Epsilon | Position | EOF | BOF | A _ | Ax _ | C _ | Constant _ -> false
| And x | Not x | Opt x | Star x | Plus x -> active_root x
| Tokenize _ | Ascribe(_, _) | Build(_, _)-> true
| S xl | Or xl -> List.exists active_root xl
in
List.iter (fun (n, x) -> if active_root x then mark SS.empty n) peg;
!actives
let fp = Printf.fprintf
let sf = Printf.sprintf
let print_indent oc d =
for i = 1 to d do
fp oc " "
done
let print_escaping oc u =
let m = String.length u in
for i = 0 to m - 1 do
match u.[i] with
| '"' -> fp oc """
| '<' -> fp oc "<"
| '>' -> fp oc ">"
| c -> output_char oc c
done
let print_string oc x = fp oc "%s" x
let has_two = function
| _ :: _ :: _ -> true
| _ -> false
let rec print_poly_tree ?(terse=false) ?(depth=0) ?(short=false) ~print_node ~print_attribute () oc t =
let terse_head n al l =
fp oc "%a%a" print_indent depth print_node n;
if al <> [] then
begin
fp oc "(";
let x = ref false in
List.iter
begin fun (name, value) ->
if !x then fp oc " " else x := true;
fp oc "%a=\"%a\"" print_attribute name print_escaping value
end
al;
fp oc ")"
end;
if has_two l then fp oc "{\n" else fp oc "\n"
in
match t with
| Node(n, al, (_::_ as l)) ->
if terse then
terse_head n al l
else
begin
if short then fp oc "<%a" print_node n else fp oc "%a<%a" print_indent depth print_node n;
List.iter
begin fun (name, value) ->
fp oc " %a=\"%a\"" print_attribute name print_escaping value
end
al;
if short then fp oc ">" else fp oc ">\n";
end;
print_poly_tree_list ~terse ~depth:(depth + 1) ~short ~print_node ~print_attribute () oc l;
if terse then
if has_two l then
fp oc "%a}\n" print_indent depth
else
()
else
if short then
fp oc "</%a>" print_node n
else
fp oc "%a</%a>\n" print_indent depth print_node n
| Node(n, al, []) ->
if terse then
terse_head n al []
else
begin
if short then
fp oc "<%a" print_node n
else
fp oc "%a<%a" print_indent depth print_node n;
List.iter
begin fun (name, value) ->
fp oc " %a=\"%a\"" print_attribute name print_escaping value
end
al;
if short then fp oc "/>" else fp oc "/>\n"
end
| Token u ->
if short then
print_escaping oc u
else
fp oc "%a%a\n" print_indent depth print_escaping u
and print_poly_tree_list ?terse ?(depth=0) ?(short=false) ~print_node ~print_attribute () oc l =
List.iter
begin fun t ->
print_poly_tree ?terse ~depth ~short ~print_node ~print_attribute () oc t
end
l
let print_tree ?terse ?depth ?short () oc t = print_poly_tree ?terse ?depth ?short ~print_node:print_string ~print_attribute:print_string () oc t
let print_tree_list ?terse ?depth ?short () oc l = print_poly_tree_list ?terse ?depth ?short ~print_node:print_string ~print_attribute:print_string () oc l
exception Bad_tree
let collect t =
let rec do_collector n attributes children = function
| [] -> (attributes, children)
| x :: rest ->
match x with
| Node_(n', l') ->
let (attributes', children') = do_collector n' [] [] l' in
do_collector n attributes (Node(n', List.rev attributes', List.rev children') :: children) rest
| Token_ u -> do_collector n attributes ((Token u) :: children) rest
| Empty_ -> do_collector n attributes children rest
| Attribute_(name, value) -> do_collector n ((name, value) :: attributes) children rest
| Pseudo_ l ->
let (attributes', children') = do_collector n attributes children l in
do_collector n attributes' children' rest
and do_tree = function
| Empty_ -> Node("*Empty", [], [])
| Attribute_(n, v) -> Node("*Attribute", [n,v], [])
| Pseudo_ l -> Node("*Pseudo", [], List.map do_tree l)
| Node_(n, children) ->
let (attributes, children') = do_collector n [] [] children in
Node(n, List.rev attributes, List.rev children')
| Token_ u -> Token u
in
do_tree t
let is_factor v u i =
let m = String.length u
and n = String.length v
in
0 <= i && i < m && n <= m - i &&
let rec loop j =
j = n or
u.[i + j] = v.[j] && loop (j + 1)
in
loop 0
let rec extract_token = function
| (Node_(_, l)|Pseudo_ l) -> extract_token_from_list l
| Token_ u -> u
| _ -> raise Fail
and extract_token_from_list = function
| [] -> raise Fail
| x :: rest ->
match x with
| Token_ u -> u
| (Pseudo_ l|Node_(_, l)) ->
begin
try
extract_token_from_list l
with
| Fail -> extract_token_from_list rest
end
| _ -> extract_token_from_list rest
let process resolve peg u =
let m = String.length u in
let cache = Hashtbl.create 1009 in
let rec loop i pe =
if Hashtbl.mem cache (i, pe) then
begin
match Hashtbl.find cache (i, pe) with
| Failure -> raise Fail
| Busy -> raise Fail
| Success x -> x
end
else
begin
Hashtbl.replace cache (i, pe) Busy;
let y =
try
Success(
match pe with
| Epsilon | Position -> (i, Empty_)
| BOF ->
if i = 0 then
(i, Empty_)
else
raise Fail
| EOF ->
if i = m then
(i, Empty_)
else
raise Fail
| Tokenize pe ->
let (j, s) = loop i pe in
(j, Token_(String.sub u i (j - i)))
| Ascribe(n, Position) ->
(i, Attribute_(n, Printf.sprintf "%d" i))
| Constant _ -> (i, Empty_)
| Ascribe(n, Constant u) -> (i, Attribute_(n, u))
| Ascribe(n, pe) ->
if false then
begin
let (j, s) = loop i pe in
let v = extract_token s in
(j, Attribute_(n, v))
end
else
begin
let (j, _) = loop i pe in
(j, Attribute_(n, String.sub u i (j - i)))
end
| C f ->
if i < m &&
begin
let c = u.[i] in
Boolean.eval
begin function
| One d -> c = d
| Many dl -> List.mem c dl
| Range(d1,d2) -> d1 <= c && c <= d2
end
f
end
then
(i + 1, Empty_)
else
raise Fail
| Ax(v, Case_insensitive) ->
let n = String.length v in
if is_factor (String.lowercase v) (String.lowercase u) i then
(i + n, Empty_)
else
raise Fail
| Ax(v, Exact) | A v ->
let n = String.length v in
if is_factor v u i then
(i + n, Empty_)
else
raise Fail
| N n -> loop i (resolve n)
| S l ->
let (i, sl) =
List.fold_left
begin fun (i, sl) pe ->
let (i, s) = loop i pe in
(i, s :: sl)
end
(i, [])
l
in
(i, Pseudo_(List.rev sl))
| Build(n, l) ->
let (i, sl) =
List.fold_left
begin fun (i, sl) pe ->
let (i, s) = loop i pe in
(i, s :: sl)
end
(i, [])
l
in
(i, Node_(n, List.rev sl))
| Or l ->
begin
let rec scan = function
| [] -> raise Fail
| pe :: rest ->
try
loop i pe
with
| Fail -> scan rest
in
scan l
end
| And pe ->
let _ = loop i pe in
(i, Empty_)
| Not pe ->
begin
if
try
let _ = loop i pe in
true
with
| Fail -> false
then
raise Fail
else
(i, Empty_)
end
| Opt pe ->
begin
try
loop i pe
with
| Fail -> (i, Empty_)
end
| Star pe ->
begin
let rec scan i sl =
try
let (i', s) = loop i pe in
if i = i' then
(i, sl)
else
scan i' (s :: sl)
with
| Fail -> (i, sl)
in
let (i, sl) = scan i [] in
(i, Pseudo_(List.rev sl))
end
| Plus pe ->
begin
let rec scan i sl =
try
let (i', s) = loop i pe in
if i = i' then
(i, sl)
else
scan i' (s :: sl)
with
| Fail -> (i, sl)
in
let (i, s) = loop i pe in
let (i, sl) = scan i [s] in
(i, Pseudo_(List.rev sl))
end
)
with
| Fail -> Failure
in
Hashtbl.add cache (i, pe) y;
match y with
| Failure|Busy -> raise Fail
| Success x -> x
end
in
loop 0 peg, cache
let descent resolve peg u =
let ((i, s), cache) = process resolve peg u in
let success = i = String.length u in
if success then
(true, i, collect s)
else
begin
let max_i = ref 0 in
Hashtbl.iter
begin fun (i, _) y ->
match y with
| Success(i, _) -> max_i := max i !max_i
| _ -> ()
end
cache;
Printf.eprintf "Parse error at character %d.\n%!" !max_i;
(false, i, collect s)
end
|
e117be27ad98a1b27903144606d284c02236ce1447cb3653b6cbf0a6a66964d9 | Risto-Stevcev/bastet | ArrayF.ml | open Interface
module type IMPL = sig
val length : 'a array -> int
val make : int -> 'a -> 'a array
val append : 'a array -> 'a array -> 'a array
val map : ('a -> 'b) -> 'a array -> 'b array
val mapi : ('a -> int -> 'b) -> 'a array -> 'b array
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
val every : ('a -> bool) -> 'a array -> bool
val slice : start:int -> end_:int -> 'a array -> 'a array
end
module type ARRAY = sig
val zip_with : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
val zip : 'a array -> 'b array -> ('a * 'b) array
module type EQ_F = functor (E : Interface.EQ) -> sig
type t = E.t array
val eq : t -> t -> bool
end
module type ORD_F = functor (O : Interface.ORD) -> sig
type t = O.t array
val eq : t -> t -> bool
val compare : t -> t -> Interface.ordering
end
module type SHOW_F = functor (S : Interface.SHOW) -> sig
type t = S.t array
val show : t -> string
end
module type TRAVERSABLE_F = functor (A : Interface.APPLICATIVE) -> sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val fold_right : ('b -> 'a -> 'a) -> 'a -> 'b t -> 'a
module Fold_Map : functor (M : Interface.MONOID) -> sig
val fold_map : ('a -> M.t) -> 'a t -> M.t
end
module Fold_Map_Any : functor (M : Interface.MONOID_ANY) -> sig
val fold_map : ('a -> 'b M.t) -> 'a t -> 'b M.t
end
module Fold_Map_Plus : functor (P : Interface.PLUS) -> sig
val fold_map : ('a -> 'b P.t) -> 'a t -> 'b P.t
end
type 'a applicative_t = 'a A.t
val traverse : ('a -> 'b applicative_t) -> 'a t -> 'b t applicative_t
val sequence : 'a applicative_t t -> 'a t applicative_t
end
module Functor : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
end
module Alt : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val alt : 'a t -> 'a t -> 'a t
end
module Apply : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val apply : ('a -> 'b) t -> 'a t -> 'b t
end
module Applicative : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val apply : ('a -> 'b) t -> 'a t -> 'b t
val pure : 'a -> 'a t
end
module Monad : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val apply : ('a -> 'b) t -> 'a t -> 'b t
val pure : 'a -> 'a t
val flat_map : 'a t -> ('a -> 'b t) -> 'b t
end
module Foldable : sig
type 'a t = 'a array
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val fold_right : ('b -> 'a -> 'a) -> 'a -> 'b t -> 'a
module Fold_Map : functor (M : Interface.MONOID) -> sig
val fold_map : ('a -> M.t) -> 'a t -> M.t
end
module Fold_Map_Any : functor (M : Interface.MONOID_ANY) -> sig
val fold_map : ('a -> 'b M.t) -> 'a t -> 'b M.t
end
module Fold_Map_Plus : functor (P : Interface.PLUS) -> sig
val fold_map : ('a -> 'b P.t) -> 'a t -> 'b P.t
end
end
module Unfoldable : sig
type 'a t = 'a array
val unfold : ('a -> ('a * 'a) option) -> 'a -> 'a t
end
module Traversable : TRAVERSABLE_F
module Eq : EQ_F
module Ord : ORD_F
module Show : SHOW_F
module Invariant : sig
type 'a t = 'a array
val imap : ('a -> 'b) -> ('b -> 'a) -> 'a t -> 'b t
end
module Extend : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val extend : ('a t -> 'b) -> 'a t -> 'b t
end
module Infix : sig
val ( <$> ) : ('a -> 'b) -> 'a Monad.t -> 'b Monad.t
val ( <@> ) : 'a Monad.t -> ('a -> 'b) -> 'b Monad.t
val ( <*> ) : ('a -> 'b) Monad.t -> 'a Monad.t -> 'b Monad.t
val ( >>= ) : 'a Monad.t -> ('a -> 'b Monad.t) -> 'b Monad.t
val ( =<< ) : ('a -> 'b Monad.t) -> 'a Monad.t -> 'b Monad.t
val ( >=> ) : ('a -> 'b Monad.t) -> ('b -> 'c Monad.t) -> 'a -> 'c Monad.t
val ( <=< ) : ('a -> 'b Monad.t) -> ('c -> 'a Monad.t) -> 'c -> 'b Monad.t
val ( <<= ) : ('a Extend.t -> 'b) -> 'a Extend.t -> 'b Extend.t
val ( =>> ) : 'a Extend.t -> ('a Extend.t -> 'b) -> 'b Extend.t
end
end
module Make (A : IMPL) : ARRAY = struct
let zip_with =
(fun f xs ys ->
let l =
match A.length xs < A.length ys with
| true -> A.length xs
| false -> A.length ys
and index = ref 0
and result = ref None in
for i = 0 to l - 1 do
let value = f (ArrayLabels.get xs i) (ArrayLabels.get ys i) in
(match !result with
| Some arr -> ArrayLabels.set arr !index value
| None -> result := Some (A.make l value));
index := !index + 1
done;
match !result with
| Some array -> array
| None -> [||]
: ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array)
let zip = (fun xs ys -> zip_with (fun a b -> a, b) xs ys : 'a array -> 'b array -> 'c array)
module type EQ_F = functor (E : EQ) -> EQ with type t = E.t array
module type ORD_F = functor (O : ORD) -> ORD with type t = O.t array
module type SHOW_F = functor (S : SHOW) -> SHOW with type t = S.t array
module type TRAVERSABLE_F = functor (A : APPLICATIVE) ->
TRAVERSABLE with type 'a t = 'a array and type 'a applicative_t = 'a A.t
module Functor : FUNCTOR with type 'a t = 'a array = struct
type 'a t = 'a array
let map = A.map
end
module Alt : ALT with type 'a t = 'a array = struct
include Functor
let alt = A.append
end
module Apply : APPLY with type 'a t = 'a array = struct
include Functor
let apply fn_array a = A.fold_left (fun acc f -> Alt.alt acc (map f a)) [||] fn_array
end
module Applicative : APPLICATIVE with type 'a t = 'a array = struct
include Apply
let pure a = [|a|]
end
module Monad : MONAD with type 'a t = 'a array = struct
include Applicative
let flat_map x f = A.fold_left (fun acc a -> Alt.alt acc (f a)) [||] x
end
module Foldable : FOLDABLE with type 'a t = 'a array = struct
type 'a t = 'a array
let fold_left = A.fold_left
and fold_right f init = ArrayLabels.fold_right ~f ~init
module Fold_Map (M : MONOID) = struct
module D =
Default.Fold_Map
(M)
(struct
type 'a t = 'a array
let fold_left, fold_right = fold_left, fold_right
end)
let fold_map = D.fold_map_default_left
end
module Fold_Map_Any (M : MONOID_ANY) = struct
module D =
Default.Fold_Map_Any
(M)
(struct
type 'a t = 'a array
let fold_left, fold_right = fold_left, fold_right
end)
let fold_map = D.fold_map_default_left
end
module Fold_Map_Plus (P : PLUS) = struct
module D =
Default.Fold_Map_Plus
(P)
(struct
type 'a t = 'a array
let fold_left, fold_right = fold_left, fold_right
end)
let fold_map = D.fold_map_default_left
end
end
module Unfoldable : UNFOLDABLE with type 'a t = 'a array = struct
type 'a t = 'a array
let rec unfold f init =
match f init with
| Some (a, next) -> Alt.alt [|a|] (unfold f next)
| None -> [||]
end
module Traversable : TRAVERSABLE_F =
functor
(A : APPLICATIVE)
->
struct
type 'a t = 'a array
and 'a applicative_t = 'a A.t
include (Functor : FUNCTOR with type 'a t := 'a t)
include (Foldable : FOLDABLE with type 'a t := 'a t)
module I = Infix.Apply (A)
let traverse f =
let open I in
ArrayLabels.fold_right
~f:(fun acc x -> A.pure (fun x y -> Alt.alt [|x|] y) <*> f acc <*> x)
~init:(A.pure [||])
module D = Default.Sequence (struct
type 'a t = 'a array
and 'a applicative_t = 'a A.t
let traverse = traverse
end)
let sequence = D.sequence_default
end
module Eq : EQ_F =
functor
(E : EQ)
->
struct
type t = E.t array
let eq xs ys = A.length xs = A.length ys && A.every (fun (a, b) -> E.eq a b) (zip xs ys)
end
module Ord : ORD_F =
functor
(O : ORD)
->
struct
include Eq (O)
let compare xs ys =
match xs, ys with
| _ when A.length xs = A.length ys ->
let index = ref 0 in
A.fold_left
(fun acc e ->
let result =
match acc <> `equal_to with
| true -> acc
| false -> O.compare e (ArrayLabels.get ys !index)
in
index := !index + 1;
result)
`equal_to
xs
| _ when A.length xs < A.length ys -> `less_than
| _ -> `greater_than
end
module Show : SHOW_F =
functor
(S : SHOW)
->
struct
module F = Functions.Foldable (Foldable)
module M = F.Monoid (String.Monoid)
type t = S.t array
let show xs = "[" ^ M.intercalate ~separator:", " (Functor.map S.show xs) ^ "]"
end
module Invariant : INVARIANT with type 'a t = 'a array = struct
type 'a t = 'a array
let imap f _ = Functor.map f
end
module Extend : EXTEND with type 'a t = 'a array = struct
include Functor
let extend f xs = A.mapi (fun _ i -> f (A.slice xs ~start:i ~end_:(A.length xs))) xs
end
module Infix = struct
include Infix.Monad (Monad)
include Infix.Extend (Extend)
end
end
| null | https://raw.githubusercontent.com/Risto-Stevcev/bastet/030db286f57d2e316897f0600d40b34777eabba6/bastet/src/ArrayF.ml | ocaml | open Interface
module type IMPL = sig
val length : 'a array -> int
val make : int -> 'a -> 'a array
val append : 'a array -> 'a array -> 'a array
val map : ('a -> 'b) -> 'a array -> 'b array
val mapi : ('a -> int -> 'b) -> 'a array -> 'b array
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
val every : ('a -> bool) -> 'a array -> bool
val slice : start:int -> end_:int -> 'a array -> 'a array
end
module type ARRAY = sig
val zip_with : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
val zip : 'a array -> 'b array -> ('a * 'b) array
module type EQ_F = functor (E : Interface.EQ) -> sig
type t = E.t array
val eq : t -> t -> bool
end
module type ORD_F = functor (O : Interface.ORD) -> sig
type t = O.t array
val eq : t -> t -> bool
val compare : t -> t -> Interface.ordering
end
module type SHOW_F = functor (S : Interface.SHOW) -> sig
type t = S.t array
val show : t -> string
end
module type TRAVERSABLE_F = functor (A : Interface.APPLICATIVE) -> sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val fold_right : ('b -> 'a -> 'a) -> 'a -> 'b t -> 'a
module Fold_Map : functor (M : Interface.MONOID) -> sig
val fold_map : ('a -> M.t) -> 'a t -> M.t
end
module Fold_Map_Any : functor (M : Interface.MONOID_ANY) -> sig
val fold_map : ('a -> 'b M.t) -> 'a t -> 'b M.t
end
module Fold_Map_Plus : functor (P : Interface.PLUS) -> sig
val fold_map : ('a -> 'b P.t) -> 'a t -> 'b P.t
end
type 'a applicative_t = 'a A.t
val traverse : ('a -> 'b applicative_t) -> 'a t -> 'b t applicative_t
val sequence : 'a applicative_t t -> 'a t applicative_t
end
module Functor : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
end
module Alt : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val alt : 'a t -> 'a t -> 'a t
end
module Apply : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val apply : ('a -> 'b) t -> 'a t -> 'b t
end
module Applicative : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val apply : ('a -> 'b) t -> 'a t -> 'b t
val pure : 'a -> 'a t
end
module Monad : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val apply : ('a -> 'b) t -> 'a t -> 'b t
val pure : 'a -> 'a t
val flat_map : 'a t -> ('a -> 'b t) -> 'b t
end
module Foldable : sig
type 'a t = 'a array
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val fold_right : ('b -> 'a -> 'a) -> 'a -> 'b t -> 'a
module Fold_Map : functor (M : Interface.MONOID) -> sig
val fold_map : ('a -> M.t) -> 'a t -> M.t
end
module Fold_Map_Any : functor (M : Interface.MONOID_ANY) -> sig
val fold_map : ('a -> 'b M.t) -> 'a t -> 'b M.t
end
module Fold_Map_Plus : functor (P : Interface.PLUS) -> sig
val fold_map : ('a -> 'b P.t) -> 'a t -> 'b P.t
end
end
module Unfoldable : sig
type 'a t = 'a array
val unfold : ('a -> ('a * 'a) option) -> 'a -> 'a t
end
module Traversable : TRAVERSABLE_F
module Eq : EQ_F
module Ord : ORD_F
module Show : SHOW_F
module Invariant : sig
type 'a t = 'a array
val imap : ('a -> 'b) -> ('b -> 'a) -> 'a t -> 'b t
end
module Extend : sig
type 'a t = 'a array
val map : ('a -> 'b) -> 'a t -> 'b t
val extend : ('a t -> 'b) -> 'a t -> 'b t
end
module Infix : sig
val ( <$> ) : ('a -> 'b) -> 'a Monad.t -> 'b Monad.t
val ( <@> ) : 'a Monad.t -> ('a -> 'b) -> 'b Monad.t
val ( <*> ) : ('a -> 'b) Monad.t -> 'a Monad.t -> 'b Monad.t
val ( >>= ) : 'a Monad.t -> ('a -> 'b Monad.t) -> 'b Monad.t
val ( =<< ) : ('a -> 'b Monad.t) -> 'a Monad.t -> 'b Monad.t
val ( >=> ) : ('a -> 'b Monad.t) -> ('b -> 'c Monad.t) -> 'a -> 'c Monad.t
val ( <=< ) : ('a -> 'b Monad.t) -> ('c -> 'a Monad.t) -> 'c -> 'b Monad.t
val ( <<= ) : ('a Extend.t -> 'b) -> 'a Extend.t -> 'b Extend.t
val ( =>> ) : 'a Extend.t -> ('a Extend.t -> 'b) -> 'b Extend.t
end
end
module Make (A : IMPL) : ARRAY = struct
let zip_with =
(fun f xs ys ->
let l =
match A.length xs < A.length ys with
| true -> A.length xs
| false -> A.length ys
and index = ref 0
and result = ref None in
for i = 0 to l - 1 do
let value = f (ArrayLabels.get xs i) (ArrayLabels.get ys i) in
(match !result with
| Some arr -> ArrayLabels.set arr !index value
| None -> result := Some (A.make l value));
index := !index + 1
done;
match !result with
| Some array -> array
| None -> [||]
: ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array)
let zip = (fun xs ys -> zip_with (fun a b -> a, b) xs ys : 'a array -> 'b array -> 'c array)
module type EQ_F = functor (E : EQ) -> EQ with type t = E.t array
module type ORD_F = functor (O : ORD) -> ORD with type t = O.t array
module type SHOW_F = functor (S : SHOW) -> SHOW with type t = S.t array
module type TRAVERSABLE_F = functor (A : APPLICATIVE) ->
TRAVERSABLE with type 'a t = 'a array and type 'a applicative_t = 'a A.t
module Functor : FUNCTOR with type 'a t = 'a array = struct
type 'a t = 'a array
let map = A.map
end
module Alt : ALT with type 'a t = 'a array = struct
include Functor
let alt = A.append
end
module Apply : APPLY with type 'a t = 'a array = struct
include Functor
let apply fn_array a = A.fold_left (fun acc f -> Alt.alt acc (map f a)) [||] fn_array
end
module Applicative : APPLICATIVE with type 'a t = 'a array = struct
include Apply
let pure a = [|a|]
end
module Monad : MONAD with type 'a t = 'a array = struct
include Applicative
let flat_map x f = A.fold_left (fun acc a -> Alt.alt acc (f a)) [||] x
end
module Foldable : FOLDABLE with type 'a t = 'a array = struct
type 'a t = 'a array
let fold_left = A.fold_left
and fold_right f init = ArrayLabels.fold_right ~f ~init
module Fold_Map (M : MONOID) = struct
module D =
Default.Fold_Map
(M)
(struct
type 'a t = 'a array
let fold_left, fold_right = fold_left, fold_right
end)
let fold_map = D.fold_map_default_left
end
module Fold_Map_Any (M : MONOID_ANY) = struct
module D =
Default.Fold_Map_Any
(M)
(struct
type 'a t = 'a array
let fold_left, fold_right = fold_left, fold_right
end)
let fold_map = D.fold_map_default_left
end
module Fold_Map_Plus (P : PLUS) = struct
module D =
Default.Fold_Map_Plus
(P)
(struct
type 'a t = 'a array
let fold_left, fold_right = fold_left, fold_right
end)
let fold_map = D.fold_map_default_left
end
end
module Unfoldable : UNFOLDABLE with type 'a t = 'a array = struct
type 'a t = 'a array
let rec unfold f init =
match f init with
| Some (a, next) -> Alt.alt [|a|] (unfold f next)
| None -> [||]
end
module Traversable : TRAVERSABLE_F =
functor
(A : APPLICATIVE)
->
struct
type 'a t = 'a array
and 'a applicative_t = 'a A.t
include (Functor : FUNCTOR with type 'a t := 'a t)
include (Foldable : FOLDABLE with type 'a t := 'a t)
module I = Infix.Apply (A)
let traverse f =
let open I in
ArrayLabels.fold_right
~f:(fun acc x -> A.pure (fun x y -> Alt.alt [|x|] y) <*> f acc <*> x)
~init:(A.pure [||])
module D = Default.Sequence (struct
type 'a t = 'a array
and 'a applicative_t = 'a A.t
let traverse = traverse
end)
let sequence = D.sequence_default
end
module Eq : EQ_F =
functor
(E : EQ)
->
struct
type t = E.t array
let eq xs ys = A.length xs = A.length ys && A.every (fun (a, b) -> E.eq a b) (zip xs ys)
end
module Ord : ORD_F =
functor
(O : ORD)
->
struct
include Eq (O)
let compare xs ys =
match xs, ys with
| _ when A.length xs = A.length ys ->
let index = ref 0 in
A.fold_left
(fun acc e ->
let result =
match acc <> `equal_to with
| true -> acc
| false -> O.compare e (ArrayLabels.get ys !index)
in
index := !index + 1;
result)
`equal_to
xs
| _ when A.length xs < A.length ys -> `less_than
| _ -> `greater_than
end
module Show : SHOW_F =
functor
(S : SHOW)
->
struct
module F = Functions.Foldable (Foldable)
module M = F.Monoid (String.Monoid)
type t = S.t array
let show xs = "[" ^ M.intercalate ~separator:", " (Functor.map S.show xs) ^ "]"
end
module Invariant : INVARIANT with type 'a t = 'a array = struct
type 'a t = 'a array
let imap f _ = Functor.map f
end
module Extend : EXTEND with type 'a t = 'a array = struct
include Functor
let extend f xs = A.mapi (fun _ i -> f (A.slice xs ~start:i ~end_:(A.length xs))) xs
end
module Infix = struct
include Infix.Monad (Monad)
include Infix.Extend (Extend)
end
end
|
|
c162d3718a31a117b52e01a9bb0408e3ee3e06fd8742f1e2b3f7afdf0ada0edf | facebookarchive/duckling_old | measure.clj | (
;; Distance
; latent distance
"number as distance"
(dim :number)
{:dim :distance
:latent true
:value (:value %1)}
"<latent dist> km"
[(dim :distance) #"(?i)k(ilo)?m?(eter)?s?"]
(-> %1
(dissoc :latent)
(merge {:unit "kilometre"
:normalized {:value (* 1000 (-> %1 :value))
:unit "metre"}}))
"<dist> meters"
[(dim :distance) #"(?i)m(eter)?"]
(-> %1
(dissoc :latent)
(merge {:unit "metre"}))
"<dist> centimeters"
[(dim :distance) #"(?i)(c(enti)?m(eter)?s?)"]
(-> %1
(dissoc :latent)
(merge {:unit "centimetre"
:normalized {:value (* 0.01 (-> %1 :value))
:unit "metre"}}))
"<dist> miles"
[(dim :distance) #"(?i)mijl?"]
(-> %1
(dissoc :latent)
(merge {:unit "mile"
:normalized {:value (* 1609 (-> %1 :value))
:unit "metre"}}))
;; volume
; latent volume
"number as volume"
(dim :number)
{:dim :volume
:latent true
:value (:value %1)}
"<latent vol> ml"
[(dim :volume) #"(?i)m(ili)?l(iter)?"]
(-> %1
(dissoc :latent)
(merge {:unit "millilitre"
:normalized {:value (* 0.001 (-> %1 :value))
:unit "litre"}}))
"<vol> hectoliters"
[(dim :volume) #"(?i)hectoliter?"]
(-> %1
(dissoc :latent)
(merge {:unit "hectolitre"
:normalized {:value (* 100 (-> %1 :value))
:unit "litre"}}))
"<vol> liters"
[(dim :volume) #"(?i)l(iter)?"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"}))
"half liter"
[#"(?i)halve liter?"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"
:value 0.5}))
"<latent vol> gallon"
[(dim :volume) #"(?i)gallon?"]
(-> %1
(dissoc :latent)
(merge {:unit "gallon"
:normalized {:value (* 3.785 (-> %1 :value))
:unit "litre"}}))
;; Quantity
three teaspoons
"<number> <units>"
[(dim :number) (dim :leven-unit)]
{:dim :quantity
:value (:value %1)
:unit (:value %2)
:form :no-product}
; a pound
"a <unit>"
[#"(?i)an?" (dim :leven-unit)]
{:dim :quantity
:value 1
:unit (:value %2)
:form :no-product}
3 pounds of flour
"<quantity> of product"
[(dim :quantity #(= :no-product (:form %))) #"(?i)de" (dim :leven-product)]
(-> %1
(assoc :product (:value %3))
(dissoc :form))
2 apples
"<number> product"
[(dim :number) (dim :leven-product)]
{:dim :quantity
:value (:value %1)
:product (:value %2)}
; an apple
"a <product>"
[#"(?i)une?" (dim :leven-product)]
{:dim :quantity
:value 1
:product (:value %2)}
for corpus
"tasse"
#"tasses?"
{:dim :leven-unit :value "tasse"}
"café"
#"caf[eé]"
{:dim :leven-product :value "café"}
"cuillere a soupe"
#"cuill?[eè]res? à soupe?"
{:dim :leven-unit :value "cuillère à soupe"}
"sucre"
#"sucre"
{:dim :leven-product :value "sucre"}
)
| null | https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/nl/rules/measure.clj | clojure | Distance
latent distance
volume
latent volume
Quantity
a pound
an apple | (
"number as distance"
(dim :number)
{:dim :distance
:latent true
:value (:value %1)}
"<latent dist> km"
[(dim :distance) #"(?i)k(ilo)?m?(eter)?s?"]
(-> %1
(dissoc :latent)
(merge {:unit "kilometre"
:normalized {:value (* 1000 (-> %1 :value))
:unit "metre"}}))
"<dist> meters"
[(dim :distance) #"(?i)m(eter)?"]
(-> %1
(dissoc :latent)
(merge {:unit "metre"}))
"<dist> centimeters"
[(dim :distance) #"(?i)(c(enti)?m(eter)?s?)"]
(-> %1
(dissoc :latent)
(merge {:unit "centimetre"
:normalized {:value (* 0.01 (-> %1 :value))
:unit "metre"}}))
"<dist> miles"
[(dim :distance) #"(?i)mijl?"]
(-> %1
(dissoc :latent)
(merge {:unit "mile"
:normalized {:value (* 1609 (-> %1 :value))
:unit "metre"}}))
"number as volume"
(dim :number)
{:dim :volume
:latent true
:value (:value %1)}
"<latent vol> ml"
[(dim :volume) #"(?i)m(ili)?l(iter)?"]
(-> %1
(dissoc :latent)
(merge {:unit "millilitre"
:normalized {:value (* 0.001 (-> %1 :value))
:unit "litre"}}))
"<vol> hectoliters"
[(dim :volume) #"(?i)hectoliter?"]
(-> %1
(dissoc :latent)
(merge {:unit "hectolitre"
:normalized {:value (* 100 (-> %1 :value))
:unit "litre"}}))
"<vol> liters"
[(dim :volume) #"(?i)l(iter)?"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"}))
"half liter"
[#"(?i)halve liter?"]
(-> %1
(dissoc :latent)
(merge {:unit "litre"
:value 0.5}))
"<latent vol> gallon"
[(dim :volume) #"(?i)gallon?"]
(-> %1
(dissoc :latent)
(merge {:unit "gallon"
:normalized {:value (* 3.785 (-> %1 :value))
:unit "litre"}}))
three teaspoons
"<number> <units>"
[(dim :number) (dim :leven-unit)]
{:dim :quantity
:value (:value %1)
:unit (:value %2)
:form :no-product}
"a <unit>"
[#"(?i)an?" (dim :leven-unit)]
{:dim :quantity
:value 1
:unit (:value %2)
:form :no-product}
3 pounds of flour
"<quantity> of product"
[(dim :quantity #(= :no-product (:form %))) #"(?i)de" (dim :leven-product)]
(-> %1
(assoc :product (:value %3))
(dissoc :form))
2 apples
"<number> product"
[(dim :number) (dim :leven-product)]
{:dim :quantity
:value (:value %1)
:product (:value %2)}
"a <product>"
[#"(?i)une?" (dim :leven-product)]
{:dim :quantity
:value 1
:product (:value %2)}
for corpus
"tasse"
#"tasses?"
{:dim :leven-unit :value "tasse"}
"café"
#"caf[eé]"
{:dim :leven-product :value "café"}
"cuillere a soupe"
#"cuill?[eè]res? à soupe?"
{:dim :leven-unit :value "cuillère à soupe"}
"sucre"
#"sucre"
{:dim :leven-product :value "sucre"}
)
|
7c4c7801a5312864d3f7c5b6286c59d6cfba8239993f562277c9643629a031dd | GaloisInc/mistral | OptParser.hs | module OptParser where
import Data.Monoid ( Monoid(..) )
import System.Console.GetOpt ( OptDescr, usageInfo )
data Parser opt = Success (opt -> opt)
| Err [String]
instance Monoid (Parser opt) where
mempty = Success id
Success f `mappend` Success g = Success (f . g)
Err ls `mappend` Err rs = Err (ls ++ rs)
l@Err{} `mappend` _ = l
_ `mappend` r@Err{} = r
success :: (opt -> opt) -> Parser opt
success = Success
failure :: String -> Parser opt
failure msg = Err [msg]
usage :: [String] -> String -> [OptDescr a] -> String
usage msgs prog = usageInfo
$ unlines (msgs ++ ["Usage: " ++ prog ++ " [OPTIONS] {file}*"])
| null | https://raw.githubusercontent.com/GaloisInc/mistral/3464ab332d73c608e64512e822fe2b8a619ec8f3/mistral/OptParser.hs | haskell | module OptParser where
import Data.Monoid ( Monoid(..) )
import System.Console.GetOpt ( OptDescr, usageInfo )
data Parser opt = Success (opt -> opt)
| Err [String]
instance Monoid (Parser opt) where
mempty = Success id
Success f `mappend` Success g = Success (f . g)
Err ls `mappend` Err rs = Err (ls ++ rs)
l@Err{} `mappend` _ = l
_ `mappend` r@Err{} = r
success :: (opt -> opt) -> Parser opt
success = Success
failure :: String -> Parser opt
failure msg = Err [msg]
usage :: [String] -> String -> [OptDescr a] -> String
usage msgs prog = usageInfo
$ unlines (msgs ++ ["Usage: " ++ prog ++ " [OPTIONS] {file}*"])
|
|
df58bda1ec8e4d7a426298d96725b290bb32ed3d8f82a431cad1a8dbc98ebfd1 | erlang/sourcer | erlang_ls_sup.erl | %%%-------------------------------------------------------------------
@doc erlang_ls top level supervisor .
%% @end
%%%-------------------------------------------------------------------
-module(erlang_ls_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%====================================================================
%% API functions
%%====================================================================
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
{ok, { {one_for_all, 0, 1}, []} }.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/erlang/sourcer/27ea9c63998b9e694eb7b654dd05b831b989e69e/apps/erlang_ls/src/erlang_ls_sup.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
API
Supervisor callbacks
====================================================================
API functions
====================================================================
====================================================================
Supervisor callbacks
====================================================================
====================================================================
==================================================================== | @doc erlang_ls top level supervisor .
-module(erlang_ls_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
{ok, { {one_for_all, 0, 1}, []} }.
Internal functions
|
e598dba35f8438c13c4bbdf59dd0d77bc3f2b22d3a2836fd5e7923ee41352b57 | gerritjvv/kafka-fast | project.clj | (defproject kafka-clj "4.0.3"
:description "fast kafka library implemented in clojure"
:url "-fast"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:javac-options ["-target" "1.8" "-source" "1.8" "-Xlint:-options"]
:global-vars {*warn-on-reflection* true
*assert* true}
:scm {:name "git"
:url "-fast.git"}
:java-source-paths ["java"]
:profiles {:test {:jvm-opts ["-Xmx1g" "-server"
------- Properties for authentication
;"-Dsun.security.krb5.debug=true"
" -Djava.security.debug = gssloginconfig , configfile , configparser , "
" -Djava.security.auth.login.config=/vagrant / vagrant / config / kafka_client_jaas.conf "
;"-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf"
]}
:uberjar {:aot :all}
:repl {:jvm-opts [
"-Xmx512m"
"-Dsun.security.krb5.debug=true"
"-Djava.security.debug=gssloginconfig,configfile,configparser,logincontext"
"-Djava.security.auth.login.config=/vagrant/vagrant/config/kafka_client_jaas.conf"
"-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf"
]}
:vagrant-digital {
:jvm-opts [
;"-Dcom.sun.management.jmxremote.port=8855"
"-Dcom.sun.management.jmxremote.authenticate=false"
"-Dcom.sun.management.jmxremote.ssl=false"
"-server" "-Xms8g" "-Xmx8g"]
:main kafka-clj.app
}
}
:main kafka-clj.app
:plugins [[lein-midje "3.2.1"]
[lein-kibit "0.0.8"]]
:test-paths ["test" "test-java"]
:dependencies [
[tcp-driver "0.1.2-SNAPSHOT"]
[com.taoensso/carmine "2.15.0" :exclusions [org.clojure/clojure]]
[org.redisson/redisson "3.2.2" :exclusions [io.netty/netty-buffer]]
[com.alexkasko.unsafe/unsafe-tools "1.4.4"]
[criterium "0.4.4" :scope "test"]
[prismatic/schema "1.1.3"]
[org.mapdb/mapdb "1.0.9"]
[org.xerial.snappy/snappy-java "1.1.2.4"]
[net.jpountz.lz4/lz4 "1.3.0"]
[org.clojure/tools.logging "0.3.1"]
[fun-utils "0.6.1" :exclusions [org.clojure/tools.logging]]
[clj-tuple "0.2.2"]
[io.netty/netty-buffer "4.1.6.Final"]
[io.netty/netty-common "4.1.6.Final"]
[com.codahale.metrics/metrics-core "3.0.2"]
[org.clojure/core.async "0.2.374"
:exclusions [org.clojure/tools.reader]]
[com.stuartsierra/component "0.3.2"]
[org.openjdk.jol/jol-core "0.5"]
[org.clojure/clojure "1.8.0" :scope "provided"]
[org.clojure/test.check "0.9.0" :scope "test"]
[midje "1.8.3" :scope "test"
:exclusions [potemkin
riddley]]
[org.clojars.runa/conjure "2.2.0" :scope "test"]
[org.apache.zookeeper/zookeeper "3.4.8" :scope "test"
:exclusions [io.netty/netty]]
[org.apache.kafka/kafka_2.10 "0.10.1.0" :scope "test"
:exclusions [io.netty/netty
log4j
org.slf4j/slf4j-api
org.slf4j/slf4j-log4j12]]
[com.github.kstyrc/embedded-redis "0.6" :scope "test"]])
| null | https://raw.githubusercontent.com/gerritjvv/kafka-fast/fd149d8744c8100b2a8f4d09f1a251812e7baf6a/kafka-clj/project.clj | clojure | "-Dsun.security.krb5.debug=true"
"-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf"
"-Dcom.sun.management.jmxremote.port=8855" | (defproject kafka-clj "4.0.3"
:description "fast kafka library implemented in clojure"
:url "-fast"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:javac-options ["-target" "1.8" "-source" "1.8" "-Xlint:-options"]
:global-vars {*warn-on-reflection* true
*assert* true}
:scm {:name "git"
:url "-fast.git"}
:java-source-paths ["java"]
:profiles {:test {:jvm-opts ["-Xmx1g" "-server"
------- Properties for authentication
" -Djava.security.debug = gssloginconfig , configfile , configparser , "
" -Djava.security.auth.login.config=/vagrant / vagrant / config / kafka_client_jaas.conf "
]}
:uberjar {:aot :all}
:repl {:jvm-opts [
"-Xmx512m"
"-Dsun.security.krb5.debug=true"
"-Djava.security.debug=gssloginconfig,configfile,configparser,logincontext"
"-Djava.security.auth.login.config=/vagrant/vagrant/config/kafka_client_jaas.conf"
"-Djava.security.krb5.conf=/vagrant/vagrant/config/krb5.conf"
]}
:vagrant-digital {
:jvm-opts [
"-Dcom.sun.management.jmxremote.authenticate=false"
"-Dcom.sun.management.jmxremote.ssl=false"
"-server" "-Xms8g" "-Xmx8g"]
:main kafka-clj.app
}
}
:main kafka-clj.app
:plugins [[lein-midje "3.2.1"]
[lein-kibit "0.0.8"]]
:test-paths ["test" "test-java"]
:dependencies [
[tcp-driver "0.1.2-SNAPSHOT"]
[com.taoensso/carmine "2.15.0" :exclusions [org.clojure/clojure]]
[org.redisson/redisson "3.2.2" :exclusions [io.netty/netty-buffer]]
[com.alexkasko.unsafe/unsafe-tools "1.4.4"]
[criterium "0.4.4" :scope "test"]
[prismatic/schema "1.1.3"]
[org.mapdb/mapdb "1.0.9"]
[org.xerial.snappy/snappy-java "1.1.2.4"]
[net.jpountz.lz4/lz4 "1.3.0"]
[org.clojure/tools.logging "0.3.1"]
[fun-utils "0.6.1" :exclusions [org.clojure/tools.logging]]
[clj-tuple "0.2.2"]
[io.netty/netty-buffer "4.1.6.Final"]
[io.netty/netty-common "4.1.6.Final"]
[com.codahale.metrics/metrics-core "3.0.2"]
[org.clojure/core.async "0.2.374"
:exclusions [org.clojure/tools.reader]]
[com.stuartsierra/component "0.3.2"]
[org.openjdk.jol/jol-core "0.5"]
[org.clojure/clojure "1.8.0" :scope "provided"]
[org.clojure/test.check "0.9.0" :scope "test"]
[midje "1.8.3" :scope "test"
:exclusions [potemkin
riddley]]
[org.clojars.runa/conjure "2.2.0" :scope "test"]
[org.apache.zookeeper/zookeeper "3.4.8" :scope "test"
:exclusions [io.netty/netty]]
[org.apache.kafka/kafka_2.10 "0.10.1.0" :scope "test"
:exclusions [io.netty/netty
log4j
org.slf4j/slf4j-api
org.slf4j/slf4j-log4j12]]
[com.github.kstyrc/embedded-redis "0.6" :scope "test"]])
|
5ce313b2904831a5f3a507814be485a79e0bab83c34b78b6d981caf40ca98fc3 | CryptoKami/cryptokami-core | Launcher.hs | -- | High-level code capable of running various scenarios in various modes.
# OPTIONS_GHC -F -pgmF autoexporter #
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/lib/src/Pos/Launcher.hs | haskell | | High-level code capable of running various scenarios in various modes. |
# OPTIONS_GHC -F -pgmF autoexporter #
|
e1cd89cbf33130dabca04a179bda41c866c543ba84dfed7c9311d3ff36d3f7ff | stchang/macrotypes | dep-ind-cur2-nat+datum-tests.rkt | #lang s-exp turnstile/examples/dep/dep-ind-cur2
(require turnstile/examples/dep/dep-ind-cur2+nat+datum
turnstile/examples/dep/dep-ind-cur2+eq2
turnstile/examples/dep/dep-ind-cur2+sugar)
(require "../rackunit-typechecking.rkt")
Π → λ ∀ ≻
same as dep - ind - cur2 - nat tests , except uses new # % datum
;; Peano nums -----------------------------------------------------------------
(check-type 0 : Nat)
(check-type 0 : (→ Nat)) ;; TODO: make this err?
(check-type 0 : Nat -> 0)
(check-type 1 : Nat)
(check-type 1 : Nat -> 1)
(check-type 2 : Nat -> 2)
(define nat-rec
(λ [C : *]
(λ [zc : C][sc : (→ C C)]
(λ [n : Nat]
(elim-Nat n
(λ [x : Nat] C)
zc
(λ [x : Nat] sc))))))
;; (→ C) same as C
(check-type nat-rec : (∀ C (→ (→ C) (→ C C) (→ Nat C))))
(check-type nat-rec : (∀ C (→ C (→ C C) (→ Nat C))))
;; nat-rec with no annotations
(check-type
(λ C
(λ zc sc
(λ n
(elim-Nat n
(λ x C)
zc
(λ x sc)))))
: (∀ C (→ C (→ C C) (→ Nat C))))
;; (λ zc) same as zc
(check-type
(λ C
(λ zc sc
(λ n
(elim-Nat n
(λ x C)
(λ zc)
(λ x sc)))))
: (∀ C (→ C (→ C C) (→ Nat C))))
(check-type (nat-rec Nat) : (→ (→ Nat) (→ Nat Nat) (→ Nat Nat)))
(check-type (nat-rec Nat) : (→ Nat (→ Nat Nat) (→ Nat Nat)))
(check-type ((nat-rec Nat) 0 (λ [n : Nat] (S n))) : (→ Nat Nat))
(check-type (nat-rec Nat 0 (λ [n : Nat] (S n))) : (→ Nat Nat))
;; basic identity example, to test eval
(define id (nat-rec Nat 0 (λ [n : Nat] (S n))))
(check-type (id 0) : Nat -> 0)
;; this example will err if eval tries to tycheck again
(check-type (id 1) : Nat)
(check-type (id 1) : Nat -> 1)
(define plus
(λ [n : Nat]
(((nat-rec (→ Nat Nat))
(λ [m : Nat] m)
(λ [pm : (→ Nat Nat)]
(λ [x : Nat]
(S (pm x)))))
n)))
(check-type plus : (→ Nat (→ Nat Nat)))
;; plus with less parens
(check-type
(λ [n : Nat]
(nat-rec (→ Nat Nat)
(λ [m : Nat] m)
(λ [pm : (→ Nat Nat)] [x : Nat] (S (pm x)))
n))
: (→ Nat Nat Nat))
;; plus, no annotations, no auto curry
(check-type
(λ n1 n2
((((nat-rec (→ Nat Nat))
(λ m m)
(λ pm (λ x (S (pm x)))))
n1)
n2))
: (→ Nat Nat Nat))
;; plus, no annotations, less parens
(check-type
(λ n1 n2
(nat-rec (→ Nat Nat)
(λ m m)
(λ pm x (S (pm x)))
n1
n2))
: (→ Nat Nat Nat))
(check-type (plus 0 0) : Nat -> 0)
(check-type (plus 1 1) : Nat -> 2)
(check-type (plus 1 0) : Nat -> 1)
(check-type (plus 0 1) : Nat -> 1)
(check-type (plus 0) : (→ Nat Nat))
(check-type ((plus 0) 0) : Nat -> 0)
(check-type ((plus 0) 1) : Nat -> 1)
(check-type ((plus 1) 0) : Nat -> 1)
(check-type ((plus 1) 1) : Nat -> 2)
(check-type ((plus 2) 1) : Nat -> 3)
(check-type ((plus 1) 2) : Nat -> 3)
(check-type (plus 2 1) : Nat -> 3)
(check-type (plus 1 2) : Nat -> 3)
;; plus zero (left)
(check-type (λ [n : Nat] (eq-refl Nat n))
: (Π [n : Nat] (= Nat (plus 0 n) n)))
;; plus zero (right)
(check-type
(λ [n : Nat]
(elim-Nat n
(λ [m : Nat] (= Nat (plus m 0) m))
(eq-refl Nat 0)
(λ [k : Nat]
(λ [p : (= Nat (plus k 0) k)]
(eq-elim (plus k 0)
(λ [W : Nat] (= Nat (S (plus k 0)) (S W)))
(eq-refl Nat (S (plus k 0)))
k
p)))))
: (Π [n : Nat] (= Nat (plus n 0) n)))
plus zero identity , no annotations
;; left:
(check-type (λ n (eq-refl Nat n))
: (Π [n : Nat] (= Nat (plus 0 n) n)))
;; right:
(check-type
(λ n
(elim-Nat n
(λ m (= Nat (plus m 0) m))
(eq-refl Nat 0)
(λ k p
(eq-elim (plus k 0)
(λ W (= Nat (S (plus k 0)) (S W)))
(eq-refl Nat (S (plus k 0)))
k
p))))
: (Π [n : Nat] (= Nat (plus n 0) n)))
;; test currying
(check-type
(λ [A : Type] (λ [x : A] x))
: (Π [B : Type] (Π [y : B] B)))
(check-type
(λ [A : Type] (λ [x : A] x))
: (Π [B : Type][y : B] B))
(check-type
(λ [A : Type][x : A] x)
: (Π [B : Type] (Π [y : B] B)))
(check-type
(λ [A : Type][x : A] x)
: (Π [B : Type][y : B] B))
this works now ( broken in dep - ind - fixed bc multi - param lambdas were nt let * )
(check-type ((λ [A : Type][x : A] x) Nat 0) : Nat -> 0)
(check-type
(((λ [A : Type][x : A] x) Nat) 0)
: Nat -> 0)
(check-type
((λ [A : Type][x : A] x) Nat 0)
: Nat -> 0)
(check-type
(plus
(((λ [A : Type][x : A] x) Nat) 0)
(((λ [A : Type][x : A] x) Nat) 0))
: Nat -> 0)
;; same as previous, less parens
(check-type
(plus
((λ [A : Type][x : A] x) Nat 0)
((λ [A : Type][x : A] x) Nat 0))
: Nat -> 0)
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-test/tests/turnstile/dep/dep-ind-cur2-nat%2Bdatum-tests.rkt | racket | Peano nums -----------------------------------------------------------------
TODO: make this err?
(→ C) same as C
nat-rec with no annotations
(λ zc) same as zc
basic identity example, to test eval
this example will err if eval tries to tycheck again
plus with less parens
plus, no annotations, no auto curry
plus, no annotations, less parens
plus zero (left)
plus zero (right)
left:
right:
test currying
same as previous, less parens | #lang s-exp turnstile/examples/dep/dep-ind-cur2
(require turnstile/examples/dep/dep-ind-cur2+nat+datum
turnstile/examples/dep/dep-ind-cur2+eq2
turnstile/examples/dep/dep-ind-cur2+sugar)
(require "../rackunit-typechecking.rkt")
Π → λ ∀ ≻
same as dep - ind - cur2 - nat tests , except uses new # % datum
(check-type 0 : Nat)
(check-type 0 : Nat -> 0)
(check-type 1 : Nat)
(check-type 1 : Nat -> 1)
(check-type 2 : Nat -> 2)
(define nat-rec
(λ [C : *]
(λ [zc : C][sc : (→ C C)]
(λ [n : Nat]
(elim-Nat n
(λ [x : Nat] C)
zc
(λ [x : Nat] sc))))))
(check-type nat-rec : (∀ C (→ (→ C) (→ C C) (→ Nat C))))
(check-type nat-rec : (∀ C (→ C (→ C C) (→ Nat C))))
(check-type
(λ C
(λ zc sc
(λ n
(elim-Nat n
(λ x C)
zc
(λ x sc)))))
: (∀ C (→ C (→ C C) (→ Nat C))))
(check-type
(λ C
(λ zc sc
(λ n
(elim-Nat n
(λ x C)
(λ zc)
(λ x sc)))))
: (∀ C (→ C (→ C C) (→ Nat C))))
(check-type (nat-rec Nat) : (→ (→ Nat) (→ Nat Nat) (→ Nat Nat)))
(check-type (nat-rec Nat) : (→ Nat (→ Nat Nat) (→ Nat Nat)))
(check-type ((nat-rec Nat) 0 (λ [n : Nat] (S n))) : (→ Nat Nat))
(check-type (nat-rec Nat 0 (λ [n : Nat] (S n))) : (→ Nat Nat))
(define id (nat-rec Nat 0 (λ [n : Nat] (S n))))
(check-type (id 0) : Nat -> 0)
(check-type (id 1) : Nat)
(check-type (id 1) : Nat -> 1)
(define plus
(λ [n : Nat]
(((nat-rec (→ Nat Nat))
(λ [m : Nat] m)
(λ [pm : (→ Nat Nat)]
(λ [x : Nat]
(S (pm x)))))
n)))
(check-type plus : (→ Nat (→ Nat Nat)))
(check-type
(λ [n : Nat]
(nat-rec (→ Nat Nat)
(λ [m : Nat] m)
(λ [pm : (→ Nat Nat)] [x : Nat] (S (pm x)))
n))
: (→ Nat Nat Nat))
(check-type
(λ n1 n2
((((nat-rec (→ Nat Nat))
(λ m m)
(λ pm (λ x (S (pm x)))))
n1)
n2))
: (→ Nat Nat Nat))
(check-type
(λ n1 n2
(nat-rec (→ Nat Nat)
(λ m m)
(λ pm x (S (pm x)))
n1
n2))
: (→ Nat Nat Nat))
(check-type (plus 0 0) : Nat -> 0)
(check-type (plus 1 1) : Nat -> 2)
(check-type (plus 1 0) : Nat -> 1)
(check-type (plus 0 1) : Nat -> 1)
(check-type (plus 0) : (→ Nat Nat))
(check-type ((plus 0) 0) : Nat -> 0)
(check-type ((plus 0) 1) : Nat -> 1)
(check-type ((plus 1) 0) : Nat -> 1)
(check-type ((plus 1) 1) : Nat -> 2)
(check-type ((plus 2) 1) : Nat -> 3)
(check-type ((plus 1) 2) : Nat -> 3)
(check-type (plus 2 1) : Nat -> 3)
(check-type (plus 1 2) : Nat -> 3)
(check-type (λ [n : Nat] (eq-refl Nat n))
: (Π [n : Nat] (= Nat (plus 0 n) n)))
(check-type
(λ [n : Nat]
(elim-Nat n
(λ [m : Nat] (= Nat (plus m 0) m))
(eq-refl Nat 0)
(λ [k : Nat]
(λ [p : (= Nat (plus k 0) k)]
(eq-elim (plus k 0)
(λ [W : Nat] (= Nat (S (plus k 0)) (S W)))
(eq-refl Nat (S (plus k 0)))
k
p)))))
: (Π [n : Nat] (= Nat (plus n 0) n)))
plus zero identity , no annotations
(check-type (λ n (eq-refl Nat n))
: (Π [n : Nat] (= Nat (plus 0 n) n)))
(check-type
(λ n
(elim-Nat n
(λ m (= Nat (plus m 0) m))
(eq-refl Nat 0)
(λ k p
(eq-elim (plus k 0)
(λ W (= Nat (S (plus k 0)) (S W)))
(eq-refl Nat (S (plus k 0)))
k
p))))
: (Π [n : Nat] (= Nat (plus n 0) n)))
(check-type
(λ [A : Type] (λ [x : A] x))
: (Π [B : Type] (Π [y : B] B)))
(check-type
(λ [A : Type] (λ [x : A] x))
: (Π [B : Type][y : B] B))
(check-type
(λ [A : Type][x : A] x)
: (Π [B : Type] (Π [y : B] B)))
(check-type
(λ [A : Type][x : A] x)
: (Π [B : Type][y : B] B))
this works now ( broken in dep - ind - fixed bc multi - param lambdas were nt let * )
(check-type ((λ [A : Type][x : A] x) Nat 0) : Nat -> 0)
(check-type
(((λ [A : Type][x : A] x) Nat) 0)
: Nat -> 0)
(check-type
((λ [A : Type][x : A] x) Nat 0)
: Nat -> 0)
(check-type
(plus
(((λ [A : Type][x : A] x) Nat) 0)
(((λ [A : Type][x : A] x) Nat) 0))
: Nat -> 0)
(check-type
(plus
((λ [A : Type][x : A] x) Nat 0)
((λ [A : Type][x : A] x) Nat 0))
: Nat -> 0)
|
db0c87f28484faa63aa5a89c4e9a323ee9f1ea4e542a59a596c9c3ae57633721 | mzp/coq-ruby | gmap.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : gmap.mli 10250 2007 - 10 - 23 15:02:23Z aspiwack $ i
Maps using the generic comparison function of ocaml . Same interface as
the module [ Map ] from the ocaml standard library .
the module [Map] from the ocaml standard library. *)
type ('a,'b) t
val empty : ('a,'b) t
val is_empty : ('a,'b) t -> bool
val add : 'a -> 'b -> ('a,'b) t -> ('a,'b) t
val find : 'a -> ('a,'b) t -> 'b
val remove : 'a -> ('a,'b) t -> ('a,'b) t
val mem : 'a -> ('a,'b) t -> bool
val iter : ('a -> 'b -> unit) -> ('a,'b) t -> unit
val map : ('b -> 'c) -> ('a,'b) t -> ('a,'c) t
val fold : ('a -> 'b -> 'c -> 'c) -> ('a,'b) t -> 'c -> 'c
(* Additions with respect to ocaml standard library. *)
val dom : ('a,'b) t -> 'a list
val rng : ('a,'b) t -> 'b list
val to_list : ('a,'b) t -> ('a * 'b) list
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/lib/gmap.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Additions with respect to ocaml standard library. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : gmap.mli 10250 2007 - 10 - 23 15:02:23Z aspiwack $ i
Maps using the generic comparison function of ocaml . Same interface as
the module [ Map ] from the ocaml standard library .
the module [Map] from the ocaml standard library. *)
type ('a,'b) t
val empty : ('a,'b) t
val is_empty : ('a,'b) t -> bool
val add : 'a -> 'b -> ('a,'b) t -> ('a,'b) t
val find : 'a -> ('a,'b) t -> 'b
val remove : 'a -> ('a,'b) t -> ('a,'b) t
val mem : 'a -> ('a,'b) t -> bool
val iter : ('a -> 'b -> unit) -> ('a,'b) t -> unit
val map : ('b -> 'c) -> ('a,'b) t -> ('a,'c) t
val fold : ('a -> 'b -> 'c -> 'c) -> ('a,'b) t -> 'c -> 'c
val dom : ('a,'b) t -> 'a list
val rng : ('a,'b) t -> 'b list
val to_list : ('a,'b) t -> ('a * 'b) list
|
e5145319b2f2b697dd7ab00cef597cba707fcbdc4e355a20c0129373d18b97cd | albertoruiz/easyVision | pipeline.hs | time ./pipeline ' video.avi -benchmark -loop 1 -frames 100 ' + RTS -N2
time ./pipeline ' video.avi -benchmark -loop 1 -frames 100 ' ' --levels=(1,20 ) ' + RTS -N2
import EasyVision
import Util.Options
compose = foldr (.) id
expensive k = compose (replicate k f) where
f im = resize (size im) . block . gaussS 10 $ im
block im = blockImage [[im,im],[im,im]]
balance f = compose . map (pipeline . f)
main = do
s <- getOption "--stages" =<< uncurry replicate `fmap` getOption "--levels" (20,1)
putStrLn $ "stages = " ++ show s
run $ camera ~> float . grayscale
>>= observe "original" id
~~> balance expensive s
>>= observe "result" id
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/old/tutorial/pipeline.hs | haskell | levels=(1,20 ) ' + RTS -N2 | time ./pipeline ' video.avi -benchmark -loop 1 -frames 100 ' + RTS -N2
import EasyVision
import Util.Options
compose = foldr (.) id
expensive k = compose (replicate k f) where
f im = resize (size im) . block . gaussS 10 $ im
block im = blockImage [[im,im],[im,im]]
balance f = compose . map (pipeline . f)
main = do
s <- getOption "--stages" =<< uncurry replicate `fmap` getOption "--levels" (20,1)
putStrLn $ "stages = " ++ show s
run $ camera ~> float . grayscale
>>= observe "original" id
~~> balance expensive s
>>= observe "result" id
|
ee4c0a87adcab9444cd0c808bec4114d3e2576b9fcd837de9b5249a12ea6d12a | ocaml/ocamlbuild | ocamlbuild_unix_plugin.ml | (***********************************************************************)
(* *)
(* ocamlbuild *)
(* *)
, , projet Gallium , INRIA Rocquencourt
(* *)
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
Original author :
open Format
open Ocamlbuild_pack
open My_unix
let report_error f =
function
| Unix.Unix_error(err, fun_name, arg) ->
fprintf f "%s: %S failed" Sys.argv.(0) fun_name;
if String.length arg > 0 then
fprintf f " on %S" arg;
fprintf f ": %s" (Unix.error_message err)
| exn -> raise exn
let mkstat unix_stat x =
let st =
try unix_stat x
with Unix.Unix_error _ as e -> raise (Sys_error (My_std.sbprintf "%a" report_error e))
in
{ stat_key = sprintf "(%d,%d)" st.Unix.st_dev st.Unix.st_ino;
stat_file_kind =
match st.Unix.st_kind with
| Unix.S_LNK -> FK_link
| Unix.S_DIR -> FK_dir
| Unix.S_CHR | Unix.S_BLK | Unix.S_FIFO | Unix.S_SOCK -> FK_other
| Unix.S_REG -> FK_file }
let is_link s = (Unix.lstat s).Unix.st_kind = Unix.S_LNK
let at_exit_once callback =
let pid = Unix.getpid () in
at_exit begin fun () ->
if pid = Unix.getpid () then callback ()
end
let run_and_open s kont =
let ic = Unix.open_process_in s in
let close () =
match Unix.close_process_in ic with
| Unix.WEXITED 0 -> ()
| Unix.WEXITED _ | Unix.WSIGNALED _ | Unix.WSTOPPED _ ->
failwith (Printf.sprintf "Error while running: %s" s) in
let res = try
kont ic
with e -> (close (); raise e)
in close (); res
let stdout_isatty () =
Unix.isatty Unix.stdout &&
try Unix.getenv "TERM" <> "dumb" with Not_found -> true
let execute_many =
let exit i = raise (My_std.Exit_with_code i) in
let exit = function
| Ocamlbuild_executor.Subcommand_failed -> exit Exit_codes.rc_executor_subcommand_failed
| Ocamlbuild_executor.Subcommand_got_signal -> exit Exit_codes.rc_executor_subcommand_got_signal
| Ocamlbuild_executor.Io_error -> exit Exit_codes.rc_executor_io_error
| Ocamlbuild_executor.Exceptionl_condition -> exit Exit_codes.rc_executor_excetptional_condition
in
Ocamlbuild_executor.execute ~exit
code assumes throughout that [ readlink ] will return a file name
relative to the current directory . Let 's make it so .
relative to the current directory. Let's make it so. *)
let myunixreadlink x =
let y = Unix.readlink x in
if Filename.is_relative y then
Filename.concat (Filename.dirname x) y
else
y
let setup () =
implem.is_degraded <- false;
implem.stdout_isatty <- stdout_isatty;
implem.gettimeofday <- Unix.gettimeofday;
implem.report_error <- report_error;
implem.execute_many <- execute_many;
implem.readlink <- myunixreadlink;
implem.run_and_open <- run_and_open;
implem.at_exit_once <- at_exit_once;
implem.is_link <- is_link;
implem.stat <- mkstat Unix.stat;
implem.lstat <- mkstat Unix.lstat;;
| null | https://raw.githubusercontent.com/ocaml/ocamlbuild/88784c87c014c535efec0b9ae7c1ac88b28132da/plugin-lib/ocamlbuild_unix_plugin.ml | ocaml | *********************************************************************
ocamlbuild
the special exception on linking described in file ../LICENSE.
********************************************************************* | , , projet Gallium , INRIA Rocquencourt
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
Original author :
open Format
open Ocamlbuild_pack
open My_unix
let report_error f =
function
| Unix.Unix_error(err, fun_name, arg) ->
fprintf f "%s: %S failed" Sys.argv.(0) fun_name;
if String.length arg > 0 then
fprintf f " on %S" arg;
fprintf f ": %s" (Unix.error_message err)
| exn -> raise exn
let mkstat unix_stat x =
let st =
try unix_stat x
with Unix.Unix_error _ as e -> raise (Sys_error (My_std.sbprintf "%a" report_error e))
in
{ stat_key = sprintf "(%d,%d)" st.Unix.st_dev st.Unix.st_ino;
stat_file_kind =
match st.Unix.st_kind with
| Unix.S_LNK -> FK_link
| Unix.S_DIR -> FK_dir
| Unix.S_CHR | Unix.S_BLK | Unix.S_FIFO | Unix.S_SOCK -> FK_other
| Unix.S_REG -> FK_file }
let is_link s = (Unix.lstat s).Unix.st_kind = Unix.S_LNK
let at_exit_once callback =
let pid = Unix.getpid () in
at_exit begin fun () ->
if pid = Unix.getpid () then callback ()
end
let run_and_open s kont =
let ic = Unix.open_process_in s in
let close () =
match Unix.close_process_in ic with
| Unix.WEXITED 0 -> ()
| Unix.WEXITED _ | Unix.WSIGNALED _ | Unix.WSTOPPED _ ->
failwith (Printf.sprintf "Error while running: %s" s) in
let res = try
kont ic
with e -> (close (); raise e)
in close (); res
let stdout_isatty () =
Unix.isatty Unix.stdout &&
try Unix.getenv "TERM" <> "dumb" with Not_found -> true
let execute_many =
let exit i = raise (My_std.Exit_with_code i) in
let exit = function
| Ocamlbuild_executor.Subcommand_failed -> exit Exit_codes.rc_executor_subcommand_failed
| Ocamlbuild_executor.Subcommand_got_signal -> exit Exit_codes.rc_executor_subcommand_got_signal
| Ocamlbuild_executor.Io_error -> exit Exit_codes.rc_executor_io_error
| Ocamlbuild_executor.Exceptionl_condition -> exit Exit_codes.rc_executor_excetptional_condition
in
Ocamlbuild_executor.execute ~exit
code assumes throughout that [ readlink ] will return a file name
relative to the current directory . Let 's make it so .
relative to the current directory. Let's make it so. *)
let myunixreadlink x =
let y = Unix.readlink x in
if Filename.is_relative y then
Filename.concat (Filename.dirname x) y
else
y
let setup () =
implem.is_degraded <- false;
implem.stdout_isatty <- stdout_isatty;
implem.gettimeofday <- Unix.gettimeofday;
implem.report_error <- report_error;
implem.execute_many <- execute_many;
implem.readlink <- myunixreadlink;
implem.run_and_open <- run_and_open;
implem.at_exit_once <- at_exit_once;
implem.is_link <- is_link;
implem.stat <- mkstat Unix.stat;
implem.lstat <- mkstat Unix.lstat;;
|
b93988e7ef89ab223d284497f97240b3ef77eaa45cb9eb945c5d7a586e0fecc1 | yesodweb/yesod | th.hs | # LANGUAGE TemplateHaskell , QuasiQuotes , OverloadedStrings , TupleSections , ViewPatterns #
import Yesod.Routes.TH
import Yesod.Routes.Parse
import THHelper
import Language.Haskell.TH.Syntax
import Criterion.Main
import Data.Text (words)
import Prelude hiding (words)
import Control.DeepSeq
import Yesod.Routes.TH.Simple
import Test.Hspec
import Control.Monad (forM_, unless)
$(do
let (cons, decs) = mkRouteCons $ map (fmap parseType) resources
clause1 <- mkDispatchClause settings resources
clause2 <- mkSimpleDispatchClause settings resources
return $ concat
[ [FunD (mkName "dispatch1") [clause1]]
, [FunD (mkName "dispatch2") [clause2]]
, decs
, [DataD [] (mkName "Route") [] cons [''Show, ''Eq]]
]
)
instance NFData Route where
rnf HomeR = ()
rnf FooR = ()
rnf (BarR i) = i `seq` ()
rnf BazR = ()
getHomeR :: Maybe Int
getHomeR = Just 1
getFooR :: Maybe Int
getFooR = Just 2
getBarR :: Int -> Maybe Int
getBarR i = Just (i + 3)
getBazR :: Maybe Int
getBazR = Just 4
samples = take 10000 $ cycle
[ words "foo"
, words "foo bar"
, words ""
, words "bar baz"
, words "bar 4"
, words "bar 1234566789"
, words "baz"
, words "baz 4"
, words "something else"
]
dispatch2a = dispatch2 `asTypeOf` dispatch1
main :: IO ()
main = do
forM_ samples $ \sample ->
unless (dispatch1 True (sample, "GET") == dispatch2a True (sample, "GET"))
(error $ show sample)
defaultMain
[ bench "dispatch1" $ nf (map (dispatch1 True . (, "GET"))) samples
, bench "dispatch2" $ nf (map (dispatch2a True . (, "GET"))) samples
, bench "dispatch1a" $ nf (map (dispatch1 True . (, "GET"))) samples
, bench "dispatch2a" $ nf (map (dispatch2a True . (, "GET"))) samples
]
| null | https://raw.githubusercontent.com/yesodweb/yesod/c59993ff287b880abbf768f1e3f56ae9b19df51e/yesod-core/bench/th.hs | haskell | # LANGUAGE TemplateHaskell , QuasiQuotes , OverloadedStrings , TupleSections , ViewPatterns #
import Yesod.Routes.TH
import Yesod.Routes.Parse
import THHelper
import Language.Haskell.TH.Syntax
import Criterion.Main
import Data.Text (words)
import Prelude hiding (words)
import Control.DeepSeq
import Yesod.Routes.TH.Simple
import Test.Hspec
import Control.Monad (forM_, unless)
$(do
let (cons, decs) = mkRouteCons $ map (fmap parseType) resources
clause1 <- mkDispatchClause settings resources
clause2 <- mkSimpleDispatchClause settings resources
return $ concat
[ [FunD (mkName "dispatch1") [clause1]]
, [FunD (mkName "dispatch2") [clause2]]
, decs
, [DataD [] (mkName "Route") [] cons [''Show, ''Eq]]
]
)
instance NFData Route where
rnf HomeR = ()
rnf FooR = ()
rnf (BarR i) = i `seq` ()
rnf BazR = ()
getHomeR :: Maybe Int
getHomeR = Just 1
getFooR :: Maybe Int
getFooR = Just 2
getBarR :: Int -> Maybe Int
getBarR i = Just (i + 3)
getBazR :: Maybe Int
getBazR = Just 4
samples = take 10000 $ cycle
[ words "foo"
, words "foo bar"
, words ""
, words "bar baz"
, words "bar 4"
, words "bar 1234566789"
, words "baz"
, words "baz 4"
, words "something else"
]
dispatch2a = dispatch2 `asTypeOf` dispatch1
main :: IO ()
main = do
forM_ samples $ \sample ->
unless (dispatch1 True (sample, "GET") == dispatch2a True (sample, "GET"))
(error $ show sample)
defaultMain
[ bench "dispatch1" $ nf (map (dispatch1 True . (, "GET"))) samples
, bench "dispatch2" $ nf (map (dispatch2a True . (, "GET"))) samples
, bench "dispatch1a" $ nf (map (dispatch1 True . (, "GET"))) samples
, bench "dispatch2a" $ nf (map (dispatch2a True . (, "GET"))) samples
]
|
|
863865a6d9b0f9783dfa52c2bb51236aee2143c7daf72b5b09b2e7358319d5d2 | ananthakumaran/eopl | 33.clj | ;; write a procedure mark-leaves-with-red-depth that takes a bintree
;; and produces a bintree of the same shape as the original, except
;; that in the new, each leaf contains the integer of nodes between it
;; and the root that contain the symbol red
(ns eopl.chap-1.33
(:use clojure.test)
(:use eopl.chap-1.31))
(defn mark-leaves-with-red-depth
([bintree] (mark-leaves-with-red-depth bintree 0))
([bintree count]
(if (leaf? bintree)
(leaf count)
(let [count (if (= 'red (content-of bintree)) (inc count) count)]
(interior-node (content-of bintree)
(mark-leaves-with-red-depth (lson bintree) count)
(mark-leaves-with-red-depth (rson bintree) count))))))
(deftest mark-leaves-with-red-depth-test
(is (= '(red
(bar (1) (1))
(red (2) (quux (2) (2))))
(mark-leaves-with-red-depth
(interior-node 'red
(interior-node 'bar
(leaf 26)
(leaf 12))
(interior-node 'red
(leaf 11)
(interior-node 'quux
(leaf 117)
(leaf 14))))))))
(run-tests)
| null | https://raw.githubusercontent.com/ananthakumaran/eopl/876d6c2e44865e2c89a05a683d99a289c71f1487/src/eopl/chap_1/33.clj | clojure | write a procedure mark-leaves-with-red-depth that takes a bintree
and produces a bintree of the same shape as the original, except
that in the new, each leaf contains the integer of nodes between it
and the root that contain the symbol red |
(ns eopl.chap-1.33
(:use clojure.test)
(:use eopl.chap-1.31))
(defn mark-leaves-with-red-depth
([bintree] (mark-leaves-with-red-depth bintree 0))
([bintree count]
(if (leaf? bintree)
(leaf count)
(let [count (if (= 'red (content-of bintree)) (inc count) count)]
(interior-node (content-of bintree)
(mark-leaves-with-red-depth (lson bintree) count)
(mark-leaves-with-red-depth (rson bintree) count))))))
(deftest mark-leaves-with-red-depth-test
(is (= '(red
(bar (1) (1))
(red (2) (quux (2) (2))))
(mark-leaves-with-red-depth
(interior-node 'red
(interior-node 'bar
(leaf 26)
(leaf 12))
(interior-node 'red
(leaf 11)
(interior-node 'quux
(leaf 117)
(leaf 14))))))))
(run-tests)
|
7519a806258f99802a0308f28fb8939ebc8055226845680ccc399f5b128e01e7 | LexiFi/menhir | item.mli | (******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
(* file LICENSE. *)
(* *)
(******************************************************************************)
open Grammar
(* An LR(0) item encodes a pair of integers, namely the index of the
production and the index of the bullet in the production's
right-hand side. *)
type t
val import: Production.index * int -> t
val export: t -> Production.index * int
(* An item can be encoded as an integer. This is used in the table
back-end only. The decoding function (really a copy of [export])
is in [TableInterpreter]. *)
val marshal: t -> int
Comparison .
val equal: t -> t -> bool
[ def item ] looks up the production associated with this item in the
grammar and returns [ prod , nt , rhs , pos , length ] , where [ prod ] is
the production 's index , [ nt ] and [ rhs ] represent the production ,
[ pos ] is the position of the bullet in the item , and [ length ] is
the length of the production 's right - hand side .
grammar and returns [prod, nt, rhs, pos, length], where [prod] is
the production's index, [nt] and [rhs] represent the production,
[pos] is the position of the bullet in the item, and [length] is
the length of the production's right-hand side. *)
val def: t -> Production.index * Nonterminal.t * Symbol.t array * int * int
(* If [item] is a start item, [startnt item] returns the start
nonterminal that corresponds to [item]. *)
val startnt: t -> Nonterminal.t
(* Printing. *)
val print: t -> string
Classifying items as shift or reduce items . A shift item is one
where the bullet can still advance . A reduce item is one where the
bullet has reached the end of the right - hand side .
where the bullet can still advance. A reduce item is one where the
bullet has reached the end of the right-hand side. *)
type kind =
| Shift of Symbol.t * t
| Reduce of Production.index
val classify: t -> kind
(* Sets of items and maps over items. Hashing these data structures is
specifically allowed. *)
module Set : GSet.S with type element = t
module Map : GMap.S with type key = t
and type Domain.t = Set.t
This functor performs precomputation that helps efficiently compute
the closure of an LR(0 ) or LR(1 ) state . The precomputation requires
time linear in the size of the grammar . The nature of the lookahead
sets remains abstract .
the closure of an LR(0) or LR(1) state. The precomputation requires
time linear in the size of the grammar. The nature of the lookahead
sets remains abstract. *)
module Closure (L : Lookahead.S) : sig
(* A state maps items to lookahead information. *)
type state = L.t Map.t
(* This takes the closure of a state through all epsilon transitions. *)
val closure: state -> state
end
| null | https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/src/item.mli | ocaml | ****************************************************************************
file LICENSE.
****************************************************************************
An LR(0) item encodes a pair of integers, namely the index of the
production and the index of the bullet in the production's
right-hand side.
An item can be encoded as an integer. This is used in the table
back-end only. The decoding function (really a copy of [export])
is in [TableInterpreter].
If [item] is a start item, [startnt item] returns the start
nonterminal that corresponds to [item].
Printing.
Sets of items and maps over items. Hashing these data structures is
specifically allowed.
A state maps items to lookahead information.
This takes the closure of a state through all epsilon transitions. |
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
open Grammar
type t
val import: Production.index * int -> t
val export: t -> Production.index * int
val marshal: t -> int
Comparison .
val equal: t -> t -> bool
[ def item ] looks up the production associated with this item in the
grammar and returns [ prod , nt , rhs , pos , length ] , where [ prod ] is
the production 's index , [ nt ] and [ rhs ] represent the production ,
[ pos ] is the position of the bullet in the item , and [ length ] is
the length of the production 's right - hand side .
grammar and returns [prod, nt, rhs, pos, length], where [prod] is
the production's index, [nt] and [rhs] represent the production,
[pos] is the position of the bullet in the item, and [length] is
the length of the production's right-hand side. *)
val def: t -> Production.index * Nonterminal.t * Symbol.t array * int * int
val startnt: t -> Nonterminal.t
val print: t -> string
Classifying items as shift or reduce items . A shift item is one
where the bullet can still advance . A reduce item is one where the
bullet has reached the end of the right - hand side .
where the bullet can still advance. A reduce item is one where the
bullet has reached the end of the right-hand side. *)
type kind =
| Shift of Symbol.t * t
| Reduce of Production.index
val classify: t -> kind
module Set : GSet.S with type element = t
module Map : GMap.S with type key = t
and type Domain.t = Set.t
This functor performs precomputation that helps efficiently compute
the closure of an LR(0 ) or LR(1 ) state . The precomputation requires
time linear in the size of the grammar . The nature of the lookahead
sets remains abstract .
the closure of an LR(0) or LR(1) state. The precomputation requires
time linear in the size of the grammar. The nature of the lookahead
sets remains abstract. *)
module Closure (L : Lookahead.S) : sig
type state = L.t Map.t
val closure: state -> state
end
|
3807c0ce1b5bbe541f456a94c4f5f40c0382dd67cdedc0cb78bb66e14ac241ea | bvaugon/ocapic | cosolilet.ml | (*************************************************************************)
(* *)
(* OCaPIC *)
(* *)
(* *)
This file is distributed under the terms of the CeCILL license .
(* See file ../../LICENSE-en. *)
(* *)
(*************************************************************************)
type peg = Out | Empty | Peg ;;
print_endline "board" ;;
let print_peg =
function
| Out ->
print_string "."
| Empty ->
print_string " "
| Peg ->
print_string "$"
;;
let print_board =
fun board ->
let i = ref 0 in
while (!i) <= 8 do
let j = ref 0 in
while (!j) <= 8 do
print_peg ((board.(!i)).(!j));
incr j
done;
print_newline ();
incr i
done
;;
print_endline "apres board ";;
let moves = Array.make 31 [| |];;
let dir = [| [|0;1|]; [|1;0|];[|0;0-1|];[|0-1;0|] |];;
let counter = ref 0;;
exception Found;;
let rec solve =
fun board m ->
incr counter;
if m = 31 then (
match Array.get (Array.get board 4) 4 with
| Peg -> true
| _ -> false
) else (
try (
(if ((!counter) mod 50) = 0 then
(print_int (!counter);
print_newline ())
);
(let i = ref 1 in
while (!i) <= 7 do (
let j = ref 1 in
while (!j) <= 7 do (
match Array.get (Array.get board (!i)) (!j) with
| Peg ->
let k = ref 0 in
while (!k) <= 3 do (
let d1 = (Array.get (Array.get dir (!k)) 0) in
let d2 = (Array.get (Array.get dir (!k)) 1) in
let i1 = ((!i)+d1) in
let i2 = (i1+d1) in
let j1 = ((!j)+d2) in
let j2 = (j1+d2) in
match Array.get (Array.get board i1) j1 with
| Peg ->
(match Array.get (Array.get board (i2)) j2 with
| Empty -> (
Array.set (Array.get board (!i)) (!j) Empty;
Array.set (Array.get board i1) j1 Empty;
Array.set (Array.get board i2) j2 Peg;
(if solve board (m+1) then (
Array.set moves m [|[|(!i);(!j)|];[|i2;j2|]|];
raise Found
));
Array.set (Array.get board (!i)) (!j) Peg;
Array.set (Array.get board i1) j1 Peg;
Array.set (Array.get board i2) j2 Empty)
| _ -> ())
| _ -> ());
incr k
done
| _ -> ());
incr j
done);
incr i
done);
false
) with
| Found -> true)
;;
let i = ref 0 in
while (!i) < 100 do
let board = [|
[| Out; Out; Out; Out; Out ; Out; Out; Out; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Peg; Peg; Peg; Peg ; Peg; Peg; Peg; Out|];
[| Out; Peg; Peg; Peg; Empty; Peg; Peg; Peg; Out|];
[| Out; Peg; Peg; Peg; Peg ; Peg; Peg; Peg; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Out; Out; Out; Out ; Out; Out; Out; Out|];
|] in
(if solve board 0 then
(print_string "
"; print_board board)
else
print_endline "Pas trouve");
print_newline ();
print_int (!i);
print_newline ();
incr i
done ;;
| null | https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/tests/osolilet/cosolilet.ml | ocaml | ***********************************************************************
OCaPIC
See file ../../LICENSE-en.
*********************************************************************** |
This file is distributed under the terms of the CeCILL license .
type peg = Out | Empty | Peg ;;
print_endline "board" ;;
let print_peg =
function
| Out ->
print_string "."
| Empty ->
print_string " "
| Peg ->
print_string "$"
;;
let print_board =
fun board ->
let i = ref 0 in
while (!i) <= 8 do
let j = ref 0 in
while (!j) <= 8 do
print_peg ((board.(!i)).(!j));
incr j
done;
print_newline ();
incr i
done
;;
print_endline "apres board ";;
let moves = Array.make 31 [| |];;
let dir = [| [|0;1|]; [|1;0|];[|0;0-1|];[|0-1;0|] |];;
let counter = ref 0;;
exception Found;;
let rec solve =
fun board m ->
incr counter;
if m = 31 then (
match Array.get (Array.get board 4) 4 with
| Peg -> true
| _ -> false
) else (
try (
(if ((!counter) mod 50) = 0 then
(print_int (!counter);
print_newline ())
);
(let i = ref 1 in
while (!i) <= 7 do (
let j = ref 1 in
while (!j) <= 7 do (
match Array.get (Array.get board (!i)) (!j) with
| Peg ->
let k = ref 0 in
while (!k) <= 3 do (
let d1 = (Array.get (Array.get dir (!k)) 0) in
let d2 = (Array.get (Array.get dir (!k)) 1) in
let i1 = ((!i)+d1) in
let i2 = (i1+d1) in
let j1 = ((!j)+d2) in
let j2 = (j1+d2) in
match Array.get (Array.get board i1) j1 with
| Peg ->
(match Array.get (Array.get board (i2)) j2 with
| Empty -> (
Array.set (Array.get board (!i)) (!j) Empty;
Array.set (Array.get board i1) j1 Empty;
Array.set (Array.get board i2) j2 Peg;
(if solve board (m+1) then (
Array.set moves m [|[|(!i);(!j)|];[|i2;j2|]|];
raise Found
));
Array.set (Array.get board (!i)) (!j) Peg;
Array.set (Array.get board i1) j1 Peg;
Array.set (Array.get board i2) j2 Empty)
| _ -> ())
| _ -> ());
incr k
done
| _ -> ());
incr j
done);
incr i
done);
false
) with
| Found -> true)
;;
let i = ref 0 in
while (!i) < 100 do
let board = [|
[| Out; Out; Out; Out; Out ; Out; Out; Out; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Peg; Peg; Peg; Peg ; Peg; Peg; Peg; Out|];
[| Out; Peg; Peg; Peg; Empty; Peg; Peg; Peg; Out|];
[| Out; Peg; Peg; Peg; Peg ; Peg; Peg; Peg; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Out; Out; Peg; Peg ; Peg; Out; Out; Out|];
[| Out; Out; Out; Out; Out ; Out; Out; Out; Out|];
|] in
(if solve board 0 then
(print_string "
"; print_board board)
else
print_endline "Pas trouve");
print_newline ();
print_int (!i);
print_newline ();
incr i
done ;;
|
037a44d8dedb745ebfbf8dbd9ed63d69b13412ce2efdbd5fa92f3298a681d84e | immoh/nsorg | core.clj | (ns nsorg.core
(:require [nsorg.zip :as nzip]
[rewrite-clj.zip :as zip]))
(defn map-option?
"Returns true if given zipper node is a map value of given keyword option.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(and (map? (nzip/sexpr zloc))
(= kw (nzip/sexpr (zip/left zloc)))))
(defn seq-option?
"Returns true if given zipper node is a seq value of given keyword option.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(and (vector? (nzip/sexpr zloc))
(= kw (nzip/sexpr (zip/left zloc)))))
(defn ns-clause?
"Returns true if given zipper node is a ns clause.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(and (sequential? (nzip/sexpr zloc))
(= kw (first (nzip/sexpr zloc)))))
(defn prefix-libspex?
"Returns true if given zipper node is a prefix libspec.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(let [sexpr (nzip/sexpr zloc)
parent-sexpr (nzip/sexpr (zip/up zloc))]
(and (sequential? sexpr)
(or (symbol? (second sexpr))
(vector? (second sexpr)))
(list? parent-sexpr)
(= kw (first parent-sexpr)))))
(defn remove-duplicates-from-map-option
"Create rule for removing duplicates map option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial map-option? kw)
:transform (fn [zloc]
(nzip/remove-duplicates-from-sexpr zloc {:map? true}))})
(defn remove-duplicates-from-seq-option
"Create rule for removing duplicates seq option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial seq-option? kw)
:transform nzip/remove-duplicates-from-sexpr})
(defn remove-duplicates-from-ns-clause
"Create rule for removing duplicates from ns clause.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial ns-clause? kw)
:transform (fn [zloc]
(nzip/remove-duplicates-from-sexpr zloc {:exclude-first? true}))})
(defn remove-duplicates-from-prefix-libspec
"Create rule for removing duplicates from prefix libspec.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial prefix-libspex? kw)
:transform (fn [zloc]
(nzip/remove-duplicates-from-sexpr zloc {:exclude-first? true}))})
(defn sort-map-option
"Create rule for sorting map option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial map-option? kw)
:transform (fn [zloc]
(nzip/order-sexpr zloc {:map? true}))})
(defn sort-seq-option
"Create rule for sorting seq option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial seq-option? kw)
:transform nzip/order-sexpr})
(defn sort-prefix-libspec
"Create rule for sorting prefix libspec.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial prefix-libspex? kw)
:transform (fn [zloc]
(nzip/order-sexpr zloc {:exclude-first? true}))})
(defn sort-ns-clause
"Create rule for sorting ns clause.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial ns-clause? kw)
:transform (fn [zloc]
(nzip/order-sexpr zloc {:exclude-first? true}))})
(def default-rules
"Default rule set."
[(remove-duplicates-from-map-option :rename)
(remove-duplicates-from-seq-option :exclude)
(remove-duplicates-from-seq-option :only)
(remove-duplicates-from-seq-option :refer)
(remove-duplicates-from-seq-option :refer-macros)
(remove-duplicates-from-prefix-libspec :import)
(remove-duplicates-from-prefix-libspec :require)
(remove-duplicates-from-prefix-libspec :use)
(remove-duplicates-from-ns-clause :import)
(remove-duplicates-from-ns-clause :require)
(remove-duplicates-from-ns-clause :require-macros)
(remove-duplicates-from-ns-clause :use)
(remove-duplicates-from-ns-clause :use-macros)
(sort-map-option :rename)
(sort-seq-option :exclude)
(sort-seq-option :only)
(sort-seq-option :refer)
(sort-seq-option :refer-macros)
(sort-prefix-libspec :import)
(sort-prefix-libspec :require)
(sort-prefix-libspec :use)
(sort-ns-clause :import)
(sort-ns-clause :require)
(sort-ns-clause :require-macros)
(sort-ns-clause :use)
(sort-ns-clause :use-macros)])
(defn rewrite-ns-form
"Rewrites ns form in the Clojure code given as a string using the given set of rules.
By default applies rules that sort ns clauses, prefix libspecs and option values alphabetically and remove
duplicates. Preserves original whitespace and comments.
Parameters:
s - string containing Clojure code
rules - collection rules to apply "
([s]
(rewrite-ns-form s {:rules default-rules}))
([s opts]
(if-let [zloc (nzip/find-ns-form (zip/of-string s))]
(zip/root-string (nzip/organize-ns-form zloc (:rules opts)))
s)))
| null | https://raw.githubusercontent.com/immoh/nsorg/12b32504d65ad4c2c3cd82a0ada4b3695e1dfb95/src/nsorg/core.clj | clojure | (ns nsorg.core
(:require [nsorg.zip :as nzip]
[rewrite-clj.zip :as zip]))
(defn map-option?
"Returns true if given zipper node is a map value of given keyword option.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(and (map? (nzip/sexpr zloc))
(= kw (nzip/sexpr (zip/left zloc)))))
(defn seq-option?
"Returns true if given zipper node is a seq value of given keyword option.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(and (vector? (nzip/sexpr zloc))
(= kw (nzip/sexpr (zip/left zloc)))))
(defn ns-clause?
"Returns true if given zipper node is a ns clause.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(and (sequential? (nzip/sexpr zloc))
(= kw (first (nzip/sexpr zloc)))))
(defn prefix-libspex?
"Returns true if given zipper node is a prefix libspec.
Parameters:
kw - option keyword
zloc - zipper node"
[kw zloc]
(let [sexpr (nzip/sexpr zloc)
parent-sexpr (nzip/sexpr (zip/up zloc))]
(and (sequential? sexpr)
(or (symbol? (second sexpr))
(vector? (second sexpr)))
(list? parent-sexpr)
(= kw (first parent-sexpr)))))
(defn remove-duplicates-from-map-option
"Create rule for removing duplicates map option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial map-option? kw)
:transform (fn [zloc]
(nzip/remove-duplicates-from-sexpr zloc {:map? true}))})
(defn remove-duplicates-from-seq-option
"Create rule for removing duplicates seq option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial seq-option? kw)
:transform nzip/remove-duplicates-from-sexpr})
(defn remove-duplicates-from-ns-clause
"Create rule for removing duplicates from ns clause.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial ns-clause? kw)
:transform (fn [zloc]
(nzip/remove-duplicates-from-sexpr zloc {:exclude-first? true}))})
(defn remove-duplicates-from-prefix-libspec
"Create rule for removing duplicates from prefix libspec.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial prefix-libspex? kw)
:transform (fn [zloc]
(nzip/remove-duplicates-from-sexpr zloc {:exclude-first? true}))})
(defn sort-map-option
"Create rule for sorting map option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial map-option? kw)
:transform (fn [zloc]
(nzip/order-sexpr zloc {:map? true}))})
(defn sort-seq-option
"Create rule for sorting seq option values.
Parameters:
kw - option keyword"
[kw]
{:predicate (partial seq-option? kw)
:transform nzip/order-sexpr})
(defn sort-prefix-libspec
"Create rule for sorting prefix libspec.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial prefix-libspex? kw)
:transform (fn [zloc]
(nzip/order-sexpr zloc {:exclude-first? true}))})
(defn sort-ns-clause
"Create rule for sorting ns clause.
Parameters:
kw - ns clause type"
[kw]
{:predicate (partial ns-clause? kw)
:transform (fn [zloc]
(nzip/order-sexpr zloc {:exclude-first? true}))})
(def default-rules
"Default rule set."
[(remove-duplicates-from-map-option :rename)
(remove-duplicates-from-seq-option :exclude)
(remove-duplicates-from-seq-option :only)
(remove-duplicates-from-seq-option :refer)
(remove-duplicates-from-seq-option :refer-macros)
(remove-duplicates-from-prefix-libspec :import)
(remove-duplicates-from-prefix-libspec :require)
(remove-duplicates-from-prefix-libspec :use)
(remove-duplicates-from-ns-clause :import)
(remove-duplicates-from-ns-clause :require)
(remove-duplicates-from-ns-clause :require-macros)
(remove-duplicates-from-ns-clause :use)
(remove-duplicates-from-ns-clause :use-macros)
(sort-map-option :rename)
(sort-seq-option :exclude)
(sort-seq-option :only)
(sort-seq-option :refer)
(sort-seq-option :refer-macros)
(sort-prefix-libspec :import)
(sort-prefix-libspec :require)
(sort-prefix-libspec :use)
(sort-ns-clause :import)
(sort-ns-clause :require)
(sort-ns-clause :require-macros)
(sort-ns-clause :use)
(sort-ns-clause :use-macros)])
(defn rewrite-ns-form
"Rewrites ns form in the Clojure code given as a string using the given set of rules.
By default applies rules that sort ns clauses, prefix libspecs and option values alphabetically and remove
duplicates. Preserves original whitespace and comments.
Parameters:
s - string containing Clojure code
rules - collection rules to apply "
([s]
(rewrite-ns-form s {:rules default-rules}))
([s opts]
(if-let [zloc (nzip/find-ns-form (zip/of-string s))]
(zip/root-string (nzip/organize-ns-form zloc (:rules opts)))
s)))
|
|
038611ada8f92e84d3d23b6249843e5426a81da019186472c0fbb96ac89ab1a5 | synduce/Synduce | contains_bool_2.ml | * @synduce -s 2 -NB --no - lifting
type 'a tree =
| Leaf of 'a
| Node of 'a * 'a tree * 'a tree
let rec tree_min = function
| Leaf x -> x
| Node (a, l, r) -> min a (min (tree_min l) (tree_min r))
;;
let rec tree_max = function
| Leaf x -> x
| Node (a, l, r) -> max a (max (tree_max l) (tree_max r))
;;
let rec is_bst = function
| Leaf x -> true
| Node (a, l, r) -> a >= tree_max r && a <= tree_min l && is_bst l && is_bst r
;;
let repr x = x
let spec x t =
let rec f = function
| Leaf a -> a = x
| Node (a, l, r) -> a = x || f l || f r
in
f t
;;
let target y t =
let rec g = function
| Leaf a -> [%synt xi_0] y a
| Node (a, l, r) -> if y < a then [%synt xi_1] (g r) else [%synt xi_2] y a (g l)
in
g t
[@@requires is_bst]
;;
| null | https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/bst/contains_bool_2.ml | ocaml | * @synduce -s 2 -NB --no - lifting
type 'a tree =
| Leaf of 'a
| Node of 'a * 'a tree * 'a tree
let rec tree_min = function
| Leaf x -> x
| Node (a, l, r) -> min a (min (tree_min l) (tree_min r))
;;
let rec tree_max = function
| Leaf x -> x
| Node (a, l, r) -> max a (max (tree_max l) (tree_max r))
;;
let rec is_bst = function
| Leaf x -> true
| Node (a, l, r) -> a >= tree_max r && a <= tree_min l && is_bst l && is_bst r
;;
let repr x = x
let spec x t =
let rec f = function
| Leaf a -> a = x
| Node (a, l, r) -> a = x || f l || f r
in
f t
;;
let target y t =
let rec g = function
| Leaf a -> [%synt xi_0] y a
| Node (a, l, r) -> if y < a then [%synt xi_1] (g r) else [%synt xi_2] y a (g l)
in
g t
[@@requires is_bst]
;;
|
|
028f82a516b60ac23ac3fda7bdffc32564dd124a3b33b2807f99149a0a79b004 | janestreet/bonsai | import.mli | open! Core
module Effect : sig
type 'a t = 'a Ui_effect.t
val sequence : unit t list -> unit t
val no_op : unit t
val external_ : string -> unit t
end
module Incr = Ui_incr
include module type of struct
include Expect_test_helpers_core
end
val dummy_source_code_position : Source_code_position.t
val opaque_const : 'a -> 'a Bonsai.Computation.t
val opaque_const_value : 'a -> 'a Bonsai.Value.t
val opaque_computation : 'a Bonsai.Computation.t -> 'a Bonsai.Computation.t
| null | https://raw.githubusercontent.com/janestreet/bonsai/4baeedc75bf73a0915e04dc02d8a49b78779e9b0/test/import.mli | ocaml | open! Core
module Effect : sig
type 'a t = 'a Ui_effect.t
val sequence : unit t list -> unit t
val no_op : unit t
val external_ : string -> unit t
end
module Incr = Ui_incr
include module type of struct
include Expect_test_helpers_core
end
val dummy_source_code_position : Source_code_position.t
val opaque_const : 'a -> 'a Bonsai.Computation.t
val opaque_const_value : 'a -> 'a Bonsai.Value.t
val opaque_computation : 'a Bonsai.Computation.t -> 'a Bonsai.Computation.t
|
|
f4fb319a7baed0a8114fdc3d885279d6338b5a393ff2bc54820b2f07637e89e8 | pouyakary/Nota | Main.hs |
module REPL.Main where
-- ─── IMPORTS ────────────────────────────────────────────────────────────────────
import REPL.Terminal
import Control.Exception
import Data.List
import Data.List
import Data.Set
import Debug.Trace
import Infrastructure.Text.Layout
import Infrastructure.Text.Shapes.Boxes
import Infrastructure.Text.Shapes.Brackets
import Infrastructure.Text.Shapes.Presets
import Infrastructure.Text.Shapes.Types
import Infrastructure.Text.Shapes.Table
import Infrastructure.Text.Tools
import Language.BackEnd.Evaluator.Main
import Language.BackEnd.Evaluator.Types
import Language.BackEnd.Renderer.Main
import Language.BackEnd.Renderer.Nodes.Number
import Language.FrontEnd.AST
import Language.FrontEnd.Parser
import Model
import System.Console.ANSI
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Error
import System.Exit
-- ─── TYPES ──────────────────────────────────────────────────────────────────────
data RunnerResult =
RunnerResult Model String
data RunnerMiddleData =
RunnerMiddleData Model SpacedBox
-- ─── GETTERS ────────────────────────────────────────────────────────────────────
getRunnerResultModel :: RunnerResult -> Model
getRunnerResultModel ( RunnerResult x _ ) = x
getRunnerResultPrintable :: RunnerResult -> String
getRunnerResultPrintable ( RunnerResult _ x ) = x
-- ─── RUN REPL ───────────────────────────────────────────────────────────────────
runREPL :: Model -> IO ( )
runREPL model =
do printTitle
repl model
where
repl :: Model -> IO ( )
repl model =
do input <- prompt $ show $ length ( history model ) + 1
newModel <- run input model
putStrLn ""
repl newModel
-- ─── PRINT TITLE ────────────────────────────────────────────────────────────────
printTitle =
do windowWidth <- terminalWidth
setTitle "Kary Nota"
putStrLn $ createLogoForWidth windowWidth
putStrLn ""
where
name = "Kary Nota"
createLogoForWidth :: Int -> String
createLogoForWidth w =
if w == -1 then name else fullBox w
fullBox :: Int -> String
fullBox w =
result where
result =
leftLine ++ " " ++ name ++ " " ++ rightLine
rightLineWidth =
5
leftLine =
repeatText '─' $ w - ( length name + 2 + rightLineWidth )
rightLine =
repeatText '─' rightLineWidth
─ ─ ─ ERROR MESSAGES ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
showError :: ParseError -> SpacedBox
showError error =
shapeBox LightBox $ spacedBox messageString where
messageString =
"ERROR: " ++ intercalate "\n " uniqueMessages
uniqueMessages =
Data.Set.toList $ Data.Set.fromList nonEmptyMessages
nonEmptyMessages =
[ x | x <- stringedMessages, x /= "!" ]
stringedMessages =
[ showMessage x | x <- errorMessages error ]
showMessage :: Message -> String
showMessage message =
case message of SysUnExpect x -> wrapp x "Unexpected "
UnExpect x -> wrapp x "Unexpected "
Expect x -> wrapp x "Expected "
Message x -> wrapp x ""
where
wrapp x prefix =
if x /= "" then prefix ++ x else "!"
-- ─── PRINT ERROR ────────────────────────────────────────────────────────────────
printParseError :: ParseError -> String -> String
printParseError error number =
spacedBoxToString $ horizontalConcat [ promptSign, errorBox ] where
promptSign =
spacedBox $ " In[!]:"
errorBox =
showError error
-- ─── PRINT RESULT ───────────────────────────────────────────────────────────────
renderMath :: AST -> String -> SpacedBox
renderMath ast number =
horizontalConcat [ outputSignSpacedbox, render ast False ] where
outputSignSpacedbox =
spacedBox $ " In[" ++ number ++ "]:"
-- ─── RENDER EVAL ERROR MESSAGE ──────────────────────────────────────────────────
renderEvalError :: String -> SpacedBox
renderEvalError error =
shapeBox LightBox $ spacedBox ( "ERROR: " ++ error )
-- ─── RENDER RESULT ──────────────────────────────────────────────────────────────
renderEvalResult :: [ Double ] -> SpacedBox
renderEvalResult results =
case length results of
0 -> spacedBox "empty."
1 -> spacedBox $ show ( results !! 0 )
_ -> numbersRowTable results
-- ─── RENDER INPUT TEXT ──────────────────────────────────────────────────────────
printInputText :: String -> IO ( )
printInputText text =
putStrLn $ " In[*]: " ++ text
-- ─── RUNNER ─────────────────────────────────────────────────────────────────────
run :: String -> Model -> IO Model
run input model =
case input of
"" ->
do printInputText "empty."
return model
"clear" ->
do printInputText "Command: Clear Screen"
clearScreen
return model
"help" ->
do printHelp
return model
"exit" ->
do printExit
exitSuccess
_ ->
case parseIntactus input of
Left err ->
do putStrLn $ printParseError err promptNumber
return model
Right ast ->
do notation <- pure $ renderMath ast promptNumber
putStrLn $ spacedBoxToString notation
putStrLn ""
newModel <- runEval ast model input promptNumber
putStrLn ""
return newModel
where
promptNumber =
show $ length ( history model ) + 1
renderOutput :: SpacedBox -> String -> IO ( )
renderOutput message promptNumber =
do putStrLn output
where
output =
spacedBoxToString $ horizontalConcat [ outputSign, message ]
outputSign =
spacedBox $ " Out[" ++ promptNumber ++ "]:"
runEval :: AST -> Model -> String -> String -> IO Model
runEval ast model inputString promptNumber =
case masterEval ast model inputString of
Left err ->
do renderOutput ( renderEvalError err ) promptNumber
return model
Right ( MasterEvalResultRight results newModel ) ->
do renderOutput ( renderEvalResult results ) promptNumber
return newModel
─ ─ ─ PRINT EXIT ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
printExit =
do width <- terminalWidth
line <- pure $ repeatText '─' width
printInputText "Command: Exit"
putStrLn ""
putStrLn line
-- ─── HELP VIEW ──────────────────────────────────────────────────────────────────
printHelp =
do printInputText "Command: Help"
putStrLn ""
putStrLn $ spacedBoxToString helpBox
where
helpBox =
horizontalConcat [ ( spacedBox " Out[*]:" ), helpTextBox ]
helpTextBox =
shapeBox LightBox $ spacedBox helpText
helpText =
"For documentations please visit:\n\n ── "
-- ────────────────────────────────────────────────────────────────────────────────
| null | https://raw.githubusercontent.com/pouyakary/Nota/d5e29eca7ea34d72835a9708977fa33c030393d1/source/REPL/Main.hs | haskell | ─── IMPORTS ────────────────────────────────────────────────────────────────────
─── TYPES ──────────────────────────────────────────────────────────────────────
─── GETTERS ────────────────────────────────────────────────────────────────────
─── RUN REPL ───────────────────────────────────────────────────────────────────
─── PRINT TITLE ────────────────────────────────────────────────────────────────
─── PRINT ERROR ────────────────────────────────────────────────────────────────
─── PRINT RESULT ───────────────────────────────────────────────────────────────
─── RENDER EVAL ERROR MESSAGE ──────────────────────────────────────────────────
─── RENDER RESULT ──────────────────────────────────────────────────────────────
─── RENDER INPUT TEXT ──────────────────────────────────────────────────────────
─── RUNNER ─────────────────────────────────────────────────────────────────────
─── HELP VIEW ──────────────────────────────────────────────────────────────────
──────────────────────────────────────────────────────────────────────────────── |
module REPL.Main where
import REPL.Terminal
import Control.Exception
import Data.List
import Data.List
import Data.Set
import Debug.Trace
import Infrastructure.Text.Layout
import Infrastructure.Text.Shapes.Boxes
import Infrastructure.Text.Shapes.Brackets
import Infrastructure.Text.Shapes.Presets
import Infrastructure.Text.Shapes.Types
import Infrastructure.Text.Shapes.Table
import Infrastructure.Text.Tools
import Language.BackEnd.Evaluator.Main
import Language.BackEnd.Evaluator.Types
import Language.BackEnd.Renderer.Main
import Language.BackEnd.Renderer.Nodes.Number
import Language.FrontEnd.AST
import Language.FrontEnd.Parser
import Model
import System.Console.ANSI
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Error
import System.Exit
data RunnerResult =
RunnerResult Model String
data RunnerMiddleData =
RunnerMiddleData Model SpacedBox
getRunnerResultModel :: RunnerResult -> Model
getRunnerResultModel ( RunnerResult x _ ) = x
getRunnerResultPrintable :: RunnerResult -> String
getRunnerResultPrintable ( RunnerResult _ x ) = x
runREPL :: Model -> IO ( )
runREPL model =
do printTitle
repl model
where
repl :: Model -> IO ( )
repl model =
do input <- prompt $ show $ length ( history model ) + 1
newModel <- run input model
putStrLn ""
repl newModel
printTitle =
do windowWidth <- terminalWidth
setTitle "Kary Nota"
putStrLn $ createLogoForWidth windowWidth
putStrLn ""
where
name = "Kary Nota"
createLogoForWidth :: Int -> String
createLogoForWidth w =
if w == -1 then name else fullBox w
fullBox :: Int -> String
fullBox w =
result where
result =
leftLine ++ " " ++ name ++ " " ++ rightLine
rightLineWidth =
5
leftLine =
repeatText '─' $ w - ( length name + 2 + rightLineWidth )
rightLine =
repeatText '─' rightLineWidth
─ ─ ─ ERROR MESSAGES ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
showError :: ParseError -> SpacedBox
showError error =
shapeBox LightBox $ spacedBox messageString where
messageString =
"ERROR: " ++ intercalate "\n " uniqueMessages
uniqueMessages =
Data.Set.toList $ Data.Set.fromList nonEmptyMessages
nonEmptyMessages =
[ x | x <- stringedMessages, x /= "!" ]
stringedMessages =
[ showMessage x | x <- errorMessages error ]
showMessage :: Message -> String
showMessage message =
case message of SysUnExpect x -> wrapp x "Unexpected "
UnExpect x -> wrapp x "Unexpected "
Expect x -> wrapp x "Expected "
Message x -> wrapp x ""
where
wrapp x prefix =
if x /= "" then prefix ++ x else "!"
printParseError :: ParseError -> String -> String
printParseError error number =
spacedBoxToString $ horizontalConcat [ promptSign, errorBox ] where
promptSign =
spacedBox $ " In[!]:"
errorBox =
showError error
renderMath :: AST -> String -> SpacedBox
renderMath ast number =
horizontalConcat [ outputSignSpacedbox, render ast False ] where
outputSignSpacedbox =
spacedBox $ " In[" ++ number ++ "]:"
renderEvalError :: String -> SpacedBox
renderEvalError error =
shapeBox LightBox $ spacedBox ( "ERROR: " ++ error )
renderEvalResult :: [ Double ] -> SpacedBox
renderEvalResult results =
case length results of
0 -> spacedBox "empty."
1 -> spacedBox $ show ( results !! 0 )
_ -> numbersRowTable results
printInputText :: String -> IO ( )
printInputText text =
putStrLn $ " In[*]: " ++ text
run :: String -> Model -> IO Model
run input model =
case input of
"" ->
do printInputText "empty."
return model
"clear" ->
do printInputText "Command: Clear Screen"
clearScreen
return model
"help" ->
do printHelp
return model
"exit" ->
do printExit
exitSuccess
_ ->
case parseIntactus input of
Left err ->
do putStrLn $ printParseError err promptNumber
return model
Right ast ->
do notation <- pure $ renderMath ast promptNumber
putStrLn $ spacedBoxToString notation
putStrLn ""
newModel <- runEval ast model input promptNumber
putStrLn ""
return newModel
where
promptNumber =
show $ length ( history model ) + 1
renderOutput :: SpacedBox -> String -> IO ( )
renderOutput message promptNumber =
do putStrLn output
where
output =
spacedBoxToString $ horizontalConcat [ outputSign, message ]
outputSign =
spacedBox $ " Out[" ++ promptNumber ++ "]:"
runEval :: AST -> Model -> String -> String -> IO Model
runEval ast model inputString promptNumber =
case masterEval ast model inputString of
Left err ->
do renderOutput ( renderEvalError err ) promptNumber
return model
Right ( MasterEvalResultRight results newModel ) ->
do renderOutput ( renderEvalResult results ) promptNumber
return newModel
─ ─ ─ PRINT EXIT ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
printExit =
do width <- terminalWidth
line <- pure $ repeatText '─' width
printInputText "Command: Exit"
putStrLn ""
putStrLn line
printHelp =
do printInputText "Command: Help"
putStrLn ""
putStrLn $ spacedBoxToString helpBox
where
helpBox =
horizontalConcat [ ( spacedBox " Out[*]:" ), helpTextBox ]
helpTextBox =
shapeBox LightBox $ spacedBox helpText
helpText =
"For documentations please visit:\n\n ── "
|
173c45057341273e875bc884067a35451de55ce3334a436905d007a20ac5c66a | fpco/ide-backend | List.hs | # LANGUAGE DeriveFunctor , , DeriveTraversable #
-- | Strict lists
module IdeSession.Strict.List (
nil
, cons
, singleton
, map
, all
, any
, reverse
, (++)
, elem
, (\\)
) where
import Prelude hiding (map, all, any, reverse, (++), elem)
import qualified Data.List as List
import IdeSession.Strict.Container
nil :: Strict [] a
nil = StrictList []
cons :: a -> Strict [] a -> Strict [] a
cons x xs = x `seq` StrictList (x : toLazyList xs)
singleton :: a -> Strict [] a
singleton x = x `seq` StrictList [x]
map :: (a -> b) -> Strict [] a -> Strict [] b
map f = force . List.map f . toLazyList
all :: (a -> Bool) -> Strict [] a -> Bool
all p = List.all p . toLazyList
any :: (a -> Bool) -> Strict [] a -> Bool
any p = List.any p . toLazyList
elem :: Eq a => a -> Strict [] a -> Bool
elem x = List.elem x . toLazyList
reverse :: Strict [] a -> Strict [] a
reverse = StrictList . List.reverse . toLazyList
(++) :: Strict [] a -> Strict [] a -> Strict [] a
xs ++ ys = StrictList $ toLazyList xs List.++ toLazyList ys
(\\) :: Eq a => Strict [] a -> Strict [] a -> Strict [] a
xs \\ ys = StrictList $ toLazyList xs List.\\ toLazyList ys
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend-common/IdeSession/Strict/List.hs | haskell | | Strict lists | # LANGUAGE DeriveFunctor , , DeriveTraversable #
module IdeSession.Strict.List (
nil
, cons
, singleton
, map
, all
, any
, reverse
, (++)
, elem
, (\\)
) where
import Prelude hiding (map, all, any, reverse, (++), elem)
import qualified Data.List as List
import IdeSession.Strict.Container
nil :: Strict [] a
nil = StrictList []
cons :: a -> Strict [] a -> Strict [] a
cons x xs = x `seq` StrictList (x : toLazyList xs)
singleton :: a -> Strict [] a
singleton x = x `seq` StrictList [x]
map :: (a -> b) -> Strict [] a -> Strict [] b
map f = force . List.map f . toLazyList
all :: (a -> Bool) -> Strict [] a -> Bool
all p = List.all p . toLazyList
any :: (a -> Bool) -> Strict [] a -> Bool
any p = List.any p . toLazyList
elem :: Eq a => a -> Strict [] a -> Bool
elem x = List.elem x . toLazyList
reverse :: Strict [] a -> Strict [] a
reverse = StrictList . List.reverse . toLazyList
(++) :: Strict [] a -> Strict [] a -> Strict [] a
xs ++ ys = StrictList $ toLazyList xs List.++ toLazyList ys
(\\) :: Eq a => Strict [] a -> Strict [] a -> Strict [] a
xs \\ ys = StrictList $ toLazyList xs List.\\ toLazyList ys
|
f8d6ba16a4162ebea20f3c48654c8046218ec14d5c35e44bd650ea4cab2e5d6d | aantron/luv | poll.ml | This file is part of Luv , released under the MIT license . See LICENSE.md for
details , or visit .
details, or visit . *)
open Test_helpers
let test_fd =
if Sys.win32 then
Luv.Process.stderr
else begin
On Linux in , trying to create a poll handle for STDERR results in
EPERM , so we create a dummy pipe instead . We do n't bother closing it :
only one will be created on tester startup , and it will be closed by the
system on process exit .
EPERM, so we create a dummy pipe instead. We don't bother closing it:
only one will be created on tester startup, and it will be closed by the
system on process exit. *)
let (_read_end, write_end) = Unix.pipe () in
(Obj.magic write_end : int)
end
let with_poll f =
let poll =
Luv.Poll.init test_fd
|> check_success_result "init"
in
f poll;
Luv.Handle.close poll ignore;
run ()
let tests = [
"poll", [
"init, close", `Quick, begin fun () ->
with_poll ignore
end;
"start, stop", `Quick, begin fun () ->
with_poll begin fun poll ->
let called = ref false in
Luv.Poll.start poll [`WRITABLE] begin fun result ->
check_success_result "result" result
|> List.mem `WRITABLE
|> Alcotest.(check bool) "writable" true;
Luv.Poll.stop poll
|> check_success_result "stop";
called := true
end;
run ();
Alcotest.(check bool) "called" true !called
end
end;
"exception", `Quick, begin fun () ->
with_poll begin fun poll ->
check_exception Exit begin fun () ->
Luv.Poll.start poll [`WRITABLE] begin fun _ ->
Luv.Poll.stop poll |> ignore;
raise Exit
end;
run ()
end
end
end;
(* This is a compilation test. If the type constraints in handle.mli are
wrong, there will be a type error in this test. *)
"handle functions", `Quick, begin fun () ->
with_poll begin fun poll ->
ignore @@ Luv.Handle.fileno poll
end
end;
]
]
| null | https://raw.githubusercontent.com/aantron/luv/4b49d3edad2179c76d685500edf1b44f61ec4be8/test/poll.ml | ocaml | This is a compilation test. If the type constraints in handle.mli are
wrong, there will be a type error in this test. | This file is part of Luv , released under the MIT license . See LICENSE.md for
details , or visit .
details, or visit . *)
open Test_helpers
let test_fd =
if Sys.win32 then
Luv.Process.stderr
else begin
On Linux in , trying to create a poll handle for STDERR results in
EPERM , so we create a dummy pipe instead . We do n't bother closing it :
only one will be created on tester startup , and it will be closed by the
system on process exit .
EPERM, so we create a dummy pipe instead. We don't bother closing it:
only one will be created on tester startup, and it will be closed by the
system on process exit. *)
let (_read_end, write_end) = Unix.pipe () in
(Obj.magic write_end : int)
end
let with_poll f =
let poll =
Luv.Poll.init test_fd
|> check_success_result "init"
in
f poll;
Luv.Handle.close poll ignore;
run ()
let tests = [
"poll", [
"init, close", `Quick, begin fun () ->
with_poll ignore
end;
"start, stop", `Quick, begin fun () ->
with_poll begin fun poll ->
let called = ref false in
Luv.Poll.start poll [`WRITABLE] begin fun result ->
check_success_result "result" result
|> List.mem `WRITABLE
|> Alcotest.(check bool) "writable" true;
Luv.Poll.stop poll
|> check_success_result "stop";
called := true
end;
run ();
Alcotest.(check bool) "called" true !called
end
end;
"exception", `Quick, begin fun () ->
with_poll begin fun poll ->
check_exception Exit begin fun () ->
Luv.Poll.start poll [`WRITABLE] begin fun _ ->
Luv.Poll.stop poll |> ignore;
raise Exit
end;
run ()
end
end
end;
"handle functions", `Quick, begin fun () ->
with_poll begin fun poll ->
ignore @@ Luv.Handle.fileno poll
end
end;
]
]
|
ec0be04ee820ff2dc5bfb7a16e0beda572e7a69bed7095847010b5b2b7207d4c | grin-compiler/ghc-grin | sieve.hs | module Main(main) where
import RTS
main = print_int (sum (sieve (upto 2 50000)))
upto :: Int -> Int -> [Int]
upto m n = if m > n then [] else m : upto (m+1) n
xfilter :: Int -> [Int] -> [Int]
xfilter y l = case l of
[] -> []
(x:xs) -> if x `rem` y == 0
then xfilter y xs
else x : xfilter y xs
sieve :: [Int] -> [Int]
sieve l = case l of
[] -> []
(x:xs) -> x : sieve (xfilter x xs)
| null | https://raw.githubusercontent.com/grin-compiler/ghc-grin/ebc4dca2e1f5b3581d4b84726730564ce909d786/ghc-grin-benchmark/boq-custom/sieve.hs | haskell | module Main(main) where
import RTS
main = print_int (sum (sieve (upto 2 50000)))
upto :: Int -> Int -> [Int]
upto m n = if m > n then [] else m : upto (m+1) n
xfilter :: Int -> [Int] -> [Int]
xfilter y l = case l of
[] -> []
(x:xs) -> if x `rem` y == 0
then xfilter y xs
else x : xfilter y xs
sieve :: [Int] -> [Int]
sieve l = case l of
[] -> []
(x:xs) -> x : sieve (xfilter x xs)
|
|
f211e49b7015b7aaa4173c62ccc26a133ef1f784a80f56fd3e999ff554df3f95 | racket/racket7 | integer-set.rkt | #lang racket/base
;; a library for integer interval sets
(require racket/contract/base
racket/match
racket/stream
racket/struct)
(provide well-formed-set?
(contract-out
(struct integer-set ((contents well-formed-set?)))
[make-range
(->i () ((i exact-integer?) (j (i) (and/c exact-integer? (>=/c i))))
[res integer-set?])]
[rename merge union (integer-set? integer-set? . -> . integer-set?)]
[split (integer-set? integer-set?
. -> .
(values integer-set? integer-set? integer-set?))]
[intersect (integer-set? integer-set? . -> . integer-set?)]
[subtract (integer-set? integer-set? . -> . integer-set?)]
[symmetric-difference
(integer-set? integer-set? . -> . integer-set?)]
[complement (->i ((s integer-set?) (min exact-integer?)
(max (min) (and/c exact-integer? (>=/c min))))
[res integer-set?])]
[member? (exact-integer? integer-set? . -> . any)]
[get-integer (integer-set? . -> . (or/c #f exact-integer?))]
[rename is-foldr foldr (any/c any/c integer-set? . -> . any)]
[partition ((listof integer-set?) . -> . (listof integer-set?))]
[count (integer-set? . -> . natural-number/c)]
[subset? (integer-set? integer-set? . -> . any)]))
;; test macro, now updated to use submodules
(define-syntax test-block
(syntax-rules ()
((_ defs (code right-ans) ...)
(module+ test
(let* defs
(let ((real-ans code))
(unless (equal? real-ans right-ans)
(printf "Test failed: ~e gave ~e. Expected ~e\n"
'code real-ans 'right-ans))) ...)))))
An integer - set is ( make - integer - set ( listof ( cons int int ) ) )
;; Each cons represents a range of integers, and the entire
;; set is the union of the ranges. The ranges must be disjoint and
;; increasing. Further, adjacent ranges must have at least
one number between them .
(define-struct integer-set (contents) #:mutable
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(λ (set) 'integer-set)
(λ (set) (integer-set-contents set))))]
#:methods gen:equal+hash
[(define (equal-proc s1 s2 rec-equal?)
(rec-equal? (integer-set-contents s1)
(integer-set-contents s2)))
(define (hash-proc set rec-hash)
(rec-hash (integer-set-contents set)))
(define (hash2-proc set rec-hash)
(rec-hash (integer-set-contents set)))]
#:methods gen:stream
[(define (stream-empty? set)
(null? (integer-set-contents set)))
(define (stream-first set)
(define contents (integer-set-contents set))
;; the contract lets us assume non-null
(caar contents))
(define (stream-rest set)
(define contents (integer-set-contents set))
(match-define (cons low hi) (car contents))
(make-integer-set
(if (= low hi)
(cdr contents)
(cons (cons (+ 1 low) hi) (cdr contents)))))])
;; well-formed-set? : X -> bool
(define (well-formed-set? x)
(let loop ((set x)
(current-num -inf.0))
(or
(null? set)
(and (pair? set)
(pair? (car set))
(exact-integer? (caar set))
(exact-integer? (cdar set))
(< (add1 current-num) (caar set))
(<= (caar set) (cdar set))
(loop (cdr set) (cdar set))))))
(test-block ()
((well-formed-set? '((0 . 4) (7 . 9))) #t)
((well-formed-set? '((-1 . 4))) #t)
((well-formed-set? '((11 . 10))) #f)
((well-formed-set? '((0 . 10) (8 . 12))) #f)
((well-formed-set? '((10 . 20) (1 . 2))) #f)
((well-formed-set? '((-10 . -20))) #f)
((well-formed-set? '((-20 . -10))) #t)
((well-formed-set? '((1 . 1))) #t)
((well-formed-set? '((1 . 1) (2 . 3))) #f)
((well-formed-set? '((1 . 1) (3 . 3))) #t)
((well-formed-set? null) #t))
;; make-range : int * int -> integer-set
creates a set of integers between i and < = j
(define make-range
(case-lambda
(() (make-integer-set null))
((i) (make-integer-set (list (cons i i))))
((i j) (make-integer-set (list (cons i j))))))
(test-block ()
((integer-set-contents (make-range)) '())
((integer-set-contents (make-range 12)) '((12 . 12)))
((integer-set-contents (make-range 97 110)) '((97 . 110)))
((integer-set-contents (make-range 111 111)) '((111 . 111))))
;; sub-range? : (cons int int) (cons int int) -> bool
;; true iff the interval [(car r1), (cdr r1)] is a subset of
;; [(car r2), (cdr r2)]
(define (sub-range? r1 r2)
(and (>= (car r1) (car r2))
(<= (cdr r1) (cdr r2))))
;; overlap? : (cons int int) (cons int int) -> bool
;; true iff the intervals [(car r1), (cdr r1)] and [(car r2), (cdr r2)]
;; have non-empty intersections and (car r1) >= (car r2)
(define (overlap? r1 r2)
(and (>= (car r1) (car r2))
(>= (cdr r1) (cdr r2))
(<= (car r1) (cdr r2))))
merge - helper : ( listof ( cons int int ) ) ( listof ( cons int int ) ) - > ( listof ( cons int int ) )
(define (merge-helper s1 s2)
(cond
((null? s2) s1)
((null? s1) s2)
(else
(let ((r1 (car s1))
(r2 (car s2)))
(cond
((sub-range? r1 r2) (merge-helper (cdr s1) s2))
((sub-range? r2 r1) (merge-helper s1 (cdr s2)))
((or (overlap? r1 r2) (= (car r1) (add1 (cdr r2))))
(merge-helper (cons (cons (car r2) (cdr r1)) (cdr s1)) (cdr s2)))
((or (overlap? r2 r1) (= (car r2) (add1 (cdr r1))))
(merge-helper (cdr s1) (cons (cons (car r1) (cdr r2)) (cdr s2))))
((< (car r1) (car r2))
(cons r1 (merge-helper (cdr s1) s2)))
(else
(cons r2 (merge-helper s1 (cdr s2)))))))))
(test-block ()
((merge-helper null null) null)
((merge-helper null '((1 . 10))) '((1 . 10)))
((merge-helper '((1 . 10)) null) '((1 . 10)))
;; r1 in r2
((merge-helper '((5 . 10)) '((5 . 10))) '((5 . 10)))
((merge-helper '((6 . 9)) '((5 . 10))) '((5 . 10)))
((merge-helper '((7 . 7)) '((5 . 10))) '((5 . 10)))
;; r2 in r1
((merge-helper '((5 . 10)) '((5 . 10))) '((5 . 10)))
((merge-helper '((5 . 10)) '((6 . 9))) '((5 . 10)))
((merge-helper '((5 . 10)) '((7 . 7))) '((5 . 10)))
;; r2 and r1 are disjoint
((merge-helper '((5 . 10)) '((12 . 14))) '((5 . 10) (12 . 14)))
((merge-helper '((12 . 14)) '((5 . 10))) '((5 . 10) (12 . 14)))
;; r1 and r1 are adjacent
((merge-helper '((5 . 10)) '((11 . 13))) '((5 . 13)))
((merge-helper '((11 . 13)) '((5 . 10))) '((5 . 13)))
;; r1 and r2 overlap
((merge-helper '((5 . 10)) '((7 . 14))) '((5 . 14)))
((merge-helper '((7 . 14)) '((5 . 10))) '((5 . 14)))
((merge-helper '((5 . 10)) '((10 . 14))) '((5 . 14)))
((merge-helper '((7 . 10)) '((5 . 7))) '((5 . 10)))
;; with lists
((merge-helper '((1 . 1) (3 . 3) (5 . 10) (100 . 200))
'((2 . 2) (10 . 12) (300 . 300)))
'((1 . 3) (5 . 12) (100 . 200) (300 . 300)))
((merge-helper '((1 . 1) (3 . 3) (5 . 5) (8 . 8) (10 . 10) (12 . 12))
'((2 . 2) (4 . 4) (6 . 7) (9 . 9) (11 . 11)))
'((1 . 12)))
((merge-helper '((2 . 2) (4 . 4) (6 . 7) (9 . 9) (11 . 11))
'((1 . 1) (3 . 3) (5 . 5) (8 . 8) (10 . 10) (12 . 12)))
'((1 . 12))))
;; merge : integer-set integer-set -> integer-set
;; Union of s1 and s2
(define (merge s1 s2)
(make-integer-set (merge-helper (integer-set-contents s1) (integer-set-contents s2))))
;; split-sub-range : (cons int int) (cons int int) -> char-set
;; (subrange? r1 r2) must hold.
;; returns [(car r2), (cdr r2)] - ([(car r1), (cdr r1)] intersect [(car r2), (cdr r2)]).
(define (split-sub-range r1 r2)
(let ((r1-car (car r1))
(r1-cdr (cdr r1))
(r2-car (car r2))
(r2-cdr (cdr r2)))
(cond
((and (= r1-car r2-car) (= r1-cdr r2-cdr)) null)
((= r1-car r2-car) (list (cons (add1 r1-cdr) r2-cdr)))
((= r1-cdr r2-cdr) (list (cons r2-car (sub1 r1-car))))
(else
(list (cons r2-car (sub1 r1-car)) (cons (add1 r1-cdr) r2-cdr))))))
(test-block ()
((split-sub-range '(1 . 10) '(1 . 10)) '())
((split-sub-range '(1 . 5) '(1 . 10)) '((6 . 10)))
((split-sub-range '(2 . 10) '(1 . 10)) '((1 . 1)))
((split-sub-range '(2 . 5) '(1 . 10)) '((1 . 1) (6 . 10))))
split - acc : ( listof ( cons int int))^5 - > integer - set^3
(define (split-acc s1 s2 i s1-i s2-i)
(cond
((null? s1) (values (make-integer-set (reverse i))
(make-integer-set (reverse s1-i))
(make-integer-set (reverse (append (reverse s2) s2-i)))))
((null? s2) (values (make-integer-set (reverse i))
(make-integer-set (reverse (append (reverse s1) s1-i)))
(make-integer-set (reverse s2-i))))
(else
(let ((r1 (car s1))
(r2 (car s2)))
(cond
((sub-range? r1 r2)
(split-acc (cdr s1) (append (split-sub-range r1 r2) (cdr s2))
(cons r1 i) s1-i s2-i))
((sub-range? r2 r1)
(split-acc (append (split-sub-range r2 r1) (cdr s1)) (cdr s2)
(cons r2 i) s1-i s2-i))
((overlap? r1 r2)
(split-acc (cons (cons (add1 (cdr r2)) (cdr r1)) (cdr s1))
(cdr s2)
(cons (cons (car r1) (cdr r2)) i)
s1-i
(cons (cons (car r2) (sub1 (car r1))) s2-i)))
((overlap? r2 r1)
(split-acc (cdr s1)
(cons (cons (add1 (cdr r1)) (cdr r2)) (cdr s2))
(cons (cons (car r2) (cdr r1)) i)
(cons (cons (car r1) (sub1 (car r2)))s1-i )
s2-i))
((< (car r1) (car r2))
(split-acc (cdr s1) s2 i (cons r1 s1-i) s2-i))
(else
(split-acc s1 (cdr s2) i s1-i (cons r2 s2-i))))))))
;; split : integer-set integer-set -> integer-set integer-set integer-set
;; returns (s1 intersect s2), s1 - (s1 intersect s2) and s2 - (s1 intersect s2)
;; Of course, s1 - (s1 intersect s2) = s1 intersect (complement s2) = s1 - s2
(define (split s1 s2)
(split-acc (integer-set-contents s1) (integer-set-contents s2) null null null))
;; intersect: integer-set integer-set -> integer-set
(define (intersect s1 s2)
(let-values (((i s1-s2 s2-s1) (split s1 s2)))
i))
;; subtract: integer-set integer-set -> integer-set
(define (subtract s1 s2)
(let-values (((i s1-s2 s2-s1) (split s1 s2)))
s1-s2))
;; symmetric-difference: integer-set integer-set -> integer-set
(define (symmetric-difference s1 s2)
(let-values (((i s1-s2 s2-s1) (split s1 s2)))
(merge s1-s2 s2-s1)))
(test-block ((s (lambda (s1 s2)
(map integer-set-contents
(call-with-values (lambda () (split (make-integer-set s1)
(make-integer-set s2))) list)))))
((s null null) '(() () ()))
((s '((1 . 10)) null) '(() ((1 . 10)) ()))
((s null '((1 . 10))) '(() () ((1 . 10))))
((s '((1 . 10)) null) '(() ((1 . 10)) ()))
((s '((1 . 10)) '((1 . 10))) '(((1 . 10)) () ()))
((s '((1 . 10)) '((2 . 5))) '(((2 . 5)) ((1 . 1) (6 . 10)) ()))
((s '((2 . 5)) '((1 . 10))) '(((2 . 5)) () ((1 . 1) (6 . 10))))
((s '((2 . 5)) '((5 . 10))) '(((5 . 5)) ((2 . 4)) ((6 . 10))))
((s '((5 . 10)) '((2 . 5))) '(((5 . 5)) ((6 . 10)) ((2 . 4))))
((s '((2 . 10)) '((5 . 14))) '(((5 . 10)) ((2 . 4)) ((11 . 14))))
((s '((5 . 14)) '((2 . 10))) '(((5 . 10)) ((11 . 14)) ((2 . 4))))
((s '((10 . 20)) '((30 . 50))) '(() ((10 . 20)) ((30 . 50))))
((s '((100 . 200)) '((30 . 50))) '(() ((100 . 200)) ((30 . 50))))
((s '((1 . 5) (7 . 9) (100 . 200) (500 . 600) (600 . 700))
'((2 . 8) (50 . 60) (101 . 104) (105 . 220)))
'(((2 . 5) (7 . 8) (101 . 104) (105 . 200))
((1 . 1) (9 . 9) (100 . 100) (500 . 600) (600 . 700))
((6 . 6) (50 . 60) (201 . 220))))
((s '((2 . 8) (50 . 60) (101 . 104) (105 . 220))
'((1 . 5) (7 . 9) (100 . 200) (500 . 600) (600 . 700)))
'(((2 . 5) (7 . 8) (101 . 104) (105 . 200))
((6 . 6) (50 . 60) (201 . 220))
((1 . 1) (9 . 9) (100 . 100) (500 . 600) (600 . 700))))
)
complement - helper : ( listof ( cons int int ) ) int int - > ( listof ( cons int int ) )
;; The current-nat accumulator keeps track of where the
;; next range in the complement should start.
(define (complement-helper s min max)
(cond
((null? s) (if (<= min max)
(list (cons min max))
null))
(else
(let ((s-car (car s)))
(cond
((< min (car s-car))
(cons (cons min (sub1 (car s-car)))
(complement-helper (cdr s) (add1 (cdr s-car)) max)))
((<= min (cdr s-car))
(complement-helper (cdr s) (add1 (cdr s-car)) max))
(else
(complement-helper (cdr s) min max)))))))
;; complement : integer-set int int -> integer-set
A set of all the nats not in s and between min and , inclusive .
;; min <= max
(define (complement s min max)
(make-integer-set (complement-helper (integer-set-contents s) min max)))
(test-block ((c (lambda (a b c)
(integer-set-contents (complement (make-integer-set a) b c)))))
((c null 0 255) '((0 . 255)))
((c '((1 . 5) (7 . 7) (10 . 200)) 0 255)
'((0 . 0) (6 . 6) (8 . 9) (201 . 255)))
((c '((0 . 254)) 0 255) '((255 . 255)))
((c '((1 . 255)) 0 255) '((0 . 0)))
((c '((0 . 255)) 0 255) null)
((c '((1 . 10)) 2 5) null)
((c '((1 . 5) (7 . 12)) 2 8) '((6 . 6)))
((c '((1 . 5) (7 . 12)) 6 6) '((6 . 6)))
((c '((1 . 5) (7 . 12)) 7 7) '()))
member?-helper : int ( listof ( cons int int ) ) - > bool
(define (member?-helper i is)
(and
(pair? is)
(or (<= (caar is) i (cdar is))
(member?-helper i (cdr is)))))
;; member? : int integer-set -> bool
(define (member? i is)
(member?-helper i (integer-set-contents is)))
(test-block ()
((member? 1 (make-integer-set null)) #f)
((member? 19 (make-integer-set '((1 . 18) (20 . 21)))) #f)
((member? 19 (make-integer-set '((1 . 2) (19 . 19) (20 . 21)))) #t))
;; get-integer : integer-set -> (union int #f)
(define (get-integer is)
(let ((l (integer-set-contents is)))
(cond
((null? l) #f)
(else (caar l)))))
(test-block ()
((get-integer (make-integer-set null)) #f)
((get-integer (make-integer-set '((1 . 2) (5 . 6)))) 1))
is - foldr - helper : ( int Y - > Y ) Y int int ( listof ( cons int int ) ) - > Y
(define (is-foldr-helper f base start stop is)
(cond
((and (> start stop) (null? is)) base)
((> start stop)
(is-foldr-helper f base (caar is) (cdar is) (cdr is)))
(else
(f start
(is-foldr-helper f base (add1 start) stop is)))))
;; is-foldr : (int Y -> Y) Y integer-set -> Y
(define (is-foldr f base is)
(let ((l (integer-set-contents is)))
(cond
((null? l) base)
(else
(is-foldr-helper f base (caar l) (cdar l) (cdr l))))))
(test-block ()
((is-foldr cons null (make-integer-set null)) null)
((is-foldr cons null (make-integer-set '((1 . 2) (5 . 10))))
'(1 2 5 6 7 8 9 10)))
partition : ( listof integer - set ) - > ( listof integer - set )
;; The coarsest refinment r of sets such that the integer-sets in r
;; are pairwise disjoint.
(define (partition sets)
(map make-integer-set (foldr partition1 null sets)))
: integer - set ( listof ( listof ( cons int int ) ) ) - > ( listof ( listof ( cons int int ) ) )
;; All the integer-sets in sets must be pairwise disjoint. Splits set
;; against each element in sets.
(define (partition1 set sets)
(let ((set (integer-set-contents set)))
(cond
((null? set) sets)
((null? sets) (list set))
(else
(let ((set2 (car sets)))
(let-values (((i s1 s2) (split-acc set set2 null null null)))
(let ((rest (partition1 s1 (cdr sets)))
(i (integer-set-contents i))
(s2 (integer-set-contents s2)))
(cond
((null? i)
(cons s2 rest))
((null? s2)
(cons i rest))
(else
(cons i (cons s2 rest)))))))))))
(test-block ((->is (lambda (str)
(foldr (lambda (c cs)
(merge (make-range (char->integer c))
cs))
(make-range)
(string->list str))))
(->is2 (lambda (str)
(integer-set-contents (->is str)))))
((partition null) null)
((map integer-set-contents (partition (list (->is "1234")))) (list (->is2 "1234")))
((map integer-set-contents (partition (list (->is "1234") (->is "0235"))))
(list (->is2 "23") (->is2 "05") (->is2 "14")))
((map integer-set-contents (partition (list (->is "12349") (->is "02359") (->is "67") (->is "29"))))
(list (->is2 "29") (->is2 "67") (->is2 "3") (->is2 "05") (->is2 "14")))
((partition1 (->is "bcdjw") null) (list (->is2 "bcdjw")))
((partition1 (->is "") null) null)
((partition1 (->is "") (list (->is2 "a") (->is2 "b") (->is2 "1")))
(list (->is2 "a") (->is2 "b") (->is2 "1")))
((partition1 (->is "bcdjw")
(list (->is2 "z")
(->is2 "ab")
(->is2 "dj")))
(list (->is2 "z") (->is2 "b") (->is2 "a") (->is2 "dj") (->is2 "cw"))))
;; count : integer-set -> nat
(define (count s)
(foldr (lambda (range sum) (+ 1 sum (- (cdr range) (car range))))
0
(integer-set-contents s)))
(test-block ()
((count (make-integer-set null)) 0)
((count (make-integer-set '((1 . 1)))) 1)
((count (make-integer-set '((-1 . 10)))) 12)
((count (make-integer-set '((-10 . -5) (-1 . 10) (12 . 12)))) 19))
subset?-helper : ( listof ( cons int int ) ) ( listof ( cons int int ) ) - > bool
(define (subset?-helper l1 l2)
(cond
((null? l1) #t)
((null? l2) #f)
(else
(let ((r1 (car l1))
(r2 (car l2)))
(cond
((sub-range? r1 r2) (subset?-helper (cdr l1) l2))
((<= (car r1) (cdr r2)) #f)
(else (subset?-helper l1 (cdr l2))))))))
(test-block ()
((subset?-helper null null) #t)
((subset?-helper null '((1 . 1))) #t)
((subset?-helper '((1 . 1)) null) #f)
((subset?-helper '((1 . 1)) '((0 . 10))) #t)
((subset?-helper '((1 . 1)) '((2 . 10))) #f)
((subset?-helper '((-4 . -4) (2 . 10)) '((-20 . -17) (-15 . -10) (-5 . -4) (-2 . 0) (1 . 12))) #t)
((subset?-helper '((-4 . -3) (2 . 10)) '((-20 . -17) (-15 . -10) (-5 . -4) (-2 . 0) (1 . 12))) #f)
((subset?-helper '((-4 . -4) (2 . 10)) '((-20 . -17) (-15 . -10) (-5 . -4) (-2 . 0) (3 . 12))) #f))
;; subset? : integer-set integer-set -> bool
(define (subset? s1 s2)
(subset?-helper (integer-set-contents s1) (integer-set-contents s2)))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/data/integer-set.rkt | racket | a library for integer interval sets
test macro, now updated to use submodules
Each cons represents a range of integers, and the entire
set is the union of the ranges. The ranges must be disjoint and
increasing. Further, adjacent ranges must have at least
the contract lets us assume non-null
well-formed-set? : X -> bool
make-range : int * int -> integer-set
sub-range? : (cons int int) (cons int int) -> bool
true iff the interval [(car r1), (cdr r1)] is a subset of
[(car r2), (cdr r2)]
overlap? : (cons int int) (cons int int) -> bool
true iff the intervals [(car r1), (cdr r1)] and [(car r2), (cdr r2)]
have non-empty intersections and (car r1) >= (car r2)
r1 in r2
r2 in r1
r2 and r1 are disjoint
r1 and r1 are adjacent
r1 and r2 overlap
with lists
merge : integer-set integer-set -> integer-set
Union of s1 and s2
split-sub-range : (cons int int) (cons int int) -> char-set
(subrange? r1 r2) must hold.
returns [(car r2), (cdr r2)] - ([(car r1), (cdr r1)] intersect [(car r2), (cdr r2)]).
split : integer-set integer-set -> integer-set integer-set integer-set
returns (s1 intersect s2), s1 - (s1 intersect s2) and s2 - (s1 intersect s2)
Of course, s1 - (s1 intersect s2) = s1 intersect (complement s2) = s1 - s2
intersect: integer-set integer-set -> integer-set
subtract: integer-set integer-set -> integer-set
symmetric-difference: integer-set integer-set -> integer-set
The current-nat accumulator keeps track of where the
next range in the complement should start.
complement : integer-set int int -> integer-set
min <= max
member? : int integer-set -> bool
get-integer : integer-set -> (union int #f)
is-foldr : (int Y -> Y) Y integer-set -> Y
The coarsest refinment r of sets such that the integer-sets in r
are pairwise disjoint.
All the integer-sets in sets must be pairwise disjoint. Splits set
against each element in sets.
count : integer-set -> nat
subset? : integer-set integer-set -> bool | #lang racket/base
(require racket/contract/base
racket/match
racket/stream
racket/struct)
(provide well-formed-set?
(contract-out
(struct integer-set ((contents well-formed-set?)))
[make-range
(->i () ((i exact-integer?) (j (i) (and/c exact-integer? (>=/c i))))
[res integer-set?])]
[rename merge union (integer-set? integer-set? . -> . integer-set?)]
[split (integer-set? integer-set?
. -> .
(values integer-set? integer-set? integer-set?))]
[intersect (integer-set? integer-set? . -> . integer-set?)]
[subtract (integer-set? integer-set? . -> . integer-set?)]
[symmetric-difference
(integer-set? integer-set? . -> . integer-set?)]
[complement (->i ((s integer-set?) (min exact-integer?)
(max (min) (and/c exact-integer? (>=/c min))))
[res integer-set?])]
[member? (exact-integer? integer-set? . -> . any)]
[get-integer (integer-set? . -> . (or/c #f exact-integer?))]
[rename is-foldr foldr (any/c any/c integer-set? . -> . any)]
[partition ((listof integer-set?) . -> . (listof integer-set?))]
[count (integer-set? . -> . natural-number/c)]
[subset? (integer-set? integer-set? . -> . any)]))
(define-syntax test-block
(syntax-rules ()
((_ defs (code right-ans) ...)
(module+ test
(let* defs
(let ((real-ans code))
(unless (equal? real-ans right-ans)
(printf "Test failed: ~e gave ~e. Expected ~e\n"
'code real-ans 'right-ans))) ...)))))
An integer - set is ( make - integer - set ( listof ( cons int int ) ) )
one number between them .
(define-struct integer-set (contents) #:mutable
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(λ (set) 'integer-set)
(λ (set) (integer-set-contents set))))]
#:methods gen:equal+hash
[(define (equal-proc s1 s2 rec-equal?)
(rec-equal? (integer-set-contents s1)
(integer-set-contents s2)))
(define (hash-proc set rec-hash)
(rec-hash (integer-set-contents set)))
(define (hash2-proc set rec-hash)
(rec-hash (integer-set-contents set)))]
#:methods gen:stream
[(define (stream-empty? set)
(null? (integer-set-contents set)))
(define (stream-first set)
(define contents (integer-set-contents set))
(caar contents))
(define (stream-rest set)
(define contents (integer-set-contents set))
(match-define (cons low hi) (car contents))
(make-integer-set
(if (= low hi)
(cdr contents)
(cons (cons (+ 1 low) hi) (cdr contents)))))])
(define (well-formed-set? x)
(let loop ((set x)
(current-num -inf.0))
(or
(null? set)
(and (pair? set)
(pair? (car set))
(exact-integer? (caar set))
(exact-integer? (cdar set))
(< (add1 current-num) (caar set))
(<= (caar set) (cdar set))
(loop (cdr set) (cdar set))))))
(test-block ()
((well-formed-set? '((0 . 4) (7 . 9))) #t)
((well-formed-set? '((-1 . 4))) #t)
((well-formed-set? '((11 . 10))) #f)
((well-formed-set? '((0 . 10) (8 . 12))) #f)
((well-formed-set? '((10 . 20) (1 . 2))) #f)
((well-formed-set? '((-10 . -20))) #f)
((well-formed-set? '((-20 . -10))) #t)
((well-formed-set? '((1 . 1))) #t)
((well-formed-set? '((1 . 1) (2 . 3))) #f)
((well-formed-set? '((1 . 1) (3 . 3))) #t)
((well-formed-set? null) #t))
creates a set of integers between i and < = j
(define make-range
(case-lambda
(() (make-integer-set null))
((i) (make-integer-set (list (cons i i))))
((i j) (make-integer-set (list (cons i j))))))
(test-block ()
((integer-set-contents (make-range)) '())
((integer-set-contents (make-range 12)) '((12 . 12)))
((integer-set-contents (make-range 97 110)) '((97 . 110)))
((integer-set-contents (make-range 111 111)) '((111 . 111))))
(define (sub-range? r1 r2)
(and (>= (car r1) (car r2))
(<= (cdr r1) (cdr r2))))
(define (overlap? r1 r2)
(and (>= (car r1) (car r2))
(>= (cdr r1) (cdr r2))
(<= (car r1) (cdr r2))))
merge - helper : ( listof ( cons int int ) ) ( listof ( cons int int ) ) - > ( listof ( cons int int ) )
(define (merge-helper s1 s2)
(cond
((null? s2) s1)
((null? s1) s2)
(else
(let ((r1 (car s1))
(r2 (car s2)))
(cond
((sub-range? r1 r2) (merge-helper (cdr s1) s2))
((sub-range? r2 r1) (merge-helper s1 (cdr s2)))
((or (overlap? r1 r2) (= (car r1) (add1 (cdr r2))))
(merge-helper (cons (cons (car r2) (cdr r1)) (cdr s1)) (cdr s2)))
((or (overlap? r2 r1) (= (car r2) (add1 (cdr r1))))
(merge-helper (cdr s1) (cons (cons (car r1) (cdr r2)) (cdr s2))))
((< (car r1) (car r2))
(cons r1 (merge-helper (cdr s1) s2)))
(else
(cons r2 (merge-helper s1 (cdr s2)))))))))
(test-block ()
((merge-helper null null) null)
((merge-helper null '((1 . 10))) '((1 . 10)))
((merge-helper '((1 . 10)) null) '((1 . 10)))
((merge-helper '((5 . 10)) '((5 . 10))) '((5 . 10)))
((merge-helper '((6 . 9)) '((5 . 10))) '((5 . 10)))
((merge-helper '((7 . 7)) '((5 . 10))) '((5 . 10)))
((merge-helper '((5 . 10)) '((5 . 10))) '((5 . 10)))
((merge-helper '((5 . 10)) '((6 . 9))) '((5 . 10)))
((merge-helper '((5 . 10)) '((7 . 7))) '((5 . 10)))
((merge-helper '((5 . 10)) '((12 . 14))) '((5 . 10) (12 . 14)))
((merge-helper '((12 . 14)) '((5 . 10))) '((5 . 10) (12 . 14)))
((merge-helper '((5 . 10)) '((11 . 13))) '((5 . 13)))
((merge-helper '((11 . 13)) '((5 . 10))) '((5 . 13)))
((merge-helper '((5 . 10)) '((7 . 14))) '((5 . 14)))
((merge-helper '((7 . 14)) '((5 . 10))) '((5 . 14)))
((merge-helper '((5 . 10)) '((10 . 14))) '((5 . 14)))
((merge-helper '((7 . 10)) '((5 . 7))) '((5 . 10)))
((merge-helper '((1 . 1) (3 . 3) (5 . 10) (100 . 200))
'((2 . 2) (10 . 12) (300 . 300)))
'((1 . 3) (5 . 12) (100 . 200) (300 . 300)))
((merge-helper '((1 . 1) (3 . 3) (5 . 5) (8 . 8) (10 . 10) (12 . 12))
'((2 . 2) (4 . 4) (6 . 7) (9 . 9) (11 . 11)))
'((1 . 12)))
((merge-helper '((2 . 2) (4 . 4) (6 . 7) (9 . 9) (11 . 11))
'((1 . 1) (3 . 3) (5 . 5) (8 . 8) (10 . 10) (12 . 12)))
'((1 . 12))))
(define (merge s1 s2)
(make-integer-set (merge-helper (integer-set-contents s1) (integer-set-contents s2))))
(define (split-sub-range r1 r2)
(let ((r1-car (car r1))
(r1-cdr (cdr r1))
(r2-car (car r2))
(r2-cdr (cdr r2)))
(cond
((and (= r1-car r2-car) (= r1-cdr r2-cdr)) null)
((= r1-car r2-car) (list (cons (add1 r1-cdr) r2-cdr)))
((= r1-cdr r2-cdr) (list (cons r2-car (sub1 r1-car))))
(else
(list (cons r2-car (sub1 r1-car)) (cons (add1 r1-cdr) r2-cdr))))))
(test-block ()
((split-sub-range '(1 . 10) '(1 . 10)) '())
((split-sub-range '(1 . 5) '(1 . 10)) '((6 . 10)))
((split-sub-range '(2 . 10) '(1 . 10)) '((1 . 1)))
((split-sub-range '(2 . 5) '(1 . 10)) '((1 . 1) (6 . 10))))
split - acc : ( listof ( cons int int))^5 - > integer - set^3
(define (split-acc s1 s2 i s1-i s2-i)
(cond
((null? s1) (values (make-integer-set (reverse i))
(make-integer-set (reverse s1-i))
(make-integer-set (reverse (append (reverse s2) s2-i)))))
((null? s2) (values (make-integer-set (reverse i))
(make-integer-set (reverse (append (reverse s1) s1-i)))
(make-integer-set (reverse s2-i))))
(else
(let ((r1 (car s1))
(r2 (car s2)))
(cond
((sub-range? r1 r2)
(split-acc (cdr s1) (append (split-sub-range r1 r2) (cdr s2))
(cons r1 i) s1-i s2-i))
((sub-range? r2 r1)
(split-acc (append (split-sub-range r2 r1) (cdr s1)) (cdr s2)
(cons r2 i) s1-i s2-i))
((overlap? r1 r2)
(split-acc (cons (cons (add1 (cdr r2)) (cdr r1)) (cdr s1))
(cdr s2)
(cons (cons (car r1) (cdr r2)) i)
s1-i
(cons (cons (car r2) (sub1 (car r1))) s2-i)))
((overlap? r2 r1)
(split-acc (cdr s1)
(cons (cons (add1 (cdr r1)) (cdr r2)) (cdr s2))
(cons (cons (car r2) (cdr r1)) i)
(cons (cons (car r1) (sub1 (car r2)))s1-i )
s2-i))
((< (car r1) (car r2))
(split-acc (cdr s1) s2 i (cons r1 s1-i) s2-i))
(else
(split-acc s1 (cdr s2) i s1-i (cons r2 s2-i))))))))
(define (split s1 s2)
(split-acc (integer-set-contents s1) (integer-set-contents s2) null null null))
(define (intersect s1 s2)
(let-values (((i s1-s2 s2-s1) (split s1 s2)))
i))
(define (subtract s1 s2)
(let-values (((i s1-s2 s2-s1) (split s1 s2)))
s1-s2))
(define (symmetric-difference s1 s2)
(let-values (((i s1-s2 s2-s1) (split s1 s2)))
(merge s1-s2 s2-s1)))
(test-block ((s (lambda (s1 s2)
(map integer-set-contents
(call-with-values (lambda () (split (make-integer-set s1)
(make-integer-set s2))) list)))))
((s null null) '(() () ()))
((s '((1 . 10)) null) '(() ((1 . 10)) ()))
((s null '((1 . 10))) '(() () ((1 . 10))))
((s '((1 . 10)) null) '(() ((1 . 10)) ()))
((s '((1 . 10)) '((1 . 10))) '(((1 . 10)) () ()))
((s '((1 . 10)) '((2 . 5))) '(((2 . 5)) ((1 . 1) (6 . 10)) ()))
((s '((2 . 5)) '((1 . 10))) '(((2 . 5)) () ((1 . 1) (6 . 10))))
((s '((2 . 5)) '((5 . 10))) '(((5 . 5)) ((2 . 4)) ((6 . 10))))
((s '((5 . 10)) '((2 . 5))) '(((5 . 5)) ((6 . 10)) ((2 . 4))))
((s '((2 . 10)) '((5 . 14))) '(((5 . 10)) ((2 . 4)) ((11 . 14))))
((s '((5 . 14)) '((2 . 10))) '(((5 . 10)) ((11 . 14)) ((2 . 4))))
((s '((10 . 20)) '((30 . 50))) '(() ((10 . 20)) ((30 . 50))))
((s '((100 . 200)) '((30 . 50))) '(() ((100 . 200)) ((30 . 50))))
((s '((1 . 5) (7 . 9) (100 . 200) (500 . 600) (600 . 700))
'((2 . 8) (50 . 60) (101 . 104) (105 . 220)))
'(((2 . 5) (7 . 8) (101 . 104) (105 . 200))
((1 . 1) (9 . 9) (100 . 100) (500 . 600) (600 . 700))
((6 . 6) (50 . 60) (201 . 220))))
((s '((2 . 8) (50 . 60) (101 . 104) (105 . 220))
'((1 . 5) (7 . 9) (100 . 200) (500 . 600) (600 . 700)))
'(((2 . 5) (7 . 8) (101 . 104) (105 . 200))
((6 . 6) (50 . 60) (201 . 220))
((1 . 1) (9 . 9) (100 . 100) (500 . 600) (600 . 700))))
)
complement - helper : ( listof ( cons int int ) ) int int - > ( listof ( cons int int ) )
(define (complement-helper s min max)
(cond
((null? s) (if (<= min max)
(list (cons min max))
null))
(else
(let ((s-car (car s)))
(cond
((< min (car s-car))
(cons (cons min (sub1 (car s-car)))
(complement-helper (cdr s) (add1 (cdr s-car)) max)))
((<= min (cdr s-car))
(complement-helper (cdr s) (add1 (cdr s-car)) max))
(else
(complement-helper (cdr s) min max)))))))
A set of all the nats not in s and between min and , inclusive .
(define (complement s min max)
(make-integer-set (complement-helper (integer-set-contents s) min max)))
(test-block ((c (lambda (a b c)
(integer-set-contents (complement (make-integer-set a) b c)))))
((c null 0 255) '((0 . 255)))
((c '((1 . 5) (7 . 7) (10 . 200)) 0 255)
'((0 . 0) (6 . 6) (8 . 9) (201 . 255)))
((c '((0 . 254)) 0 255) '((255 . 255)))
((c '((1 . 255)) 0 255) '((0 . 0)))
((c '((0 . 255)) 0 255) null)
((c '((1 . 10)) 2 5) null)
((c '((1 . 5) (7 . 12)) 2 8) '((6 . 6)))
((c '((1 . 5) (7 . 12)) 6 6) '((6 . 6)))
((c '((1 . 5) (7 . 12)) 7 7) '()))
member?-helper : int ( listof ( cons int int ) ) - > bool
(define (member?-helper i is)
(and
(pair? is)
(or (<= (caar is) i (cdar is))
(member?-helper i (cdr is)))))
(define (member? i is)
(member?-helper i (integer-set-contents is)))
(test-block ()
((member? 1 (make-integer-set null)) #f)
((member? 19 (make-integer-set '((1 . 18) (20 . 21)))) #f)
((member? 19 (make-integer-set '((1 . 2) (19 . 19) (20 . 21)))) #t))
(define (get-integer is)
(let ((l (integer-set-contents is)))
(cond
((null? l) #f)
(else (caar l)))))
(test-block ()
((get-integer (make-integer-set null)) #f)
((get-integer (make-integer-set '((1 . 2) (5 . 6)))) 1))
is - foldr - helper : ( int Y - > Y ) Y int int ( listof ( cons int int ) ) - > Y
(define (is-foldr-helper f base start stop is)
(cond
((and (> start stop) (null? is)) base)
((> start stop)
(is-foldr-helper f base (caar is) (cdar is) (cdr is)))
(else
(f start
(is-foldr-helper f base (add1 start) stop is)))))
(define (is-foldr f base is)
(let ((l (integer-set-contents is)))
(cond
((null? l) base)
(else
(is-foldr-helper f base (caar l) (cdar l) (cdr l))))))
(test-block ()
((is-foldr cons null (make-integer-set null)) null)
((is-foldr cons null (make-integer-set '((1 . 2) (5 . 10))))
'(1 2 5 6 7 8 9 10)))
partition : ( listof integer - set ) - > ( listof integer - set )
(define (partition sets)
(map make-integer-set (foldr partition1 null sets)))
: integer - set ( listof ( listof ( cons int int ) ) ) - > ( listof ( listof ( cons int int ) ) )
(define (partition1 set sets)
(let ((set (integer-set-contents set)))
(cond
((null? set) sets)
((null? sets) (list set))
(else
(let ((set2 (car sets)))
(let-values (((i s1 s2) (split-acc set set2 null null null)))
(let ((rest (partition1 s1 (cdr sets)))
(i (integer-set-contents i))
(s2 (integer-set-contents s2)))
(cond
((null? i)
(cons s2 rest))
((null? s2)
(cons i rest))
(else
(cons i (cons s2 rest)))))))))))
(test-block ((->is (lambda (str)
(foldr (lambda (c cs)
(merge (make-range (char->integer c))
cs))
(make-range)
(string->list str))))
(->is2 (lambda (str)
(integer-set-contents (->is str)))))
((partition null) null)
((map integer-set-contents (partition (list (->is "1234")))) (list (->is2 "1234")))
((map integer-set-contents (partition (list (->is "1234") (->is "0235"))))
(list (->is2 "23") (->is2 "05") (->is2 "14")))
((map integer-set-contents (partition (list (->is "12349") (->is "02359") (->is "67") (->is "29"))))
(list (->is2 "29") (->is2 "67") (->is2 "3") (->is2 "05") (->is2 "14")))
((partition1 (->is "bcdjw") null) (list (->is2 "bcdjw")))
((partition1 (->is "") null) null)
((partition1 (->is "") (list (->is2 "a") (->is2 "b") (->is2 "1")))
(list (->is2 "a") (->is2 "b") (->is2 "1")))
((partition1 (->is "bcdjw")
(list (->is2 "z")
(->is2 "ab")
(->is2 "dj")))
(list (->is2 "z") (->is2 "b") (->is2 "a") (->is2 "dj") (->is2 "cw"))))
(define (count s)
(foldr (lambda (range sum) (+ 1 sum (- (cdr range) (car range))))
0
(integer-set-contents s)))
(test-block ()
((count (make-integer-set null)) 0)
((count (make-integer-set '((1 . 1)))) 1)
((count (make-integer-set '((-1 . 10)))) 12)
((count (make-integer-set '((-10 . -5) (-1 . 10) (12 . 12)))) 19))
subset?-helper : ( listof ( cons int int ) ) ( listof ( cons int int ) ) - > bool
(define (subset?-helper l1 l2)
(cond
((null? l1) #t)
((null? l2) #f)
(else
(let ((r1 (car l1))
(r2 (car l2)))
(cond
((sub-range? r1 r2) (subset?-helper (cdr l1) l2))
((<= (car r1) (cdr r2)) #f)
(else (subset?-helper l1 (cdr l2))))))))
(test-block ()
((subset?-helper null null) #t)
((subset?-helper null '((1 . 1))) #t)
((subset?-helper '((1 . 1)) null) #f)
((subset?-helper '((1 . 1)) '((0 . 10))) #t)
((subset?-helper '((1 . 1)) '((2 . 10))) #f)
((subset?-helper '((-4 . -4) (2 . 10)) '((-20 . -17) (-15 . -10) (-5 . -4) (-2 . 0) (1 . 12))) #t)
((subset?-helper '((-4 . -3) (2 . 10)) '((-20 . -17) (-15 . -10) (-5 . -4) (-2 . 0) (1 . 12))) #f)
((subset?-helper '((-4 . -4) (2 . 10)) '((-20 . -17) (-15 . -10) (-5 . -4) (-2 . 0) (3 . 12))) #f))
(define (subset? s1 s2)
(subset?-helper (integer-set-contents s1) (integer-set-contents s2)))
|
d6cce2b42c390c9964a6cb67d5622072922d7633c7b810e94069f5f267b7cc11 | typelead/intellij-eta | PsiElement.hs | module FFI.Com.IntelliJ.Psi.PsiElement where
import P
data {-# CLASS "com.intellij.psi.PsiElement" #-}
PsiElement = PsiElement (Object# PsiElement)
deriving Class
| null | https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Com/IntelliJ/Psi/PsiElement.hs | haskell | # CLASS "com.intellij.psi.PsiElement" # | module FFI.Com.IntelliJ.Psi.PsiElement where
import P
PsiElement = PsiElement (Object# PsiElement)
deriving Class
|
cf243806592683dd0a165d6a36882e809dda261127c6833a22cbac4e0177ebc5 | wireless-net/erlang-nommu | wxPrinter.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxPrinter</a>.
%% @type wxPrinter(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxPrinter).
-include("wxe.hrl").
-export([createAbortWindow/3,destroy/1,getAbort/1,getLastError/0,getPrintDialogData/1,
new/0,new/1,print/3,print/4,printDialog/2,reportError/4,setup/2]).
%% inherited exports
-export([parent_class/1]).
-export_type([wxPrinter/0]).
%% @hidden
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-type wxPrinter() :: wx:wx_object().
%% @equiv new([])
-spec new() -> wxPrinter().
new() ->
new([]).
%% @doc See <a href="#wxprinterwxprinter">external documentation</a>.
-spec new([Option]) -> wxPrinter() when
Option :: {data, wxPrintDialogData:wxPrintDialogData()}.
new(Options)
when is_list(Options) ->
MOpts = fun({data, #wx_ref{type=DataT,ref=DataRef}}, Acc) -> ?CLASS(DataT,wxPrintDialogData),[<<1:32/?UI,DataRef:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxPrinter_new,
<<BinOpt/binary>>).
%% @doc See <a href="#wxprintercreateabortwindow">external documentation</a>.
-spec createAbortWindow(This, Parent, Printout) -> wxWindow:wxWindow() when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout().
createAbortWindow(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},#wx_ref{type=PrintoutT,ref=PrintoutRef}) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
?CLASS(PrintoutT,wxPrintout),
wxe_util:call(?wxPrinter_CreateAbortWindow,
<<ThisRef:32/?UI,ParentRef:32/?UI,PrintoutRef:32/?UI>>).
%% @doc See <a href="#wxprintergetabort">external documentation</a>.
-spec getAbort(This) -> boolean() when
This::wxPrinter().
getAbort(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxPrinter),
wxe_util:call(?wxPrinter_GetAbort,
<<ThisRef:32/?UI>>).
%% @doc See <a href="#wxprintergetlasterror">external documentation</a>.
%%<br /> Res = ?wxPRINTER_NO_ERROR | ?wxPRINTER_CANCELLED | ?wxPRINTER_ERROR
-spec getLastError() -> wx:wx_enum().
getLastError() ->
wxe_util:call(?wxPrinter_GetLastError,
<<>>).
%% @doc See <a href="#wxprintergetprintdialogdata">external documentation</a>.
-spec getPrintDialogData(This) -> wxPrintDialogData:wxPrintDialogData() when
This::wxPrinter().
getPrintDialogData(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxPrinter),
wxe_util:call(?wxPrinter_GetPrintDialogData,
<<ThisRef:32/?UI>>).
%% @equiv print(This,Parent,Printout, [])
-spec print(This, Parent, Printout) -> boolean() when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout().
print(This,Parent,Printout)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_record(Printout, wx_ref) ->
print(This,Parent,Printout, []).
%% @doc See <a href="#wxprinterprint">external documentation</a>.
-spec print(This, Parent, Printout, [Option]) -> boolean() when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout(),
Option :: {prompt, boolean()}.
print(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},#wx_ref{type=PrintoutT,ref=PrintoutRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
?CLASS(PrintoutT,wxPrintout),
MOpts = fun({prompt, Prompt}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Prompt)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxPrinter_Print,
<<ThisRef:32/?UI,ParentRef:32/?UI,PrintoutRef:32/?UI, 0:32,BinOpt/binary>>).
%% @doc See <a href="#wxprinterprintdialog">external documentation</a>.
-spec printDialog(This, Parent) -> wxDC:wxDC() when
This::wxPrinter(), Parent::wxWindow:wxWindow().
printDialog(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
wxe_util:call(?wxPrinter_PrintDialog,
<<ThisRef:32/?UI,ParentRef:32/?UI>>).
%% @doc See <a href="#wxprinterreporterror">external documentation</a>.
-spec reportError(This, Parent, Printout, Message) -> ok when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout(), Message::unicode:chardata().
reportError(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},#wx_ref{type=PrintoutT,ref=PrintoutRef},Message)
when is_list(Message) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
?CLASS(PrintoutT,wxPrintout),
Message_UC = unicode:characters_to_binary([Message,0]),
wxe_util:cast(?wxPrinter_ReportError,
<<ThisRef:32/?UI,ParentRef:32/?UI,PrintoutRef:32/?UI,(byte_size(Message_UC)):32/?UI,(Message_UC)/binary, 0:(((8- ((0+byte_size(Message_UC)) band 16#7)) band 16#7))/unit:8>>).
%% @doc See <a href="#wxprintersetup">external documentation</a>.
-spec setup(This, Parent) -> boolean() when
This::wxPrinter(), Parent::wxWindow:wxWindow().
setup(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
wxe_util:call(?wxPrinter_Setup,
<<ThisRef:32/?UI,ParentRef:32/?UI>>).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxPrinter()) -> ok.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxPrinter),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/wx/src/gen/wxPrinter.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxPrinter</a>.
@type wxPrinter(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
@equiv new([])
@doc See <a href="#wxprinterwxprinter">external documentation</a>.
@doc See <a href="#wxprintercreateabortwindow">external documentation</a>.
@doc See <a href="#wxprintergetabort">external documentation</a>.
@doc See <a href="#wxprintergetlasterror">external documentation</a>.
<br /> Res = ?wxPRINTER_NO_ERROR | ?wxPRINTER_CANCELLED | ?wxPRINTER_ERROR
@doc See <a href="#wxprintergetprintdialogdata">external documentation</a>.
@equiv print(This,Parent,Printout, [])
@doc See <a href="#wxprinterprint">external documentation</a>.
@doc See <a href="#wxprinterprintdialog">external documentation</a>.
@doc See <a href="#wxprinterreporterror">external documentation</a>.
@doc See <a href="#wxprintersetup">external documentation</a>.
@doc Destroys this object, do not use object again | Copyright Ericsson AB 2008 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxPrinter).
-include("wxe.hrl").
-export([createAbortWindow/3,destroy/1,getAbort/1,getLastError/0,getPrintDialogData/1,
new/0,new/1,print/3,print/4,printDialog/2,reportError/4,setup/2]).
-export([parent_class/1]).
-export_type([wxPrinter/0]).
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-type wxPrinter() :: wx:wx_object().
-spec new() -> wxPrinter().
new() ->
new([]).
-spec new([Option]) -> wxPrinter() when
Option :: {data, wxPrintDialogData:wxPrintDialogData()}.
new(Options)
when is_list(Options) ->
MOpts = fun({data, #wx_ref{type=DataT,ref=DataRef}}, Acc) -> ?CLASS(DataT,wxPrintDialogData),[<<1:32/?UI,DataRef:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxPrinter_new,
<<BinOpt/binary>>).
-spec createAbortWindow(This, Parent, Printout) -> wxWindow:wxWindow() when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout().
createAbortWindow(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},#wx_ref{type=PrintoutT,ref=PrintoutRef}) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
?CLASS(PrintoutT,wxPrintout),
wxe_util:call(?wxPrinter_CreateAbortWindow,
<<ThisRef:32/?UI,ParentRef:32/?UI,PrintoutRef:32/?UI>>).
-spec getAbort(This) -> boolean() when
This::wxPrinter().
getAbort(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxPrinter),
wxe_util:call(?wxPrinter_GetAbort,
<<ThisRef:32/?UI>>).
-spec getLastError() -> wx:wx_enum().
getLastError() ->
wxe_util:call(?wxPrinter_GetLastError,
<<>>).
-spec getPrintDialogData(This) -> wxPrintDialogData:wxPrintDialogData() when
This::wxPrinter().
getPrintDialogData(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxPrinter),
wxe_util:call(?wxPrinter_GetPrintDialogData,
<<ThisRef:32/?UI>>).
-spec print(This, Parent, Printout) -> boolean() when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout().
print(This,Parent,Printout)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_record(Printout, wx_ref) ->
print(This,Parent,Printout, []).
-spec print(This, Parent, Printout, [Option]) -> boolean() when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout(),
Option :: {prompt, boolean()}.
print(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},#wx_ref{type=PrintoutT,ref=PrintoutRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
?CLASS(PrintoutT,wxPrintout),
MOpts = fun({prompt, Prompt}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Prompt)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxPrinter_Print,
<<ThisRef:32/?UI,ParentRef:32/?UI,PrintoutRef:32/?UI, 0:32,BinOpt/binary>>).
-spec printDialog(This, Parent) -> wxDC:wxDC() when
This::wxPrinter(), Parent::wxWindow:wxWindow().
printDialog(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
wxe_util:call(?wxPrinter_PrintDialog,
<<ThisRef:32/?UI,ParentRef:32/?UI>>).
-spec reportError(This, Parent, Printout, Message) -> ok when
This::wxPrinter(), Parent::wxWindow:wxWindow(), Printout::wxPrintout:wxPrintout(), Message::unicode:chardata().
reportError(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},#wx_ref{type=PrintoutT,ref=PrintoutRef},Message)
when is_list(Message) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
?CLASS(PrintoutT,wxPrintout),
Message_UC = unicode:characters_to_binary([Message,0]),
wxe_util:cast(?wxPrinter_ReportError,
<<ThisRef:32/?UI,ParentRef:32/?UI,PrintoutRef:32/?UI,(byte_size(Message_UC)):32/?UI,(Message_UC)/binary, 0:(((8- ((0+byte_size(Message_UC)) band 16#7)) band 16#7))/unit:8>>).
-spec setup(This, Parent) -> boolean() when
This::wxPrinter(), Parent::wxWindow:wxWindow().
setup(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}) ->
?CLASS(ThisT,wxPrinter),
?CLASS(ParentT,wxWindow),
wxe_util:call(?wxPrinter_Setup,
<<ThisRef:32/?UI,ParentRef:32/?UI>>).
-spec destroy(This::wxPrinter()) -> ok.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxPrinter),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
|
4fb9b53f8bb87f4dd2eb7f16ef1d8d8e772def9c6cf0feffaaf17ca35502d05b | esl/MongooseIM | ct_markdown_errors_hook.erl | %%% @doc Writes a markdown file with error information
-module(ct_markdown_errors_hook).
%% @doc Add the following line in your *.spec file to enable this:
%% {ct_hooks, [ct_markdown_errors_hook]}.
%% Callbacks
-export([id/1]).
-export([init/2]).
-export([post_init_per_suite/4,
post_init_per_group/4,
post_init_per_testcase/4]).
-export([post_end_per_suite/4,
post_end_per_group/4,
post_end_per_testcase/4]).
-record(state, { file, summary_file, truncated_counter_file, suite, limit }).
%% @doc Return a unique id for this CTH.
id(_Opts) ->
"ct_markdown_errors_hook_001".
%% @doc Always called before any other callback function. Use this to initiate
%% any common state.
init(_Id, _Opts) ->
File = "/tmp/ct_markdown",
TrFile = "/tmp/ct_markdown_truncated",
SummaryFile = "/tmp/ct_summary",
file:write_file(File, ""),
file:write_file(SummaryFile, ""),
file:delete(TrFile),
{ok, #state{ file = File, summary_file = SummaryFile, truncated_counter_file = TrFile, limit = 25 }}.
post_init_per_suite(SuiteName, Config, Return, State) ->
State2 = handle_return(SuiteName, init_per_suite, Return, Config, State),
{Return, State2#state{suite = SuiteName}}.
post_init_per_group(_GroupName, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, init_per_group, Return, Config, State),
{Return, State2#state{}}.
post_init_per_testcase(TC, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, TC, Return, Config, State),
{Return, State2}.
post_end_per_suite(SuiteName, Config, Return, State) ->
State2 = handle_return(SuiteName, end_per_suite, Return, Config, State),
{Return, State2#state{suite = ''}}.
post_end_per_group(_GroupName, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, end_per_group, Return, Config, State),
{Return, State2#state{}}.
%% @doc Called after each test case.
post_end_per_testcase(TC, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, TC, Return, Config, State),
{Return, State2}.
handle_return(SuiteName, Place, Return, Config, State) ->
try handle_return_unsafe(SuiteName, Place, Return, Config, State)
catch Class:Error:StackTrace ->
ct:pal("issue=handle_return_unsafe_failed reason=~p:~p~n"
"stacktrace=~p", [Class, Error, StackTrace]),
State
end.
handle_return_unsafe(SuiteName, Place, Return, Config, State) ->
case to_error_message(Return) of
ok ->
State;
Error ->
FullGroupName = full_group_name(Config),
log_summary(SuiteName, FullGroupName, Place, State),
F = fun() ->
log_error(SuiteName, FullGroupName, Place, Error, Config, State)
end,
exec_limited_number_of_times(F, State)
end.
exec_limited_number_of_times(_F, State=#state{limit=0, file=_File,
truncated_counter_file = TrFile}) ->
%% Log truncated, increment counter
TrCounter = old_truncated_counter_value(TrFile),
file:write_file(TrFile, integer_to_binary(TrCounter+1)),
State;
exec_limited_number_of_times(F, State=#state{limit=Limit}) ->
F(),
State#state{limit=Limit-1}.
old_truncated_counter_value(TrFile) ->
case file:read_file(TrFile) of
{ok, Bin} ->
binary_to_integer(Bin);
_ ->
0
end.
log_summary(SuiteName, GroupName, Place, #state{summary_file = SummaryFile}) ->
SummaryText = make_summary_text(SuiteName, GroupName, Place),
file:write_file(SummaryFile, [SummaryText, $\n], [append]),
ok.
log_error(SuiteName, GroupName, Place, Error, Config, #state{file = File, summary_file = _SummaryFile}) ->
_MaybeLogLink = make_log_link(Config),
LogLink = make_log_link(Config),
syntax
%% -github/dear-github/issues/166
%% <details>
%% <summary>Click to expand</summary>
%% whatever
%% </details>
SummaryText = make_summary_text(SuiteName, GroupName, Place),
BinError = iolist_to_binary(io_lib:format("~p", [Error])),
Content = truncate_binary(1500, reindent(BinError)),
%% Don't use exml here to avoid escape errors
Out = <<"<details><summary>", SummaryText/binary, "</summary>\n"
"\n\n```erlang\n", Content/binary, "\n```\n",
LogLink/binary, "</details>\n">>,
file:write_file(File, Out, [append]),
ok.
make_summary_text(SuiteName, '', '') ->
atom_to_binary(SuiteName, utf8);
make_summary_text(SuiteName, '', TC) ->
BSuiteName = atom_to_binary(SuiteName, utf8),
BTC = atom_to_binary(TC, utf8),
<<BSuiteName/binary, ":", BTC/binary>>;
make_summary_text(SuiteName, GroupName, TC) ->
BSuiteName = atom_to_binary(SuiteName, utf8),
BGroupName = atom_to_binary(GroupName, utf8),
BTC = atom_to_binary(TC, utf8),
<<BSuiteName/binary, ":", BGroupName/binary, ":", BTC/binary>>.
make_log_link(Config) ->
LogFile = proplists:get_value(tc_logfile, Config, ""),
case LogFile of
"" ->
<<>>;
_ ->
<<"\n[Report log](", (list_to_binary(LogFile))/binary, ")\n">>
end.
to_error_message(Return) ->
case Return of
{'EXIT', _} ->
Return;
{fail, _} ->
Return;
{error, _} ->
Return;
{skip, _} ->
ok;
_ ->
ok
end.
truncate_binary(Len, Bin) ->
case byte_size(Bin) > Len of
true ->
Prefix = binary:part(Bin, {0,Len}),
<<Prefix/binary, "...">>;
false ->
Bin
end.
reindent(Bin) ->
Use 2 whitespaces instead of 4 for indention
%% to make more compact look
binary:replace(Bin, <<" ">>, <<" ">>, [global]).
get_group_names(Config) ->
%% tc_group_path contains something like:
%% [[{name,muc_rsm_all},parallel],
[ { name , rdbms_muc_all},{repeat_until_all_ok,3},parallel ] ]
Where muc_rsm_all is subgroup of rdbms_muc_all .
Path = proplists:get_value(tc_group_path, Config, []),
TopGroup = proplists:get_value(tc_group_properties, Config, []),
Names = [ proplists:get_value(name, Props) || Props <- lists:reverse([TopGroup|Path]) ],
%% Just in case drop undefined
[Name || Name <- Names, Name =/= undefined].
full_group_name(Config) ->
Groups path , example [ main_group , sub_group1 , sub_sub_group ... ]
Groups = get_group_names(Config),
join_atoms(Groups).
join_atoms(Atoms) ->
Strings = [atom_to_list(A) || A <- Atoms],
list_to_atom(string:join(Strings, ":")).
| null | https://raw.githubusercontent.com/esl/MongooseIM/8b8c294b1b01dc178eed1b3b28ca0fbbd73f382c/big_tests/src/ct_markdown_errors_hook.erl | erlang | @doc Writes a markdown file with error information
@doc Add the following line in your *.spec file to enable this:
{ct_hooks, [ct_markdown_errors_hook]}.
Callbacks
@doc Return a unique id for this CTH.
@doc Always called before any other callback function. Use this to initiate
any common state.
@doc Called after each test case.
Log truncated, increment counter
-github/dear-github/issues/166
<details>
<summary>Click to expand</summary>
whatever
</details>
Don't use exml here to avoid escape errors
to make more compact look
tc_group_path contains something like:
[[{name,muc_rsm_all},parallel],
Just in case drop undefined | -module(ct_markdown_errors_hook).
-export([id/1]).
-export([init/2]).
-export([post_init_per_suite/4,
post_init_per_group/4,
post_init_per_testcase/4]).
-export([post_end_per_suite/4,
post_end_per_group/4,
post_end_per_testcase/4]).
-record(state, { file, summary_file, truncated_counter_file, suite, limit }).
id(_Opts) ->
"ct_markdown_errors_hook_001".
init(_Id, _Opts) ->
File = "/tmp/ct_markdown",
TrFile = "/tmp/ct_markdown_truncated",
SummaryFile = "/tmp/ct_summary",
file:write_file(File, ""),
file:write_file(SummaryFile, ""),
file:delete(TrFile),
{ok, #state{ file = File, summary_file = SummaryFile, truncated_counter_file = TrFile, limit = 25 }}.
post_init_per_suite(SuiteName, Config, Return, State) ->
State2 = handle_return(SuiteName, init_per_suite, Return, Config, State),
{Return, State2#state{suite = SuiteName}}.
post_init_per_group(_GroupName, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, init_per_group, Return, Config, State),
{Return, State2#state{}}.
post_init_per_testcase(TC, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, TC, Return, Config, State),
{Return, State2}.
post_end_per_suite(SuiteName, Config, Return, State) ->
State2 = handle_return(SuiteName, end_per_suite, Return, Config, State),
{Return, State2#state{suite = ''}}.
post_end_per_group(_GroupName, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, end_per_group, Return, Config, State),
{Return, State2#state{}}.
post_end_per_testcase(TC, Config, Return, State=#state{suite = SuiteName}) ->
State2 = handle_return(SuiteName, TC, Return, Config, State),
{Return, State2}.
handle_return(SuiteName, Place, Return, Config, State) ->
try handle_return_unsafe(SuiteName, Place, Return, Config, State)
catch Class:Error:StackTrace ->
ct:pal("issue=handle_return_unsafe_failed reason=~p:~p~n"
"stacktrace=~p", [Class, Error, StackTrace]),
State
end.
handle_return_unsafe(SuiteName, Place, Return, Config, State) ->
case to_error_message(Return) of
ok ->
State;
Error ->
FullGroupName = full_group_name(Config),
log_summary(SuiteName, FullGroupName, Place, State),
F = fun() ->
log_error(SuiteName, FullGroupName, Place, Error, Config, State)
end,
exec_limited_number_of_times(F, State)
end.
exec_limited_number_of_times(_F, State=#state{limit=0, file=_File,
truncated_counter_file = TrFile}) ->
TrCounter = old_truncated_counter_value(TrFile),
file:write_file(TrFile, integer_to_binary(TrCounter+1)),
State;
exec_limited_number_of_times(F, State=#state{limit=Limit}) ->
F(),
State#state{limit=Limit-1}.
old_truncated_counter_value(TrFile) ->
case file:read_file(TrFile) of
{ok, Bin} ->
binary_to_integer(Bin);
_ ->
0
end.
log_summary(SuiteName, GroupName, Place, #state{summary_file = SummaryFile}) ->
SummaryText = make_summary_text(SuiteName, GroupName, Place),
file:write_file(SummaryFile, [SummaryText, $\n], [append]),
ok.
log_error(SuiteName, GroupName, Place, Error, Config, #state{file = File, summary_file = _SummaryFile}) ->
_MaybeLogLink = make_log_link(Config),
LogLink = make_log_link(Config),
syntax
SummaryText = make_summary_text(SuiteName, GroupName, Place),
BinError = iolist_to_binary(io_lib:format("~p", [Error])),
Content = truncate_binary(1500, reindent(BinError)),
Out = <<"<details><summary>", SummaryText/binary, "</summary>\n"
"\n\n```erlang\n", Content/binary, "\n```\n",
LogLink/binary, "</details>\n">>,
file:write_file(File, Out, [append]),
ok.
make_summary_text(SuiteName, '', '') ->
atom_to_binary(SuiteName, utf8);
make_summary_text(SuiteName, '', TC) ->
BSuiteName = atom_to_binary(SuiteName, utf8),
BTC = atom_to_binary(TC, utf8),
<<BSuiteName/binary, ":", BTC/binary>>;
make_summary_text(SuiteName, GroupName, TC) ->
BSuiteName = atom_to_binary(SuiteName, utf8),
BGroupName = atom_to_binary(GroupName, utf8),
BTC = atom_to_binary(TC, utf8),
<<BSuiteName/binary, ":", BGroupName/binary, ":", BTC/binary>>.
make_log_link(Config) ->
LogFile = proplists:get_value(tc_logfile, Config, ""),
case LogFile of
"" ->
<<>>;
_ ->
<<"\n[Report log](", (list_to_binary(LogFile))/binary, ")\n">>
end.
to_error_message(Return) ->
case Return of
{'EXIT', _} ->
Return;
{fail, _} ->
Return;
{error, _} ->
Return;
{skip, _} ->
ok;
_ ->
ok
end.
truncate_binary(Len, Bin) ->
case byte_size(Bin) > Len of
true ->
Prefix = binary:part(Bin, {0,Len}),
<<Prefix/binary, "...">>;
false ->
Bin
end.
reindent(Bin) ->
Use 2 whitespaces instead of 4 for indention
binary:replace(Bin, <<" ">>, <<" ">>, [global]).
get_group_names(Config) ->
[ { name , rdbms_muc_all},{repeat_until_all_ok,3},parallel ] ]
Where muc_rsm_all is subgroup of rdbms_muc_all .
Path = proplists:get_value(tc_group_path, Config, []),
TopGroup = proplists:get_value(tc_group_properties, Config, []),
Names = [ proplists:get_value(name, Props) || Props <- lists:reverse([TopGroup|Path]) ],
[Name || Name <- Names, Name =/= undefined].
full_group_name(Config) ->
Groups path , example [ main_group , sub_group1 , sub_sub_group ... ]
Groups = get_group_names(Config),
join_atoms(Groups).
join_atoms(Atoms) ->
Strings = [atom_to_list(A) || A <- Atoms],
list_to_atom(string:join(Strings, ":")).
|
e8f8c22117865de4a18049f7e1fe974baf794f5e65213e12b50ae8289d882a54 | TyOverby/mono | rain.ml |
open Notty
open Notty.Infix
let () = Random.self_init ()
let rec (--) a b = if a > b then [] else a :: succ a -- b
let uchar x = I.uchar (Uchar.of_int x)
let nsym = 4096
let glitch = nsym / 20
let symbols = Array.(concat [
init 58 (fun x -> uchar (0xff66 + x) 1 1);
init 10 (fun x -> uchar (0x30 + x) 1 1);
init 26 ( fun x - > uchar ( 0x61 + x ) 1 1 ) ;
init 14 ( fun x - > uchar ( 0x21 + x ) 1 1 ) ;
])
let sym () = symbols.(Random.int (Array.length symbols))
let syms = Array.init nsym (fun _ -> sym ())
let gen_wait h = `Wait Random.(int (h / 2))
and gen_line h =
`Line Random.(0, int (nsym - h), int (h + h / 2) + 1, int 2 + 1)
let gen (w, h as dim) =
let lines = 1 -- w |> List.map @@ fun _ ->
if Random.float 1. < 0.1 then gen_line h else gen_wait h in
(dim, lines)
let step ((_, h as dim), xs) =
let xs = xs |> List.map @@ function
`Wait 0 -> gen_line h
| `Wait n -> `Wait (n - 1)
| `Line (i, _, win, k) when i - win + k >= h -> gen_wait h
| `Line (i, s, win, k) -> `Line (i + k, s, win, k) in
Random.(for _ = 0 to int glitch do syms.(int nsym) <- sym () done);
(dim, xs)
let bg = A.(rgb ~r:0 ~g:0 ~b:0 |> bg)
let fg i n =
let chan x = x *. 255. |> truncate
and t = float i /. float n in
let t1 = exp (-. t /. 0.02) |> chan
and t2 = exp (-. t /. 0.45) |> chan in
A.(rgb_888 ~r:t1 ~b:t1 ~g:t2 |> fg)
let show ((w, h), xs) =
let f = function
`Wait _ -> I.void 1 0
| `Line (i, sym, win, _) ->
let last = i - win
and off = max 0 (i - h + 1) in
let rec chars w =
let ix = w + last in
if 0 <= min ix w then syms.(sym + ix) :: chars (w - 1) else [] in
let rec images acc i = function
| [] -> acc
| x::xs -> let img = I.attr (fg i win ++ bg) x in
images (img :: acc) (i + 1) xs in
chars (win - off) |> images [] off |>
I.vcat |> I.vpad (max 0 (i - win)) 0 in
(List.map f xs |> I.hcat) </> I.char ~attr:bg ' ' w h
open Notty_unix
type r = [ Unescape.event | `Resize of int * int | `End | `Timer ]
let event ~delay t =
if Term.pending t then (Term.event t :> r) else
let open Unix in
match select [Term.fds t |> fst] [] [] delay with
| ([], _, _) -> `Timer
| (_::_, _, _) -> (Term.event t :> r)
| exception Unix_error (EINTR, _, _) -> (Term.event t :> r)
let loop t ~frame st =
let rec go st deadline =
let now = Unix.gettimeofday () in
if deadline <= now then
( Term.image t (show st); go (step st) (frame +. deadline) )
else match event ~delay:(deadline -. now) t with
| `End | `Key (`Escape, _) | `Key (`ASCII 'C', [`Ctrl]) -> ()
| `Resize _ | `Key (`ASCII ' ', _) -> go (gen (Term.size t)) deadline
| _ -> go st deadline in
go st (Unix.gettimeofday ())
let () =
let t = Term.create () in
loop t ~frame:0.075 (gen (Term.size t));
Term.release t
| null | https://raw.githubusercontent.com/TyOverby/mono/94225736a93457d5c9aeed399c4ae1a08b239fd5/vendor/pqwy-notty/examples/rain.ml | ocaml |
open Notty
open Notty.Infix
let () = Random.self_init ()
let rec (--) a b = if a > b then [] else a :: succ a -- b
let uchar x = I.uchar (Uchar.of_int x)
let nsym = 4096
let glitch = nsym / 20
let symbols = Array.(concat [
init 58 (fun x -> uchar (0xff66 + x) 1 1);
init 10 (fun x -> uchar (0x30 + x) 1 1);
init 26 ( fun x - > uchar ( 0x61 + x ) 1 1 ) ;
init 14 ( fun x - > uchar ( 0x21 + x ) 1 1 ) ;
])
let sym () = symbols.(Random.int (Array.length symbols))
let syms = Array.init nsym (fun _ -> sym ())
let gen_wait h = `Wait Random.(int (h / 2))
and gen_line h =
`Line Random.(0, int (nsym - h), int (h + h / 2) + 1, int 2 + 1)
let gen (w, h as dim) =
let lines = 1 -- w |> List.map @@ fun _ ->
if Random.float 1. < 0.1 then gen_line h else gen_wait h in
(dim, lines)
let step ((_, h as dim), xs) =
let xs = xs |> List.map @@ function
`Wait 0 -> gen_line h
| `Wait n -> `Wait (n - 1)
| `Line (i, _, win, k) when i - win + k >= h -> gen_wait h
| `Line (i, s, win, k) -> `Line (i + k, s, win, k) in
Random.(for _ = 0 to int glitch do syms.(int nsym) <- sym () done);
(dim, xs)
let bg = A.(rgb ~r:0 ~g:0 ~b:0 |> bg)
let fg i n =
let chan x = x *. 255. |> truncate
and t = float i /. float n in
let t1 = exp (-. t /. 0.02) |> chan
and t2 = exp (-. t /. 0.45) |> chan in
A.(rgb_888 ~r:t1 ~b:t1 ~g:t2 |> fg)
let show ((w, h), xs) =
let f = function
`Wait _ -> I.void 1 0
| `Line (i, sym, win, _) ->
let last = i - win
and off = max 0 (i - h + 1) in
let rec chars w =
let ix = w + last in
if 0 <= min ix w then syms.(sym + ix) :: chars (w - 1) else [] in
let rec images acc i = function
| [] -> acc
| x::xs -> let img = I.attr (fg i win ++ bg) x in
images (img :: acc) (i + 1) xs in
chars (win - off) |> images [] off |>
I.vcat |> I.vpad (max 0 (i - win)) 0 in
(List.map f xs |> I.hcat) </> I.char ~attr:bg ' ' w h
open Notty_unix
type r = [ Unescape.event | `Resize of int * int | `End | `Timer ]
let event ~delay t =
if Term.pending t then (Term.event t :> r) else
let open Unix in
match select [Term.fds t |> fst] [] [] delay with
| ([], _, _) -> `Timer
| (_::_, _, _) -> (Term.event t :> r)
| exception Unix_error (EINTR, _, _) -> (Term.event t :> r)
let loop t ~frame st =
let rec go st deadline =
let now = Unix.gettimeofday () in
if deadline <= now then
( Term.image t (show st); go (step st) (frame +. deadline) )
else match event ~delay:(deadline -. now) t with
| `End | `Key (`Escape, _) | `Key (`ASCII 'C', [`Ctrl]) -> ()
| `Resize _ | `Key (`ASCII ' ', _) -> go (gen (Term.size t)) deadline
| _ -> go st deadline in
go st (Unix.gettimeofday ())
let () =
let t = Term.create () in
loop t ~frame:0.075 (gen (Term.size t));
Term.release t
|
|
91e1c1e4e23c0fc9f71d21623536bee5fb5eea25f1e79db53dccc866083534eb | awslabs/s2n-bignum | bignum_montmul_p256_alt.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
Montgomery multiplication modulo p_256 using using traditional x86 muls .
(* ========================================================================= *)
(**** print_literal_from_elf "x86/p256/bignum_montmul_p256_alt.o";;
****)
let bignum_montmul_p256_alt_mc =
define_assert_from_elf "bignum_montmul_p256_alt_mc" "x86/p256/bignum_montmul_p256_alt.o"
[
0x53; (* PUSH (% rbx) *)
0x41; 0x54; (* PUSH (% r12) *)
0x41; 0x55; (* PUSH (% r13) *)
0x41; 0x56; (* PUSH (% r14) *)
0x41; 0x57; (* PUSH (% r15) *)
MOV ( % rcx ) ( % rdx )
MOV ( % rbx ) ( ( % % ( rcx,0 ) ) )
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
MOV ( % r8 ) ( % rax )
MOV ( % r9 ) ( % rdx )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
0x45; 0x31; 0xd2; (* XOR (% r10d) (% r10d) *)
0x49; 0x01; 0xc1; (* ADD (% r9) (% rax) *)
0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *)
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
0x45; 0x31; 0xdb; (* XOR (% r11d) (% r11d) *)
0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *)
0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *)
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
0x45; 0x31; 0xe4; (* XOR (% r12d) (% r12d) *)
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *)
MOV ( % rbx ) ( ( % % ( rcx,8 ) ) )
0x45; 0x31; 0xed; (* XOR (% r13d) (% r13d) *)
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
0x49; 0x01; 0xc1; (* ADD (% r9) (% rax) *)
0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *)
SBB ( % r14 ) ( % r14 )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r14 )
0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *)
0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *)
SBB ( % r14 ) ( % r14 )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r14 )
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *)
SBB ( % r14 ) ( % r14 )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r14 )
0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *)
0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *)
0x45; 0x31; 0xf6; (* XOR (% r14d) (% r14d) *)
0x48; 0xbb; 0x00; 0x00; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00;
MOV ( % rbx ) ( Imm64 ( word 4294967296 ) )
MOV ( % rax ) ( % r8 )
MUL2 ( % rdx,% rax ) ( % rbx )
0x49; 0x01; 0xc1; (* ADD (% r9) (% rax) *)
0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *)
SBB ( % r15 ) ( % r15 )
MOV ( % rax ) ( % r9 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r15 )
0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *)
0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *)
SBB ( % r15 ) ( % r15 )
0x48; 0xf7; 0xd3; (* NOT (% rbx) *)
( % rbx ) ( % % ( rbx,2 ) )
MOV ( % rax ) ( % r8 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r15 )
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *)
SBB ( % r15 ) ( % r15 )
MOV ( % rax ) ( % r9 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r15 )
0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *)
0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *)
0x4d; 0x11; 0xf6; (* ADC (% r14) (% r14) *)
MOV ( % rbx ) ( ( % % ( rcx,16 ) ) )
XOR ( % r15d ) ( % r15d )
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *)
0x49; 0x11; 0xd3; (* ADC (% r11) (% rdx) *)
SBB ( % r8 ) ( % r8 )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r8 )
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *)
SBB ( % r8 ) ( % r8 )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r8 )
0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *)
0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *)
SBB ( % r8 ) ( % r8 )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r8 )
0x49; 0x01; 0xc5; (* ADD (% r13) (% rax) *)
0x49; 0x11; 0xd6; (* ADC (% r14) (% rdx) *)
0x4d; 0x11; 0xff; (* ADC (% r15) (% r15) *)
MOV ( % rbx ) ( ( % % ( rcx,24 ) ) )
0x45; 0x31; 0xc0; (* XOR (% r8d) (% r8d) *)
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *)
SBB ( % r9 ) ( % r9 )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r9 )
0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *)
0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *)
SBB ( % r9 ) ( % r9 )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r9 )
0x49; 0x01; 0xc5; (* ADD (% r13) (% rax) *)
0x49; 0x11; 0xd6; (* ADC (% r14) (% rdx) *)
SBB ( % r9 ) ( % r9 )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r9 )
0x49; 0x01; 0xc6; (* ADD (% r14) (% rax) *)
0x49; 0x11; 0xd7; (* ADC (% r15) (% rdx) *)
0x4d; 0x11; 0xc0; (* ADC (% r8) (% r8) *)
0x45; 0x31; 0xc9; (* XOR (% r9d) (% r9d) *)
0x48; 0xbb; 0x00; 0x00; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00;
MOV ( % rbx ) ( Imm64 ( word 4294967296 ) )
MOV ( % rax ) ( % r10 )
MUL2 ( % rdx,% rax ) ( % rbx )
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x11; 0xd4; (* ADC (% r12) (% rdx) *)
SBB ( % rcx ) ( % rcx )
MOV ( % rax ) ( % r11 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % rcx )
0x49; 0x01; 0xc4; (* ADD (% r12) (% rax) *)
0x49; 0x11; 0xd5; (* ADC (% r13) (% rdx) *)
SBB ( % rcx ) ( % rcx )
0x48; 0xf7; 0xd3; (* NOT (% rbx) *)
( % rbx ) ( % % ( rbx,2 ) )
MOV ( % rax ) ( % r10 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % rcx )
0x49; 0x01; 0xc5; (* ADD (% r13) (% rax) *)
0x49; 0x11; 0xd6; (* ADC (% r14) (% rdx) *)
SBB ( % rcx ) ( % rcx )
MOV ( % rax ) ( % r11 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % rcx )
0x49; 0x01; 0xc6; (* ADD (% r14) (% rax) *)
0x49; 0x11; 0xd7; (* ADC (% r15) (% rdx) *)
0x4d; 0x11; 0xc8; (* ADC (% r8) (% r9) *)
0xb9; 0x01; 0x00; 0x00; 0x00;
MOV ( % ecx ) ( Imm32 ( word 1 ) )
0x4c; 0x01; 0xe1; (* ADD (% rcx) (% r12) *)
DEC ( % rbx )
0x4c; 0x11; 0xeb; (* ADC (% rbx) (% r13) *)
DEC ( % r9 )
MOV ( % rax ) ( % r9 )
0x4d; 0x11; 0xf1; (* ADC (% r9) (% r14) *)
0x41; 0xbb; 0xfe; 0xff; 0xff; 0xff;
MOV ( % r11d ) ( Imm32 ( word 4294967294 ) )
0x4d; 0x11; 0xfb; (* ADC (% r11) (% r15) *)
0x4c; 0x11; 0xc0; (* ADC (% rax) (% r8) *)
CMOVB ( % r12 ) ( % rcx )
CMOVB ( % r13 ) ( % rbx )
CMOVB ( % r14 ) ( % r9 )
CMOVB ( % r15 ) ( % r11 )
MOV ( ( % % ( rdi,0 ) ) ) ( % r12 )
MOV ( ( % % ( rdi,8 ) ) ) ( % r13 )
MOV ( ( % % ( rdi,16 ) ) ) ( % r14 )
MOV ( ( % % ( ) ) ) ( % r15 )
0x41; 0x5f; (* POP (% r15) *)
0x41; 0x5e; (* POP (% r14) *)
0x41; 0x5d; (* POP (% r13) *)
0x41; 0x5c; (* POP (% r12) *)
0x5b; (* POP (% rbx) *)
RET
];;
let BIGNUM_MONTMUL_P256_ALT_EXEC = X86_MK_CORE_EXEC_RULE bignum_montmul_p256_alt_mc;;
(* ------------------------------------------------------------------------- *)
(* Proof. *)
(* ------------------------------------------------------------------------- *)
let p_256 = new_definition `p_256 = 115792089210356248762697446949407573530086143415290314195533631308867097853951`;;
let BIGNUM_MONTMUL_P256_ALT_CORRECT = time prove
(`!z x y a b pc.
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_montmul_p256_alt_mc) /\
read RIP s = word(pc + 0x09) /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = word (pc + 0x229) /\
(a * b <= 2 EXP 256 * p_256
==> bignum_from_memory (z,4) s =
(inverse_mod p_256 (2 EXP 256) * a * b) MOD p_256))
(MAYCHANGE [RIP; RAX; RBX; RCX; RDX;
R8; R9; R10; R11; R12; R13; R14; R15] ,,
MAYCHANGE [memory :> bytes(z,8 * 4)] ,,
MAYCHANGE SOME_FLAGS)`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `y:int64`; `a:num`; `b:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
* * Globalize the a * b < = 2 EXP 256 * p_256 assumption * *
ASM_CASES_TAC `a * b <= 2 EXP 256 * p_256` THENL
[ASM_REWRITE_TAC[]; X86_SIM_TAC BIGNUM_MONTMUL_P256_ALT_EXEC (1--167)] THEN
ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN
BIGNUM_DIGITIZE_TAC "y_" `bignum_from_memory (y,4) s0` THEN
(*** Simulate the core pre-reduced result accumulation ***)
MAP_EVERY (fun n ->
X86_STEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC [n] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_RULE
`word_sub x (word_neg y):int64 = word_add x y`]) THEN
TRY(ACCUMULATE_ARITH_TAC("s"^string_of_int n)))
(1--149) THEN
ABBREV_TAC
`t = bignum_of_wordlist
[sum_s133; sum_s141; sum_s147; sum_s148; sum_s149]` THEN
SUBGOAL_THEN
`t < 2 * p_256 /\ (2 EXP 256 * t == a * b) (mod p_256)`
STRIP_ASSUME_TAC THENL
[ACCUMULATOR_POP_ASSUM_LIST
(STRIP_ASSUME_TAC o end_itlist CONJ o DECARRY_RULE) THEN
CONJ_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`ab <= 2 EXP 256 * p
==> 2 EXP 256 * t < ab + 2 EXP 256 * p ==> t < 2 * p`)) THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
REWRITE_TAC[p_256; REAL_ARITH `a:real < b + c <=> a - b < c`] THEN
ASM_REWRITE_TAC[] THEN BOUNDER_TAC[];
REWRITE_TAC[REAL_CONGRUENCE; p_256] THEN CONV_TAC NUM_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
ASM_REWRITE_TAC[] THEN REAL_INTEGER_TAC];
ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN
(*** Final correction stage ***)
X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC
[151;153;156;158;159] (150--167) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN
TRANS_TAC EQ_TRANS `t MOD p_256` THEN CONJ_TAC THENL
[ALL_TAC;
REWRITE_TAC[GSYM CONG] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP
(NUMBER_RULE
`(e * t == a * b) (mod p)
==> (e * i == 1) (mod p) ==> (t == i * a * b) (mod p)`)) THEN
REWRITE_TAC[INVERSE_MOD_RMUL_EQ; COPRIME_REXP; COPRIME_2] THEN
REWRITE_TAC[p_256] THEN CONV_TAC NUM_REDUCE_CONV] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN
MAP_EVERY EXISTS_TAC
[`256`; `if t < p_256 then &t:real else &t - &p_256`] THEN
REPEAT CONJ_TAC THENL
[REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN BOUNDER_TAC[];
REWRITE_TAC[p_256] THEN ARITH_TAC;
REWRITE_TAC[p_256] THEN ARITH_TAC;
ALL_TAC;
ASM_SIMP_TAC[MOD_CASES] THEN
GEN_REWRITE_TAC LAND_CONV [COND_RAND] THEN
SIMP_TAC[REAL_OF_NUM_SUB; GSYM NOT_LT]] THEN
SUBGOAL_THEN `carry_s159 <=> p_256 <= t` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `320` THEN
EXPAND_TAC "t" THEN
REWRITE_TAC[p_256; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN
CONV_TAC NUM_REDUCE_CONV THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
REWRITE_TAC[GSYM NOT_LT; COND_SWAP]] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "t" THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist; p_256] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; VAL_WORD_BITVAL] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC);;
let BIGNUM_MONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 40),48) /\
ALL (nonoverlapping (word_sub stackpointer (word 40),40))
[(word pc,0x233); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(a * b <= 2 EXP 256 * p_256
==> bignum_from_memory (z,4) s =
(inverse_mod p_256 (2 EXP 256) * a * b) MOD p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 40),40)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC
bignum_montmul_p256_alt_mc BIGNUM_MONTMUL_P256_ALT_CORRECT
`[RBX; R12; R13; R14; R15]` 40);;
(* ------------------------------------------------------------------------- *)
(* Show that it also works as "almost-Montgomery" if desired. That is, even *)
(* without the further range assumption on inputs we still get a congruence. *)
But the output , still 256 bits , may then not be fully reduced mod p_256 .
(* ------------------------------------------------------------------------- *)
let BIGNUM_AMONTMUL_P256_ALT_CORRECT = time prove
(`!z x y a b pc.
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_montmul_p256_alt_mc) /\
read RIP s = word(pc + 0x09) /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = word (pc + 0x229) /\
(bignum_from_memory (z,4) s ==
inverse_mod p_256 (2 EXP 256) * a * b) (mod p_256))
(MAYCHANGE [RIP; RAX; RBX; RCX; RDX;
R8; R9; R10; R11; R12; R13; R14; R15] ,,
MAYCHANGE [memory :> bytes(z,8 * 4)] ,,
MAYCHANGE SOME_FLAGS)`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `y:int64`; `a:num`; `b:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN
BIGNUM_DIGITIZE_TAC "y_" `bignum_from_memory (y,4) s0` THEN
(*** Simulate the core pre-reduced result accumulation ***)
MAP_EVERY (fun n ->
X86_STEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC [n] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_RULE
`word_sub x (word_neg y):int64 = word_add x y`]) THEN
TRY(ACCUMULATE_ARITH_TAC("s"^string_of_int n)))
(1--149) THEN
ABBREV_TAC
`t = bignum_of_wordlist
[sum_s133; sum_s141; sum_s147; sum_s148; sum_s149]` THEN
SUBGOAL_THEN
`t < 2 EXP 256 + p_256 /\ (2 EXP 256 * t == a * b) (mod p_256)`
STRIP_ASSUME_TAC THENL
[ACCUMULATOR_POP_ASSUM_LIST
(STRIP_ASSUME_TAC o end_itlist CONJ o DECARRY_RULE) THEN
CONJ_TAC THENL
[MATCH_MP_TAC(ARITH_RULE
`2 EXP 256 * t <= (2 EXP 256 - 1) EXP 2 + (2 EXP 256 - 1) * p
==> t < 2 EXP 256 + p`) THEN
REWRITE_TAC[p_256] THEN CONV_TAC NUM_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
REWRITE_TAC[p_256; REAL_ARITH `a:real < b + c <=> a - b < c`] THEN
ASM_REWRITE_TAC[] THEN BOUNDER_TAC[];
REWRITE_TAC[REAL_CONGRUENCE; p_256] THEN CONV_TAC NUM_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
ASM_REWRITE_TAC[] THEN REAL_INTEGER_TAC];
ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN
(*** Final correction stage ***)
X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC
[151;153;156;158;159] (150--167) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP
(NUMBER_RULE
`(e * t == ab) (mod p)
==> (e * i == 1) (mod p) /\ (s == t) (mod p)
==> (s == i * ab) (mod p)`)) THEN
REWRITE_TAC[INVERSE_MOD_RMUL_EQ; COPRIME_REXP; COPRIME_2] THEN
CONJ_TAC THENL
[REWRITE_TAC[p_256] THEN CONV_TAC NUM_REDUCE_CONV; ALL_TAC] THEN
SUBGOAL_THEN `carry_s159 <=> p_256 <= t` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `320` THEN
EXPAND_TAC "t" THEN
REWRITE_TAC[p_256; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN
CONV_TAC NUM_REDUCE_CONV THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
REWRITE_TAC[GSYM NOT_LT; COND_SWAP]] THEN
MATCH_MP_TAC(NUMBER_RULE `!b:num. x + b * p = y ==> (x == y) (mod p)`) THEN
EXISTS_TAC `bitval(p_256 <= t)` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REWRITE_TAC[REAL_OF_NUM_LE] THEN
ONCE_REWRITE_TAC[REAL_ARITH `a + b:real = c <=> c - b = a`] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`256`; `&0:real`] THEN CONJ_TAC THENL
[UNDISCH_TAC `t < 2 EXP 256 + p_256` THEN
REWRITE_TAC[bitval; p_256; GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC;
REWRITE_TAC[INTEGER_CLOSED]] THEN
CONJ_TAC THENL
[CONV_TAC(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN BOUNDER_TAC[];
ALL_TAC] THEN
CONV_TAC(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV) THEN
REWRITE_TAC[bitval] THEN COND_CASES_TAC THEN
EXPAND_TAC "t" THEN REWRITE_TAC[bignum_of_wordlist] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST (MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
REWRITE_TAC[BITVAL_CLAUSES; p_256] THEN
CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC);;
let BIGNUM_AMONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 40),48) /\
ALL (nonoverlapping (word_sub stackpointer (word 40),40))
[(word pc,0x233); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(bignum_from_memory (z,4) s ==
inverse_mod p_256 (2 EXP 256) * a * b) (mod p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 40),40)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC
bignum_montmul_p256_alt_mc BIGNUM_AMONTMUL_P256_ALT_CORRECT
`[RBX; R12; R13; R14; R15]` 40);;
(* ------------------------------------------------------------------------- *)
(* Correctness of Windows ABI version. *)
(* ------------------------------------------------------------------------- *)
let windows_bignum_montmul_p256_alt_mc = define_from_elf
"windows_bignum_montmul_p256_alt_mc" "x86/p256/bignum_montmul_p256_alt.obj";;
let WINDOWS_BIGNUM_MONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 56),64) /\
ALL (nonoverlapping (word_sub stackpointer (word 56),56))
[(word pc,0x240); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x240) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(a * b <= 2 EXP 256 * p_256
==> bignum_from_memory (z,4) s =
(inverse_mod p_256 (2 EXP 256) * a * b) MOD p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 56),56)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC
windows_bignum_montmul_p256_alt_mc bignum_montmul_p256_alt_mc
BIGNUM_MONTMUL_P256_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);;
let WINDOWS_BIGNUM_AMONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 56),64) /\
ALL (nonoverlapping (word_sub stackpointer (word 56),56))
[(word pc,0x240); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x240) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(bignum_from_memory (z,4) s ==
inverse_mod p_256 (2 EXP 256) * a * b) (mod p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 56),56)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC
windows_bignum_montmul_p256_alt_mc bignum_montmul_p256_alt_mc
BIGNUM_AMONTMUL_P256_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_montmul_p256_alt.ml | ocaml | =========================================================================
=========================================================================
*** print_literal_from_elf "x86/p256/bignum_montmul_p256_alt.o";;
***
PUSH (% rbx)
PUSH (% r12)
PUSH (% r13)
PUSH (% r14)
PUSH (% r15)
XOR (% r10d) (% r10d)
ADD (% r9) (% rax)
ADC (% r10) (% rdx)
XOR (% r11d) (% r11d)
ADD (% r10) (% rax)
ADC (% r11) (% rdx)
XOR (% r12d) (% r12d)
ADD (% r11) (% rax)
ADC (% r12) (% rdx)
XOR (% r13d) (% r13d)
ADD (% r9) (% rax)
ADC (% r10) (% rdx)
ADD (% r10) (% rax)
ADC (% r11) (% rdx)
ADD (% r11) (% rax)
ADC (% r12) (% rdx)
ADD (% r12) (% rax)
ADC (% r13) (% rdx)
XOR (% r14d) (% r14d)
ADD (% r9) (% rax)
ADC (% r10) (% rdx)
ADD (% r10) (% rax)
ADC (% r11) (% rdx)
NOT (% rbx)
ADD (% r11) (% rax)
ADC (% r12) (% rdx)
ADD (% r12) (% rax)
ADC (% r13) (% rdx)
ADC (% r14) (% r14)
ADD (% r10) (% rax)
ADC (% r11) (% rdx)
ADD (% r11) (% rax)
ADC (% r12) (% rdx)
ADD (% r12) (% rax)
ADC (% r13) (% rdx)
ADD (% r13) (% rax)
ADC (% r14) (% rdx)
ADC (% r15) (% r15)
XOR (% r8d) (% r8d)
ADD (% r11) (% rax)
ADC (% r12) (% rdx)
ADD (% r12) (% rax)
ADC (% r13) (% rdx)
ADD (% r13) (% rax)
ADC (% r14) (% rdx)
ADD (% r14) (% rax)
ADC (% r15) (% rdx)
ADC (% r8) (% r8)
XOR (% r9d) (% r9d)
ADD (% r11) (% rax)
ADC (% r12) (% rdx)
ADD (% r12) (% rax)
ADC (% r13) (% rdx)
NOT (% rbx)
ADD (% r13) (% rax)
ADC (% r14) (% rdx)
ADD (% r14) (% rax)
ADC (% r15) (% rdx)
ADC (% r8) (% r9)
ADD (% rcx) (% r12)
ADC (% rbx) (% r13)
ADC (% r9) (% r14)
ADC (% r11) (% r15)
ADC (% rax) (% r8)
POP (% r15)
POP (% r14)
POP (% r13)
POP (% r12)
POP (% rbx)
-------------------------------------------------------------------------
Proof.
-------------------------------------------------------------------------
** Simulate the core pre-reduced result accumulation **
** Final correction stage **
-------------------------------------------------------------------------
Show that it also works as "almost-Montgomery" if desired. That is, even
without the further range assumption on inputs we still get a congruence.
-------------------------------------------------------------------------
** Simulate the core pre-reduced result accumulation **
** Final correction stage **
-------------------------------------------------------------------------
Correctness of Windows ABI version.
------------------------------------------------------------------------- |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
Montgomery multiplication modulo p_256 using using traditional x86 muls .
let bignum_montmul_p256_alt_mc =
define_assert_from_elf "bignum_montmul_p256_alt_mc" "x86/p256/bignum_montmul_p256_alt.o"
[
MOV ( % rcx ) ( % rdx )
MOV ( % rbx ) ( ( % % ( rcx,0 ) ) )
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
MOV ( % r8 ) ( % rax )
MOV ( % r9 ) ( % rdx )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
MOV ( % rbx ) ( ( % % ( rcx,8 ) ) )
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SBB ( % r14 ) ( % r14 )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r14 )
SBB ( % r14 ) ( % r14 )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r14 )
SBB ( % r14 ) ( % r14 )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r14 )
0x48; 0xbb; 0x00; 0x00; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00;
MOV ( % rbx ) ( Imm64 ( word 4294967296 ) )
MOV ( % rax ) ( % r8 )
MUL2 ( % rdx,% rax ) ( % rbx )
SBB ( % r15 ) ( % r15 )
MOV ( % rax ) ( % r9 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r15 )
SBB ( % r15 ) ( % r15 )
( % rbx ) ( % % ( rbx,2 ) )
MOV ( % rax ) ( % r8 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r15 )
SBB ( % r15 ) ( % r15 )
MOV ( % rax ) ( % r9 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r15 )
MOV ( % rbx ) ( ( % % ( rcx,16 ) ) )
XOR ( % r15d ) ( % r15d )
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SBB ( % r8 ) ( % r8 )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r8 )
SBB ( % r8 ) ( % r8 )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r8 )
SBB ( % r8 ) ( % r8 )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r8 )
MOV ( % rbx ) ( ( % % ( rcx,24 ) ) )
MOV ( % rax ) ( ( % % ( rsi,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SBB ( % r9 ) ( % r9 )
MOV ( % rax ) ( ( % % ( rsi,8 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r9 )
SBB ( % r9 ) ( % r9 )
MOV ( % rax ) ( ( % % ( rsi,16 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r9 )
SBB ( % r9 ) ( % r9 )
MOV ( % rax ) ( ( % % ( rsi,24 ) ) )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % r9 )
0x48; 0xbb; 0x00; 0x00; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00;
MOV ( % rbx ) ( Imm64 ( word 4294967296 ) )
MOV ( % rax ) ( % r10 )
MUL2 ( % rdx,% rax ) ( % rbx )
SBB ( % rcx ) ( % rcx )
MOV ( % rax ) ( % r11 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % rcx )
SBB ( % rcx ) ( % rcx )
( % rbx ) ( % % ( rbx,2 ) )
MOV ( % rax ) ( % r10 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % rcx )
SBB ( % rcx ) ( % rcx )
MOV ( % rax ) ( % r11 )
MUL2 ( % rdx,% rax ) ( % rbx )
SUB ( % rdx ) ( % rcx )
0xb9; 0x01; 0x00; 0x00; 0x00;
MOV ( % ecx ) ( Imm32 ( word 1 ) )
DEC ( % rbx )
DEC ( % r9 )
MOV ( % rax ) ( % r9 )
0x41; 0xbb; 0xfe; 0xff; 0xff; 0xff;
MOV ( % r11d ) ( Imm32 ( word 4294967294 ) )
CMOVB ( % r12 ) ( % rcx )
CMOVB ( % r13 ) ( % rbx )
CMOVB ( % r14 ) ( % r9 )
CMOVB ( % r15 ) ( % r11 )
MOV ( ( % % ( rdi,0 ) ) ) ( % r12 )
MOV ( ( % % ( rdi,8 ) ) ) ( % r13 )
MOV ( ( % % ( rdi,16 ) ) ) ( % r14 )
MOV ( ( % % ( ) ) ) ( % r15 )
RET
];;
let BIGNUM_MONTMUL_P256_ALT_EXEC = X86_MK_CORE_EXEC_RULE bignum_montmul_p256_alt_mc;;
let p_256 = new_definition `p_256 = 115792089210356248762697446949407573530086143415290314195533631308867097853951`;;
let BIGNUM_MONTMUL_P256_ALT_CORRECT = time prove
(`!z x y a b pc.
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_montmul_p256_alt_mc) /\
read RIP s = word(pc + 0x09) /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = word (pc + 0x229) /\
(a * b <= 2 EXP 256 * p_256
==> bignum_from_memory (z,4) s =
(inverse_mod p_256 (2 EXP 256) * a * b) MOD p_256))
(MAYCHANGE [RIP; RAX; RBX; RCX; RDX;
R8; R9; R10; R11; R12; R13; R14; R15] ,,
MAYCHANGE [memory :> bytes(z,8 * 4)] ,,
MAYCHANGE SOME_FLAGS)`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `y:int64`; `a:num`; `b:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
* * Globalize the a * b < = 2 EXP 256 * p_256 assumption * *
ASM_CASES_TAC `a * b <= 2 EXP 256 * p_256` THENL
[ASM_REWRITE_TAC[]; X86_SIM_TAC BIGNUM_MONTMUL_P256_ALT_EXEC (1--167)] THEN
ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN
BIGNUM_DIGITIZE_TAC "y_" `bignum_from_memory (y,4) s0` THEN
MAP_EVERY (fun n ->
X86_STEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC [n] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_RULE
`word_sub x (word_neg y):int64 = word_add x y`]) THEN
TRY(ACCUMULATE_ARITH_TAC("s"^string_of_int n)))
(1--149) THEN
ABBREV_TAC
`t = bignum_of_wordlist
[sum_s133; sum_s141; sum_s147; sum_s148; sum_s149]` THEN
SUBGOAL_THEN
`t < 2 * p_256 /\ (2 EXP 256 * t == a * b) (mod p_256)`
STRIP_ASSUME_TAC THENL
[ACCUMULATOR_POP_ASSUM_LIST
(STRIP_ASSUME_TAC o end_itlist CONJ o DECARRY_RULE) THEN
CONJ_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`ab <= 2 EXP 256 * p
==> 2 EXP 256 * t < ab + 2 EXP 256 * p ==> t < 2 * p`)) THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
REWRITE_TAC[p_256; REAL_ARITH `a:real < b + c <=> a - b < c`] THEN
ASM_REWRITE_TAC[] THEN BOUNDER_TAC[];
REWRITE_TAC[REAL_CONGRUENCE; p_256] THEN CONV_TAC NUM_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
ASM_REWRITE_TAC[] THEN REAL_INTEGER_TAC];
ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN
X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC
[151;153;156;158;159] (150--167) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN
TRANS_TAC EQ_TRANS `t MOD p_256` THEN CONJ_TAC THENL
[ALL_TAC;
REWRITE_TAC[GSYM CONG] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP
(NUMBER_RULE
`(e * t == a * b) (mod p)
==> (e * i == 1) (mod p) ==> (t == i * a * b) (mod p)`)) THEN
REWRITE_TAC[INVERSE_MOD_RMUL_EQ; COPRIME_REXP; COPRIME_2] THEN
REWRITE_TAC[p_256] THEN CONV_TAC NUM_REDUCE_CONV] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN
MAP_EVERY EXISTS_TAC
[`256`; `if t < p_256 then &t:real else &t - &p_256`] THEN
REPEAT CONJ_TAC THENL
[REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN BOUNDER_TAC[];
REWRITE_TAC[p_256] THEN ARITH_TAC;
REWRITE_TAC[p_256] THEN ARITH_TAC;
ALL_TAC;
ASM_SIMP_TAC[MOD_CASES] THEN
GEN_REWRITE_TAC LAND_CONV [COND_RAND] THEN
SIMP_TAC[REAL_OF_NUM_SUB; GSYM NOT_LT]] THEN
SUBGOAL_THEN `carry_s159 <=> p_256 <= t` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `320` THEN
EXPAND_TAC "t" THEN
REWRITE_TAC[p_256; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN
CONV_TAC NUM_REDUCE_CONV THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
REWRITE_TAC[GSYM NOT_LT; COND_SWAP]] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "t" THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist; p_256] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; VAL_WORD_BITVAL] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC);;
let BIGNUM_MONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 40),48) /\
ALL (nonoverlapping (word_sub stackpointer (word 40),40))
[(word pc,0x233); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(a * b <= 2 EXP 256 * p_256
==> bignum_from_memory (z,4) s =
(inverse_mod p_256 (2 EXP 256) * a * b) MOD p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 40),40)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC
bignum_montmul_p256_alt_mc BIGNUM_MONTMUL_P256_ALT_CORRECT
`[RBX; R12; R13; R14; R15]` 40);;
But the output , still 256 bits , may then not be fully reduced mod p_256 .
let BIGNUM_AMONTMUL_P256_ALT_CORRECT = time prove
(`!z x y a b pc.
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_montmul_p256_alt_mc) /\
read RIP s = word(pc + 0x09) /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = word (pc + 0x229) /\
(bignum_from_memory (z,4) s ==
inverse_mod p_256 (2 EXP 256) * a * b) (mod p_256))
(MAYCHANGE [RIP; RAX; RBX; RCX; RDX;
R8; R9; R10; R11; R12; R13; R14; R15] ,,
MAYCHANGE [memory :> bytes(z,8 * 4)] ,,
MAYCHANGE SOME_FLAGS)`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `y:int64`; `a:num`; `b:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN
BIGNUM_DIGITIZE_TAC "y_" `bignum_from_memory (y,4) s0` THEN
MAP_EVERY (fun n ->
X86_STEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC [n] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_RULE
`word_sub x (word_neg y):int64 = word_add x y`]) THEN
TRY(ACCUMULATE_ARITH_TAC("s"^string_of_int n)))
(1--149) THEN
ABBREV_TAC
`t = bignum_of_wordlist
[sum_s133; sum_s141; sum_s147; sum_s148; sum_s149]` THEN
SUBGOAL_THEN
`t < 2 EXP 256 + p_256 /\ (2 EXP 256 * t == a * b) (mod p_256)`
STRIP_ASSUME_TAC THENL
[ACCUMULATOR_POP_ASSUM_LIST
(STRIP_ASSUME_TAC o end_itlist CONJ o DECARRY_RULE) THEN
CONJ_TAC THENL
[MATCH_MP_TAC(ARITH_RULE
`2 EXP 256 * t <= (2 EXP 256 - 1) EXP 2 + (2 EXP 256 - 1) * p
==> t < 2 EXP 256 + p`) THEN
REWRITE_TAC[p_256] THEN CONV_TAC NUM_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
REWRITE_TAC[p_256; REAL_ARITH `a:real < b + c <=> a - b < c`] THEN
ASM_REWRITE_TAC[] THEN BOUNDER_TAC[];
REWRITE_TAC[REAL_CONGRUENCE; p_256] THEN CONV_TAC NUM_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["a"; "b"; "t"] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; bignum_of_wordlist] THEN
ASM_REWRITE_TAC[] THEN REAL_INTEGER_TAC];
ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN
X86_ACCSTEPS_TAC BIGNUM_MONTMUL_P256_ALT_EXEC
[151;153;156;158;159] (150--167) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP
(NUMBER_RULE
`(e * t == ab) (mod p)
==> (e * i == 1) (mod p) /\ (s == t) (mod p)
==> (s == i * ab) (mod p)`)) THEN
REWRITE_TAC[INVERSE_MOD_RMUL_EQ; COPRIME_REXP; COPRIME_2] THEN
CONJ_TAC THENL
[REWRITE_TAC[p_256] THEN CONV_TAC NUM_REDUCE_CONV; ALL_TAC] THEN
SUBGOAL_THEN `carry_s159 <=> p_256 <= t` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `320` THEN
EXPAND_TAC "t" THEN
REWRITE_TAC[p_256; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN
CONV_TAC NUM_REDUCE_CONV THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
REWRITE_TAC[GSYM NOT_LT; COND_SWAP]] THEN
MATCH_MP_TAC(NUMBER_RULE `!b:num. x + b * p = y ==> (x == y) (mod p)`) THEN
EXISTS_TAC `bitval(p_256 <= t)` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REWRITE_TAC[REAL_OF_NUM_LE] THEN
ONCE_REWRITE_TAC[REAL_ARITH `a + b:real = c <=> c - b = a`] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`256`; `&0:real`] THEN CONJ_TAC THENL
[UNDISCH_TAC `t < 2 EXP 256 + p_256` THEN
REWRITE_TAC[bitval; p_256; GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC;
REWRITE_TAC[INTEGER_CLOSED]] THEN
CONJ_TAC THENL
[CONV_TAC(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN BOUNDER_TAC[];
ALL_TAC] THEN
CONV_TAC(ONCE_DEPTH_CONV BIGNUM_EXPAND_CONV) THEN
REWRITE_TAC[bitval] THEN COND_CASES_TAC THEN
EXPAND_TAC "t" THEN REWRITE_TAC[bignum_of_wordlist] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST (MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
REWRITE_TAC[BITVAL_CLAUSES; p_256] THEN
CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC);;
let BIGNUM_AMONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 40),48) /\
ALL (nonoverlapping (word_sub stackpointer (word 40),40))
[(word pc,0x233); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x233) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(bignum_from_memory (z,4) s ==
inverse_mod p_256 (2 EXP 256) * a * b) (mod p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 40),40)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC
bignum_montmul_p256_alt_mc BIGNUM_AMONTMUL_P256_ALT_CORRECT
`[RBX; R12; R13; R14; R15]` 40);;
let windows_bignum_montmul_p256_alt_mc = define_from_elf
"windows_bignum_montmul_p256_alt_mc" "x86/p256/bignum_montmul_p256_alt.obj";;
let WINDOWS_BIGNUM_MONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 56),64) /\
ALL (nonoverlapping (word_sub stackpointer (word 56),56))
[(word pc,0x240); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x240) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(a * b <= 2 EXP 256 * p_256
==> bignum_from_memory (z,4) s =
(inverse_mod p_256 (2 EXP 256) * a * b) MOD p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 56),56)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC
windows_bignum_montmul_p256_alt_mc bignum_montmul_p256_alt_mc
BIGNUM_MONTMUL_P256_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);;
let WINDOWS_BIGNUM_AMONTMUL_P256_ALT_SUBROUTINE_CORRECT = time prove
(`!z x y a b pc stackpointer returnaddress.
nonoverlapping (z,8 * 4) (word_sub stackpointer (word 56),64) /\
ALL (nonoverlapping (word_sub stackpointer (word 56),56))
[(word pc,0x240); (x,8 * 4); (y,8 * 4)] /\
nonoverlapping (word pc,0x240) (z,8 * 4)
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_montmul_p256_alt_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = a /\
bignum_from_memory (y,4) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(bignum_from_memory (z,4) s ==
inverse_mod p_256 (2 EXP 256) * a * b) (mod p_256))
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 4);
memory :> bytes(word_sub stackpointer (word 56),56)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC
windows_bignum_montmul_p256_alt_mc bignum_montmul_p256_alt_mc
BIGNUM_AMONTMUL_P256_ALT_CORRECT `[RBX; R12; R13; R14; R15]` 40);;
|
1c4099244255e11ad1c9eac152b79b4a695f7909d4e0168064093513491ee8cd | gvolpe/haskell-book-exercises | intermission.hs | --- Lamda expressions
addOneIfOdd n = case odd n of
True -> f n
False -> n
where f = \n -> n + 1
addFive = \x -> \y -> (if x > y then y else x) + 5
mflip f x y = f y x
-- Pattern matching
f :: (a, b, c) -> (d, e, f) -> ((a, d), (c, f))
f (a, _, c) (d, _, f) = ((a, d), (c, f))
-- Case Expressions
functionC x y = case x > y of
True -> x
False -> y
ifEvenAdd2 n = case even n of
True -> (n+2)
False -> n
nums x = case compare x 0 of
LT -> -1
GT -> 1
EQ -> 0
| null | https://raw.githubusercontent.com/gvolpe/haskell-book-exercises/5c1b9d8dc729ee5a90c8709b9c889cbacb30a2cb/chapter7/intermission.hs | haskell | - Lamda expressions
Pattern matching
Case Expressions | addOneIfOdd n = case odd n of
True -> f n
False -> n
where f = \n -> n + 1
addFive = \x -> \y -> (if x > y then y else x) + 5
mflip f x y = f y x
f :: (a, b, c) -> (d, e, f) -> ((a, d), (c, f))
f (a, _, c) (d, _, f) = ((a, d), (c, f))
functionC x y = case x > y of
True -> x
False -> y
ifEvenAdd2 n = case even n of
True -> (n+2)
False -> n
nums x = case compare x 0 of
LT -> -1
GT -> 1
EQ -> 0
|
a1980f1db91b7866fe5e328c415e85dd39ef89fcdf3cab28246b2e18f5474a78 | repl-electric/cassiopeia | buffers.clj | (ns cassiopeia.engine.buffers
(:use
[overtone.live]
[overtone.helpers audio-file lib file doc]))
(defn buffer-mix-to-mono [b]
(ensure-buffer-active! b)
(let [n-chans (:n-channels b)
rate (:rate b)]
(cond
(= 1 n-chans) b
:else
(let [data (buffer-data b)
partitioned (partition n-chans (seq data))
mixed (mapv (fn [samps] (/ (apply + samps) n-chans)) partitioned)
tmp-file-path (mk-path (mk-tmp-dir!) "mono-file.wav")]
(write-wav mixed tmp-file-path rate 1)
(let [new-b (buffer-alloc-read tmp-file-path)]
(future (rm-rf! tmp-file-path))
new-b)))))
| null | https://raw.githubusercontent.com/repl-electric/cassiopeia/a42c01752fc8dd04ea5db95c8037f393c29cdb75/src/cassiopeia/engine/buffers.clj | clojure | (ns cassiopeia.engine.buffers
(:use
[overtone.live]
[overtone.helpers audio-file lib file doc]))
(defn buffer-mix-to-mono [b]
(ensure-buffer-active! b)
(let [n-chans (:n-channels b)
rate (:rate b)]
(cond
(= 1 n-chans) b
:else
(let [data (buffer-data b)
partitioned (partition n-chans (seq data))
mixed (mapv (fn [samps] (/ (apply + samps) n-chans)) partitioned)
tmp-file-path (mk-path (mk-tmp-dir!) "mono-file.wav")]
(write-wav mixed tmp-file-path rate 1)
(let [new-b (buffer-alloc-read tmp-file-path)]
(future (rm-rf! tmp-file-path))
new-b)))))
|
|
52e8e13106d7ced56c4d4071e09f6af9ccc7ba921fb452fb4ef09839bf91ef6b | jwiegley/notes | schroedinger3.hs | import System.Random
flipCoin :: StdGen -> Bool
flipCoin gen = fst $ random gen
data Cat = Cat String deriving Show
data Probable a = Live a | Dead deriving Show
flipCat :: StdGen -> a -> Probable a
flipCat gen cat = if flipCoin gen
then Live cat
else Dead
data Schroedinger a
= Opened (Probable a)
| Unopened StdGen a deriving Show
instance Monad Schroedinger where
Opened Dead >>= _ = Opened Dead
Opened (Live a) >>= f = f a
Unopened y x >>= f = Opened (flipCat y x) >>= f
return x = Opened (Live x)
main = do
gen <- getStdGen
print (do
box <- Unopened gen (Cat "Felix")
-- The cat's fate is undecided
return box)
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/schroedinger3.hs | haskell | The cat's fate is undecided | import System.Random
flipCoin :: StdGen -> Bool
flipCoin gen = fst $ random gen
data Cat = Cat String deriving Show
data Probable a = Live a | Dead deriving Show
flipCat :: StdGen -> a -> Probable a
flipCat gen cat = if flipCoin gen
then Live cat
else Dead
data Schroedinger a
= Opened (Probable a)
| Unopened StdGen a deriving Show
instance Monad Schroedinger where
Opened Dead >>= _ = Opened Dead
Opened (Live a) >>= f = f a
Unopened y x >>= f = Opened (flipCat y x) >>= f
return x = Opened (Live x)
main = do
gen <- getStdGen
print (do
box <- Unopened gen (Cat "Felix")
return box)
|
38b0bae9c50cbddf506921eb638b04b0d14ed27ea854e1fd34f09daac7a0426c | tomsmalley/semantic-reflex | Rail.hs | # LANGUAGE TemplateHaskell #
-- | Semantic UI rails.
-- -ui.com/elements/rail.html
module Reflex.Dom.SemanticUI.Rail
(
-- * Rail
rail, rail'
, RailConfig (..)
, RailSide (..)
, railConfig_dividing
, railConfig_internal
, railConfig_attached
, railConfig_close
, railConfig_size
, railConfig_elConfig
) where
import Control.Lens.TH (makeLensesWith, lensRules, simpleLenses)
import Data.Default
import Data.Semigroup ((<>))
import Reflex
import Reflex.Dom.Core
import Reflex.Active
import Reflex.Dom.SemanticUI.Common
import Reflex.Dom.SemanticUI.Transition
data RailSide = LeftRail | RightRail
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText RailSide where
toClassText LeftRail = "left"
toClassText RightRail = "right"
data RailClose = Close | VeryClose
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText RailClose where
toClassText Close = "close"
toClassText VeryClose = "very close"
data RailConfig t = RailConfig
{ _railConfig_dividing :: Active t Bool
, _railConfig_internal :: Active t Bool
, _railConfig_attached :: Active t Bool
, _railConfig_close :: Active t (Maybe RailClose)
, _railConfig_size :: Active t (Maybe Size)
, _railConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''RailConfig
instance HasElConfig t (RailConfig t) where
elConfig = railConfig_elConfig
instance Reflex t => Default (RailConfig t) where
def = RailConfig
{ _railConfig_dividing = pure False
, _railConfig_internal = pure False
, _railConfig_attached = pure False
, _railConfig_close = pure Nothing
, _railConfig_size = pure Nothing
, _railConfig_elConfig = def
}
-- | Make the rail div classes from the configuration
railConfigClasses :: Reflex t => RailConfig t -> Active t Classes
railConfigClasses RailConfig {..} = dynClasses
[ pure $ Just "ui rail"
, boolClass "dividing" _railConfig_dividing
, boolClass "internal" _railConfig_internal
, boolClass "attached" _railConfig_attached
, fmap toClassText <$> _railConfig_close
, fmap toClassText <$> _railConfig_size
]
-- | Rail UI Element.
rail'
:: UI t m => RailSide -> RailConfig t -> m a
-> m (Element EventResult (DomBuilderSpace m) t, a)
rail' railSide config@RailConfig {..} content
= ui' "div" elConf content
where
elConf = _railConfig_elConfig <> def
{ _classes = addClass (toClassText railSide)
<$> railConfigClasses config }
-- | Rail UI Element.
rail :: UI t m => RailSide -> RailConfig t -> m a -> m a
rail railSide config = fmap snd . rail' railSide config
| null | https://raw.githubusercontent.com/tomsmalley/semantic-reflex/5a973390fae1facbc4351b75ea59210d6756b8e5/semantic-reflex/src/Reflex/Dom/SemanticUI/Rail.hs | haskell | | Semantic UI rails.
-ui.com/elements/rail.html
* Rail
| Make the rail div classes from the configuration
| Rail UI Element.
| Rail UI Element. | # LANGUAGE TemplateHaskell #
module Reflex.Dom.SemanticUI.Rail
(
rail, rail'
, RailConfig (..)
, RailSide (..)
, railConfig_dividing
, railConfig_internal
, railConfig_attached
, railConfig_close
, railConfig_size
, railConfig_elConfig
) where
import Control.Lens.TH (makeLensesWith, lensRules, simpleLenses)
import Data.Default
import Data.Semigroup ((<>))
import Reflex
import Reflex.Dom.Core
import Reflex.Active
import Reflex.Dom.SemanticUI.Common
import Reflex.Dom.SemanticUI.Transition
data RailSide = LeftRail | RightRail
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText RailSide where
toClassText LeftRail = "left"
toClassText RightRail = "right"
data RailClose = Close | VeryClose
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText RailClose where
toClassText Close = "close"
toClassText VeryClose = "very close"
data RailConfig t = RailConfig
{ _railConfig_dividing :: Active t Bool
, _railConfig_internal :: Active t Bool
, _railConfig_attached :: Active t Bool
, _railConfig_close :: Active t (Maybe RailClose)
, _railConfig_size :: Active t (Maybe Size)
, _railConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''RailConfig
instance HasElConfig t (RailConfig t) where
elConfig = railConfig_elConfig
instance Reflex t => Default (RailConfig t) where
def = RailConfig
{ _railConfig_dividing = pure False
, _railConfig_internal = pure False
, _railConfig_attached = pure False
, _railConfig_close = pure Nothing
, _railConfig_size = pure Nothing
, _railConfig_elConfig = def
}
railConfigClasses :: Reflex t => RailConfig t -> Active t Classes
railConfigClasses RailConfig {..} = dynClasses
[ pure $ Just "ui rail"
, boolClass "dividing" _railConfig_dividing
, boolClass "internal" _railConfig_internal
, boolClass "attached" _railConfig_attached
, fmap toClassText <$> _railConfig_close
, fmap toClassText <$> _railConfig_size
]
rail'
:: UI t m => RailSide -> RailConfig t -> m a
-> m (Element EventResult (DomBuilderSpace m) t, a)
rail' railSide config@RailConfig {..} content
= ui' "div" elConf content
where
elConf = _railConfig_elConfig <> def
{ _classes = addClass (toClassText railSide)
<$> railConfigClasses config }
rail :: UI t m => RailSide -> RailConfig t -> m a -> m a
rail railSide config = fmap snd . rail' railSide config
|
d5a260408500afde58af4cab4c589daef0d5a94f2aba7e2c07d96b6c684690e0 | opencensus-beam/opencensus-prometheus | oc_stat_exporter_prometheus.erl | -module(oc_stat_exporter_prometheus).
-export([collect_mf/2,
deregister_cleanup/1]).
-behaviour(prometheus_collector).
collect_mf(_Registry, Callback) ->
ViewDatas = oc_stat:export(),
[Callback(view_data_to_mf(ViewData)) || ViewData <- ViewDatas],
ok.
deregister_cleanup(_Registry) ->
ok.
-spec view_data_to_mf(oc_stat_view:view_data()) ->
prometheus_model:'MetricFamily'().
view_data_to_mf(#{name := Name,
description := Description,
ctags := CTags,
tags := Tags,
data := #{type := Type,
rows := Rows}}) ->
FullRows = augment_rows_tags(Rows, Tags, CTags),
Metrics = rows_to_metrics(Type, FullRows),
prometheus_model_helpers:create_mf(sanitize(Name), Description, to_prom_type(Type), Metrics).
augment_rows_tags(Rows, Tags, CTags) ->
[{maps:to_list(maps:merge(CTags, maps:from_list(lists:zip(Tags, TagsV)))), Value}
|| #{tags := TagsV, value := Value} <- Rows].
rows_to_metrics(latest, Rows) ->
prometheus_model_helpers:gauge_metrics(Rows);
rows_to_metrics(count, Rows) ->
prometheus_model_helpers:counter_metrics(Rows);
rows_to_metrics(sum, Rows) ->
[prometheus_model_helpers:summary_metric(Tags, Count, Sum)
|| {Tags, #{count := Count, sum := Sum}} <- Rows];
rows_to_metrics(distribution, Rows) ->
[prometheus_model_helpers:histogram_metric(
Tags, sum_bucket_counters(Buckets), Count, Sum)
|| {Tags, #{count := Count, sum := Sum, buckets := Buckets}} <- Rows].
sum_bucket_counters([{Bound, Start} | Counters]) ->
sum_bucket_counters(Counters, [{Bound, Start}], Start).
sum_bucket_counters([], LAcc, _CAcc) ->
LAcc;
sum_bucket_counters([{Bucket, Counter} | Counters], LAcc, CAcc) ->
sum_bucket_counters(Counters, LAcc ++ [{Bucket, CAcc + Counter}], CAcc + Counter).
to_prom_type(latest) ->
gauge;
to_prom_type(count) ->
counter;
to_prom_type(sum) ->
summary;
to_prom_type(distribution) ->
histogram.
%% replace all non-alphanumeric characters with underscores
sanitize(String) ->
case re:replace(String, "[^[:alpha:][:digit:]:]+", "_", [global]) of
[$_ | _]=S ->
["key", S];
[D | _]=S when D >= 48 andalso D =< 57->
["key_", S];
S ->
S
end.
| null | https://raw.githubusercontent.com/opencensus-beam/opencensus-prometheus/1909783ab63fd8a14c347a8dcd83f541782c98de/src/oc_stat_exporter_prometheus.erl | erlang | replace all non-alphanumeric characters with underscores | -module(oc_stat_exporter_prometheus).
-export([collect_mf/2,
deregister_cleanup/1]).
-behaviour(prometheus_collector).
collect_mf(_Registry, Callback) ->
ViewDatas = oc_stat:export(),
[Callback(view_data_to_mf(ViewData)) || ViewData <- ViewDatas],
ok.
deregister_cleanup(_Registry) ->
ok.
-spec view_data_to_mf(oc_stat_view:view_data()) ->
prometheus_model:'MetricFamily'().
view_data_to_mf(#{name := Name,
description := Description,
ctags := CTags,
tags := Tags,
data := #{type := Type,
rows := Rows}}) ->
FullRows = augment_rows_tags(Rows, Tags, CTags),
Metrics = rows_to_metrics(Type, FullRows),
prometheus_model_helpers:create_mf(sanitize(Name), Description, to_prom_type(Type), Metrics).
augment_rows_tags(Rows, Tags, CTags) ->
[{maps:to_list(maps:merge(CTags, maps:from_list(lists:zip(Tags, TagsV)))), Value}
|| #{tags := TagsV, value := Value} <- Rows].
rows_to_metrics(latest, Rows) ->
prometheus_model_helpers:gauge_metrics(Rows);
rows_to_metrics(count, Rows) ->
prometheus_model_helpers:counter_metrics(Rows);
rows_to_metrics(sum, Rows) ->
[prometheus_model_helpers:summary_metric(Tags, Count, Sum)
|| {Tags, #{count := Count, sum := Sum}} <- Rows];
rows_to_metrics(distribution, Rows) ->
[prometheus_model_helpers:histogram_metric(
Tags, sum_bucket_counters(Buckets), Count, Sum)
|| {Tags, #{count := Count, sum := Sum, buckets := Buckets}} <- Rows].
sum_bucket_counters([{Bound, Start} | Counters]) ->
sum_bucket_counters(Counters, [{Bound, Start}], Start).
sum_bucket_counters([], LAcc, _CAcc) ->
LAcc;
sum_bucket_counters([{Bucket, Counter} | Counters], LAcc, CAcc) ->
sum_bucket_counters(Counters, LAcc ++ [{Bucket, CAcc + Counter}], CAcc + Counter).
to_prom_type(latest) ->
gauge;
to_prom_type(count) ->
counter;
to_prom_type(sum) ->
summary;
to_prom_type(distribution) ->
histogram.
sanitize(String) ->
case re:replace(String, "[^[:alpha:][:digit:]:]+", "_", [global]) of
[$_ | _]=S ->
["key", S];
[D | _]=S when D >= 48 andalso D =< 57->
["key_", S];
S ->
S
end.
|
504241b2b714844034ec196bc2d203da0a0467f4cdd31fca533ae237af90eb2f | finnishtransportagency/harja | turvallisuuspoikkeaman_kirjaus_test.clj | (ns harja.palvelin.integraatiot.api.turvallisuuspoikkeaman-kirjaus-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[harja.testi :refer :all]
[harja.palvelin.komponentit.liitteet :as liitteet]
[com.stuartsierra.component :as component]
[harja.palvelin.integraatiot.api.turvallisuuspoikkeama :as turvallisuuspoikkeama]
[harja.palvelin.integraatiot.api.tyokalut :as api-tyokalut]
[cheshire.core :as cheshire]
[taoensso.timbre :as log]
[clojure.core.match :refer [match]]
[harja.palvelin.integraatiot.turi.turi-komponentti :as turi]
[clj-time.coerce :as c]
[clj-time.core :as t]
[harja.kyselyt.konversio :as konv]
[clojure.string :as str]))
(def kayttaja "yit-rakennus")
(def jarjestelma-fixture
(laajenna-integraatiojarjestelmafixturea
kayttaja
:liitteiden-hallinta (component/using (liitteet/->Liitteet nil) [:db])
:turi (component/using
(turi/->Turi {})
[:db :integraatioloki :liitteiden-hallinta])
:api-turvallisuuspoikkeama (component/using (turvallisuuspoikkeama/->Turvallisuuspoikkeama)
[:http-palvelin :db :integraatioloki :liitteiden-hallinta :turi])))
(use-fixtures :once jarjestelma-fixture)
(defn hae-turvallisuuspoikkeama-ulkoisella-idlla [ulkoinen-id]
(as-> (first (q (str "SELECT
id,
urakka,
tapahtunut,
kasitelty,
sijainti,
kuvaus,
sairauspoissaolopaivat,
sairaalavuorokaudet,
tr_numero,
tr_alkuosa,
tr_alkuetaisyys,
tr_loppuosa,
tr_loppuetaisyys,
vahinkoluokittelu,
vakavuusaste,
tyyppi,
tyontekijanammatti,
tyontekijanammatti_muu,
aiheutuneet_seuraukset,
vammat,
vahingoittuneet_ruumiinosat,
sairauspoissaolo_jatkuu,
ilmoittaja_etunimi,
ilmoittaja_sukunimi,
vaylamuoto,
toteuttaja,
tilaaja,
turvallisuuskoordinaattori_etunimi,
turvallisuuskoordinaattori_sukunimi,
tapahtuman_otsikko,
paikan_kuvaus,
vaarallisten_aineiden_kuljetus,
vaarallisten_aineiden_vuoto,
juurisyy1, juurisyy1_selite,
juurisyy2, juurisyy2_selite,
juurisyy3, juurisyy3_selite
FROM turvallisuuspoikkeama
WHERE ulkoinen_id = " ulkoinen-id
" LIMIT 1;")))
turpo
Tapahtumapvm > clj - time
(assoc turpo 2 (c/from-sql-date (get turpo 2)))
(assoc turpo 3 (c/from-sql-date (get turpo 3)))
;; Vahinkoluokittelu -> set
(assoc turpo 13 (into #{} (when-let [arvo (get turpo 13)]
(.getArray arvo))))
;; Tyyppi -> set
(assoc turpo 15 (into #{} (when-let [arvo (get turpo 15)]
(.getArray arvo))))))
(defn hae-korjaavat-toimenpiteet [turpo-id]
(as-> (q (str "SELECT
kuvaus,
suoritettu,
otsikko,
vastuuhenkilo,
toteuttaja,
tila
FROM korjaavatoimenpide
WHERE turvallisuuspoikkeama = " turpo-id ";"))
toimenpide
(mapv #(assoc % 1 (c/from-sql-date (get % 1))) toimenpide)))
(deftest tallenna-turvallisuuspoikkeama
(let [ulkoinen-id 757577
urakka (hae-urakan-id-nimella "Oulun alueurakka 2005-2012")
liitteiden-maara-ennen (first (first (q "select count(id) FROM liite")))
tp-kannassa-ennen-pyyntoa (ffirst (q (str "SELECT COUNT(*) FROM turvallisuuspoikkeama;")))
vastaus (api-tyokalut/post-kutsu ["/api/urakat/" urakka "/turvallisuuspoikkeama"]
kayttaja portti
(-> "test/resurssit/api/turvallisuuspoikkeama.json"
slurp
(.replace "__PAIKKA__" "Liukas tie keskellä metsää.")
(.replace "__TAPAHTUMAPAIVAMAARA__" "2016-01-30T12:00:00Z")))]
(cheshire/decode (:body vastaus) true)
(is (= 200 (:status vastaus)))
, että turpon kirjaus
(let [tp-kannassa-pyynnon-jalkeen (ffirst (q (str "SELECT COUNT(*) FROM turvallisuuspoikkeama;")))
liite-id (ffirst (q (str "SELECT id FROM liite WHERE nimi = 'testitp36934853.jpg';")))
tp-id (ffirst (q (str "SELECT id FROM turvallisuuspoikkeama WHERE kuvaus ='Aura-auto suistui tieltä väistäessä jalankulkijaa.'")))
kommentti-id (ffirst (q (str "SELECT id FROM kommentti WHERE kommentti='Testikommentti';")))]
(is (= (+ tp-kannassa-ennen-pyyntoa 1) tp-kannassa-pyynnon-jalkeen))
(is (number? liite-id))
(is (number? tp-id))
(is (number? kommentti-id)))
, että data
(let [uusin-tp (hae-turvallisuuspoikkeama-ulkoisella-idlla ulkoinen-id)
turpo-id (first uusin-tp)
korjaavat-toimenpiteet (hae-korjaavat-toimenpiteet turpo-id)
[juurisyy1 juurisyy1-selite
juurisyy2 juurisyy2-selite
juurisyy3 juurisyy3-selite] (drop 33 uusin-tp)]
Testissä on 1 juurisyy , on puutteelliset henkilönsuojaimet
(is (= juurisyy1 "puutteelliset_henkilonsuojaimet"))
(is (= juurisyy1-selite "ei ollut suojaliivit päällä"))
(is (= nil juurisyy2 juurisyy2-selite juurisyy3 juurisyy3-selite))
(is (t/year (nth uusin-tp 3)) 2016)
(is (t/month (nth uusin-tp 3)) 1)
(is (t/day (nth uusin-tp 3)) 30)
(is (= (nth uusin-tp 5) "Aura-auto suistui tieltä väistäessä jalankulkijaa."))
(is (= (nth uusin-tp 13) #{"henkilovahinko"}))
(is (= (nth uusin-tp 14) "vakava"))
(is (= (nth uusin-tp 15) #{"tyotapaturma" "vaaratilanne"}))
(is (= (nth uusin-tp 16) "muu_tyontekija"))
(is (= (nth uusin-tp 17) "Auraaja"))
(is (= (nth uusin-tp 18) "Sairaalareissu"))
Vain 1 .
(is (= (konv/array->set (nth uusin-tp 20)) #{"selka"}))
(is (= (nth uusin-tp 22) "Veera"))
(is (= (nth uusin-tp 23) "Veistelijä"))
(is (= (nth uusin-tp 29) "Aura-auto suistui tieltä"))
(is (= (nth uusin-tp 30) "Liukas tie keskellä metsää."))
(is (= (count korjaavat-toimenpiteet) 1))
(is (match (first korjaavat-toimenpiteet)
["Kaadetaan risteystä pimentävä pensaikko"
(_ :guard #(and (= (t/year %) 2016)
(= (t/month %) 1)
(= (t/day %) 30)))
"Kaadetaan pensaikko"
nil
"Erkki Esimerkki"
"avoin"]
true))
Myös
(let [vanhat-korjaavat-toimenpiteet (hae-korjaavat-toimenpiteet turpo-id)
_ (api-tyokalut/post-kutsu ["/api/urakat/" urakka "/turvallisuuspoikkeama"]
kayttaja portti
(-> "test/resurssit/api/turvallisuuspoikkeama.json"
slurp
(.replace "__PAIKKA__" "Liukas tie metsän reunalla.")
(.replace "__TAPAHTUMAPAIVAMAARA__" "2016-01-30T12:00:00Z")))
uusin-paivitetty-tp (hae-turvallisuuspoikkeama-ulkoisella-idlla ulkoinen-id)
turpo-id (first uusin-paivitetty-tp)
korjaavat-toimenpiteet (hae-korjaavat-toimenpiteet turpo-id)
liitteiden-maara-jalkeen (first (first (q "select count(id) FROM liite")))]
Varmistetaan , ettei
(is (= (+ 1 liitteiden-maara-ennen) liitteiden-maara-jalkeen))
(is (= (nth uusin-paivitetty-tp 30) "Liukas tie metsän reunalla."))
Halutaan , että vanhoja , vaan uudet lisätään
(is (= (count korjaavat-toimenpiteet) (+ (count vanhat-korjaavat-toimenpiteet) 1)))))
(u "DELETE FROM turvallisuuspoikkeama_kommentti WHERE turvallisuuspoikkeama =
(SELECT id FROM turvallisuuspoikkeama WHERE ulkoinen_id = " ulkoinen-id ");")
(u "DELETE FROM turvallisuuspoikkeama_liite WHERE turvallisuuspoikkeama =
(SELECT id FROM turvallisuuspoikkeama WHERE ulkoinen_id = " ulkoinen-id ");")
(u "DELETE FROM korjaavatoimenpide WHERE turvallisuuspoikkeama =
(SELECT id FROM turvallisuuspoikkeama WHERE ulkoinen_id = " ulkoinen-id ");")
(u "DELETE FROM turvallisuuspoikkeama WHERE ulkoinen_id = " ulkoinen-id ";")))
(deftest tallenna-turvallisuuspoikkeama-tulevaisuuteen-kaatuu
(let [urakka (hae-urakan-id-nimella "Oulun alueurakka 2005-2012")
vastaus (api-tyokalut/post-kutsu ["/api/urakat/" urakka "/turvallisuuspoikkeama"]
kayttaja portti
(-> "test/resurssit/api/turvallisuuspoikkeama.json"
slurp
(.replace "__PAIKKA__" "Liukas tie keskellä metsää.")
(.replace "__TAPAHTUMAPAIVAMAARA__" "2066-10-01T00:00:00Z")))]
(cheshire/decode (:body vastaus) true)
(is (not= 200 (:status vastaus)) "Onnea 60-vuotias Harja!")
(is (str/includes? (:body vastaus) "Tapahtumapäivämäärä ei voi olla tulevaisuudessa"))))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/c57d742beaff2bef7b30318819f07d4a13423404/test/clj/harja/palvelin/integraatiot/api/turvallisuuspoikkeaman_kirjaus_test.clj | clojure | Vahinkoluokittelu -> set
Tyyppi -> set
"))
")
")
") | (ns harja.palvelin.integraatiot.api.turvallisuuspoikkeaman-kirjaus-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[harja.testi :refer :all]
[harja.palvelin.komponentit.liitteet :as liitteet]
[com.stuartsierra.component :as component]
[harja.palvelin.integraatiot.api.turvallisuuspoikkeama :as turvallisuuspoikkeama]
[harja.palvelin.integraatiot.api.tyokalut :as api-tyokalut]
[cheshire.core :as cheshire]
[taoensso.timbre :as log]
[clojure.core.match :refer [match]]
[harja.palvelin.integraatiot.turi.turi-komponentti :as turi]
[clj-time.coerce :as c]
[clj-time.core :as t]
[harja.kyselyt.konversio :as konv]
[clojure.string :as str]))
(def kayttaja "yit-rakennus")
(def jarjestelma-fixture
(laajenna-integraatiojarjestelmafixturea
kayttaja
:liitteiden-hallinta (component/using (liitteet/->Liitteet nil) [:db])
:turi (component/using
(turi/->Turi {})
[:db :integraatioloki :liitteiden-hallinta])
:api-turvallisuuspoikkeama (component/using (turvallisuuspoikkeama/->Turvallisuuspoikkeama)
[:http-palvelin :db :integraatioloki :liitteiden-hallinta :turi])))
(use-fixtures :once jarjestelma-fixture)
(defn hae-turvallisuuspoikkeama-ulkoisella-idlla [ulkoinen-id]
(as-> (first (q (str "SELECT
id,
urakka,
tapahtunut,
kasitelty,
sijainti,
kuvaus,
sairauspoissaolopaivat,
sairaalavuorokaudet,
tr_numero,
tr_alkuosa,
tr_alkuetaisyys,
tr_loppuosa,
tr_loppuetaisyys,
vahinkoluokittelu,
vakavuusaste,
tyyppi,
tyontekijanammatti,
tyontekijanammatti_muu,
aiheutuneet_seuraukset,
vammat,
vahingoittuneet_ruumiinosat,
sairauspoissaolo_jatkuu,
ilmoittaja_etunimi,
ilmoittaja_sukunimi,
vaylamuoto,
toteuttaja,
tilaaja,
turvallisuuskoordinaattori_etunimi,
turvallisuuskoordinaattori_sukunimi,
tapahtuman_otsikko,
paikan_kuvaus,
vaarallisten_aineiden_kuljetus,
vaarallisten_aineiden_vuoto,
juurisyy1, juurisyy1_selite,
juurisyy2, juurisyy2_selite,
juurisyy3, juurisyy3_selite
FROM turvallisuuspoikkeama
WHERE ulkoinen_id = " ulkoinen-id
" LIMIT 1;")))
turpo
Tapahtumapvm > clj - time
(assoc turpo 2 (c/from-sql-date (get turpo 2)))
(assoc turpo 3 (c/from-sql-date (get turpo 3)))
(assoc turpo 13 (into #{} (when-let [arvo (get turpo 13)]
(.getArray arvo))))
(assoc turpo 15 (into #{} (when-let [arvo (get turpo 15)]
(.getArray arvo))))))
(defn hae-korjaavat-toimenpiteet [turpo-id]
(as-> (q (str "SELECT
kuvaus,
suoritettu,
otsikko,
vastuuhenkilo,
toteuttaja,
tila
FROM korjaavatoimenpide
toimenpide
(mapv #(assoc % 1 (c/from-sql-date (get % 1))) toimenpide)))
(deftest tallenna-turvallisuuspoikkeama
(let [ulkoinen-id 757577
urakka (hae-urakan-id-nimella "Oulun alueurakka 2005-2012")
liitteiden-maara-ennen (first (first (q "select count(id) FROM liite")))
tp-kannassa-ennen-pyyntoa (ffirst (q (str "SELECT COUNT(*) FROM turvallisuuspoikkeama;")))
vastaus (api-tyokalut/post-kutsu ["/api/urakat/" urakka "/turvallisuuspoikkeama"]
kayttaja portti
(-> "test/resurssit/api/turvallisuuspoikkeama.json"
slurp
(.replace "__PAIKKA__" "Liukas tie keskellä metsää.")
(.replace "__TAPAHTUMAPAIVAMAARA__" "2016-01-30T12:00:00Z")))]
(cheshire/decode (:body vastaus) true)
(is (= 200 (:status vastaus)))
, että turpon kirjaus
(let [tp-kannassa-pyynnon-jalkeen (ffirst (q (str "SELECT COUNT(*) FROM turvallisuuspoikkeama;")))
liite-id (ffirst (q (str "SELECT id FROM liite WHERE nimi = 'testitp36934853.jpg';")))
tp-id (ffirst (q (str "SELECT id FROM turvallisuuspoikkeama WHERE kuvaus ='Aura-auto suistui tieltä väistäessä jalankulkijaa.'")))
kommentti-id (ffirst (q (str "SELECT id FROM kommentti WHERE kommentti='Testikommentti';")))]
(is (= (+ tp-kannassa-ennen-pyyntoa 1) tp-kannassa-pyynnon-jalkeen))
(is (number? liite-id))
(is (number? tp-id))
(is (number? kommentti-id)))
, että data
(let [uusin-tp (hae-turvallisuuspoikkeama-ulkoisella-idlla ulkoinen-id)
turpo-id (first uusin-tp)
korjaavat-toimenpiteet (hae-korjaavat-toimenpiteet turpo-id)
[juurisyy1 juurisyy1-selite
juurisyy2 juurisyy2-selite
juurisyy3 juurisyy3-selite] (drop 33 uusin-tp)]
Testissä on 1 juurisyy , on puutteelliset henkilönsuojaimet
(is (= juurisyy1 "puutteelliset_henkilonsuojaimet"))
(is (= juurisyy1-selite "ei ollut suojaliivit päällä"))
(is (= nil juurisyy2 juurisyy2-selite juurisyy3 juurisyy3-selite))
(is (t/year (nth uusin-tp 3)) 2016)
(is (t/month (nth uusin-tp 3)) 1)
(is (t/day (nth uusin-tp 3)) 30)
(is (= (nth uusin-tp 5) "Aura-auto suistui tieltä väistäessä jalankulkijaa."))
(is (= (nth uusin-tp 13) #{"henkilovahinko"}))
(is (= (nth uusin-tp 14) "vakava"))
(is (= (nth uusin-tp 15) #{"tyotapaturma" "vaaratilanne"}))
(is (= (nth uusin-tp 16) "muu_tyontekija"))
(is (= (nth uusin-tp 17) "Auraaja"))
(is (= (nth uusin-tp 18) "Sairaalareissu"))
Vain 1 .
(is (= (konv/array->set (nth uusin-tp 20)) #{"selka"}))
(is (= (nth uusin-tp 22) "Veera"))
(is (= (nth uusin-tp 23) "Veistelijä"))
(is (= (nth uusin-tp 29) "Aura-auto suistui tieltä"))
(is (= (nth uusin-tp 30) "Liukas tie keskellä metsää."))
(is (= (count korjaavat-toimenpiteet) 1))
(is (match (first korjaavat-toimenpiteet)
["Kaadetaan risteystä pimentävä pensaikko"
(_ :guard #(and (= (t/year %) 2016)
(= (t/month %) 1)
(= (t/day %) 30)))
"Kaadetaan pensaikko"
nil
"Erkki Esimerkki"
"avoin"]
true))
Myös
(let [vanhat-korjaavat-toimenpiteet (hae-korjaavat-toimenpiteet turpo-id)
_ (api-tyokalut/post-kutsu ["/api/urakat/" urakka "/turvallisuuspoikkeama"]
kayttaja portti
(-> "test/resurssit/api/turvallisuuspoikkeama.json"
slurp
(.replace "__PAIKKA__" "Liukas tie metsän reunalla.")
(.replace "__TAPAHTUMAPAIVAMAARA__" "2016-01-30T12:00:00Z")))
uusin-paivitetty-tp (hae-turvallisuuspoikkeama-ulkoisella-idlla ulkoinen-id)
turpo-id (first uusin-paivitetty-tp)
korjaavat-toimenpiteet (hae-korjaavat-toimenpiteet turpo-id)
liitteiden-maara-jalkeen (first (first (q "select count(id) FROM liite")))]
Varmistetaan , ettei
(is (= (+ 1 liitteiden-maara-ennen) liitteiden-maara-jalkeen))
(is (= (nth uusin-paivitetty-tp 30) "Liukas tie metsän reunalla."))
Halutaan , että vanhoja , vaan uudet lisätään
(is (= (count korjaavat-toimenpiteet) (+ (count vanhat-korjaavat-toimenpiteet) 1)))))
(u "DELETE FROM turvallisuuspoikkeama_kommentti WHERE turvallisuuspoikkeama =
(u "DELETE FROM turvallisuuspoikkeama_liite WHERE turvallisuuspoikkeama =
(u "DELETE FROM korjaavatoimenpide WHERE turvallisuuspoikkeama =
(u "DELETE FROM turvallisuuspoikkeama WHERE ulkoinen_id = " ulkoinen-id ";")))
(deftest tallenna-turvallisuuspoikkeama-tulevaisuuteen-kaatuu
(let [urakka (hae-urakan-id-nimella "Oulun alueurakka 2005-2012")
vastaus (api-tyokalut/post-kutsu ["/api/urakat/" urakka "/turvallisuuspoikkeama"]
kayttaja portti
(-> "test/resurssit/api/turvallisuuspoikkeama.json"
slurp
(.replace "__PAIKKA__" "Liukas tie keskellä metsää.")
(.replace "__TAPAHTUMAPAIVAMAARA__" "2066-10-01T00:00:00Z")))]
(cheshire/decode (:body vastaus) true)
(is (not= 200 (:status vastaus)) "Onnea 60-vuotias Harja!")
(is (str/includes? (:body vastaus) "Tapahtumapäivämäärä ei voi olla tulevaisuudessa"))))
|
77ebef64d0c7a16015233cb1d2b43707b9876d77e984e172d01c76e8cd71e3fb | linyinfeng/myml | Subst.hs | # LANGUAGE LambdaCase #
module Myml.Subst
( substTerm,
TypeSubst (..),
compositeTypeSubst,
compositeTermSubst,
)
where
import Control.Monad.Except
import Control.Monad.Reader
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import Myml.Syntax
import Prettyprinter
substTerm :: Map.Map VarName Term -> Term -> Term
substTerm s t = runReader (substTerm' t) s
substTerm' :: Term -> Reader (Map.Map VarName Term) Term
substTerm' (TmAbs x t) =
handleTermBind x >>= \(newX, inner) -> TmAbs newX <$> inner (substTerm' t)
substTerm' (TmApp t1 t2) = TmApp <$> substTerm' t1 <*> substTerm' t2
substTerm' (TmVar x) =
ask >>= \s -> return (fromMaybe (TmVar x) (Map.lookup x s))
substTerm' (TmLet x t1 t2) = do
t1' <- substTerm' t1
(newX, inner) <- handleTermBind x
TmLet newX t1' <$> inner (substTerm' t2)
substTerm' t = return t
compositeTermSubst ::
Map.Map VarName Term -> Map.Map VarName Term -> Map.Map VarName Term
compositeTermSubst sa sb = Map.map (substTerm sa) sb `Map.union` sa
class TypeSubst a where
substType :: Map.Map VarName TypeSubstituter -> a -> Either Error a
substType s t = runReader (runExceptT (substType' t)) s
substType' :: a -> ExceptT Error (Reader (Map.Map VarName TypeSubstituter)) a
compositeTypeSubst ::
Map.Map VarName TypeSubstituter ->
Map.Map VarName TypeSubstituter ->
Either Error (Map.Map VarName TypeSubstituter)
compositeTypeSubst sa sb =
flip Map.union sa <$> sequence (Map.map (substType sa) sb)
instance TypeSubst TypeSubstituter where
substType' (TySubProper t) = TySubProper <$> substType' t
substType' (TySubPresenceWithType p) = TySubPresenceWithType <$> substType' p
substType' (TySubPresence p) = TySubPresence <$> substType' p
substType' (TySubRow r) = TySubRow <$> substType' r
instance TypeSubst Type where
substType' (TyVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (TyVar x)
Just (TySubProper t) -> return t
Just s -> throwError (ErrVarKindConflict x KProper (kindOfTySub s))
substType' (TyArrow t1 t2) = TyArrow <$> substType' t1 <*> substType' t2
substType' (TyRecord row) = TyRecord <$> substType' row
substType' (TyVariant row) = TyVariant <$> substType' row
substType' (TyMu x t) =
handleTypeBind x (TySubProper . TyVar)
>>= \(newX, inner) -> TyMu newX <$> inner (substType' t)
substType' (TyRef t) = TyRef <$> substType' t
substType' TyInteger = return TyInteger
substType' TyChar = return TyChar
instance TypeSubst TypeRow where
substType' RowEmpty = return RowEmpty
substType' (RowVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (RowVar x)
Just (TySubRow r) -> return r
Just s -> throwError (ErrVarKindConflict x KRow (kindOfTySub s))
substType' (RowPresence l p r) =
RowPresence l <$> substType' p <*> substType' r
substType' (RowMu x r) =
handleTypeBind x (TySubRow . RowVar)
>>= \(newX, inner) -> RowMu newX <$> inner (substType' r)
instance TypeSubst TypePresence where
substType' Absent = return Absent
substType' (Present t) = Present <$> substType' t
substType' (PresenceVarWithType x t) =
asks (Map.lookup x) >>= \case
Nothing -> PresenceVarWithType x <$> substType' t
Just (TySubPresenceWithType p) -> case p of
PresenceWithTypeAbsent -> return Absent
PresenceWithTypePresent -> Present <$> substType' t
PresenceWithTypeVar x' -> PresenceVarWithType x' <$> substType' t
Just s ->
throwError (ErrVarKindConflict x KPresenceWithType (kindOfTySub s))
substType' (PresenceVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (PresenceVar x)
Just (TySubPresence p) -> return p
Just s -> throwError (ErrVarKindConflict x KPresence (kindOfTySub s))
instance TypeSubst PresenceWithType where
substType' PresenceWithTypeAbsent = return PresenceWithTypeAbsent
substType' PresenceWithTypePresent = return PresenceWithTypePresent
substType' (PresenceWithTypeVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (PresenceWithTypeVar x)
Just (TySubPresenceWithType i) -> return i
Just s ->
throwError (ErrVarKindConflict x KPresenceWithType (kindOfTySub s))
instance TypeSubst TypeScheme where
substType' (ScmForall x KProper s) =
handleTypeBind x (TySubProper . TyVar)
>>= \(newX, inner) -> ScmForall newX KProper <$> inner (substType' s)
substType' (ScmForall x KPresence s) =
handleTypeBind x (TySubPresence . PresenceVar)
>>= \(newX, inner) -> ScmForall newX KPresence <$> inner (substType' s)
substType' (ScmForall x (KArrow KProper KPresence) s) =
handleTypeBind x (TySubPresenceWithType . PresenceWithTypeVar)
>>= \(newX, inner) ->
ScmForall newX (KArrow KProper KPresence) <$> inner (substType' s)
substType' (ScmForall x KRow s) =
handleTypeBind x (TySubRow . RowVar)
>>= \(newX, inner) -> ScmForall newX KRow <$> inner (substType' s)
substType' (ScmForall _ k _) = error ("Unknown kind: " ++ show (pretty k))
substType' (ScmMono t) = ScmMono <$> substType' t
fvVarTermMap :: Map.Map VarName Term -> Set.Set VarName
fvVarTermMap = Map.foldl (\a b -> a `Set.union` fvTerm b) Set.empty
fvVarTySubMap ::
Map.Map VarName TypeSubstituter -> Either Error (Set.Set VarName)
fvVarTySubMap m = Map.keysSet <$> Map.foldl folder (Right Map.empty) m
where
folder set sub = do
set' <- set
fvSub <- fvTySub sub
mapUnionWithKind set' fvSub
handleTermBind ::
VarName ->
Reader
(Map.Map VarName Term)
( VarName,
Reader (Map.Map VarName Term) a -> Reader (Map.Map VarName Term) a
)
handleTermBind x = do
m <- ask
let fvS = fvVarTermMap m
return
( if x `Set.notMember` fvS
then (x, local (Map.delete x))
else
let newX = uniqueName fvS x
in (newX, local (`compositeTermSubst` Map.singleton x (TmVar newX)))
)
handleTypeBind ::
VarName ->
(VarName -> TypeSubstituter) ->
ExceptT
Error
(Reader (Map.Map VarName TypeSubstituter))
( VarName,
ExceptT Error (Reader (Map.Map VarName TypeSubstituter)) a ->
ExceptT Error (Reader (Map.Map VarName TypeSubstituter)) a
)
handleTypeBind x cons = do
m <- ask
fvS <- liftEither (fvVarTySubMap m)
if x `Set.notMember` fvS
then return (x, local (Map.delete x))
else
let newX = uniqueName fvS x
in do
newM <-
liftEither
(compositeTypeSubst m (Map.singleton x (cons newX)))
return (newX, local (const newM))
| null | https://raw.githubusercontent.com/linyinfeng/myml/1220a1474784eebce9ff95f46a3ff0a5f756e9a7/src/Myml/Subst.hs | haskell | # LANGUAGE LambdaCase #
module Myml.Subst
( substTerm,
TypeSubst (..),
compositeTypeSubst,
compositeTermSubst,
)
where
import Control.Monad.Except
import Control.Monad.Reader
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import Myml.Syntax
import Prettyprinter
substTerm :: Map.Map VarName Term -> Term -> Term
substTerm s t = runReader (substTerm' t) s
substTerm' :: Term -> Reader (Map.Map VarName Term) Term
substTerm' (TmAbs x t) =
handleTermBind x >>= \(newX, inner) -> TmAbs newX <$> inner (substTerm' t)
substTerm' (TmApp t1 t2) = TmApp <$> substTerm' t1 <*> substTerm' t2
substTerm' (TmVar x) =
ask >>= \s -> return (fromMaybe (TmVar x) (Map.lookup x s))
substTerm' (TmLet x t1 t2) = do
t1' <- substTerm' t1
(newX, inner) <- handleTermBind x
TmLet newX t1' <$> inner (substTerm' t2)
substTerm' t = return t
compositeTermSubst ::
Map.Map VarName Term -> Map.Map VarName Term -> Map.Map VarName Term
compositeTermSubst sa sb = Map.map (substTerm sa) sb `Map.union` sa
class TypeSubst a where
substType :: Map.Map VarName TypeSubstituter -> a -> Either Error a
substType s t = runReader (runExceptT (substType' t)) s
substType' :: a -> ExceptT Error (Reader (Map.Map VarName TypeSubstituter)) a
compositeTypeSubst ::
Map.Map VarName TypeSubstituter ->
Map.Map VarName TypeSubstituter ->
Either Error (Map.Map VarName TypeSubstituter)
compositeTypeSubst sa sb =
flip Map.union sa <$> sequence (Map.map (substType sa) sb)
instance TypeSubst TypeSubstituter where
substType' (TySubProper t) = TySubProper <$> substType' t
substType' (TySubPresenceWithType p) = TySubPresenceWithType <$> substType' p
substType' (TySubPresence p) = TySubPresence <$> substType' p
substType' (TySubRow r) = TySubRow <$> substType' r
instance TypeSubst Type where
substType' (TyVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (TyVar x)
Just (TySubProper t) -> return t
Just s -> throwError (ErrVarKindConflict x KProper (kindOfTySub s))
substType' (TyArrow t1 t2) = TyArrow <$> substType' t1 <*> substType' t2
substType' (TyRecord row) = TyRecord <$> substType' row
substType' (TyVariant row) = TyVariant <$> substType' row
substType' (TyMu x t) =
handleTypeBind x (TySubProper . TyVar)
>>= \(newX, inner) -> TyMu newX <$> inner (substType' t)
substType' (TyRef t) = TyRef <$> substType' t
substType' TyInteger = return TyInteger
substType' TyChar = return TyChar
instance TypeSubst TypeRow where
substType' RowEmpty = return RowEmpty
substType' (RowVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (RowVar x)
Just (TySubRow r) -> return r
Just s -> throwError (ErrVarKindConflict x KRow (kindOfTySub s))
substType' (RowPresence l p r) =
RowPresence l <$> substType' p <*> substType' r
substType' (RowMu x r) =
handleTypeBind x (TySubRow . RowVar)
>>= \(newX, inner) -> RowMu newX <$> inner (substType' r)
instance TypeSubst TypePresence where
substType' Absent = return Absent
substType' (Present t) = Present <$> substType' t
substType' (PresenceVarWithType x t) =
asks (Map.lookup x) >>= \case
Nothing -> PresenceVarWithType x <$> substType' t
Just (TySubPresenceWithType p) -> case p of
PresenceWithTypeAbsent -> return Absent
PresenceWithTypePresent -> Present <$> substType' t
PresenceWithTypeVar x' -> PresenceVarWithType x' <$> substType' t
Just s ->
throwError (ErrVarKindConflict x KPresenceWithType (kindOfTySub s))
substType' (PresenceVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (PresenceVar x)
Just (TySubPresence p) -> return p
Just s -> throwError (ErrVarKindConflict x KPresence (kindOfTySub s))
instance TypeSubst PresenceWithType where
substType' PresenceWithTypeAbsent = return PresenceWithTypeAbsent
substType' PresenceWithTypePresent = return PresenceWithTypePresent
substType' (PresenceWithTypeVar x) =
asks (Map.lookup x) >>= \case
Nothing -> return (PresenceWithTypeVar x)
Just (TySubPresenceWithType i) -> return i
Just s ->
throwError (ErrVarKindConflict x KPresenceWithType (kindOfTySub s))
instance TypeSubst TypeScheme where
substType' (ScmForall x KProper s) =
handleTypeBind x (TySubProper . TyVar)
>>= \(newX, inner) -> ScmForall newX KProper <$> inner (substType' s)
substType' (ScmForall x KPresence s) =
handleTypeBind x (TySubPresence . PresenceVar)
>>= \(newX, inner) -> ScmForall newX KPresence <$> inner (substType' s)
substType' (ScmForall x (KArrow KProper KPresence) s) =
handleTypeBind x (TySubPresenceWithType . PresenceWithTypeVar)
>>= \(newX, inner) ->
ScmForall newX (KArrow KProper KPresence) <$> inner (substType' s)
substType' (ScmForall x KRow s) =
handleTypeBind x (TySubRow . RowVar)
>>= \(newX, inner) -> ScmForall newX KRow <$> inner (substType' s)
substType' (ScmForall _ k _) = error ("Unknown kind: " ++ show (pretty k))
substType' (ScmMono t) = ScmMono <$> substType' t
fvVarTermMap :: Map.Map VarName Term -> Set.Set VarName
fvVarTermMap = Map.foldl (\a b -> a `Set.union` fvTerm b) Set.empty
fvVarTySubMap ::
Map.Map VarName TypeSubstituter -> Either Error (Set.Set VarName)
fvVarTySubMap m = Map.keysSet <$> Map.foldl folder (Right Map.empty) m
where
folder set sub = do
set' <- set
fvSub <- fvTySub sub
mapUnionWithKind set' fvSub
handleTermBind ::
VarName ->
Reader
(Map.Map VarName Term)
( VarName,
Reader (Map.Map VarName Term) a -> Reader (Map.Map VarName Term) a
)
handleTermBind x = do
m <- ask
let fvS = fvVarTermMap m
return
( if x `Set.notMember` fvS
then (x, local (Map.delete x))
else
let newX = uniqueName fvS x
in (newX, local (`compositeTermSubst` Map.singleton x (TmVar newX)))
)
handleTypeBind ::
VarName ->
(VarName -> TypeSubstituter) ->
ExceptT
Error
(Reader (Map.Map VarName TypeSubstituter))
( VarName,
ExceptT Error (Reader (Map.Map VarName TypeSubstituter)) a ->
ExceptT Error (Reader (Map.Map VarName TypeSubstituter)) a
)
handleTypeBind x cons = do
m <- ask
fvS <- liftEither (fvVarTySubMap m)
if x `Set.notMember` fvS
then return (x, local (Map.delete x))
else
let newX = uniqueName fvS x
in do
newM <-
liftEither
(compositeTypeSubst m (Map.singleton x (cons newX)))
return (newX, local (const newM))
|
|
7cf22d9c9bdd17a183506abdfd8d8d8a6f54ace25aa42649989b06ce255f9ee9 | Frozenlock/wacnet | objects.cljs | (ns wacnet.explorer.objects
(:require [reagent.core :as r]
[re-com.core :as re]
[goog.string :as gstring]
[ajax.core :refer [GET POST DELETE]]
[clojure.string :as s]
[wacnet.templates.common :as tp]
[wacnet.routes :as routes]
[wacnet.bacnet-utils :as bu :refer-macros [object-types-map engineering-units-map]]))
(def object-int-name-map
(into {} (for [[k v] bu/object-types]
[(str v) (-> (name k)
(s/replace #"-" " ")
(s/capitalize))])))
(defn object-type-name
"Given an object type (number), return its name."
[object-type]
(get object-int-name-map (str object-type)))
( defn short - id - to - identifier
;; "Convert a short id to the extended identifier.
Example : \"1.1\ " -- > [: analog - input 1 ] "
;; [id]
( let [ [ type instance ] ( s / split i d # " \. " )
;; types (into {} (for [[k v] object-types]
;; [v k]))]
;; [(get types (js/parseInt type))
;; (js/parseInt instance)]))
(defn identifier-to-short-id [identifier]
(let [[type instance] identifier]
(str (get bu/object-types type) "." instance)))
(defn object-icon
"Return an icon component depending on the object type."
[object-type]
(let [objects {"0" [:span [:i.fa.fa-fw.fa-sign-in]" "[:i.fa.fa-fw.fa-signal]] ;; analog input
"1" [:span [:i.fa.fa-fw.fa-signal]" "[:i.fa.fa-fw.fa-sign-out]] ;; analog output
"2" [:span [:i.fa.fa-fw.fa-signal]] ;; analog value
"3" [:span [:i.fa.fa-fw.fa-sign-in]" "[:i.fa.fa-fw.fa-adjust]] ;; binary input
"4" [:span [:i.fa.fa-fw.fa-adjust]" "[:i.fa.fa-fw.fa-sign-out]] ;; binary output
"5" [:span [:i.fa.fa-fw.fa-adjust]] ;; binary value
"8" [:span [:i.fa.fa-fw.fa-server]] ;; device
"10" [:span [:i.fa.fa-fw.fa-file-o]] ;;file
"12" [:span [:i.fa.fa-fw.fa-circle-o-notch]] ;; loop
}]
(get objects object-type)))
(defn object-value
"If the object is binary, return ON/OFF instead of 0 and 1."
[object-type present-value]
(if (some #{object-type} ["3" "4" "5"])
;; binary objects
(cond
(= 1 present-value) [:div.label.label-success "ON"]
(= 0 present-value) [:div.label.label-danger "OFF"]
:else [:div])
;; other objects
[:span {:style {:text-align "right"}}
(let [v present-value]
(cond
(number? v) (gstring/format "%.2f" v)
(or (nil? v) (coll? v)) "---"
(boolean? v) (str v)
:else (name v)))]))
(defn api-path [api-root & args]
(str api-root (s/join "/" args)))
(defn create-object! [loading? error? device-id props-map configs callback]
(reset! loading? true)
(reset! error? nil)
(POST (api-path (:api-root configs) "bacnet" "devices" device-id "objects")
{:handler (fn [resp]
(reset! loading? nil)
(when callback
(callback resp))
(prn resp))
:params props-map
:response-format :transit
:error-handler (fn [error-resp]
(reset! loading? nil)
(reset! error? (:response error-resp)))}))
(comment
{:object-instance "1", :object-id "0.1", :status-flags {:in-alarm false, :fault false, :out-of-service true, :overridden false}, :present-value 0, :object-type "0", :out-of-service true, :event-state :normal, :object-name "Analog Input 1", :units "no units", :href ":3449/api/v1/bacnet/devices/1338/objects/0.1"})
(defn create-new-object-modal [device-id configs callback close-modal!]
(let [object-props (r/atom {:object-type "0"
:object-name "Input"
:description ""
:units ""
})
obj-type-a (r/cursor object-props [:object-type])
units-a (r/cursor object-props [:units])
error? (r/atom nil)
loading? (r/atom nil)
obj-choices (->> (for [[k v] object-int-name-map]
{:id k :label v})
(sort-by :label))
units-choices (->> (for [[k v] bu/engineering-units]
{:id k :label v})
(sort-by :label))]
(fn [device-id configs callback]
[:div
[:div.modal-header [:h3 [:i.fa.fa-plus] " New BACnet Object"]]
[:div.modal-body
[re/v-box
:gap "10px"
:children [[re/single-dropdown :choices obj-choices
:model obj-type-a :on-change #(reset! obj-type-a %) :width "200px"]
[:div [:b "Object name"] [tp/live-edit :input object-props :object-name]]
[:div [:b "Description (optional)"] [tp/live-edit :textarea object-props :description]]
[:div [:b "Units "]
[re/single-dropdown
:choices units-choices
:model units-a :on-change #(reset! units-a %) :width "300px"]]
(when-let [err @error?]
[:span.alert.alert-warning {:style {:width "100%"}} (str err)])]]]
[:div.modal-footer
[re/h-box :children
;:gap "10px"
[[re/gap :size "1"]
[:button.btn.btn-default {:on-click close-modal!} "Cancel"]
[re/gap :size "10px"]
[:button.btn.btn-primary
{:disabled (empty? (:object-name @object-props))
:on-click #(create-object! loading? error? device-id @object-props
configs callback)}
"Create!" (when @loading?
[:span " " [:i.fa.fa-spinner.fa-pulse]])]]]]])))
(defn delete-object! [loading? error? device-id props-map configs callback]
(reset! loading? true)
(reset! error? nil)
(DELETE (api-path (:api-root configs) "bacnet" "devices" device-id "objects"
(str (:object-type props-map) "." (:object-instance props-map)))
{:handler (fn [resp]
(reset! loading? nil)
(when callback
(callback resp))
(prn resp))
:params props-map
:response-format :transit
:error-handler (fn [error-resp]
(reset! loading? nil)
(reset! error? (:response error-resp)))}))
(defn delete-object-modal [bacnet-object configs callback close-modal!]
(let [error? (r/atom nil)
loading? (r/atom nil)]
(fn [bacnet-object configs callback]
[:div
[:div.modal-header [:h3 [:i.fa.fa-trash] " Delete BACnet object"]]
[:div.modal-body
[:div.alert.alert-warning "Are you sure you want to delete this object?"
[:div [:strong (:object-name bacnet-object)]]]
(when-let [err @error?]
[:span.alert.alert-warning {:style {:width "100%"}} (str err)])]
[:div.modal-footer
[re/h-box :children
[[re/gap :size "1"]
[:button.btn.btn-default {:on-click close-modal!} "Cancel"]
[re/gap :size "10px"]
[:button.btn.btn-danger
{:on-click #(delete-object! loading? error? (:device-id bacnet-object)
bacnet-object configs callback)} "Delete!"
(when @loading?
[:span " " [:i.fa.fa-spinner.fa-pulse]])]]]
]])))
( defn control - loop - view [ obj ]
;; (let [p-id (:project-id obj)
;; d-id (:device-id obj)
;; o-fn (fn [k]
;; (let [c-o (make-loop-obj obj k)]
;; [:span
;; [inline-object c-o]
;; ]))]
;; [re/v-box
;; :children [[re/line :size "1px"]
;; [re/box :child [:span (bfo/object-icon (:object-type obj)) " "
;; (t/t @t/locale :objects/control-loop)]]
;; [re/h-box
;; :gap "20px"
;; :children
;; [[re/v-box
: size " 1 "
: children [ [ re / title : level : level3 : underline ? true
;; :label (t/t @t/locale :vigilia/controlled)]
;; (o-fn :controlled-variable-reference)]]
;; [re/line :size "1px"]
;; ;[re/label :label [:i.fa.fa-arrow-right]]
;; [re/v-box
: size " 1 "
: children [ [ re / title : level : level3 : underline ? true
;; :label (t/t @t/locale :vigilia/manipulated)]
;; (o-fn :manipulated-variable-reference)]]
;; [re/line :size "1px"]
;; [re/v-box
: size " 1 "
: children [ [ re / title : level : level3 : underline ? true
;; :label (t/t @t/locale :vigilia/setpoint)]
;; (o-fn :setpoint-reference)]]]]]]))
(defn device-link [obj]
(let [d-id (:device-id obj)]
(when d-id
[:a {:href (routes/path-for :devices-with-id :device-id d-id)}
"("d-id")" " " [:b (:device-name obj)]])))
(defn make-parent-device-link
"Given the device-id, will retrieve the device name and make a link."
[object configs]
(let [parent-device (r/atom nil)]
(fn [object configs]
(let [{:keys [device-id]} object]
(when-not (= (:device-id @parent-device) device-id)
(GET (api-path (:api-root configs)
"bacnet" "devices" device-id)
{:response-format :transit
:handler #(reset! parent-device %)
:error-handler prn}))
[:div (device-link @parent-device)]))))
(defn map-to-bootstrap [map]
[:div
(for [m map]
^{:key (key m)}
[:div.row {:style {:background "rgba(0,0,0,0.05)"
:border-radius "3px"
:margin "2px"}}
[:div.col-sm-4 [:strong (name (key m))]]
[:div.col-sm-8 {:style {:overflow :hidden}}
(let [v (val m)]
(if (map? v)
(map-to-bootstrap v)
[:div {:style {:margin-left "1em"}}
(cond (keyword? v) (name v)
(and (coll? v) (> (count v) 2)) [:ul
(for [[id item] (map-indexed vector v)]
^{:key id}
[:li (str item)])]
:else (str v))]))]])])
(defn prop-table [object configs]
(let [last-update-object (r/atom nil)
error? (r/atom nil)
loading? (r/atom nil)]
(fn [object configs]
(let [current-object (or @last-update-object object)
;; use the latest object data, or fallback to the provided object
{:keys [project-id device-id object-type object-instance]} current-object
object-type-name (-> object-type object-type-name)
load-props-fn (fn []
(reset! loading? true)
(reset! error? nil)
(GET (:href object)
{:response-format :transit
:handler #(do (reset! last-update-object %)
(reset! loading? nil))
:error-handler (fn [error-resp]
(reset! loading? nil)
(reset! error? (:response error-resp)))}))]
[:div
[re/v-box
:gap "10px"
;:min-width "500px"
:children [[:a {:href (:href object)
:target "_blank"} "See in API " [:i.fa.fa-external-link]]
[re/gap :size "10px"]
(when-let [err @error?]
[:span.alert.alert-warning {:style {:width "100%"}} (str err)])
[map-to-bootstrap (dissoc current-object :href :object-id)]
[:button.btn.btn-sm.btn-default {:on-click load-props-fn}
"Load all properties"
(when @loading?
[:span " " [:i.fa.fa-spinner.fa-pulse]])]]]]))))
(defn prop-modal [vigilia-object configs ok-btn]
[:div
[:div.modal-header
[:h3 [object-icon (:object-type vigilia-object)]
" "(or (seq (:object-name vigilia-object))
"< no name >")]]
[:div.modal-body
[prop-table vigilia-object configs]]
[:div.modal-footer ok-btn]])
| null | https://raw.githubusercontent.com/Frozenlock/wacnet/69947dc02c91ae160c759a0abe97d4f472e9a876/src/cljs/wacnet/explorer/objects.cljs | clojure | "Convert a short id to the extended identifier.
[id]
types (into {} (for [[k v] object-types]
[v k]))]
[(get types (js/parseInt type))
(js/parseInt instance)]))
analog input
analog output
analog value
binary input
binary output
binary value
device
file
loop
binary objects
other objects
:gap "10px"
(let [p-id (:project-id obj)
d-id (:device-id obj)
o-fn (fn [k]
(let [c-o (make-loop-obj obj k)]
[:span
[inline-object c-o]
]))]
[re/v-box
:children [[re/line :size "1px"]
[re/box :child [:span (bfo/object-icon (:object-type obj)) " "
(t/t @t/locale :objects/control-loop)]]
[re/h-box
:gap "20px"
:children
[[re/v-box
:label (t/t @t/locale :vigilia/controlled)]
(o-fn :controlled-variable-reference)]]
[re/line :size "1px"]
;[re/label :label [:i.fa.fa-arrow-right]]
[re/v-box
:label (t/t @t/locale :vigilia/manipulated)]
(o-fn :manipulated-variable-reference)]]
[re/line :size "1px"]
[re/v-box
:label (t/t @t/locale :vigilia/setpoint)]
(o-fn :setpoint-reference)]]]]]]))
use the latest object data, or fallback to the provided object
:min-width "500px" | (ns wacnet.explorer.objects
(:require [reagent.core :as r]
[re-com.core :as re]
[goog.string :as gstring]
[ajax.core :refer [GET POST DELETE]]
[clojure.string :as s]
[wacnet.templates.common :as tp]
[wacnet.routes :as routes]
[wacnet.bacnet-utils :as bu :refer-macros [object-types-map engineering-units-map]]))
(def object-int-name-map
(into {} (for [[k v] bu/object-types]
[(str v) (-> (name k)
(s/replace #"-" " ")
(s/capitalize))])))
(defn object-type-name
"Given an object type (number), return its name."
[object-type]
(get object-int-name-map (str object-type)))
( defn short - id - to - identifier
Example : \"1.1\ " -- > [: analog - input 1 ] "
( let [ [ type instance ] ( s / split i d # " \. " )
(defn identifier-to-short-id [identifier]
(let [[type instance] identifier]
(str (get bu/object-types type) "." instance)))
(defn object-icon
"Return an icon component depending on the object type."
[object-type]
}]
(get objects object-type)))
(defn object-value
"If the object is binary, return ON/OFF instead of 0 and 1."
[object-type present-value]
(if (some #{object-type} ["3" "4" "5"])
(cond
(= 1 present-value) [:div.label.label-success "ON"]
(= 0 present-value) [:div.label.label-danger "OFF"]
:else [:div])
[:span {:style {:text-align "right"}}
(let [v present-value]
(cond
(number? v) (gstring/format "%.2f" v)
(or (nil? v) (coll? v)) "---"
(boolean? v) (str v)
:else (name v)))]))
(defn api-path [api-root & args]
(str api-root (s/join "/" args)))
(defn create-object! [loading? error? device-id props-map configs callback]
(reset! loading? true)
(reset! error? nil)
(POST (api-path (:api-root configs) "bacnet" "devices" device-id "objects")
{:handler (fn [resp]
(reset! loading? nil)
(when callback
(callback resp))
(prn resp))
:params props-map
:response-format :transit
:error-handler (fn [error-resp]
(reset! loading? nil)
(reset! error? (:response error-resp)))}))
(comment
{:object-instance "1", :object-id "0.1", :status-flags {:in-alarm false, :fault false, :out-of-service true, :overridden false}, :present-value 0, :object-type "0", :out-of-service true, :event-state :normal, :object-name "Analog Input 1", :units "no units", :href ":3449/api/v1/bacnet/devices/1338/objects/0.1"})
(defn create-new-object-modal [device-id configs callback close-modal!]
(let [object-props (r/atom {:object-type "0"
:object-name "Input"
:description ""
:units ""
})
obj-type-a (r/cursor object-props [:object-type])
units-a (r/cursor object-props [:units])
error? (r/atom nil)
loading? (r/atom nil)
obj-choices (->> (for [[k v] object-int-name-map]
{:id k :label v})
(sort-by :label))
units-choices (->> (for [[k v] bu/engineering-units]
{:id k :label v})
(sort-by :label))]
(fn [device-id configs callback]
[:div
[:div.modal-header [:h3 [:i.fa.fa-plus] " New BACnet Object"]]
[:div.modal-body
[re/v-box
:gap "10px"
:children [[re/single-dropdown :choices obj-choices
:model obj-type-a :on-change #(reset! obj-type-a %) :width "200px"]
[:div [:b "Object name"] [tp/live-edit :input object-props :object-name]]
[:div [:b "Description (optional)"] [tp/live-edit :textarea object-props :description]]
[:div [:b "Units "]
[re/single-dropdown
:choices units-choices
:model units-a :on-change #(reset! units-a %) :width "300px"]]
(when-let [err @error?]
[:span.alert.alert-warning {:style {:width "100%"}} (str err)])]]]
[:div.modal-footer
[re/h-box :children
[[re/gap :size "1"]
[:button.btn.btn-default {:on-click close-modal!} "Cancel"]
[re/gap :size "10px"]
[:button.btn.btn-primary
{:disabled (empty? (:object-name @object-props))
:on-click #(create-object! loading? error? device-id @object-props
configs callback)}
"Create!" (when @loading?
[:span " " [:i.fa.fa-spinner.fa-pulse]])]]]]])))
(defn delete-object! [loading? error? device-id props-map configs callback]
(reset! loading? true)
(reset! error? nil)
(DELETE (api-path (:api-root configs) "bacnet" "devices" device-id "objects"
(str (:object-type props-map) "." (:object-instance props-map)))
{:handler (fn [resp]
(reset! loading? nil)
(when callback
(callback resp))
(prn resp))
:params props-map
:response-format :transit
:error-handler (fn [error-resp]
(reset! loading? nil)
(reset! error? (:response error-resp)))}))
(defn delete-object-modal [bacnet-object configs callback close-modal!]
(let [error? (r/atom nil)
loading? (r/atom nil)]
(fn [bacnet-object configs callback]
[:div
[:div.modal-header [:h3 [:i.fa.fa-trash] " Delete BACnet object"]]
[:div.modal-body
[:div.alert.alert-warning "Are you sure you want to delete this object?"
[:div [:strong (:object-name bacnet-object)]]]
(when-let [err @error?]
[:span.alert.alert-warning {:style {:width "100%"}} (str err)])]
[:div.modal-footer
[re/h-box :children
[[re/gap :size "1"]
[:button.btn.btn-default {:on-click close-modal!} "Cancel"]
[re/gap :size "10px"]
[:button.btn.btn-danger
{:on-click #(delete-object! loading? error? (:device-id bacnet-object)
bacnet-object configs callback)} "Delete!"
(when @loading?
[:span " " [:i.fa.fa-spinner.fa-pulse]])]]]
]])))
( defn control - loop - view [ obj ]
: size " 1 "
: children [ [ re / title : level : level3 : underline ? true
: size " 1 "
: children [ [ re / title : level : level3 : underline ? true
: size " 1 "
: children [ [ re / title : level : level3 : underline ? true
(defn device-link [obj]
(let [d-id (:device-id obj)]
(when d-id
[:a {:href (routes/path-for :devices-with-id :device-id d-id)}
"("d-id")" " " [:b (:device-name obj)]])))
(defn make-parent-device-link
"Given the device-id, will retrieve the device name and make a link."
[object configs]
(let [parent-device (r/atom nil)]
(fn [object configs]
(let [{:keys [device-id]} object]
(when-not (= (:device-id @parent-device) device-id)
(GET (api-path (:api-root configs)
"bacnet" "devices" device-id)
{:response-format :transit
:handler #(reset! parent-device %)
:error-handler prn}))
[:div (device-link @parent-device)]))))
(defn map-to-bootstrap [map]
[:div
(for [m map]
^{:key (key m)}
[:div.row {:style {:background "rgba(0,0,0,0.05)"
:border-radius "3px"
:margin "2px"}}
[:div.col-sm-4 [:strong (name (key m))]]
[:div.col-sm-8 {:style {:overflow :hidden}}
(let [v (val m)]
(if (map? v)
(map-to-bootstrap v)
[:div {:style {:margin-left "1em"}}
(cond (keyword? v) (name v)
(and (coll? v) (> (count v) 2)) [:ul
(for [[id item] (map-indexed vector v)]
^{:key id}
[:li (str item)])]
:else (str v))]))]])])
(defn prop-table [object configs]
(let [last-update-object (r/atom nil)
error? (r/atom nil)
loading? (r/atom nil)]
(fn [object configs]
(let [current-object (or @last-update-object object)
{:keys [project-id device-id object-type object-instance]} current-object
object-type-name (-> object-type object-type-name)
load-props-fn (fn []
(reset! loading? true)
(reset! error? nil)
(GET (:href object)
{:response-format :transit
:handler #(do (reset! last-update-object %)
(reset! loading? nil))
:error-handler (fn [error-resp]
(reset! loading? nil)
(reset! error? (:response error-resp)))}))]
[:div
[re/v-box
:gap "10px"
:children [[:a {:href (:href object)
:target "_blank"} "See in API " [:i.fa.fa-external-link]]
[re/gap :size "10px"]
(when-let [err @error?]
[:span.alert.alert-warning {:style {:width "100%"}} (str err)])
[map-to-bootstrap (dissoc current-object :href :object-id)]
[:button.btn.btn-sm.btn-default {:on-click load-props-fn}
"Load all properties"
(when @loading?
[:span " " [:i.fa.fa-spinner.fa-pulse]])]]]]))))
(defn prop-modal [vigilia-object configs ok-btn]
[:div
[:div.modal-header
[:h3 [object-icon (:object-type vigilia-object)]
" "(or (seq (:object-name vigilia-object))
"< no name >")]]
[:div.modal-body
[prop-table vigilia-object configs]]
[:div.modal-footer ok-btn]])
|
16d4a7bd2254ff38d1c054a056861a499291238b3756c68ad6b92cf5fcc80b71 | jafingerhut/dolly | dir.clj | Copyright ( c ) , 2012 . 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 ^{:author "Stuart Sierra"
:doc "Track namespace dependencies and changes by monitoring
file-modification timestamps"}
dolly.copieddeps.tns.clojure.tools.namespace.dir
(:require [dolly.copieddeps.tns.clojure.tools.namespace.file :as file]
[dolly.copieddeps.tns.clojure.tools.namespace.track :as track]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as string])
(:import (java.io File) (java.util.regex Pattern)))
(defn- find-files [dirs]
(->> dirs
(map io/file)
(filter #(.exists ^File %))
(mapcat file-seq)
(filter file/clojure-file?)
(map #(.getCanonicalFile ^File %))))
(defn- modified-files [tracker files]
(filter #(< (::time tracker 0) (.lastModified ^File %)) files))
(defn- deleted-files [tracker files]
(set/difference (::files tracker #{}) (set files)))
(defn- update-files [tracker deleted modified]
(let [now (System/currentTimeMillis)]
(-> tracker
(update-in [::files] #(if % (apply disj % deleted) #{}))
(file/remove-files deleted)
(update-in [::files] into modified)
(file/add-files modified)
(assoc ::time now))))
(defn- dirs-on-classpath []
(filter #(.isDirectory ^File %)
(map #(File. ^String %)
(string/split
(System/getProperty "java.class.path")
(Pattern/compile (Pattern/quote File/pathSeparator))))))
(defn scan
"Scans directories for files which have changed since the last time
'scan' was run; update the dependency tracker with
new/changed/deleted files.
If no dirs given, defaults to all directories on the classpath."
[tracker & dirs]
(let [ds (or (seq dirs) (dirs-on-classpath))
files (find-files ds)
deleted (seq (deleted-files tracker files))
modified (seq (modified-files tracker files))]
(if (or deleted modified)
(update-files tracker deleted modified)
tracker)))
(defn scan-all
"Scans directories for all Clojure source files and updates the
dependency tracker to reload files. If no dirs given, defaults to
all directories on the classpath."
[tracker & dirs]
(let [ds (or (seq dirs) (dirs-on-classpath))
files (find-files ds)
deleted (seq (deleted-files tracker files))]
(update-files tracker deleted files)))
| null | https://raw.githubusercontent.com/jafingerhut/dolly/6dfe7f3bcd58d81fba7793d214230792b6140ffd/src/dolly/copieddeps/tns/clojure/tools/namespace/dir.clj | clojure | 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.
update the dependency tracker with | Copyright ( c ) , 2012 . All rights reserved . The use and
distribution terms for this software are covered by the Eclipse
(ns ^{:author "Stuart Sierra"
:doc "Track namespace dependencies and changes by monitoring
file-modification timestamps"}
dolly.copieddeps.tns.clojure.tools.namespace.dir
(:require [dolly.copieddeps.tns.clojure.tools.namespace.file :as file]
[dolly.copieddeps.tns.clojure.tools.namespace.track :as track]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as string])
(:import (java.io File) (java.util.regex Pattern)))
(defn- find-files [dirs]
(->> dirs
(map io/file)
(filter #(.exists ^File %))
(mapcat file-seq)
(filter file/clojure-file?)
(map #(.getCanonicalFile ^File %))))
(defn- modified-files [tracker files]
(filter #(< (::time tracker 0) (.lastModified ^File %)) files))
(defn- deleted-files [tracker files]
(set/difference (::files tracker #{}) (set files)))
(defn- update-files [tracker deleted modified]
(let [now (System/currentTimeMillis)]
(-> tracker
(update-in [::files] #(if % (apply disj % deleted) #{}))
(file/remove-files deleted)
(update-in [::files] into modified)
(file/add-files modified)
(assoc ::time now))))
(defn- dirs-on-classpath []
(filter #(.isDirectory ^File %)
(map #(File. ^String %)
(string/split
(System/getProperty "java.class.path")
(Pattern/compile (Pattern/quote File/pathSeparator))))))
(defn scan
"Scans directories for files which have changed since the last time
new/changed/deleted files.
If no dirs given, defaults to all directories on the classpath."
[tracker & dirs]
(let [ds (or (seq dirs) (dirs-on-classpath))
files (find-files ds)
deleted (seq (deleted-files tracker files))
modified (seq (modified-files tracker files))]
(if (or deleted modified)
(update-files tracker deleted modified)
tracker)))
(defn scan-all
"Scans directories for all Clojure source files and updates the
dependency tracker to reload files. If no dirs given, defaults to
all directories on the classpath."
[tracker & dirs]
(let [ds (or (seq dirs) (dirs-on-classpath))
files (find-files ds)
deleted (seq (deleted-files tracker files))]
(update-files tracker deleted files)))
|
dce137e1afc3d0f4de17a0ca0092a51223db72e885f68346248769c67ace24e1 | chicken-mobile/chicken-sdl2-android-builder | controller-device-event.scm | ;;
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
;;
Copyright © 2013 , 2015 - 2016 .
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(export controller-device-event?
controller-device-event-which
controller-device-event-which-set!)
(define-event-type "SDL_ControllerDeviceEvent"
types: (SDL_CONTROLLERDEVICEADDED
SDL_CONTROLLERDEVICEREMOVED
SDL_CONTROLLERDEVICEREMAPPED)
pred: controller-device-event?
print: ((which joy-device-event-which))
("cdevice.which"
type: Sint32
getter: controller-device-event-which
setter: controller-device-event-which-set!
guard: (Sint32-guard "sdl2:controller-device-event field which")))
| null | https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2-internals/accessors/events/controller-device-event.scm | scheme |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE. | chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
Copyright © 2013 , 2015 - 2016 .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
(export controller-device-event?
controller-device-event-which
controller-device-event-which-set!)
(define-event-type "SDL_ControllerDeviceEvent"
types: (SDL_CONTROLLERDEVICEADDED
SDL_CONTROLLERDEVICEREMOVED
SDL_CONTROLLERDEVICEREMAPPED)
pred: controller-device-event?
print: ((which joy-device-event-which))
("cdevice.which"
type: Sint32
getter: controller-device-event-which
setter: controller-device-event-which-set!
guard: (Sint32-guard "sdl2:controller-device-event field which")))
|
dc9d80895370e643b34daa6eebea6821f86c8bb3ff1fbc3c618eaa33470adeca | EFanZh/EOPL-Exercises | exercise-7.6.rkt | #lang eopl
Exercise 7.6 [ ★ ] Extend the checker to handle assignments ( section 4.3 ) .
;; 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" "(" identifier ":" type ")" expression) proc-exp]
[expression ("(" expression expression ")") call-exp]
[expression ("letrec" type identifier "(" identifier ":" type ")" "=" expression "in" expression) letrec-exp]
[expression ("set" identifier "=" expression) assign-exp]
[type ("int") int-type]
[type ("bool") bool-type]
[type ("(" type "->" type ")") proc-type]))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar))
;; Data structures - expressed values.
(define-datatype proc proc?
[procedure [bvar 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)])))
;; Data structures - environment.
(define-datatype environment environment?
[empty-env]
[extend-env [bvar symbol?]
[bval reference?]
[saved-env environment?]])
(define extend-env-rec
(lambda (p-name b-var p-body saved-env)
(let* ([ref (newref 'undefined)]
[rec-env (extend-env p-name ref saved-env)])
(setref! ref (proc-val (procedure b-var p-body rec-env)))
rec-env)))
(define apply-env
(lambda (env search-sym)
(cases environment env
[empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)]
[extend-env (bvar bval saved-env) (if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym))])))
;; Data structures - type environment.
(define-datatype type-environment type-environment?
[empty-tenv-record]
[extended-tenv-record [sym symbol?]
[type type?]
[tenv type-environment?]])
(define apply-tenv
(lambda (tenv sym)
(cases type-environment tenv
[empty-tenv-record () (eopl:error 'apply-tenv "Unbound variable ~s" sym)]
[extended-tenv-record (sym1 val1 old-env) (if (eqv? sym sym1)
val1
(apply-tenv old-env sym))])))
(define empty-tenv empty-tenv-record)
(define extend-tenv extended-tenv-record)
;; Data structures - store.
(define the-store 'uninitialized)
(define empty-store
(lambda ()
'()))
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
(define reference?
(lambda (v)
(integer? v)))
(define newref
(lambda (val)
(let ([next-ref (length the-store)])
(set! the-store (append the-store (list val)))
next-ref)))
(define deref
(lambda (ref)
(list-ref the-store ref)))
(define report-invalid-reference
(lambda (ref the-store)
(eopl:error 'setref "illegal reference ~s in store ~s" ref the-store)))
(define setref!
(lambda (ref val)
(set! the-store (letrec ([setref-inner (lambda (store1 ref1)
(cond [(null? store1) (report-invalid-reference ref the-store)]
[(zero? ref1) (cons val (cdr store1))]
[else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))]))])
(setref-inner the-store ref)))))
Checker .
(define type-to-external-form
(lambda (ty)
(cases type ty
[int-type () 'int]
[bool-type () 'bool]
[proc-type (arg-type result-type) (list (type-to-external-form arg-type)
'->
(type-to-external-form result-type))])))
(define report-unequal-types
(lambda (ty1 ty2 exp)
(eopl:error 'check-equal-type!
"Types didn't match: ~s != ~a in~%~a"
(type-to-external-form ty1)
(type-to-external-form ty2)
exp)))
(define check-equal-type!
(lambda (ty1 ty2 exp)
(when (not (equal? ty1 ty2))
(report-unequal-types ty1 ty2 exp))))
(define report-rator-not-a-proc-type
(lambda (rator-type rator)
(eopl:error 'type-of-expression
"Rator not a proc type:~%~s~%had rator type ~s"
rator
(type-to-external-form rator-type))))
(define type-of
(lambda (exp tenv)
(cases expression exp
[const-exp (num) (int-type)]
[var-exp (var) (apply-tenv tenv var)]
[diff-exp (exp1 exp2) (let ([ty1 (type-of exp1 tenv)]
[ty2 (type-of exp2 tenv)])
(check-equal-type! ty1 (int-type) exp1)
(check-equal-type! ty2 (int-type) exp2)
(int-type))]
[zero?-exp (exp1) (let ([ty1 (type-of exp1 tenv)])
(check-equal-type! ty1 (int-type) exp1)
(bool-type))]
[if-exp (exp1 exp2 exp3) (let ([ty1 (type-of exp1 tenv)]
[ty2 (type-of exp2 tenv)]
[ty3 (type-of exp3 tenv)])
(check-equal-type! ty1 (bool-type) exp1)
(check-equal-type! ty2 ty3 exp)
ty2)]
[let-exp (var exp1 body) (let ([exp1-type (type-of exp1 tenv)])
(type-of body (extend-tenv var exp1-type tenv)))]
[proc-exp (var var-type body) (let ([result-type (type-of body (extend-tenv var var-type tenv))])
(proc-type var-type result-type))]
[call-exp (rator rand) (let ([rator-type (type-of rator tenv)]
[rand-type (type-of rand tenv)])
(cases type rator-type
[proc-type (arg-type result-type) (begin (check-equal-type! arg-type rand-type rand)
result-type)]
[else (report-rator-not-a-proc-type rator-type rator)]))]
[letrec-exp (p-result-type p-name b-var b-var-type p-body letrec-body)
(let ([tenv-for-letrec-body (extend-tenv p-name (proc-type b-var-type p-result-type) tenv)])
(let ([p-body-type (type-of p-body (extend-tenv b-var b-var-type tenv-for-letrec-body))])
(check-equal-type! p-body-type p-result-type p-body)
(type-of letrec-body tenv-for-letrec-body)))]
[assign-exp (var exp1)
(check-equal-type! (apply-tenv tenv var) (type-of exp1 tenv) exp1)
(int-type)])))
(define type-of-program
(lambda (pgm)
[cases program pgm (a-program (exp1) (type-of exp1 (empty-tenv)))]))
;; Interpreter.
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
[procedure (var body saved-env) (value-of body (extend-env var (newref arg) saved-env))])))
(define value-of
(lambda (exp env)
(cases expression exp
[const-exp (num) (num-val num)]
[var-exp (var) (deref (apply-env env var))]
[diff-exp (exp1 exp2) (let ([val1 (expval->num (value-of exp1 env))]
[val2 (expval->num (value-of exp2 env))])
(num-val (- val1 val2)))]
[zero?-exp (exp1) (let ([val1 (expval->num (value-of exp1 env))])
(if (zero? val1)
(bool-val #t)
(bool-val #f)))]
[if-exp (exp0 exp1 exp2) (if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env))]
[let-exp (var exp1 body) (let ([val (newref (value-of exp1 env))])
(value-of body (extend-env var val env)))]
[proc-exp (bvar ty body) (proc-val (procedure bvar body env))]
[call-exp (rator rand) (let ([proc (expval->proc (value-of rator env))]
[arg (value-of rand env)])
(apply-procedure proc arg))]
[letrec-exp (ty1 p-name b-var ty2 p-body letrec-body) (value-of letrec-body
(extend-env-rec p-name b-var p-body env))]
[assign-exp (var exp1)
(setref! (apply-env env var) (value-of exp1 env))
(num-val 27)])))
(define value-of-program
(lambda (pgm)
(initialize-store!)
(cases program pgm
[a-program (body) (value-of body (empty-env))])))
Interface .
(define check
(lambda (string)
(type-to-external-form (type-of-program (scan&parse string)))))
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(provide check num-val run)
| null | https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-7.6.rkt | racket | Grammar.
Data structures - expressed values.
Data structures - environment.
Data structures - type environment.
Data structures - store.
Interpreter. | #lang eopl
Exercise 7.6 [ ★ ] Extend the checker to handle assignments ( section 4.3 ) .
(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" "(" identifier ":" type ")" expression) proc-exp]
[expression ("(" expression expression ")") call-exp]
[expression ("letrec" type identifier "(" identifier ":" type ")" "=" expression "in" expression) letrec-exp]
[expression ("set" identifier "=" expression) assign-exp]
[type ("int") int-type]
[type ("bool") bool-type]
[type ("(" type "->" type ")") proc-type]))
(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 [bvar 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 reference?]
[saved-env environment?]])
(define extend-env-rec
(lambda (p-name b-var p-body saved-env)
(let* ([ref (newref 'undefined)]
[rec-env (extend-env p-name ref saved-env)])
(setref! ref (proc-val (procedure b-var p-body rec-env)))
rec-env)))
(define apply-env
(lambda (env search-sym)
(cases environment env
[empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)]
[extend-env (bvar bval saved-env) (if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym))])))
(define-datatype type-environment type-environment?
[empty-tenv-record]
[extended-tenv-record [sym symbol?]
[type type?]
[tenv type-environment?]])
(define apply-tenv
(lambda (tenv sym)
(cases type-environment tenv
[empty-tenv-record () (eopl:error 'apply-tenv "Unbound variable ~s" sym)]
[extended-tenv-record (sym1 val1 old-env) (if (eqv? sym sym1)
val1
(apply-tenv old-env sym))])))
(define empty-tenv empty-tenv-record)
(define extend-tenv extended-tenv-record)
(define the-store 'uninitialized)
(define empty-store
(lambda ()
'()))
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
(define reference?
(lambda (v)
(integer? v)))
(define newref
(lambda (val)
(let ([next-ref (length the-store)])
(set! the-store (append the-store (list val)))
next-ref)))
(define deref
(lambda (ref)
(list-ref the-store ref)))
(define report-invalid-reference
(lambda (ref the-store)
(eopl:error 'setref "illegal reference ~s in store ~s" ref the-store)))
(define setref!
(lambda (ref val)
(set! the-store (letrec ([setref-inner (lambda (store1 ref1)
(cond [(null? store1) (report-invalid-reference ref the-store)]
[(zero? ref1) (cons val (cdr store1))]
[else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))]))])
(setref-inner the-store ref)))))
Checker .
(define type-to-external-form
(lambda (ty)
(cases type ty
[int-type () 'int]
[bool-type () 'bool]
[proc-type (arg-type result-type) (list (type-to-external-form arg-type)
'->
(type-to-external-form result-type))])))
(define report-unequal-types
(lambda (ty1 ty2 exp)
(eopl:error 'check-equal-type!
"Types didn't match: ~s != ~a in~%~a"
(type-to-external-form ty1)
(type-to-external-form ty2)
exp)))
(define check-equal-type!
(lambda (ty1 ty2 exp)
(when (not (equal? ty1 ty2))
(report-unequal-types ty1 ty2 exp))))
(define report-rator-not-a-proc-type
(lambda (rator-type rator)
(eopl:error 'type-of-expression
"Rator not a proc type:~%~s~%had rator type ~s"
rator
(type-to-external-form rator-type))))
(define type-of
(lambda (exp tenv)
(cases expression exp
[const-exp (num) (int-type)]
[var-exp (var) (apply-tenv tenv var)]
[diff-exp (exp1 exp2) (let ([ty1 (type-of exp1 tenv)]
[ty2 (type-of exp2 tenv)])
(check-equal-type! ty1 (int-type) exp1)
(check-equal-type! ty2 (int-type) exp2)
(int-type))]
[zero?-exp (exp1) (let ([ty1 (type-of exp1 tenv)])
(check-equal-type! ty1 (int-type) exp1)
(bool-type))]
[if-exp (exp1 exp2 exp3) (let ([ty1 (type-of exp1 tenv)]
[ty2 (type-of exp2 tenv)]
[ty3 (type-of exp3 tenv)])
(check-equal-type! ty1 (bool-type) exp1)
(check-equal-type! ty2 ty3 exp)
ty2)]
[let-exp (var exp1 body) (let ([exp1-type (type-of exp1 tenv)])
(type-of body (extend-tenv var exp1-type tenv)))]
[proc-exp (var var-type body) (let ([result-type (type-of body (extend-tenv var var-type tenv))])
(proc-type var-type result-type))]
[call-exp (rator rand) (let ([rator-type (type-of rator tenv)]
[rand-type (type-of rand tenv)])
(cases type rator-type
[proc-type (arg-type result-type) (begin (check-equal-type! arg-type rand-type rand)
result-type)]
[else (report-rator-not-a-proc-type rator-type rator)]))]
[letrec-exp (p-result-type p-name b-var b-var-type p-body letrec-body)
(let ([tenv-for-letrec-body (extend-tenv p-name (proc-type b-var-type p-result-type) tenv)])
(let ([p-body-type (type-of p-body (extend-tenv b-var b-var-type tenv-for-letrec-body))])
(check-equal-type! p-body-type p-result-type p-body)
(type-of letrec-body tenv-for-letrec-body)))]
[assign-exp (var exp1)
(check-equal-type! (apply-tenv tenv var) (type-of exp1 tenv) exp1)
(int-type)])))
(define type-of-program
(lambda (pgm)
[cases program pgm (a-program (exp1) (type-of exp1 (empty-tenv)))]))
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
[procedure (var body saved-env) (value-of body (extend-env var (newref arg) saved-env))])))
(define value-of
(lambda (exp env)
(cases expression exp
[const-exp (num) (num-val num)]
[var-exp (var) (deref (apply-env env var))]
[diff-exp (exp1 exp2) (let ([val1 (expval->num (value-of exp1 env))]
[val2 (expval->num (value-of exp2 env))])
(num-val (- val1 val2)))]
[zero?-exp (exp1) (let ([val1 (expval->num (value-of exp1 env))])
(if (zero? val1)
(bool-val #t)
(bool-val #f)))]
[if-exp (exp0 exp1 exp2) (if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env))]
[let-exp (var exp1 body) (let ([val (newref (value-of exp1 env))])
(value-of body (extend-env var val env)))]
[proc-exp (bvar ty body) (proc-val (procedure bvar body env))]
[call-exp (rator rand) (let ([proc (expval->proc (value-of rator env))]
[arg (value-of rand env)])
(apply-procedure proc arg))]
[letrec-exp (ty1 p-name b-var ty2 p-body letrec-body) (value-of letrec-body
(extend-env-rec p-name b-var p-body env))]
[assign-exp (var exp1)
(setref! (apply-env env var) (value-of exp1 env))
(num-val 27)])))
(define value-of-program
(lambda (pgm)
(initialize-store!)
(cases program pgm
[a-program (body) (value-of body (empty-env))])))
Interface .
(define check
(lambda (string)
(type-to-external-form (type-of-program (scan&parse string)))))
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(provide check num-val run)
|
068b0c7367d1d4491127bd7c82410f5df4e5139d673eb2c7b00868fc23ae5391 | manuel-serrano/bigloo | engine.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / cigloo / Engine / engine.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : We d Jul 12 15:53:47 1995 * /
* Last change : Thu Nov 4 08:05:19 1999 ( serrano ) * /
;* ------------------------------------------------------------- */
;* We have read the argument line. We start the real compilation */
;* process. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module engine_engine
(export (cigloo)
(translate-file <string> <bool> <symbol>))
(import tools_speek
engine_param
engine_translate
translate_eval
parser_lexer))
;*---------------------------------------------------------------------*/
;* bigloo-name */
;*---------------------------------------------------------------------*/
(define-macro (bigloo-name)
*bigloo-name*)
;*---------------------------------------------------------------------*/
;* cigloo ... */
;*---------------------------------------------------------------------*/
(define (cigloo)
;; the reader settup
(init-lexer!)
(if (string? *dest*)
(begin
(set! *oport* (open-output-file *dest*))
(if (not (output-port? *oport*))
(error "cigloo" "Can't open file for output" *dest*)
(unwind-protect (engine) (close-output-port *oport*))))
(begin
;; when emiting on stdout we switch to a silent mode
(set! *verbose* -1)
(engine))))
;*---------------------------------------------------------------------*/
;* *file-processed* ... */
;*---------------------------------------------------------------------*/
(define *file-processed* '())
;*---------------------------------------------------------------------*/
;* engine ... */
;*---------------------------------------------------------------------*/
(define (engine)
;; first of all, we emit identification comment and
the include clauses .
(if (>=fx *verbose* 0)
(fprint *oport* ";; " *cigloo-name*
", to be used with " (bigloo-name) "."))
(if *directives*
(fprint *oport* "(directives"))
(fprint *oport* " (extern")
;; we start emiting the opaque types
(for-each (lambda (name)
(fprint *oport* "(type " name " (opaque) \"" name "\")"))
*opaque-type*)
;; we compile the files
(if (null? *src*)
(translate-stdin 'emit)
(for-each (lambda (fname) (translate-file fname 'file 'open))
(reverse! *src*)))
;; and we close include clauses
(if *directives*
(if *eval-stub?*
(begin
(fprint *oport* " )")
(translate-eval-declarations)
(fprint *oport* " )")
(translate-eval-stubs))
(fprint *oport* " ))"))
(fprint *oport* " )")))
;*---------------------------------------------------------------------*/
;* translate-stdin ... */
;*---------------------------------------------------------------------*/
(define (translate-stdin mode)
(translate (current-input-port) "stdin" mode))
;*---------------------------------------------------------------------*/
;* translate-file ... */
;*---------------------------------------------------------------------*/
(define (translate-file fname path mode)
[assert check (mode) (or (eq? mode 'open) (eq? mode 'scan))]
(let ((fname (cond
((eq? path '<include>)
(or (and *src-dirname*
(find-file/path
(string-append *src-dirname* "/" fname)
*include-path*))
(find-file/path fname *include-path*)))
((eq? path 'include)
(if *src-dirname*
(string-append *src-dirname* "/" fname)
fname))
(else
(set! *src-dirname* (dirname fname))
(if (string=? *src-dirname* ".")
(set! *src-dirname* #f))
fname))))
(cond
((or (not (string? fname)) (not (file-exists? fname)))
(error "cigloo" "Can't find file " fname))
((member fname *file-processed*)
'done)
(else
(set! *file-processed* (cons fname *file-processed*))
(let ((port (open-input-file fname)))
(if (not (input-port? port))
(error "cigloo" "Can't open file for input" fname)
(unwind-protect (translate port fname mode)
(close-input-port port))))))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/cigloo/Engine/engine.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* We have read the argument line. We start the real compilation */
* process. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* bigloo-name */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* cigloo ... */
*---------------------------------------------------------------------*/
the reader settup
when emiting on stdout we switch to a silent mode
*---------------------------------------------------------------------*/
* *file-processed* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* engine ... */
*---------------------------------------------------------------------*/
first of all, we emit identification comment and
we start emiting the opaque types
we compile the files
and we close include clauses
*---------------------------------------------------------------------*/
* translate-stdin ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* translate-file ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / cigloo / Engine / engine.scm * /
* Author : * /
* Creation : We d Jul 12 15:53:47 1995 * /
* Last change : Thu Nov 4 08:05:19 1999 ( serrano ) * /
(module engine_engine
(export (cigloo)
(translate-file <string> <bool> <symbol>))
(import tools_speek
engine_param
engine_translate
translate_eval
parser_lexer))
(define-macro (bigloo-name)
*bigloo-name*)
(define (cigloo)
(init-lexer!)
(if (string? *dest*)
(begin
(set! *oport* (open-output-file *dest*))
(if (not (output-port? *oport*))
(error "cigloo" "Can't open file for output" *dest*)
(unwind-protect (engine) (close-output-port *oport*))))
(begin
(set! *verbose* -1)
(engine))))
(define *file-processed* '())
(define (engine)
the include clauses .
(if (>=fx *verbose* 0)
(fprint *oport* ";; " *cigloo-name*
", to be used with " (bigloo-name) "."))
(if *directives*
(fprint *oport* "(directives"))
(fprint *oport* " (extern")
(for-each (lambda (name)
(fprint *oport* "(type " name " (opaque) \"" name "\")"))
*opaque-type*)
(if (null? *src*)
(translate-stdin 'emit)
(for-each (lambda (fname) (translate-file fname 'file 'open))
(reverse! *src*)))
(if *directives*
(if *eval-stub?*
(begin
(fprint *oport* " )")
(translate-eval-declarations)
(fprint *oport* " )")
(translate-eval-stubs))
(fprint *oport* " ))"))
(fprint *oport* " )")))
(define (translate-stdin mode)
(translate (current-input-port) "stdin" mode))
(define (translate-file fname path mode)
[assert check (mode) (or (eq? mode 'open) (eq? mode 'scan))]
(let ((fname (cond
((eq? path '<include>)
(or (and *src-dirname*
(find-file/path
(string-append *src-dirname* "/" fname)
*include-path*))
(find-file/path fname *include-path*)))
((eq? path 'include)
(if *src-dirname*
(string-append *src-dirname* "/" fname)
fname))
(else
(set! *src-dirname* (dirname fname))
(if (string=? *src-dirname* ".")
(set! *src-dirname* #f))
fname))))
(cond
((or (not (string? fname)) (not (file-exists? fname)))
(error "cigloo" "Can't find file " fname))
((member fname *file-processed*)
'done)
(else
(set! *file-processed* (cons fname *file-processed*))
(let ((port (open-input-file fname)))
(if (not (input-port? port))
(error "cigloo" "Can't open file for input" fname)
(unwind-protect (translate port fname mode)
(close-input-port port))))))))
|
728be3a44514f3b2e5294bfa829163fbb3952bda15e773a9cb98b488ea9246f3 | cj1128/sicp-review | 3.7.scm | Exercise 3.7
;; Define a procedure make-joint that accomplishes to make joint accounts
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin
(set! balance (- balance amount))
balance)
"Insufficient funds!"))
(define (deposit amount)
(begin
(set! balance (+ balance amount))
balance))
(define (dispatch p m)
(if (eq? password p)
(cond
((eq? m 'withdraw) withdraw)
((eq? m 'deposite) deposit)
(else (error "Unknown request: MAKE-ACCOUNT" m)))
(lambda (_)
"Incorrect Password!")))
dispatch)
(define (make-joint acc passwd new-passwd)
(lambda (p)
(if (eq? p new-passwd)
(lambda (op)
(acc passwd op))
"Incorrect Password!")))
(define acc (make-account 100 'cj))
(define acc2 (make-joint acc 'cj 'abc))
(display ((acc 'cj 'withdraw) 50))
(newline)
(display (((acc2 'abc) 'withdraw) 20))
(newline)
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-3/3.1/3.7.scm | scheme | Define a procedure make-joint that accomplishes to make joint accounts | Exercise 3.7
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin
(set! balance (- balance amount))
balance)
"Insufficient funds!"))
(define (deposit amount)
(begin
(set! balance (+ balance amount))
balance))
(define (dispatch p m)
(if (eq? password p)
(cond
((eq? m 'withdraw) withdraw)
((eq? m 'deposite) deposit)
(else (error "Unknown request: MAKE-ACCOUNT" m)))
(lambda (_)
"Incorrect Password!")))
dispatch)
(define (make-joint acc passwd new-passwd)
(lambda (p)
(if (eq? p new-passwd)
(lambda (op)
(acc passwd op))
"Incorrect Password!")))
(define acc (make-account 100 'cj))
(define acc2 (make-joint acc 'cj 'abc))
(display ((acc 'cj 'withdraw) 50))
(newline)
(display (((acc2 'abc) 'withdraw) 20))
(newline)
|
aabaec61c62b60b32b9849cdd7ecd301678ba8c73120e00e0bb4e795648c6294 | dbuenzli/trel | trel.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2017 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2017 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
let strf = Fmt.str
(* Lazy sequences of values. *)
module Seq = struct
type 'a t =
| Empty
| Cons of 'a * 'a t
| Delay of 'a t Lazy.t
let empty = Empty
let cons v s = Cons (v, s)
let delay sazy = Delay sazy
let rec is_empty s = match s with
| Empty -> true
| Cons _ -> false
| Delay xs -> is_empty (Lazy.force xs)
let rec head = function
| Empty -> None
| Cons (x, _) -> Some x
| Delay xs -> head (Lazy.force xs)
let rec get_head = function
| Empty -> invalid_arg "Sequence is empty"
| Cons (x, _) -> x
| Delay xs -> get_head (Lazy.force xs)
let rec tail = function
| Empty -> invalid_arg "Sequence is empty"
| Cons (_, xs) -> xs
| Delay xs -> tail (Lazy.force xs)
let to_list ?limit s =
let limit = match limit with
| Some l when l < 0 -> invalid_arg (strf "negative limit (%d)" l)
| Some l -> l
| None -> -1
in
let rec loop limit acc s = match limit = 0 with
| true -> List.rev acc
| false ->
match s with
| Empty -> List.rev acc
| Delay s -> loop limit acc (Lazy.force s)
| Cons (x, xs) ->
let limit = if limit = -1 then limit else limit - 1 in
loop limit (x :: acc) xs
in
loop limit [] s
let rec mplus s0 s1 = match s0 with
| Empty -> s1
| Cons (x, xs) -> Cons (x, Delay (lazy (mplus s1 xs)))
| Delay xs ->
match s1 with
| Empty -> s0
| Cons (y, ys) -> Cons (y, Delay (lazy (mplus (Lazy.force xs) ys)))
| Delay ys -> Delay (lazy (mplus (Lazy.force xs) s1))
let rec bind s f = match s with
| Empty -> Empty
| Cons (x, xs) -> mplus (f x) (Delay (lazy (bind xs f)))
| Delay s -> Delay (lazy (bind (Lazy.force s) f))
let rec map f s = match s with
| Empty -> Empty
| Cons (x, xs) -> Cons (f x, map f xs)
| Delay s -> Delay (lazy (map f (Lazy.force s)))
end
type 'a seq = 'a Seq.t
(* Type identifiers
See #1 *)
module Tid = struct type _ t = .. end
module type Tid = sig
type t
type _ Tid.t += Tid : t Tid.t
end
type 'a tid = (module Tid with type t = 'a)
let tid () (type s) =
let module M = struct
type t = s
type _ Tid.t += Tid : t Tid.t
end
in
(module M : Tid with type t = s)
type ('a, 'b) teq = Teq : ('a, 'a) teq
let teq : type r s. r tid -> s tid -> (r, s) teq option =
fun r s ->
let module R = (val r : Tid with type t = r) in
let module S = (val s : Tid with type t = s) in
match R.Tid with
| S.Tid -> Some Teq
| _ -> None
(* Domains
FIXME try to be more clever about domains for structural types,
we are generative which is annoying. Give structure to
tid + hash-consing ? *)
module Dom = struct
type 'a t =
{ name : string;
tid : 'a tid;
equal : 'a -> 'a -> bool;
pp : Format.formatter -> 'a -> unit }
let pp_abstr ppf _ = Fmt.pf ppf "<abstr>"
let v ?(name = "unknown") ?(pp = pp_abstr) ?(equal = ( = )) () =
let tid = tid () in
{ name; tid; equal; pp }
module type V = sig
type t
val equal : t -> t -> bool
val pp : Format.formatter -> t -> unit
end
let of_type : type a. (module V with type t = a) -> a t =
fun (module V) -> v ~pp:V.pp ~equal:V.equal ()
let with_dom ?name ?pp d =
let name = match name with None -> d.name | Some n -> n in
let pp = match pp with None -> d.pp | Some pp -> pp in
{ d with name; pp }
let name d = d.name
let pp_value d = d.pp
let equal_value d = d.equal
let equal : type a b. a t -> b t -> bool =
fun d0 d1 -> match teq d0.tid d1.tid with
| None -> false
| Some Teq -> true
let pp ppf d = Fmt.string ppf d.name
(* Predefined domains *)
let unit =
let pp ppf () = Fmt.pf ppf "()" in
v ~name:"unit" ~pp ~equal:(( = ) : unit -> unit -> bool) ()
let bool =
v ~name:"bool" ~pp:Fmt.bool ~equal:(( = ) : bool -> bool -> bool) ()
let int =
v ~name:"int" ~pp:Fmt.int ~equal:(( = ) : int -> int -> bool) ()
let float =
v ~name:"float" ~pp:Fmt.float ~equal:(( = ) : float -> float -> bool) ()
let string =
v ~name:"string" ~pp:Fmt.string ~equal:(( = ) : string -> string -> bool) ()
let pair f s =
let name = strf "%s * %s" f.name s.name in
let pp = Fmt.Dump.pair f.pp s.pp in
let equal (f0, s0) (f1, s1) = f.equal f0 f1 && s.equal s0 s1 in
v ~name ~pp ~equal ()
let list e =
let equal l0 l1 = List.for_all2 e.equal l0 l1 in
let pp = Fmt.Dump.list e.pp in
let name = match String.contains e.name ' ' with
| true -> strf "(%s) list" e.name
| false -> strf "%s list" e.name
in
v ~name ~pp ~equal ()
end
type 'a dom = 'a Dom.t
(* Variables *)
type 'a var = { id : int; name : string option; tid : 'a tid; }
module Var = struct
type t = V : 'a var -> t
let compare (V v0) (V v1) = (compare : int -> int -> int) v0.id v1.id
end
(* Terms
N.B. We type function applications rather than pure values and
variables. This allows to keep variables untyped which seems to
lead to a more lightweight edsl. *)
type 'a term =
| Var of 'a var
| Ret of 'a dom * 'a ret
and 'a ret =
| App : ('a -> 'b) ret * 'a dom * 'a term -> 'b ret
| Pure : 'a -> 'a ret
let var ?name id = Var { id; name; tid = tid () }
let const dom v = Ret (dom, Pure v)
let pure f = Pure f
let app dom v ret = App (ret, dom, v)
let ret dom ret = Ret (dom, ret)
let unit = const Dom.unit ()
let bool = const Dom.bool
let int = const Dom.int
let float = const Dom.float
let string = const Dom.string
let pair fst snd = (fst, snd)
let pair fdom sdom tdom =
fun fst snd -> pure pair |> app fdom fst |> app sdom snd |> ret tdom
let pp_var ppf v = match v.name with
| Some n -> Fmt.pf ppf "%s" n
| None -> Fmt.pf ppf "_%d" v.id
let rec pp_term : type a. Format.formatter -> a term -> unit =
FIXME not T.R.
fun ppf -> function
| Var v -> pp_var ppf v
| Ret (d, ret) ->
match ret with
| Pure v -> d.Dom.pp ppf v
FIXME add a name to Ret ?
and pp_ret : type a. Format.formatter -> a ret -> unit =
fun ppf -> function
| Pure _ -> ()
| App (f, d, v) ->
Fmt.pf ppf "@[<1>(<fun>";
Fmt.pf ppf "@ %a %a" pp_term v pp_ret f;
Fmt.pf ppf ")@]";
(* Substitutions *)
module Subst = struct
module Vmap = Map.Make (Var)
type binding = B : 'a var * 'a term -> binding
type t = binding Vmap.t
let empty = Vmap.empty
let add var t s = Vmap.add (Var.V var) (B (var, t)) s
let find : type a. a var -> t -> a term option =
fun v s ->
try
let B (v', t) = Vmap.find (Var.V v) s in
match teq v.tid v'.tid with None -> None | Some Teq -> Some t
with Not_found -> None
let iter_bindings f = Vmap.iter (fun _ v -> f v)
end
let rec _term_value : type a. a term -> Subst.t -> a =
fun t s -> match t with
| Ret (d, t) -> _ret_value t s
| Var v ->
match Subst.find v s with
| Some t -> _term_value t s
| None -> raise Exit
and _ret_value : type a. a ret -> Subst.t -> a =
fun r s -> match r with
| Pure v -> v
| App (f, _, v) -> (_ret_value f s) (_term_value v s)
let term_value t s = try Some (_term_value t s) with Exit -> None
let ret_value t s = try Some (_ret_value t s) with Exit -> None
let rec term_ret : type a. a term -> Subst.t -> (a dom * a ret) option =
fun t s -> match t with
| Ret (d, t) -> Some (d, t)
| Var v ->
match Subst.find v s with
| Some t -> term_ret t s
| None -> None
let pp_var_value pp_value v ppf var =
Fmt.pf ppf "@[<1>(%a@ = %a)@]" pp_var var pp_value v
let pp_binding ppf (Subst.B (var, term)) =
pp_var_value pp_term term ppf var
let pp_binding_value subst ppf (Subst.B (var, term) as b) =
match term_ret term subst with
| None -> pp_binding ppf b
| Some (d, ret) ->
match ret_value ret subst with
| Some v -> pp_var_value d.Dom.pp v ppf var
| None -> pp_var_value pp_ret ret ppf var
let pp_subst ppf subst =
Fmt.pf ppf "@[<1>(%a)@]"
(Fmt.iter ~sep:Fmt.sp Subst.iter_bindings pp_binding) subst
let pp_subst_values ppf subst =
Fmt.pf ppf "@[<1>(%a)@]"
(Fmt.iter ~sep:Fmt.sp Subst.iter_bindings (pp_binding_value subst)) subst
Unification
let rec walk t s = match t with
| Var v -> (match Subst.find v s with None -> t | Some v -> walk v s)
| t -> t
let rec unify : type a. a term -> a term -> Subst.t -> Subst.t option =
FIXME not T.R.
fun t0 t1 s -> match walk t0 s, walk t1 s with
| Var v0, Var v1 when v0.id = v1.id -> Some s
| Var v, t | t, Var v -> Some (Subst.add v t s)
| Ret (d0, r0), Ret (d1, r1) ->
if not (d0.Dom.tid == d1.Dom.tid) then None else
match r0, r1 with
| Pure v0, Pure v1 -> if d0.Dom.equal v0 v1 then Some s else None
| App _, App _ -> unify_ret r0 r1 s
| _, _ -> None
and unify_ret : type a. a ret -> a ret -> Subst.t -> Subst.t option =
fun r0 r1 s -> match r0, r1 with
| App (f0, d0, v0), App (f1, d1, v1) ->
begin match teq d0.Dom.tid d1.Dom.tid with
| None -> None
| Some Teq ->
match unify v0 v1 s with
| None -> None
| Some s -> unify_ret f0 f1 s
end
| Pure f0, Pure f1 when f0 == f1 -> Some s
| _, _ -> None
State
type state = { next_vid : int; subst : Subst.t }
let empty = { next_vid = 0; subst = Subst.empty }
let pp_state ppf st = pp_subst_values ppf st.subst
(* Goals *)
type goal = state -> state Seq.t
let fail _ = Seq.empty
let succeed st = Seq.cons st Seq.empty
let ( = ) t0 t1 st = match unify t0 t1 st.subst with
| None -> Seq.empty
| Some subst -> succeed { st with subst }
let ( || ) g0 g1 st = Seq.mplus (g0 st) (g1 st)
let ( && ) g0 g1 st = Seq.bind (g0 st) g1
let delay gazy st = Seq.delay (lazy ((Lazy.force gazy) st))
let fresh lambda st =
let var = var st.next_vid in
lambda var { st with next_vid = st.next_vid + 1 }
module Fresh = struct
let v1 = fresh
let v2 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
(lambda v1 v2) { st with next_vid = st.next_vid + 2 }
let v3 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
(lambda v1 v2 v3) { st with next_vid = st.next_vid + 3 }
let v4 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
let v4 = var (st.next_vid + 3) in
(lambda v1 v2 v3 v4) { st with next_vid = st.next_vid + 4 }
let v5 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
let v4 = var (st.next_vid + 3) in
let v5 = var (st.next_vid + 4) in
(lambda v1 v2 v3 v4 v5) { st with next_vid = st.next_vid + 5 }
let v6 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
let v4 = var (st.next_vid + 3) in
let v5 = var (st.next_vid + 4) in
let v6 = var (st.next_vid + 5) in
(lambda v1 v2 v3 v4 v5 v6) { st with next_vid = st.next_vid + 6 }
end
(* Reification *)
module Value = struct
type 'a t = 'a term * Subst.t
let v var subst = (var, subst)
let name (var, _) = match var with
| Var v -> strf "%a" pp_var v | _ -> assert false
let find (var, subst) = term_value var subst
let get (var, subst) = match term_value var subst with
| None -> invalid_arg (strf "%a is undefined" pp_term var)
| Some v -> v
let term (var, subst) = walk var subst
let pp ppf (var, subst) = match term_ret var subst with
| None -> pp_term ppf var
| Some (d, ret) ->
match ret_value ret subst with
| Some v -> d.Dom.pp ppf v
| None -> pp_ret ppf ret
let get1 x = get x
let get2 x y = get x, get y
let get3 x y z = get x, get y, get z
let get4 x y z r = get x, get y, get z, get r
let get5 x y z r s = get x, get y, get z, get r, get s
let get6 x y z r s t = get x, get y, get z, get r, get s, get t
let find1 x = find x
let find2 x y = find x, find y
let find3 x y z = find x, find y, find z
let find4 x y z r = find x, find y, find z, find r
let find5 x y z r s = find x, find y, find z, find r, find s
let find6 x y z r s t = find x, find y, find z, find r, find s, find t
end
type 'a value = 'a Value.t
type ('q, 'r) reifier = { next_vid : int; query : 'q; reify : state -> 'r }
let reifier query reify = { next_vid = 0; query; reify = (fun _ -> reify) }
let query ?name r =
let var = var ?name r.next_vid in
let next_vid = r.next_vid + 1 in
let query = r.query var in
let reify st = r.reify st (Value.v var st.subst) in
{ next_vid; query; reify }
let _run r = r.query { empty with next_vid = r.next_vid }
let run r = Seq.map r.reify (_run r)
let rec success g = not (Seq.is_empty (g empty))
module Query = struct
let v1 ?n0 r = query ?name:n0 r
let v2 ?n0 ?n1 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let next_vid = r.next_vid + 2 in
let query = r.query v0 v1 in
let reify st = r.reify st (Value.v v0 st.subst) (Value.v v1 st.subst) in
{ next_vid; query; reify }
let v3 ?n0 ?n1 ?n2 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let next_vid = r.next_vid + 3 in
let query = r.query v0 v1 v2 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
in
{ next_vid; query; reify }
let v4 ?n0 ?n1 ?n2 ?n3 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let v3 = var ?name:n3 (r.next_vid + 3) in
let next_vid = r.next_vid + 4 in
let query = r.query v0 v1 v2 v3 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
(Value.v v3 st.subst)
in
{ next_vid; query; reify }
let v5 ?n0 ?n1 ?n2 ?n3 ?n4 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let v3 = var ?name:n3 (r.next_vid + 3) in
let v4 = var ?name:n4 (r.next_vid + 4) in
let next_vid = r.next_vid + 5 in
let query = r.query v0 v1 v2 v3 v4 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
(Value.v v3 st.subst) (Value.v v4 st.subst)
in
{ next_vid; query; reify }
let v6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let v3 = var ?name:n3 (r.next_vid + 3) in
let v4 = var ?name:n4 (r.next_vid + 4) in
let v5 = var ?name:n5 (r.next_vid + 5) in
let next_vid = r.next_vid + 6 in
let query = r.query v0 v1 v2 v3 v4 v5 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
(Value.v v3 st.subst) (Value.v v4 st.subst) (Value.v v5 st.subst)
in
{ next_vid; query; reify }
end
module Reifier = struct
let get1 ?n0 q = Query.v1 ?n0 (reifier q Value.get1)
let get2 ?n0 ?n1 q = Query.v2 ?n0 ?n1 (reifier q Value.get2)
let get3 ?n0 ?n1 ?n2 q = Query.v3 ?n0 ?n1 ?n2 (reifier q Value.get3)
let get4 ?n0 ?n1 ?n2 ?n3 q = Query.v4 ?n0 ?n1 ?n2 ?n3 (reifier q Value.get4)
let get5 ?n0 ?n1 ?n2 ?n3 ?n4 q =
Query.v5 ?n0 ?n1 ?n2 ?n3 ?n4 (reifier q Value.get5)
let get6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q =
Query.v6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 (reifier q Value.get6)
let find1 ?n0 q = Query.v1 ?n0 (reifier q Value.find1)
let find2 ?n0 ?n1 q = Query.v2 ?n0 ?n1 (reifier q Value.find2)
let find3 ?n0 ?n1 ?n2 q = Query.v3 ?n0 ?n1 ?n2 (reifier q Value.find3)
let find4 ?n0 ?n1 ?n2 ?n3 q = Query.v4 ?n0 ?n1 ?n2 ?n3 (reifier q Value.find4)
let find5 ?n0 ?n1 ?n2 ?n3 ?n4 q =
Query.v5 ?n0 ?n1 ?n2 ?n3 ?n4 (reifier q Value.find5)
let find6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q =
Query.v6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 (reifier q Value.find6)
end
module Run = struct
let get1 ?limit q = Seq.to_list ?limit @@ run (Reifier.get1 q)
let get2 ?limit q = Seq.to_list ?limit @@ run (Reifier.get2 q)
let get3 ?limit q = Seq.to_list ?limit @@ run (Reifier.get3 q)
let get4 ?limit q = Seq.to_list ?limit @@ run (Reifier.get4 q)
let get5 ?limit q = Seq.to_list ?limit @@ run (Reifier.get5 q)
let get6 ?limit q = Seq.to_list ?limit @@ run (Reifier.get6 q)
let find1 ?limit q = Seq.to_list ?limit @@ run (Reifier.find1 q)
let find2 ?limit q = Seq.to_list ?limit @@ run (Reifier.find2 q)
let find3 ?limit q = Seq.to_list ?limit @@ run (Reifier.find3 q)
let find4 ?limit q = Seq.to_list ?limit @@ run (Reifier.find4 q)
let find5 ?limit q = Seq.to_list ?limit @@ run (Reifier.find5 q)
let find6 ?limit q = Seq.to_list ?limit @@ run (Reifier.find6 q)
end
State introspection
let states r = _run r
let inspect ?limit r = Seq.to_list ?limit (states r)
module Inspect = struct
let v1 ?limit ?n0 q = inspect ?limit (Reifier.find1 ?n0 q)
let v2 ?limit ?n0 ?n1 q = inspect ?limit (Reifier.find2 ?n0 ?n1 q)
let v3 ?limit ?n0 ?n1 ?n2 q = inspect ?limit (Reifier.find3 ?n0 ?n1 ?n2 q)
let v4 ?limit ?n0 ?n1 ?n2 ?n3 q =
inspect ?limit (Reifier.find4 ?n0 ?n1 ?n2 ?n3 q)
let v5 ?limit ?n0 ?n1 ?n2 ?n3 ?n4 q =
inspect ?limit (Reifier.find5 ?n0 ?n1 ?n2 ?n3 ?n4 q)
let v6 ?limit ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q =
inspect ?limit (Reifier.find6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q)
end
---------------------------------------------------------------------------
Copyright ( c ) 2017
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) 2017 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/dbuenzli/trel/8ccfb136733b4597fb5b6a0c88d15ee2f147cdad/src/trel.ml | ocaml | Lazy sequences of values.
Type identifiers
See #1
Domains
FIXME try to be more clever about domains for structural types,
we are generative which is annoying. Give structure to
tid + hash-consing ?
Predefined domains
Variables
Terms
N.B. We type function applications rather than pure values and
variables. This allows to keep variables untyped which seems to
lead to a more lightweight edsl.
Substitutions
Goals
Reification | ---------------------------------------------------------------------------
Copyright ( c ) 2017 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2017 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
let strf = Fmt.str
module Seq = struct
type 'a t =
| Empty
| Cons of 'a * 'a t
| Delay of 'a t Lazy.t
let empty = Empty
let cons v s = Cons (v, s)
let delay sazy = Delay sazy
let rec is_empty s = match s with
| Empty -> true
| Cons _ -> false
| Delay xs -> is_empty (Lazy.force xs)
let rec head = function
| Empty -> None
| Cons (x, _) -> Some x
| Delay xs -> head (Lazy.force xs)
let rec get_head = function
| Empty -> invalid_arg "Sequence is empty"
| Cons (x, _) -> x
| Delay xs -> get_head (Lazy.force xs)
let rec tail = function
| Empty -> invalid_arg "Sequence is empty"
| Cons (_, xs) -> xs
| Delay xs -> tail (Lazy.force xs)
let to_list ?limit s =
let limit = match limit with
| Some l when l < 0 -> invalid_arg (strf "negative limit (%d)" l)
| Some l -> l
| None -> -1
in
let rec loop limit acc s = match limit = 0 with
| true -> List.rev acc
| false ->
match s with
| Empty -> List.rev acc
| Delay s -> loop limit acc (Lazy.force s)
| Cons (x, xs) ->
let limit = if limit = -1 then limit else limit - 1 in
loop limit (x :: acc) xs
in
loop limit [] s
let rec mplus s0 s1 = match s0 with
| Empty -> s1
| Cons (x, xs) -> Cons (x, Delay (lazy (mplus s1 xs)))
| Delay xs ->
match s1 with
| Empty -> s0
| Cons (y, ys) -> Cons (y, Delay (lazy (mplus (Lazy.force xs) ys)))
| Delay ys -> Delay (lazy (mplus (Lazy.force xs) s1))
let rec bind s f = match s with
| Empty -> Empty
| Cons (x, xs) -> mplus (f x) (Delay (lazy (bind xs f)))
| Delay s -> Delay (lazy (bind (Lazy.force s) f))
let rec map f s = match s with
| Empty -> Empty
| Cons (x, xs) -> Cons (f x, map f xs)
| Delay s -> Delay (lazy (map f (Lazy.force s)))
end
type 'a seq = 'a Seq.t
module Tid = struct type _ t = .. end
module type Tid = sig
type t
type _ Tid.t += Tid : t Tid.t
end
type 'a tid = (module Tid with type t = 'a)
let tid () (type s) =
let module M = struct
type t = s
type _ Tid.t += Tid : t Tid.t
end
in
(module M : Tid with type t = s)
type ('a, 'b) teq = Teq : ('a, 'a) teq
let teq : type r s. r tid -> s tid -> (r, s) teq option =
fun r s ->
let module R = (val r : Tid with type t = r) in
let module S = (val s : Tid with type t = s) in
match R.Tid with
| S.Tid -> Some Teq
| _ -> None
module Dom = struct
type 'a t =
{ name : string;
tid : 'a tid;
equal : 'a -> 'a -> bool;
pp : Format.formatter -> 'a -> unit }
let pp_abstr ppf _ = Fmt.pf ppf "<abstr>"
let v ?(name = "unknown") ?(pp = pp_abstr) ?(equal = ( = )) () =
let tid = tid () in
{ name; tid; equal; pp }
module type V = sig
type t
val equal : t -> t -> bool
val pp : Format.formatter -> t -> unit
end
let of_type : type a. (module V with type t = a) -> a t =
fun (module V) -> v ~pp:V.pp ~equal:V.equal ()
let with_dom ?name ?pp d =
let name = match name with None -> d.name | Some n -> n in
let pp = match pp with None -> d.pp | Some pp -> pp in
{ d with name; pp }
let name d = d.name
let pp_value d = d.pp
let equal_value d = d.equal
let equal : type a b. a t -> b t -> bool =
fun d0 d1 -> match teq d0.tid d1.tid with
| None -> false
| Some Teq -> true
let pp ppf d = Fmt.string ppf d.name
let unit =
let pp ppf () = Fmt.pf ppf "()" in
v ~name:"unit" ~pp ~equal:(( = ) : unit -> unit -> bool) ()
let bool =
v ~name:"bool" ~pp:Fmt.bool ~equal:(( = ) : bool -> bool -> bool) ()
let int =
v ~name:"int" ~pp:Fmt.int ~equal:(( = ) : int -> int -> bool) ()
let float =
v ~name:"float" ~pp:Fmt.float ~equal:(( = ) : float -> float -> bool) ()
let string =
v ~name:"string" ~pp:Fmt.string ~equal:(( = ) : string -> string -> bool) ()
let pair f s =
let name = strf "%s * %s" f.name s.name in
let pp = Fmt.Dump.pair f.pp s.pp in
let equal (f0, s0) (f1, s1) = f.equal f0 f1 && s.equal s0 s1 in
v ~name ~pp ~equal ()
let list e =
let equal l0 l1 = List.for_all2 e.equal l0 l1 in
let pp = Fmt.Dump.list e.pp in
let name = match String.contains e.name ' ' with
| true -> strf "(%s) list" e.name
| false -> strf "%s list" e.name
in
v ~name ~pp ~equal ()
end
type 'a dom = 'a Dom.t
type 'a var = { id : int; name : string option; tid : 'a tid; }
module Var = struct
type t = V : 'a var -> t
let compare (V v0) (V v1) = (compare : int -> int -> int) v0.id v1.id
end
type 'a term =
| Var of 'a var
| Ret of 'a dom * 'a ret
and 'a ret =
| App : ('a -> 'b) ret * 'a dom * 'a term -> 'b ret
| Pure : 'a -> 'a ret
let var ?name id = Var { id; name; tid = tid () }
let const dom v = Ret (dom, Pure v)
let pure f = Pure f
let app dom v ret = App (ret, dom, v)
let ret dom ret = Ret (dom, ret)
let unit = const Dom.unit ()
let bool = const Dom.bool
let int = const Dom.int
let float = const Dom.float
let string = const Dom.string
let pair fst snd = (fst, snd)
let pair fdom sdom tdom =
fun fst snd -> pure pair |> app fdom fst |> app sdom snd |> ret tdom
let pp_var ppf v = match v.name with
| Some n -> Fmt.pf ppf "%s" n
| None -> Fmt.pf ppf "_%d" v.id
let rec pp_term : type a. Format.formatter -> a term -> unit =
FIXME not T.R.
fun ppf -> function
| Var v -> pp_var ppf v
| Ret (d, ret) ->
match ret with
| Pure v -> d.Dom.pp ppf v
FIXME add a name to Ret ?
and pp_ret : type a. Format.formatter -> a ret -> unit =
fun ppf -> function
| Pure _ -> ()
| App (f, d, v) ->
Fmt.pf ppf "@[<1>(<fun>";
Fmt.pf ppf "@ %a %a" pp_term v pp_ret f;
Fmt.pf ppf ")@]";
module Subst = struct
module Vmap = Map.Make (Var)
type binding = B : 'a var * 'a term -> binding
type t = binding Vmap.t
let empty = Vmap.empty
let add var t s = Vmap.add (Var.V var) (B (var, t)) s
let find : type a. a var -> t -> a term option =
fun v s ->
try
let B (v', t) = Vmap.find (Var.V v) s in
match teq v.tid v'.tid with None -> None | Some Teq -> Some t
with Not_found -> None
let iter_bindings f = Vmap.iter (fun _ v -> f v)
end
let rec _term_value : type a. a term -> Subst.t -> a =
fun t s -> match t with
| Ret (d, t) -> _ret_value t s
| Var v ->
match Subst.find v s with
| Some t -> _term_value t s
| None -> raise Exit
and _ret_value : type a. a ret -> Subst.t -> a =
fun r s -> match r with
| Pure v -> v
| App (f, _, v) -> (_ret_value f s) (_term_value v s)
let term_value t s = try Some (_term_value t s) with Exit -> None
let ret_value t s = try Some (_ret_value t s) with Exit -> None
let rec term_ret : type a. a term -> Subst.t -> (a dom * a ret) option =
fun t s -> match t with
| Ret (d, t) -> Some (d, t)
| Var v ->
match Subst.find v s with
| Some t -> term_ret t s
| None -> None
let pp_var_value pp_value v ppf var =
Fmt.pf ppf "@[<1>(%a@ = %a)@]" pp_var var pp_value v
let pp_binding ppf (Subst.B (var, term)) =
pp_var_value pp_term term ppf var
let pp_binding_value subst ppf (Subst.B (var, term) as b) =
match term_ret term subst with
| None -> pp_binding ppf b
| Some (d, ret) ->
match ret_value ret subst with
| Some v -> pp_var_value d.Dom.pp v ppf var
| None -> pp_var_value pp_ret ret ppf var
let pp_subst ppf subst =
Fmt.pf ppf "@[<1>(%a)@]"
(Fmt.iter ~sep:Fmt.sp Subst.iter_bindings pp_binding) subst
let pp_subst_values ppf subst =
Fmt.pf ppf "@[<1>(%a)@]"
(Fmt.iter ~sep:Fmt.sp Subst.iter_bindings (pp_binding_value subst)) subst
Unification
let rec walk t s = match t with
| Var v -> (match Subst.find v s with None -> t | Some v -> walk v s)
| t -> t
let rec unify : type a. a term -> a term -> Subst.t -> Subst.t option =
FIXME not T.R.
fun t0 t1 s -> match walk t0 s, walk t1 s with
| Var v0, Var v1 when v0.id = v1.id -> Some s
| Var v, t | t, Var v -> Some (Subst.add v t s)
| Ret (d0, r0), Ret (d1, r1) ->
if not (d0.Dom.tid == d1.Dom.tid) then None else
match r0, r1 with
| Pure v0, Pure v1 -> if d0.Dom.equal v0 v1 then Some s else None
| App _, App _ -> unify_ret r0 r1 s
| _, _ -> None
and unify_ret : type a. a ret -> a ret -> Subst.t -> Subst.t option =
fun r0 r1 s -> match r0, r1 with
| App (f0, d0, v0), App (f1, d1, v1) ->
begin match teq d0.Dom.tid d1.Dom.tid with
| None -> None
| Some Teq ->
match unify v0 v1 s with
| None -> None
| Some s -> unify_ret f0 f1 s
end
| Pure f0, Pure f1 when f0 == f1 -> Some s
| _, _ -> None
State
type state = { next_vid : int; subst : Subst.t }
let empty = { next_vid = 0; subst = Subst.empty }
let pp_state ppf st = pp_subst_values ppf st.subst
type goal = state -> state Seq.t
let fail _ = Seq.empty
let succeed st = Seq.cons st Seq.empty
let ( = ) t0 t1 st = match unify t0 t1 st.subst with
| None -> Seq.empty
| Some subst -> succeed { st with subst }
let ( || ) g0 g1 st = Seq.mplus (g0 st) (g1 st)
let ( && ) g0 g1 st = Seq.bind (g0 st) g1
let delay gazy st = Seq.delay (lazy ((Lazy.force gazy) st))
let fresh lambda st =
let var = var st.next_vid in
lambda var { st with next_vid = st.next_vid + 1 }
module Fresh = struct
let v1 = fresh
let v2 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
(lambda v1 v2) { st with next_vid = st.next_vid + 2 }
let v3 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
(lambda v1 v2 v3) { st with next_vid = st.next_vid + 3 }
let v4 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
let v4 = var (st.next_vid + 3) in
(lambda v1 v2 v3 v4) { st with next_vid = st.next_vid + 4 }
let v5 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
let v4 = var (st.next_vid + 3) in
let v5 = var (st.next_vid + 4) in
(lambda v1 v2 v3 v4 v5) { st with next_vid = st.next_vid + 5 }
let v6 lambda st =
let v1 = var (st.next_vid ) in
let v2 = var (st.next_vid + 1) in
let v3 = var (st.next_vid + 2) in
let v4 = var (st.next_vid + 3) in
let v5 = var (st.next_vid + 4) in
let v6 = var (st.next_vid + 5) in
(lambda v1 v2 v3 v4 v5 v6) { st with next_vid = st.next_vid + 6 }
end
module Value = struct
type 'a t = 'a term * Subst.t
let v var subst = (var, subst)
let name (var, _) = match var with
| Var v -> strf "%a" pp_var v | _ -> assert false
let find (var, subst) = term_value var subst
let get (var, subst) = match term_value var subst with
| None -> invalid_arg (strf "%a is undefined" pp_term var)
| Some v -> v
let term (var, subst) = walk var subst
let pp ppf (var, subst) = match term_ret var subst with
| None -> pp_term ppf var
| Some (d, ret) ->
match ret_value ret subst with
| Some v -> d.Dom.pp ppf v
| None -> pp_ret ppf ret
let get1 x = get x
let get2 x y = get x, get y
let get3 x y z = get x, get y, get z
let get4 x y z r = get x, get y, get z, get r
let get5 x y z r s = get x, get y, get z, get r, get s
let get6 x y z r s t = get x, get y, get z, get r, get s, get t
let find1 x = find x
let find2 x y = find x, find y
let find3 x y z = find x, find y, find z
let find4 x y z r = find x, find y, find z, find r
let find5 x y z r s = find x, find y, find z, find r, find s
let find6 x y z r s t = find x, find y, find z, find r, find s, find t
end
type 'a value = 'a Value.t
type ('q, 'r) reifier = { next_vid : int; query : 'q; reify : state -> 'r }
let reifier query reify = { next_vid = 0; query; reify = (fun _ -> reify) }
let query ?name r =
let var = var ?name r.next_vid in
let next_vid = r.next_vid + 1 in
let query = r.query var in
let reify st = r.reify st (Value.v var st.subst) in
{ next_vid; query; reify }
let _run r = r.query { empty with next_vid = r.next_vid }
let run r = Seq.map r.reify (_run r)
let rec success g = not (Seq.is_empty (g empty))
module Query = struct
let v1 ?n0 r = query ?name:n0 r
let v2 ?n0 ?n1 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let next_vid = r.next_vid + 2 in
let query = r.query v0 v1 in
let reify st = r.reify st (Value.v v0 st.subst) (Value.v v1 st.subst) in
{ next_vid; query; reify }
let v3 ?n0 ?n1 ?n2 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let next_vid = r.next_vid + 3 in
let query = r.query v0 v1 v2 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
in
{ next_vid; query; reify }
let v4 ?n0 ?n1 ?n2 ?n3 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let v3 = var ?name:n3 (r.next_vid + 3) in
let next_vid = r.next_vid + 4 in
let query = r.query v0 v1 v2 v3 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
(Value.v v3 st.subst)
in
{ next_vid; query; reify }
let v5 ?n0 ?n1 ?n2 ?n3 ?n4 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let v3 = var ?name:n3 (r.next_vid + 3) in
let v4 = var ?name:n4 (r.next_vid + 4) in
let next_vid = r.next_vid + 5 in
let query = r.query v0 v1 v2 v3 v4 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
(Value.v v3 st.subst) (Value.v v4 st.subst)
in
{ next_vid; query; reify }
let v6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 r =
let v0 = var ?name:n0 (r.next_vid ) in
let v1 = var ?name:n1 (r.next_vid + 1) in
let v2 = var ?name:n2 (r.next_vid + 2) in
let v3 = var ?name:n3 (r.next_vid + 3) in
let v4 = var ?name:n4 (r.next_vid + 4) in
let v5 = var ?name:n5 (r.next_vid + 5) in
let next_vid = r.next_vid + 6 in
let query = r.query v0 v1 v2 v3 v4 v5 in
let reify st = r.reify st
(Value.v v0 st.subst) (Value.v v1 st.subst) (Value.v v2 st.subst)
(Value.v v3 st.subst) (Value.v v4 st.subst) (Value.v v5 st.subst)
in
{ next_vid; query; reify }
end
module Reifier = struct
let get1 ?n0 q = Query.v1 ?n0 (reifier q Value.get1)
let get2 ?n0 ?n1 q = Query.v2 ?n0 ?n1 (reifier q Value.get2)
let get3 ?n0 ?n1 ?n2 q = Query.v3 ?n0 ?n1 ?n2 (reifier q Value.get3)
let get4 ?n0 ?n1 ?n2 ?n3 q = Query.v4 ?n0 ?n1 ?n2 ?n3 (reifier q Value.get4)
let get5 ?n0 ?n1 ?n2 ?n3 ?n4 q =
Query.v5 ?n0 ?n1 ?n2 ?n3 ?n4 (reifier q Value.get5)
let get6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q =
Query.v6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 (reifier q Value.get6)
let find1 ?n0 q = Query.v1 ?n0 (reifier q Value.find1)
let find2 ?n0 ?n1 q = Query.v2 ?n0 ?n1 (reifier q Value.find2)
let find3 ?n0 ?n1 ?n2 q = Query.v3 ?n0 ?n1 ?n2 (reifier q Value.find3)
let find4 ?n0 ?n1 ?n2 ?n3 q = Query.v4 ?n0 ?n1 ?n2 ?n3 (reifier q Value.find4)
let find5 ?n0 ?n1 ?n2 ?n3 ?n4 q =
Query.v5 ?n0 ?n1 ?n2 ?n3 ?n4 (reifier q Value.find5)
let find6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q =
Query.v6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 (reifier q Value.find6)
end
module Run = struct
let get1 ?limit q = Seq.to_list ?limit @@ run (Reifier.get1 q)
let get2 ?limit q = Seq.to_list ?limit @@ run (Reifier.get2 q)
let get3 ?limit q = Seq.to_list ?limit @@ run (Reifier.get3 q)
let get4 ?limit q = Seq.to_list ?limit @@ run (Reifier.get4 q)
let get5 ?limit q = Seq.to_list ?limit @@ run (Reifier.get5 q)
let get6 ?limit q = Seq.to_list ?limit @@ run (Reifier.get6 q)
let find1 ?limit q = Seq.to_list ?limit @@ run (Reifier.find1 q)
let find2 ?limit q = Seq.to_list ?limit @@ run (Reifier.find2 q)
let find3 ?limit q = Seq.to_list ?limit @@ run (Reifier.find3 q)
let find4 ?limit q = Seq.to_list ?limit @@ run (Reifier.find4 q)
let find5 ?limit q = Seq.to_list ?limit @@ run (Reifier.find5 q)
let find6 ?limit q = Seq.to_list ?limit @@ run (Reifier.find6 q)
end
State introspection
let states r = _run r
let inspect ?limit r = Seq.to_list ?limit (states r)
module Inspect = struct
let v1 ?limit ?n0 q = inspect ?limit (Reifier.find1 ?n0 q)
let v2 ?limit ?n0 ?n1 q = inspect ?limit (Reifier.find2 ?n0 ?n1 q)
let v3 ?limit ?n0 ?n1 ?n2 q = inspect ?limit (Reifier.find3 ?n0 ?n1 ?n2 q)
let v4 ?limit ?n0 ?n1 ?n2 ?n3 q =
inspect ?limit (Reifier.find4 ?n0 ?n1 ?n2 ?n3 q)
let v5 ?limit ?n0 ?n1 ?n2 ?n3 ?n4 q =
inspect ?limit (Reifier.find5 ?n0 ?n1 ?n2 ?n3 ?n4 q)
let v6 ?limit ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q =
inspect ?limit (Reifier.find6 ?n0 ?n1 ?n2 ?n3 ?n4 ?n5 q)
end
---------------------------------------------------------------------------
Copyright ( c ) 2017
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) 2017 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.
---------------------------------------------------------------------------*)
|
08422fa72e8d672c0d82c6efee56986214a783d30713a864e51a9fe750db1742 | ghcjs/jsaddle-dom | VoidCallback.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.VoidCallback
(newVoidCallback, newVoidCallbackSync, newVoidCallbackAsync,
VoidCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/VoidCallback Mozilla VoidCallback documentation >
newVoidCallback :: (MonadDOM m) => JSM () -> m VoidCallback
newVoidCallback callback
= liftDOM
(VoidCallback . Callback <$> function (\ _ _ [] -> callback))
| < -US/docs/Web/API/VoidCallback Mozilla VoidCallback documentation >
newVoidCallbackSync :: (MonadDOM m) => JSM () -> m VoidCallback
newVoidCallbackSync callback
= liftDOM
(VoidCallback . Callback <$> function (\ _ _ [] -> callback))
| < -US/docs/Web/API/VoidCallback Mozilla VoidCallback documentation >
newVoidCallbackAsync :: (MonadDOM m) => JSM () -> m VoidCallback
newVoidCallbackAsync callback
= liftDOM
(VoidCallback . Callback <$> asyncFunction (\ _ _ [] -> callback))
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/VoidCallback.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.VoidCallback
(newVoidCallback, newVoidCallbackSync, newVoidCallbackAsync,
VoidCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/VoidCallback Mozilla VoidCallback documentation >
newVoidCallback :: (MonadDOM m) => JSM () -> m VoidCallback
newVoidCallback callback
= liftDOM
(VoidCallback . Callback <$> function (\ _ _ [] -> callback))
| < -US/docs/Web/API/VoidCallback Mozilla VoidCallback documentation >
newVoidCallbackSync :: (MonadDOM m) => JSM () -> m VoidCallback
newVoidCallbackSync callback
= liftDOM
(VoidCallback . Callback <$> function (\ _ _ [] -> callback))
| < -US/docs/Web/API/VoidCallback Mozilla VoidCallback documentation >
newVoidCallbackAsync :: (MonadDOM m) => JSM () -> m VoidCallback
newVoidCallbackAsync callback
= liftDOM
(VoidCallback . Callback <$> asyncFunction (\ _ _ [] -> callback))
|
1d3947c59f339eb3ed29a19a3c9739527b284aed162e2b7fbdccacbb8830fd13 | camlp5/camlp5 | extfun.mli | (* camlp5r *)
(* extfun.mli,v *)
Copyright ( c ) INRIA 2007 - 2017
* Extensible functions .
This module implements pattern matching extensible functions .
To extend , use syntax [ pa_extfun.cmo ] :
[ extfun e with [ pattern_matching ] ]
This module implements pattern matching extensible functions.
To extend, use syntax [pa_extfun.cmo]:
[extfun e with [ pattern_matching ]] *)
type ('a, 'b) t;;
(** The type of the extensible functions of type ['a -> 'b] *)
val empty : ('a, 'b) t;;
(** Empty extensible function *)
val apply : ('a, 'b) t -> 'a -> 'b;;
(** Apply an extensible function *)
exception Failure;;
(** Match failure while applying an extensible function *)
val print : ('a, 'b) t -> unit;;
(** Print patterns in the order they are recorded *)
(**/**)
type ('a, 'b) matching =
{ patt : patt; has_when : bool; expr : ('a, 'b) expr }
and patt =
Eapp of patt list
| Eacc of patt list
| Econ of string
| Estr of string
| Eint of string
| Etup of patt list
| Erec of (patt * patt) list
| Evar of unit
and ('a, 'b) expr = 'a -> 'b option;;
val extend : ('a, 'b) t -> (patt * bool * ('a, 'b) expr) list -> ('a, 'b) t;;
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/ocaml_src/lib/extfun.mli | ocaml | camlp5r
extfun.mli,v
* The type of the extensible functions of type ['a -> 'b]
* Empty extensible function
* Apply an extensible function
* Match failure while applying an extensible function
* Print patterns in the order they are recorded
*/* | Copyright ( c ) INRIA 2007 - 2017
* Extensible functions .
This module implements pattern matching extensible functions .
To extend , use syntax [ pa_extfun.cmo ] :
[ extfun e with [ pattern_matching ] ]
This module implements pattern matching extensible functions.
To extend, use syntax [pa_extfun.cmo]:
[extfun e with [ pattern_matching ]] *)
type ('a, 'b) t;;
val empty : ('a, 'b) t;;
val apply : ('a, 'b) t -> 'a -> 'b;;
exception Failure;;
val print : ('a, 'b) t -> unit;;
type ('a, 'b) matching =
{ patt : patt; has_when : bool; expr : ('a, 'b) expr }
and patt =
Eapp of patt list
| Eacc of patt list
| Econ of string
| Estr of string
| Eint of string
| Etup of patt list
| Erec of (patt * patt) list
| Evar of unit
and ('a, 'b) expr = 'a -> 'b option;;
val extend : ('a, 'b) t -> (patt * bool * ('a, 'b) expr) list -> ('a, 'b) t;;
|
90679f25f9bdd2e34cb422594a0d124c8d9d7ba15c9a8e73616a6eb325c16bd3 | inria-parkas/sundialsml | sundials_ROArray.ml | (***********************************************************************)
(* *)
(* OCaml interface to Sundials *)
(* *)
, , and
( / ENS ) ( / ENS ) ( UPMC / ENS / Inria )
(* *)
Copyright 2021 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
(* under a New BSD License, refer to the file LICENSE. *)
(* *)
(***********************************************************************)
include Array
type 'a t = 'a array
let from_array = Array.copy
let to_array = Array.copy
let iteri2 f a b =
let la = length a in
if la <> length b then
invalid_arg "ROArray.iter2i: arrays must have the same length"
else
for i = 0 to la - 1 do
f i (unsafe_get a i) (unsafe_get b i)
done
let iter3 f a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.iter3: arrays must have the same length"
else
for i = 0 to la - 1 do
f (unsafe_get a i) (unsafe_get b i) (unsafe_get c i)
done
let iteri3 f a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.iter3i: arrays must have the same length"
else
for i = 0 to la - 1 do
f i (unsafe_get a i) (unsafe_get b i) (unsafe_get c i)
done
let map3 f a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.map3: arrays must have the same length"
else begin
if la = 0 then [||] else begin
let r = make la (f (unsafe_get a 0) (unsafe_get b 0) (unsafe_get c 0)) in
for i = 1 to la - 1 do
unsafe_set r i (f (unsafe_get a i) (unsafe_get b i) (unsafe_get c i))
done;
r
end
end
let fold_left2 f x a b =
let la = length a in
if la <> length b then
invalid_arg "ROArray.fold_left2: arrays must have the same length"
else
let r = ref x in
for i = 0 to la - 1 do
r := f !r (unsafe_get a i) (unsafe_get b i)
done;
!r
let fold_left3 f x a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.fold_left2: arrays must have the same length"
else
let r = ref x in
for i = 0 to la - 1 do
r := f !r (unsafe_get a i) (unsafe_get b i) (unsafe_get c i)
done;
!r
let for_all2 p a b =
let n = length a in
if n <> length b then
invalid_arg "ROArray.for_all2: arrays must have the same length";
let rec loop i =
if i = n then true
else if p (unsafe_get a i) (unsafe_get b i) then loop (succ i)
else false in
loop 0
| null | https://raw.githubusercontent.com/inria-parkas/sundialsml/b1e07d7ef6184a441faf925841bf9a04d7cf94ea/src/sundials/sundials_ROArray.ml | ocaml | *********************************************************************
OCaml interface to Sundials
under a New BSD License, refer to the file LICENSE.
********************************************************************* | , , and
( / ENS ) ( / ENS ) ( UPMC / ENS / Inria )
Copyright 2021 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
include Array
type 'a t = 'a array
let from_array = Array.copy
let to_array = Array.copy
let iteri2 f a b =
let la = length a in
if la <> length b then
invalid_arg "ROArray.iter2i: arrays must have the same length"
else
for i = 0 to la - 1 do
f i (unsafe_get a i) (unsafe_get b i)
done
let iter3 f a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.iter3: arrays must have the same length"
else
for i = 0 to la - 1 do
f (unsafe_get a i) (unsafe_get b i) (unsafe_get c i)
done
let iteri3 f a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.iter3i: arrays must have the same length"
else
for i = 0 to la - 1 do
f i (unsafe_get a i) (unsafe_get b i) (unsafe_get c i)
done
let map3 f a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.map3: arrays must have the same length"
else begin
if la = 0 then [||] else begin
let r = make la (f (unsafe_get a 0) (unsafe_get b 0) (unsafe_get c 0)) in
for i = 1 to la - 1 do
unsafe_set r i (f (unsafe_get a i) (unsafe_get b i) (unsafe_get c i))
done;
r
end
end
let fold_left2 f x a b =
let la = length a in
if la <> length b then
invalid_arg "ROArray.fold_left2: arrays must have the same length"
else
let r = ref x in
for i = 0 to la - 1 do
r := f !r (unsafe_get a i) (unsafe_get b i)
done;
!r
let fold_left3 f x a b c =
let la = length a in
if la <> length b || la <> length c then
invalid_arg "ROArray.fold_left2: arrays must have the same length"
else
let r = ref x in
for i = 0 to la - 1 do
r := f !r (unsafe_get a i) (unsafe_get b i) (unsafe_get c i)
done;
!r
let for_all2 p a b =
let n = length a in
if n <> length b then
invalid_arg "ROArray.for_all2: arrays must have the same length";
let rec loop i =
if i = n then true
else if p (unsafe_get a i) (unsafe_get b i) then loop (succ i)
else false in
loop 0
|
feaf932d29f456abd89a0df592bfc07e9188b7855f6e7f989fb4011916919ca0 | input-output-hk/ouroboros-network | Translation.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE DerivingVia #
module Ouroboros.Consensus.HardFork.Combinator.Translation (
-- * Translate from one era to the next
EraTranslation (..)
, trivialEraTranslation
) where
import NoThunks.Class (NoThunks, OnlyCheckWhnfNamed (..))
import Ouroboros.Consensus.Ledger.Abstract
import Ouroboros.Consensus.TypeFamilyWrappers
import Ouroboros.Consensus.HardFork.Combinator.State.Types
import Ouroboros.Consensus.HardFork.Combinator.Util.InPairs
(InPairs (..), RequiringBoth (..))
------------------------------------------------------------------------------
Translate from one era to the next
------------------------------------------------------------------------------
Translate from one era to the next
-------------------------------------------------------------------------------}
data EraTranslation xs = EraTranslation {
translateLedgerState :: InPairs (RequiringBoth WrapLedgerConfig (Translate LedgerState)) xs
, translateChainDepState :: InPairs (RequiringBoth WrapConsensusConfig (Translate WrapChainDepState)) xs
, translateLedgerView :: InPairs (RequiringBoth WrapLedgerConfig (TranslateForecast LedgerState WrapLedgerView)) xs
}
deriving NoThunks
via OnlyCheckWhnfNamed "EraTranslation" (EraTranslation xs)
trivialEraTranslation :: EraTranslation '[blk]
trivialEraTranslation = EraTranslation {
translateLedgerState = PNil
, translateLedgerView = PNil
, translateChainDepState = PNil
}
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus/src/Ouroboros/Consensus/HardFork/Combinator/Translation.hs | haskell | # LANGUAGE DataKinds #
* Translate from one era to the next
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------} | # LANGUAGE DerivingVia #
module Ouroboros.Consensus.HardFork.Combinator.Translation (
EraTranslation (..)
, trivialEraTranslation
) where
import NoThunks.Class (NoThunks, OnlyCheckWhnfNamed (..))
import Ouroboros.Consensus.Ledger.Abstract
import Ouroboros.Consensus.TypeFamilyWrappers
import Ouroboros.Consensus.HardFork.Combinator.State.Types
import Ouroboros.Consensus.HardFork.Combinator.Util.InPairs
(InPairs (..), RequiringBoth (..))
Translate from one era to the next
Translate from one era to the next
data EraTranslation xs = EraTranslation {
translateLedgerState :: InPairs (RequiringBoth WrapLedgerConfig (Translate LedgerState)) xs
, translateChainDepState :: InPairs (RequiringBoth WrapConsensusConfig (Translate WrapChainDepState)) xs
, translateLedgerView :: InPairs (RequiringBoth WrapLedgerConfig (TranslateForecast LedgerState WrapLedgerView)) xs
}
deriving NoThunks
via OnlyCheckWhnfNamed "EraTranslation" (EraTranslation xs)
trivialEraTranslation :: EraTranslation '[blk]
trivialEraTranslation = EraTranslation {
translateLedgerState = PNil
, translateLedgerView = PNil
, translateChainDepState = PNil
}
|
85458cbdff0badff4f38a389cff96125016c1df9970af3c58d09503a9fd124f4 | tommaisey/aeon | bool.syntax.scm | ( & & ) : : Bool - > Bool
(define-syntax and2
(syntax-rules ()
((_ p q) (if p q #f))))
(define-syntax and3
(syntax-rules ()
((_ p q r) (and2 p (and2 q r)))))
( || ) : : Bool - > Bool
(define-syntax or2
(syntax-rules ()
((_ p q) (if p p q))))
(define-syntax or3
(syntax-rules ()
((_ p q r) (or2 p (or2 q r)))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rhs/src/data/bool.syntax.scm | scheme | ( & & ) : : Bool - > Bool
(define-syntax and2
(syntax-rules ()
((_ p q) (if p q #f))))
(define-syntax and3
(syntax-rules ()
((_ p q r) (and2 p (and2 q r)))))
( || ) : : Bool - > Bool
(define-syntax or2
(syntax-rules ()
((_ p q) (if p p q))))
(define-syntax or3
(syntax-rules ()
((_ p q r) (or2 p (or2 q r)))))
|
|
60b7edaf52f511bcc50148a22655132ef4971ff95b1a629f0ca40968dd69b880 | tommaisey/aeon | index.help.scm | (import (sosc) (rsc3))
Allocate and set values at buffer 10 .
(with-sc3
(lambda (fd)
(async fd (b-alloc 10 6 1))
(send fd (b-setn1 10 0 (list 50 100 200 400 800 1600)))))
;; Index into the above buffer for frequency values.
(let ((f (mul (index 10 (mul (lf-saw kr 2 3) 4)) (mce2 1 9))))
(audition (out 0 (mul (sin-osc ar f 0) 0.1))))
;; Free buffer
(with-sc3
(lambda (fd)
(async fd (b-free 10))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/oscillators/index.help.scm | scheme | Index into the above buffer for frequency values.
Free buffer | (import (sosc) (rsc3))
Allocate and set values at buffer 10 .
(with-sc3
(lambda (fd)
(async fd (b-alloc 10 6 1))
(send fd (b-setn1 10 0 (list 50 100 200 400 800 1600)))))
(let ((f (mul (index 10 (mul (lf-saw kr 2 3) 4)) (mce2 1 9))))
(audition (out 0 (mul (sin-osc ar f 0) 0.1))))
(with-sc3
(lambda (fd)
(async fd (b-free 10))))
|
f596a2bcfd2fd4c8a13221d101b06f5c1b719698afa1fd5b81faccdb5af19168 | sellout/Kilns | patterns.lisp | (in-package #:kell-calculus)
(defclass pattern-language ()
(grammar :initarg :grammar))
(defvar *current-pattern-language* nil
"This is the currently active pattern language.")
;;; A pattern ξ is an element of a pattern language L. A pattern ξ acts as a
;;; binder in the calculus. A pattern can bind name variables, of the form (a),
;;; where a ∈ N, and process variables. All name and process variables appearing
;;; in a pattern ξ are bound by the pattern. Name variables can only match
;;; names. Process variables can only match processes. Patterns are supposed to
;;; be linear with respect to process variables, that is, each process variable
;;; x occurs only once in a given pattern ξ.
;;;
;;; We make the following assumptions on a pattern language L:
– A pattern language L is a set of patterns that are multisets of single
;;; patterns ξm, ξd, ξu, and ξk. The language L can be described by a
;;; grammar, with the multiset union being represented by parallel
;;; composition.
• ξm is taken from the set Ξm and is a local message pattern : it is used
;;; to match local messages;
;;; • ξd is taken from the set Ξd and is a down message pattern: it is used
;;; to match messages from immediate subkells;
• ξu is taken from the set and is a up message pattern : it is used to
match messages from the environment of the enclosing ;
• ξk is taken from the set Ξk and is a message pattern : it is used
;;; to match immediate subkells.
(defclass pattern ()
((local-message-pattern :initform nil :initarg :local-message-pattern :type list
:accessor local-message-pattern)
(down-message-pattern :initform nil :initarg :down-message-pattern :type list
:accessor down-message-pattern)
(up-message-pattern :initform nil :initarg :up-message-pattern :type list
:accessor up-message-pattern)
(kell-message-pattern :initform nil :initarg :kell-message-pattern :type list
:accessor kell-message-pattern)))
(defmethod print-object ((obj pattern) stream)
(let ((patterns (append (local-message-pattern obj)
(down-message-pattern obj)
(up-message-pattern obj)
(kell-message-pattern obj))))
(format stream "~:[~{~a~}~;(par ~{~a~^ ~})~]"
(< 1 (length patterns)) patterns)))
(defun up (process)
"Paralleling `cont`, this is used to create an up-pattern with the new
syntax."
(setf (continuation process) 'up)
process)
(defun down (process)
"Paralleling `cont`, this is used to create a down-pattern with the new
syntax."
(setf (continuation process) 'down)
process)
FIXME : somewhere around here we need to ensure only one is in the
;;; pattern
(defgeneric convert-process-to-pattern (process &optional pattern)
(:method ((process parallel-composition)
&optional (pattern (make-instance 'pattern)))
(mapc (lambda (sub-process)
(convert-process-to-pattern sub-process pattern))
(append (messages process) (kells process)))
pattern)
(:method ((process message) &optional (pattern (make-instance 'pattern)))
FIXME : should only happen with pnp - jK & FraKtal
(setf (argument process) kilns:_))
(case (continuation process)
(down (push process (down-message-pattern pattern)))
(up (push process (up-message-pattern pattern)))
(otherwise (push process (local-message-pattern pattern))))
pattern)
(:method ((process kell) &optional (pattern (make-instance 'pattern)))
(push process (kell-message-pattern pattern))
pattern))
;;; – One can decide whether a pattern matches a given term. More precisely,
;;; each pattern language is equipped with a decidable relation match, which
associates a pair ⟨ξ , M⟩ , consisting of a pattern ξ and a multiset of
;;; annotated messages M, with defined substitutions that make the pattern
;;; match the multiset of annotated messages, if there are such substitutions,
and with ∅ otherwise ( see section 3.2 for more details ) .
We write θ ∈ match(ξ , M ) for ⟨⟨ξ , M⟩ , θ⟩ ∈ match .
(defun compose-hash-tables (&rest hash-tables)
(let ((combined-hash-table (make-hash-table)))
(mapc (lambda (hash-table)
(maphash (lambda (key value)
(setf (gethash key combined-hash-table)
(append (gethash key combined-hash-table)
value)))
hash-table))
hash-tables)
combined-hash-table))
(defgeneric match (pattern process &optional substitutions)
(:method ((pattern pattern) (process list)
&optional (substitutions (make-empty-environment)))
(values (match-local (local-message-pattern pattern)
process
substitutions)))
(:method ((pattern pattern) (kell kell)
&optional (substitutions (make-empty-environment)))
(let ((processes (append (multiple-value-bind (subst procs)
(match-list #'match-local
(local-message-pattern pattern)
(messages kell)
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-list #'match-down
(down-message-pattern pattern)
(apply #'compose-hash-tables
(mapcar #'messages
(subkells kell)))
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-list #'match-up
(up-message-pattern pattern)
(handler-case
(messages (parent kell))
(unbound-slot () nil))
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-list #'match-kell
(kell-message-pattern pattern)
(kells kell)
substitutions)
(setf substitutions subst)
procs))))
(values substitutions processes)))
(:method ((pattern process) (process process)
&optional (substitutions (make-empty-environment)))
;; FIXME: This should ensure that _all_ processes match, not just enough to
;; satisfy pattern.
(let ((processes (remove nil
(append (multiple-value-bind (subst procs)
(match-local (messages-in pattern)
(messages-in process)
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-kell (kells-in pattern)
(kells-in process)
substitutions)
(setf substitutions subst)
procs)))))
(values substitutions processes)))
(:method (pattern process &optional (substitutions (make-empty-environment)))
(values (unify pattern process substitutions)
process))
(:method :around
(pattern process &optional (substitutions (make-empty-environment)))
FIXME : not really ignorable , but CCL complains
(declare (ignorable pattern process substitutions))
(handler-case (call-next-method)
(unification-failure () (values nil nil)))))
(defun match-list (type-function patterns processes substitutions)
"Finds one match in PROCESSES for each item in PATTERNS. Also ensures that the
same process doesn’t match multiple patterns."
(let* ((matched-processes ())
(processes
(mapcar (lambda (pattern)
(block per-pattern
(mapc (lambda (process)
(when (not (find process matched-processes))
(let ((subst (funcall type-function
pattern
process
substitutions)))
(when subst
(setf substitutions subst)
(push process matched-processes)
(return-from per-pattern process)))))
(gethash (name pattern) processes))
(error 'unification-failure
:format-control "Could not unify ~s with any process in ~s"
:format-arguments (list pattern processes))))
patterns)))
(values substitutions processes)))
(defgeneric match-local (pattern process &optional substitutions)
(:method ((patterns list) (processes list)
&optional (substitutions (make-empty-environment)))
"Finds one match in PROCESSES for each item in PATTERNS. Also ensures that
the same process doesn’t match multiple patterns."
(if (= (length patterns) (length processes))
(let ((processes
(mapcar (lambda (pattern)
(block per-pattern
(mapc (lambda (process)
(let ((subst (match-local pattern process
substitutions)))
(when subst
(setf substitutions subst)
(setf processes (remove process processes))
(return-from per-pattern process))))
processes)
(error 'unification-failure
:format-control "Could not unify ~s with any process in ~s"
:format-arguments (list pattern processes))))
patterns)))
(values substitutions processes))
(error 'unification-failure
:format-control "Can not unify two different length lists: ~s ~s"
:format-arguments (list patterns processes)))))
(defgeneric match-down (pattern process &optional substitutions))
(defgeneric match-up (pattern process &optional substitutions))
(defgeneric match-kell (pattern process &optional substitutions)
(:method ((patterns list) (processes list)
&optional (substitutions (make-empty-environment)))
"Finds one match in PROCESSES for each item in PATTERNS. Also ensures that
the same process doesn’t match multiple patterns."
(let ((processes
(mapcar (lambda (pattern)
(block per-pattern
(mapc (lambda (process)
(let ((subst (match-kell pattern process
substitutions)))
(when subst
(setf substitutions subst)
(setf processes (remove process processes))
(return-from per-pattern process))))
processes)
(error 'unification-failure
:format-control "Could not unify ~s with any process in ~s"
:format-arguments (list pattern processes))))
patterns)))
(values substitutions processes))))
– Pattern languages are equipped with three functions fn , bn , and bv , that
;;; map a pattern ξ to its set of free names, bound name variables, and bound
;;; process variables, respectively. Note that patterns may have free names,
;;; but cannot have free process variables (i.e. all process variables
;;; appearing in a pattern are bound in the pattern).
(defmethod free-names ((pattern pattern))
(reduce #'union
(append (local-message-pattern pattern)
(down-message-pattern pattern)
(up-message-pattern pattern)
(kell-message-pattern pattern))
:key #'free-names))
(defgeneric bound-names (pattern)
(:documentation
"This returns a list of all channel-names that are bound by the given pattern."))
(defgeneric bound-variables (pattern)
(:documentation
"This returns a list of all process-variables that are bound by the given
pattern."))
;;; – Pattern languages are equipped with a function sk, which maps a pattern ξ
;;; to a multiset of names. Intuitively, ξ.sk corresponds to the multiset of
channel names on which pattern ξ expects messages or ( we use
;;; indifferently an infix or a postfix notation for sk). We identify
ξ.sk = { ai | i ∈ I } with the action ∏ i∈I ai ( see section 3.3 for more
;;; details). By definition, we set ξ.sk.supp ⊆ fn(ξ). In other terms, a
;;; pattern may not bind a name that appears in its set of channel names (a
;;; trigger must know channel names in order to receive messages on them).
(defgeneric channel-names (pattern)
(:documentation "Returns a hash-table with 4 entries - one each for local, up,
down, and kell names."))
;;; – Pattern languages are equipped with a structural congruence relation
between patterns , noted ≡. We assume the following properties : if ξ ≡ ζ ,
then fn(ξ ) = fn(ζ ) , ξ.sk = ζ.sk , and bn(ξ ) ∪ bv(ξ ) = bn(ζ ) bv(ζ ) .
;;; Moreover, the interpretation of join patterns as multisets of simple
;;; patterns implies that the structural congruence on patterns must include
;;; the associativity and commutativity of the parallel composition operator.
;;; – A pattern language is compatible with the structural congruence defined
below ( see section 3.2 for more details ) , in particular if P ≡ Q then
there is no Kell calculus context that can distinguish between P and Q.
(defmethod structurally-congruent ((left pattern) (right pattern))
(and (set= (free-names left) (free-names right))
(set= (channel-names left) (channel-names right))
(set= (union (bound-names left) (bound-variables left))
(union (bound-names right) (bound-variables right)))))
| null | https://raw.githubusercontent.com/sellout/Kilns/467ba599f457812daea41a7c56f74a1ec1cdc9b2/src/kell-calculus/patterns.lisp | lisp | A pattern ξ is an element of a pattern language L. A pattern ξ acts as a
binder in the calculus. A pattern can bind name variables, of the form (a),
where a ∈ N, and process variables. All name and process variables appearing
in a pattern ξ are bound by the pattern. Name variables can only match
names. Process variables can only match processes. Patterns are supposed to
be linear with respect to process variables, that is, each process variable
x occurs only once in a given pattern ξ.
We make the following assumptions on a pattern language L:
patterns ξm, ξd, ξu, and ξk. The language L can be described by a
grammar, with the multiset union being represented by parallel
composition.
to match local messages;
• ξd is taken from the set Ξd and is a down message pattern: it is used
to match messages from immediate subkells;
to match immediate subkells.
pattern
– One can decide whether a pattern matches a given term. More precisely,
each pattern language is equipped with a decidable relation match, which
annotated messages M, with defined substitutions that make the pattern
match the multiset of annotated messages, if there are such substitutions,
FIXME: This should ensure that _all_ processes match, not just enough to
satisfy pattern.
map a pattern ξ to its set of free names, bound name variables, and bound
process variables, respectively. Note that patterns may have free names,
but cannot have free process variables (i.e. all process variables
appearing in a pattern are bound in the pattern).
– Pattern languages are equipped with a function sk, which maps a pattern ξ
to a multiset of names. Intuitively, ξ.sk corresponds to the multiset of
indifferently an infix or a postfix notation for sk). We identify
details). By definition, we set ξ.sk.supp ⊆ fn(ξ). In other terms, a
pattern may not bind a name that appears in its set of channel names (a
trigger must know channel names in order to receive messages on them).
– Pattern languages are equipped with a structural congruence relation
Moreover, the interpretation of join patterns as multisets of simple
patterns implies that the structural congruence on patterns must include
the associativity and commutativity of the parallel composition operator.
– A pattern language is compatible with the structural congruence defined | (in-package #:kell-calculus)
(defclass pattern-language ()
(grammar :initarg :grammar))
(defvar *current-pattern-language* nil
"This is the currently active pattern language.")
– A pattern language L is a set of patterns that are multisets of single
• ξm is taken from the set Ξm and is a local message pattern : it is used
• ξu is taken from the set and is a up message pattern : it is used to
• ξk is taken from the set Ξk and is a message pattern : it is used
(defclass pattern ()
((local-message-pattern :initform nil :initarg :local-message-pattern :type list
:accessor local-message-pattern)
(down-message-pattern :initform nil :initarg :down-message-pattern :type list
:accessor down-message-pattern)
(up-message-pattern :initform nil :initarg :up-message-pattern :type list
:accessor up-message-pattern)
(kell-message-pattern :initform nil :initarg :kell-message-pattern :type list
:accessor kell-message-pattern)))
(defmethod print-object ((obj pattern) stream)
(let ((patterns (append (local-message-pattern obj)
(down-message-pattern obj)
(up-message-pattern obj)
(kell-message-pattern obj))))
(format stream "~:[~{~a~}~;(par ~{~a~^ ~})~]"
(< 1 (length patterns)) patterns)))
(defun up (process)
"Paralleling `cont`, this is used to create an up-pattern with the new
syntax."
(setf (continuation process) 'up)
process)
(defun down (process)
"Paralleling `cont`, this is used to create a down-pattern with the new
syntax."
(setf (continuation process) 'down)
process)
FIXME : somewhere around here we need to ensure only one is in the
(defgeneric convert-process-to-pattern (process &optional pattern)
(:method ((process parallel-composition)
&optional (pattern (make-instance 'pattern)))
(mapc (lambda (sub-process)
(convert-process-to-pattern sub-process pattern))
(append (messages process) (kells process)))
pattern)
(:method ((process message) &optional (pattern (make-instance 'pattern)))
FIXME : should only happen with pnp - jK & FraKtal
(setf (argument process) kilns:_))
(case (continuation process)
(down (push process (down-message-pattern pattern)))
(up (push process (up-message-pattern pattern)))
(otherwise (push process (local-message-pattern pattern))))
pattern)
(:method ((process kell) &optional (pattern (make-instance 'pattern)))
(push process (kell-message-pattern pattern))
pattern))
associates a pair ⟨ξ , M⟩ , consisting of a pattern ξ and a multiset of
and with ∅ otherwise ( see section 3.2 for more details ) .
We write θ ∈ match(ξ , M ) for ⟨⟨ξ , M⟩ , θ⟩ ∈ match .
(defun compose-hash-tables (&rest hash-tables)
(let ((combined-hash-table (make-hash-table)))
(mapc (lambda (hash-table)
(maphash (lambda (key value)
(setf (gethash key combined-hash-table)
(append (gethash key combined-hash-table)
value)))
hash-table))
hash-tables)
combined-hash-table))
(defgeneric match (pattern process &optional substitutions)
(:method ((pattern pattern) (process list)
&optional (substitutions (make-empty-environment)))
(values (match-local (local-message-pattern pattern)
process
substitutions)))
(:method ((pattern pattern) (kell kell)
&optional (substitutions (make-empty-environment)))
(let ((processes (append (multiple-value-bind (subst procs)
(match-list #'match-local
(local-message-pattern pattern)
(messages kell)
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-list #'match-down
(down-message-pattern pattern)
(apply #'compose-hash-tables
(mapcar #'messages
(subkells kell)))
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-list #'match-up
(up-message-pattern pattern)
(handler-case
(messages (parent kell))
(unbound-slot () nil))
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-list #'match-kell
(kell-message-pattern pattern)
(kells kell)
substitutions)
(setf substitutions subst)
procs))))
(values substitutions processes)))
(:method ((pattern process) (process process)
&optional (substitutions (make-empty-environment)))
(let ((processes (remove nil
(append (multiple-value-bind (subst procs)
(match-local (messages-in pattern)
(messages-in process)
substitutions)
(setf substitutions subst)
procs)
(multiple-value-bind (subst procs)
(match-kell (kells-in pattern)
(kells-in process)
substitutions)
(setf substitutions subst)
procs)))))
(values substitutions processes)))
(:method (pattern process &optional (substitutions (make-empty-environment)))
(values (unify pattern process substitutions)
process))
(:method :around
(pattern process &optional (substitutions (make-empty-environment)))
FIXME : not really ignorable , but CCL complains
(declare (ignorable pattern process substitutions))
(handler-case (call-next-method)
(unification-failure () (values nil nil)))))
(defun match-list (type-function patterns processes substitutions)
"Finds one match in PROCESSES for each item in PATTERNS. Also ensures that the
same process doesn’t match multiple patterns."
(let* ((matched-processes ())
(processes
(mapcar (lambda (pattern)
(block per-pattern
(mapc (lambda (process)
(when (not (find process matched-processes))
(let ((subst (funcall type-function
pattern
process
substitutions)))
(when subst
(setf substitutions subst)
(push process matched-processes)
(return-from per-pattern process)))))
(gethash (name pattern) processes))
(error 'unification-failure
:format-control "Could not unify ~s with any process in ~s"
:format-arguments (list pattern processes))))
patterns)))
(values substitutions processes)))
(defgeneric match-local (pattern process &optional substitutions)
(:method ((patterns list) (processes list)
&optional (substitutions (make-empty-environment)))
"Finds one match in PROCESSES for each item in PATTERNS. Also ensures that
the same process doesn’t match multiple patterns."
(if (= (length patterns) (length processes))
(let ((processes
(mapcar (lambda (pattern)
(block per-pattern
(mapc (lambda (process)
(let ((subst (match-local pattern process
substitutions)))
(when subst
(setf substitutions subst)
(setf processes (remove process processes))
(return-from per-pattern process))))
processes)
(error 'unification-failure
:format-control "Could not unify ~s with any process in ~s"
:format-arguments (list pattern processes))))
patterns)))
(values substitutions processes))
(error 'unification-failure
:format-control "Can not unify two different length lists: ~s ~s"
:format-arguments (list patterns processes)))))
(defgeneric match-down (pattern process &optional substitutions))
(defgeneric match-up (pattern process &optional substitutions))
(defgeneric match-kell (pattern process &optional substitutions)
(:method ((patterns list) (processes list)
&optional (substitutions (make-empty-environment)))
"Finds one match in PROCESSES for each item in PATTERNS. Also ensures that
the same process doesn’t match multiple patterns."
(let ((processes
(mapcar (lambda (pattern)
(block per-pattern
(mapc (lambda (process)
(let ((subst (match-kell pattern process
substitutions)))
(when subst
(setf substitutions subst)
(setf processes (remove process processes))
(return-from per-pattern process))))
processes)
(error 'unification-failure
:format-control "Could not unify ~s with any process in ~s"
:format-arguments (list pattern processes))))
patterns)))
(values substitutions processes))))
– Pattern languages are equipped with three functions fn , bn , and bv , that
(defmethod free-names ((pattern pattern))
(reduce #'union
(append (local-message-pattern pattern)
(down-message-pattern pattern)
(up-message-pattern pattern)
(kell-message-pattern pattern))
:key #'free-names))
(defgeneric bound-names (pattern)
(:documentation
"This returns a list of all channel-names that are bound by the given pattern."))
(defgeneric bound-variables (pattern)
(:documentation
"This returns a list of all process-variables that are bound by the given
pattern."))
channel names on which pattern ξ expects messages or ( we use
ξ.sk = { ai | i ∈ I } with the action ∏ i∈I ai ( see section 3.3 for more
(defgeneric channel-names (pattern)
(:documentation "Returns a hash-table with 4 entries - one each for local, up,
down, and kell names."))
between patterns , noted ≡. We assume the following properties : if ξ ≡ ζ ,
then fn(ξ ) = fn(ζ ) , ξ.sk = ζ.sk , and bn(ξ ) ∪ bv(ξ ) = bn(ζ ) bv(ζ ) .
below ( see section 3.2 for more details ) , in particular if P ≡ Q then
there is no Kell calculus context that can distinguish between P and Q.
(defmethod structurally-congruent ((left pattern) (right pattern))
(and (set= (free-names left) (free-names right))
(set= (channel-names left) (channel-names right))
(set= (union (bound-names left) (bound-variables left))
(union (bound-names right) (bound-variables right)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.