_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
46f7250066fbd7ac06799fe0b086e70f4d9a3c4744e0d511995dc42ab124e6eb
spacegangster/space-ui
animations.cljc
(ns space-ui.style.animations "CSS animation property groups") (defn pulse "constant pulse" [keyframes-name] {:animation-duration :2s :animation-timing-function :ease-in-out :animation-name keyframes-name :animation-iteration-count :infinite :animation-direction :alternate :animation-fill-mode :forwards}) (defn one-fill "this animation stays after play" [keyframes-name & [duration-ms]] (let [duration (cond (not duration-ms) :1000ms (number? duration-ms) (str duration-ms "ms") :else duration-ms)] {:animation-duration duration :animation-timing-function :ease-in-out :animation-name keyframes-name :animation-iteration-count 1 :animation-fill-mode :forwards})) (defn pulse--one-out "this animation fades in and out" [keyframes-name] {:animation-duration :1400ms :animation-timing-function :ease-in-out :animation-name keyframes-name :animation-iteration-count 2 :animation-direction :alternate}) (defn animation-oscillation-opacity [] {:animation "1s ease-in-out :keyframes/oscillating-opacity infinite alternate"})
null
https://raw.githubusercontent.com/spacegangster/space-ui/74825c904b6b456d845c3b3d669ce795b33f5ba9/src/space_ui/style/animations.cljc
clojure
(ns space-ui.style.animations "CSS animation property groups") (defn pulse "constant pulse" [keyframes-name] {:animation-duration :2s :animation-timing-function :ease-in-out :animation-name keyframes-name :animation-iteration-count :infinite :animation-direction :alternate :animation-fill-mode :forwards}) (defn one-fill "this animation stays after play" [keyframes-name & [duration-ms]] (let [duration (cond (not duration-ms) :1000ms (number? duration-ms) (str duration-ms "ms") :else duration-ms)] {:animation-duration duration :animation-timing-function :ease-in-out :animation-name keyframes-name :animation-iteration-count 1 :animation-fill-mode :forwards})) (defn pulse--one-out "this animation fades in and out" [keyframes-name] {:animation-duration :1400ms :animation-timing-function :ease-in-out :animation-name keyframes-name :animation-iteration-count 2 :animation-direction :alternate}) (defn animation-oscillation-opacity [] {:animation "1s ease-in-out :keyframes/oscillating-opacity infinite alternate"})
d8ec722ea7e527581e627b385d8ba875301daf73438ba7c67bc128362c777ecc
johnmn3/cljs-thread
id.cljs
(ns cljs-thread.id) (defprotocol IDable "Protocol for types which have an ID" (get-id [x] "Returns id if a value has an ID."))
null
https://raw.githubusercontent.com/johnmn3/cljs-thread/e98edc26ae71d1e17cea96a1f0e978df41b34d3f/src/cljs_thread/id.cljs
clojure
(ns cljs-thread.id) (defprotocol IDable "Protocol for types which have an ID" (get-id [x] "Returns id if a value has an ID."))
f3c3cc3f4b76e376ad26cb2c0c6a2e95581eaf694aa026bd03a2208f379a7b93
OCADml/OSCADml
bespoke_sweeps.ml
(** {0 Bespoke Sweeps} *) open OCADml open OSCADml * Sometimes one may need more control than what { { ! OCADml . Path3.to_transforms } [ Path3.to_transforms ] } ( and by extension { { ! OCADml . Mesh.path_extrude } [ Mesh.path_extrude ] } ) provide . For instance , as demonstrated below with the { { ! wavey } wavey cylinder } , when non - monotonic scaling throughout a sweep is desired . In those scenarios , generating / composing lists of { { ! OCADml . Affine3.t } [ Affine3.t ] } by other means and giving those to { { ! } [ Mesh.sweep ] } is an option . {{!OCADml.Path3.to_transforms} [Path3.to_transforms]} (and by extension {{!OCADml.Mesh.path_extrude} [Mesh.path_extrude]}) provide. For instance, as demonstrated below with the {{!wavey} wavey cylinder}, when non-monotonic scaling throughout a sweep is desired. In those scenarios, generating/composing lists of {{!OCADml.Affine3.t} [Affine3.t]} by other means and giving those to {{!OCADml.Mesh.sweep} [Mesh.sweep]} is an option. *) (** {1 Flat Spiral} *) (** A plain, centred square with which to draw our spiral. *) let square = Poly2.square ~center:true (v2 10. 10.) (** A series of affine transformation matrices describing a spiral. *) let transforms = let step = 0.001 in let f i = let t = Float.of_int i *. step in Affine3.( mul (axis_rotate (v3 0. 0. 1.) (t *. Float.pi *. 40.)) (translate (v3 (10. +. (500. *. t)) 0. 0.)) ) in List.init (Int.of_float (1. /. step) + 1) f * { { ! } [ Mesh.sweep ] } applies each of the transforms to [ square ] in its { i original } state , linking up each resulting loop of points with the next to form a mesh that we can convert into an OpenSCAD polyhedron . [square] in its {i original} state, linking up each resulting loop of points with the next to form a mesh that we can convert into an OpenSCAD polyhedron. *) let () = Scad.to_file "spiral.scad" @@ Scad.of_mesh @@ Mesh.sweep ~transforms square * { % html : < p style="text - align : center ; " > < img src="_assets / spiral.png " style="width:150mm;"/ > < /p > % } <p style="text-align:center;"> <img src="_assets/spiral.png" style="width:150mm;"/> </p> %} *) * { 1 : wavey Wavey Hollow Cylinder } let () = let r = 10. and h = 20. and s = 2. and step = 4. and rad d = d *. Float.pi /. 180. in let f i = let t = Float.of_int i *. step in Affine3.( mul (mul (rotate (v3 (rad 90.) 0. (rad t))) (translate (v3 r 0. 0.))) (scale (v3 1. (h +. (s *. Float.sin (rad (t *. 6.)))) 1.)) ) in Mesh.sweep ~transforms:(List.init ((360 / 4) + 1) f) (Poly2.square (v2 2. 1.)) |> Scad.of_mesh |> Scad.to_file "wave_cylinder.scad" * { % html : < p style="text - align : center ; " > < img src="_assets / wave_cylinder.png " style="width:150mm;"/ > < /p > % } <p style="text-align:center;"> <img src="_assets/wave_cylinder.png" style="width:150mm;"/> </p> %} *)
null
https://raw.githubusercontent.com/OCADml/OSCADml/a1d5e9d6aa9f703e0a7eb419128593ef9c694072/examples/bespoke_sweeps.ml
ocaml
* {0 Bespoke Sweeps} * {1 Flat Spiral} * A plain, centred square with which to draw our spiral. * A series of affine transformation matrices describing a spiral.
open OCADml open OSCADml * Sometimes one may need more control than what { { ! OCADml . Path3.to_transforms } [ Path3.to_transforms ] } ( and by extension { { ! OCADml . Mesh.path_extrude } [ Mesh.path_extrude ] } ) provide . For instance , as demonstrated below with the { { ! wavey } wavey cylinder } , when non - monotonic scaling throughout a sweep is desired . In those scenarios , generating / composing lists of { { ! OCADml . Affine3.t } [ Affine3.t ] } by other means and giving those to { { ! } [ Mesh.sweep ] } is an option . {{!OCADml.Path3.to_transforms} [Path3.to_transforms]} (and by extension {{!OCADml.Mesh.path_extrude} [Mesh.path_extrude]}) provide. For instance, as demonstrated below with the {{!wavey} wavey cylinder}, when non-monotonic scaling throughout a sweep is desired. In those scenarios, generating/composing lists of {{!OCADml.Affine3.t} [Affine3.t]} by other means and giving those to {{!OCADml.Mesh.sweep} [Mesh.sweep]} is an option. *) let square = Poly2.square ~center:true (v2 10. 10.) let transforms = let step = 0.001 in let f i = let t = Float.of_int i *. step in Affine3.( mul (axis_rotate (v3 0. 0. 1.) (t *. Float.pi *. 40.)) (translate (v3 (10. +. (500. *. t)) 0. 0.)) ) in List.init (Int.of_float (1. /. step) + 1) f * { { ! } [ Mesh.sweep ] } applies each of the transforms to [ square ] in its { i original } state , linking up each resulting loop of points with the next to form a mesh that we can convert into an OpenSCAD polyhedron . [square] in its {i original} state, linking up each resulting loop of points with the next to form a mesh that we can convert into an OpenSCAD polyhedron. *) let () = Scad.to_file "spiral.scad" @@ Scad.of_mesh @@ Mesh.sweep ~transforms square * { % html : < p style="text - align : center ; " > < img src="_assets / spiral.png " style="width:150mm;"/ > < /p > % } <p style="text-align:center;"> <img src="_assets/spiral.png" style="width:150mm;"/> </p> %} *) * { 1 : wavey Wavey Hollow Cylinder } let () = let r = 10. and h = 20. and s = 2. and step = 4. and rad d = d *. Float.pi /. 180. in let f i = let t = Float.of_int i *. step in Affine3.( mul (mul (rotate (v3 (rad 90.) 0. (rad t))) (translate (v3 r 0. 0.))) (scale (v3 1. (h +. (s *. Float.sin (rad (t *. 6.)))) 1.)) ) in Mesh.sweep ~transforms:(List.init ((360 / 4) + 1) f) (Poly2.square (v2 2. 1.)) |> Scad.of_mesh |> Scad.to_file "wave_cylinder.scad" * { % html : < p style="text - align : center ; " > < img src="_assets / wave_cylinder.png " style="width:150mm;"/ > < /p > % } <p style="text-align:center;"> <img src="_assets/wave_cylinder.png" style="width:150mm;"/> </p> %} *)
da7b68e638f392e854fcd6fb18daa52b7f9dcfb602be88265801fa34c1965184
jaredly/reepl
show_devtools.cljs
(ns reepl.show-devtools (:require [clojure.string :as str] [reagent.core :as r] [devtools.format :as devtools] [cljs.pprint :as pprint] [reepl.helpers :as helpers]) (:require-macros [reagent.ratom :refer [reaction]])) (def styles {:value-head {:flex-direction :row} :value-toggle {:font-size 9 :padding 4 :cursor :pointer}}) (def view (partial helpers/view styles)) (def text (partial helpers/text styles)) (def button (partial helpers/button styles)) (defn str? [val] (= js/String (type val))) (defn pprint-str [val] (pprint/write val :stream nil)) (defn js-array? [val] (= js/Array (type val))) (defn parse-style [raw] (into {} (map (fn [line] (let [[k v] (str/split line ":")] [(keyword k) v]))(str/split raw ";")))) (defn show-el [val show-value] (let [type (first val) opts (second val) children (drop 2 val)] (if (= "object" type) [show-value (.-object opts) (.-config opts)] (into [(keyword type) {:style (when opts (parse-style (.-style opts)))}] (map #(if-not (js-array? %) % (show-el % show-value)) children)) ))) (defn openable [header val config show-value] (let [open (r/atom false)] (fn [_ _] (let [is-open @open] [view :value-with-body [view :value-head [view {:on-click #(swap! open not) :style :value-toggle} (if is-open "▼" "▶")] (show-el header show-value)] (when is-open (show-el (devtools/body-api-call val config) show-value)) ])))) ;; see (defn show-devtools [val config show-value] (if (var? val) nil (let [header (try (devtools/header-api-call val config) (catch js/Error e e))] (cond (not header) nil (instance? js/Error header) [view :inline-value "Error expanding lazy value"] :else (if-not (devtools/has-body-api-call val config) [view :inline-value (show-el header show-value)] [openable header val config show-value] )))))
null
https://raw.githubusercontent.com/jaredly/reepl/96a8979c574b3979a7aeeed27e57a2ec4d357350/src/reepl/show_devtools.cljs
clojure
see
(ns reepl.show-devtools (:require [clojure.string :as str] [reagent.core :as r] [devtools.format :as devtools] [cljs.pprint :as pprint] [reepl.helpers :as helpers]) (:require-macros [reagent.ratom :refer [reaction]])) (def styles {:value-head {:flex-direction :row} :value-toggle {:font-size 9 :padding 4 :cursor :pointer}}) (def view (partial helpers/view styles)) (def text (partial helpers/text styles)) (def button (partial helpers/button styles)) (defn str? [val] (= js/String (type val))) (defn pprint-str [val] (pprint/write val :stream nil)) (defn js-array? [val] (= js/Array (type val))) (defn parse-style [raw] (into {} (map (fn [line] (let [[k v] (str/split line ":")] [(keyword k) v]))(str/split raw ";")))) (defn show-el [val show-value] (let [type (first val) opts (second val) children (drop 2 val)] (if (= "object" type) [show-value (.-object opts) (.-config opts)] (into [(keyword type) {:style (when opts (parse-style (.-style opts)))}] (map #(if-not (js-array? %) % (show-el % show-value)) children)) ))) (defn openable [header val config show-value] (let [open (r/atom false)] (fn [_ _] (let [is-open @open] [view :value-with-body [view :value-head [view {:on-click #(swap! open not) :style :value-toggle} (if is-open "▼" "▶")] (show-el header show-value)] (when is-open (show-el (devtools/body-api-call val config) show-value)) ])))) (defn show-devtools [val config show-value] (if (var? val) nil (let [header (try (devtools/header-api-call val config) (catch js/Error e e))] (cond (not header) nil (instance? js/Error header) [view :inline-value "Error expanding lazy value"] :else (if-not (devtools/has-body-api-call val config) [view :inline-value (show-el header show-value)] [openable header val config show-value] )))))
f11b88bac1f3d4c37ac4fad5fb78101de2b670862a45d960f4d8c2c143574a95
psholtz/MIT-SICP
game.scm
(load "prisoner.scm") ;; ++++++++++++++++++++++++++++++++++++++++++++++++++ Problem 1 ;; ;; Definition of "extract-entry" ;; ++++++++++++++++++++++++++++++++++++++++++++++++++ ;; ;; The *game-association-list* is defined as follows: ;; (define *game-association-list* (list (list (list "c" "c") (list 3 3)) (list (list "c" "d") (list 0 5)) (list (list "d" "c") (list 5 0)) (list (list "d" "d") (list 1 1)))) ;; ;; We can extract a specific entry in this list by using the "list-ref" procedure. ;; ;; For example: ;; (list-ref *game-association-list* 0) = = > ( ( " c " " c " ) ( 3 3 ) ) (list-ref *game-association-list* 1) ;; ==> (("c" "d") (0 5)) ;; ;; and so on. To extract the entry associated with a specific play, we need to extract ;; the "car" of the entry, and make sure that both elements of this "car" correspond ;; to both elements of the argument play. ;; ;; We define our "extract-entry" procedure as follows: ;; (define (extract-entry play *game-association-list*) ;; ;; Returns "true" if the play matches the entry: ;; (define (compare play entry) (let ((test (car entry))) (and (string=? (car play) (car test)) (string=? (cadr play) (cadr test))))) (let ;; ;; Get references to each entry in the *game-association-list*: ;; ((first (list-ref *game-association-list* 0)) (second (list-ref *game-association-list* 1)) (third (list-ref *game-association-list* 2)) (fourth (list-ref *game-association-list* 3))) ;; ;; If we find a match, return that specific entry: ;; (cond ((compare play first) first) ((compare play second) second) ((compare play third) third) ((compare play fourth) fourth) (else '())))) ;; ;; We can test our procedure as follows: ;; (extract-entry (make-play "c" "c") *game-association-list*) = = > ( ( " c " " c " ) ( 3 3 ) ) (extract-entry (make-play "c" "d") *game-association-list*) ;; ==> (("c" "d") (0 5)) (extract-entry (make-play "d" "c") *game-association-list*) = = > ( ( " d " " c " ) ( 5 0 ) ) (extract-entry (make-play "d" "d") *game-association-list*) = = > ( ( " d " " d " ) ( 1 1 ) ) (extract-entry (make-play "x" "x") *game-association-list*) ;; ==> () ;; ;; Similarly, since "get-point-list" is defined as: ;; (define (get-point-list game) (cadr (extract-entry game *game-association-list*))) (get-point-list (make-play "c" "c")) = = > ( 3 3 ) (get-point-list (make-play "c" "d")) = = > ( 0 5 ) (get-point-list (make-play "d" "c")) = = > ( 5 0 ) (get-point-list (make-play "d" "d")) = = > ( 1 1 ) ;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Problem 2 ;; Use " play - loop " to play games between the five strategies . ;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ;; For reference , the five strategies are defined as : ;; ;; Always "defect" (define (NASTY my-history other-history) "d") ;; Always "cooperate" (define (PATSY my-history other-history) "c") " Defect " or " cooperate " with 50 - 50 chance (define (SPASTIC my-history other-history) (if (= (random 2) 0) "c" "d")) (define (EGALITARIAN my-history other-history) (define (count-instances-of test hist) (cond ((empty-history? hist) 0) ((string=? (most-recent-play hist) test) (+ (count-instances-of test (rest-of-plays hist)) 1)) (else (count-instances-of test (rest-of-plays hist))))) (let ((ds (count-instances-of "d" other-history)) (cs (count-instances-of "c" other-history))) (if (> ds cs) "d" "c"))) " Cooperate " on first round , otherwise return " eye for eye " (define (EYE-FOR-EYE my-history other-history) (if (empty-history? my-history) "c" (most-recent-play other-history))) ;; NASTY is a highly " dominant " strategy . It never " loses " outright , at worst tying only when it plays against itself . Otherwise , NASTY is able to beat all the other strategies . ;; When NASTY plays against the following opponents , we obtain the following results : ;; ;; ;; ------------------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;;------------------------------------------------------------------------------------ NASTY | Ties | Wins | Wins | Wins | Wins | | 1.0 points | 5.0 points | 2.88 points | 1.04 points | 1.04 points | ;;------------------------------------------------------------------------------------ ;; ;; Note that in all these plays , SPASTIC is a stochastic strategy and will generate ;; slightly different point values which vary from round to round. ;; ;; PATSY never wins , and it loses badly against NASTY and SPASTIC . However , it ties with itself , EGALITARIAN and EYE - FOR - EYE . ;; When PATSY plays against the following opponents , we obtain the following results : ;; ;; ;; ---------------------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;;--------------------------------------------------------------------------------------- PATSY | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.29 points | 3.0 points | 3.0 points | ;;--------------------------------------------------------------------------------------- ;; ;; Despite being ostensibly " random " , the SPASTIC strategy fares quite well . When playing ;; against itself, the results are (essentially) a draw, where it wins or loses by a slight ;; random margin. Similarly, the results against EYE-FOR-EYE are usually neutral (i.e., a tie) with an occasional very slighty win on the side of SPASTIC . SPASTIC wins decisively against PATSY , and loses against NASTY . ;; The most interesting behavior is when SPASTIC plays EGALITARIAN . Usually ( roughly 70 % of the time ) , SPASTIC will win decisively , but occassionally ( roughly 30 % of the time ) it ;; will lose (quite badly). ;; Note that SPASTIC is a stochastic strategy and will generate slightly different point ;; values which vary from round to round. Specifically, when playing against itself, SPASTIC will either win or lose , but only by a very narrow margin , both opponents ;; obtaining nearly the same number of points. This state of affairs is labeled a ;; "stochastic tie". ;; When SPASTIC plays against the following opponents , we obtain the following results : ;; ;; ;; --------------------------------------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;;-------------------------------------------------------------------------------------------------------- SPASTIC | Loses | Wins | " Stochastic Tie " | 70 % Wins | Tie or Slight Win | | 0.527 points | 4.1 points | 2.32 points | 2.77 points | 2.29 points | | | | | 30 % Loss | | | | | | 1.22 points | | ;;-------------------------------------------------------------------------------------------------------- ;; ;; EGALITARIAN almost always " ties " , or , even when " winning " or " losing " , does so only by a very narrow margin . The most interesting behavior comes with SPASTIC , where 50 % of the time , EGALITARIAN wins with a score of 2.47 , whereas 50 % of the time , EGALITARIAN loses with a score of 1.87 . ;; When EGALITARIAN plays against the following opponents , we obtain the following results : ;; ;; ;; ------------------------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;;--------------------------------------------------------------------------------------------- EGALITARIAN | Slight Loss | 50 % Wins | Tie | Tie | | 0.99 points | 3.0 points | 2.47 points | 3.0 points | 3.0 points | | | | 50 % Loses | | | | | | 1.87 points | | | ;;--------------------------------------------------------------------------------------------- ;; ;; Like EGALITARIAN , EYE - FOR - EYE also almost always " ties " , or , even when " winning " or " losing " , does so only by a very narrow margin . EYE - FOR - EYE will tie PATSY , EGALITARIAN and EYE - FOR - EYE ( itself ) . It will tie or slightly lose to SPASTIC , and will slightly lose to NASTY . ;; ;; ;; ------------------------------------------------------------------------------------ | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;;-------------------------------------------------------------------------------------------------- ;; EYE-FOR-EYE | Slight Loss | Tie | Tie or Slight Loss | Tie | Tie | | 0.99 points | 3.0 points | 2.23 points | 3.0 points | 3.0 points | ;;-------------------------------------------------------------------------------------------------- ;; ;; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Problem 3 ;; Explore more efficient ways to code EGALITARIAN . ;; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ;; For reference , the original definition of EGALITARIAN was given as : ;; (define (EGALITARIAN my-history other-history) (define (count-instances-of test hist) (cond ((empty-history? hist) 0) ((string=? (most-recent-play hist) test) (+ (count-instances-of test (rest-of-plays hist)) 1)) (else (count-instances-of test (rest-of-plays hist))))) (let ((ds (count-instances-of "d" other-history)) (cs (count-instances-of "c" other-history))) (if (> ds cs) "d" "c"))) ;; For any one particular game play , the code here makes : ;; ( 1 ) a " linear " walk down the " other - history " list ; ( 2 ) a second " linear " walk down the " other - history " list ; ;; ;; So for each game play, if the "other-history" is of size k, ;; the procedure executes in O(2*k) time. ;; In other words , when the history is of length 1 , the play executes in time 2 * 1 . When the history is of length 2 , the play executes in time 2 * 2 . When the history is of length k , the play executes in time 2*k . ;; ;; We are executing a total of n plays. That means the total ;; time to execute all n plays is: ;; T(n ) = 2 * ( 1 + 2 + ... + n ) T(n ) = 2 * n * ( n + 1 ) / 2 ;; T(n) = n * (n+1) ;; ;; In O-notation, this procedure will execute in O(n^2) time. ;; ;; 's new definition of EGALITARIAN is given as : ;; (define (EGALITARIAN my-history other-history) (define (majority-loop cs ds hist) (cond ((empty-history? hist) (if (> ds cs) "d" "c")) ((string=? (most-recent-play hist) "c") (majority-loop (+ 1 cs) ds (rest-of-plays hist))) (else (majority-loop cs (+ 1 ds) (rest-of-plays hist))))) (majority-loop 0 0 other-history)) ;; Using this procedure , for any one particular game play , we ;; still make a "linear" walk down the length of the "other-history" list , but for each game play , we only make one linear walk down this list , not two . ;; ;; ;; Hence, for each game play, if the "history" is of size k, the ;; procedure executes in O(k) time. ;; ;; In other words, we expect the procedure to execute roughly twice as fast as the previous EGALITARIAN procedure . ;; ;; We are executing a total of n plays. That means the total ;; time to execute all n plays is: ;; T(n ) = 1 + 2 + .. + n T(n ) = n * ( n+1 ) / 2 ;; ;; In O-notation, this procedure will execute in O(n^2) time. ;; ;; In other words, in O-notation, this procedure will executes in ;; roughly the same order of magnitude time as the previous procedure : it scales as n^2 , where n is the number of game plays . ;; However, there is some (considerable) savings in this procedure, owing to the fact that each game play executes in roughly 1/2 the time that it took using the first procedure . ;; ;; ;; As a test, let's implement a "timed-play-loop" procedure that ;; (a) runs more play sets; and (b) prints out timing statistics, ;; so we can see whether program execution actually performs the ;; way we would predict. ;; (define (timed-play-loop strat0 strat1 times) ;; ;; Play-loop-iter procedure for executing the game play an arbitrary number of times ;; (define (timed-play-loop-iter count history0 history1 limit) (cond ((= count limit) (print-out-results history0 history1 limit)) (else (let ((result0 (strat0 history0 history1)) (result1 (strat1 history1 history0))) (timed-play-loop-iter (+ count 1) (extend-history result0 history0) (extend-history result1 history1) limit))))) ;; ;; Bracket execution loop for timing purposes ;; (let ((start (real-time-clock))) (timed-play-loop-iter 0 the-empty-history the-empty-history times) (let ((finish (real-time-clock))) (display "Timing: ") (display (- finish start))))) ;; Let 's build a matrix of the time it takes to execute 500 game plays ( roughly 5 times more plays than in a normal round , using " play - loop " ) , ;; and see which procedures are the slowest. ;; ;; The entries in the matrix correspond to the time (ticks) required for the 500 game plays to execute . The following matrix uses the " original " definition of the EGALITARIAN procedure : ;; ;; ;; ----------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;; --------------------------------------------------------------------------------- | NASTY | 15 | 13 | 40 | 415 | 15 | ;; --------------------------------------------------------------------------------- | PATSY | 13 | 10 | 11 | 407 | 10 | ;; --------------------------------------------------------------------------------- | SPASTIC | 40 | 11 | 14 | 439 | 13 | ;; --------------------------------------------------------------------------------- | EGALITARIAN | 415 | 407 | 439 | 801 | 408 | ;; --------------------------------------------------------------------------------- | EYE - FOR - EYE | 15 | 10 | 13 | 408 | 10 | ;; --------------------------------------------------------------------------------- ;; ;; Clear EGALITARIAN takes much longer to execute than do the other strategies , requiring roughly 400 ticks to execute the 500 plays . Notice also that when playing against itself , EGALITARIAN requires roughly 2 * 400 = 800 ticks to execute the 500 plays . ;; ;; We anticipate that the new definition of the EGALITARIAN procedure will run roughly ;; twice as quickly. Using the new definition, we obtain the following performance matrix: ;; ;; ;; ----------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;; --------------------------------------------------------------------------------- | NASTY | 15 | 13 | 14 | 250 | 17 | ;; --------------------------------------------------------------------------------- | PATSY | 13 | 9 | 12 | 243 | 10 | ;; --------------------------------------------------------------------------------- | SPASTIC | 14 | 12 | 13 | 253 | 14 | ;; --------------------------------------------------------------------------------- | EGALITARIAN | 250 | 243 | 253 | 476 | 241 | ;; --------------------------------------------------------------------------------- | EYE - FOR - EYE | 17 | 10 | 14 | 241 | 10 | ;; --------------------------------------------------------------------------------- ;; ;; ;; As anticipated, the performance is still slow (i.e., O(n^2)), although the new ;; procedure performs roughly twice as efficiently as the original procedure (as ;; we anticipated). ;; ;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Problem 4 ;; Write a new " eye - for - two - eyes " strategy . ;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++ ;; ;; For reference, the original EYE-FOR-EYE strategy is defined as: ;; (define (EYE-FOR-EYE my-history other-history) (if (empty-history? my-history) "c" (most-recent-play other-history))) ;; EYE - FOR - TWO - EYES will cooperate if either of the two most recent ;; plays of the opponent where cooperate. ;; (define (EYE-FOR-TWO-EYES my-history other-history) (if (empty-history? other-history) "c" (let ((result1 (most-recent-play other-history))) (if (empty-history? (rest-of-plays other-history)) "c" (let ((result2 (most-recent-play (rest-of-plays other-history)))) (if (or (string=? result1 "c") (string=? result2 "c")) "c" "d")))))) ;; ;; Let's run some unit tests, to make sure the procedure works the way we want. ;; For this game strategy, "our" history does not enter into the calculation. ;; We can pad our strategy with a random number "x": ;; (define temp-my-0 the-empty-history) (define temp-my-1 (list "x")) (define temp-my-2 (list "x" "x")) (define temp-my-3 (list "x" "x" "x")) (define temp-my-4 (list "x" "x" "x" "x")) ;; ;; Run the actual unit tests: ;; (EYE-FOR-TWO-EYES temp-my-0 the-empty-history) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-1 (list "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-1 (list "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-2 (list "c" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-2 (list "c" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-2 (list "d" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-2 (list "d" "d")) ;; ==> "d" (EYE-FOR-TWO-EYES temp-my-3 (list "c" "c" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-3 (list "c" "c" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-3 (list "c" "d" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-3 (list "c" "d" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-3 (list "d" "c" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-3 (list "d" "c" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-3 (list "d" "d" "c")) ;; ==> "d" (EYE-FOR-TWO-EYES temp-my-3 (list "d" "d" "d")) ;; ==> "d" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "c" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "c" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "d" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "d" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "c" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "c" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "d" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "d" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "c" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "c" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "d" "c")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "d" "d")) ;; ==> "c" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "c" "c")) ;; ==> "d" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "c" "d")) ;; ==> "d" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "d" "c")) ;; ==> "d" (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "d" "d")) ;; ==> "d" ;; ;; Looks like the strategy works as advertised. ;; ;; Let's run the strategy against the other strategies, and compile the results: ;; ;; ;; ------------------------------- Loses against NASTY ;; ------------------------------- NASTY : 1.09 points EYE - FOR - TWO - EYES : 0.98 points ;; ------------------------------- ;; ;; ;; ------------------------------- Ties against PATSY ;; ------------------------------- PATSY : 3.0 points EYE - FOR - TWO - EYES : 3.0 points ;; ------------------------------- ;; ;; ;; ------------------------------- Loses against SPASTIC ;; ------------------------------- SPASTIC : 3.0 points EYE - FOR - TWO - EYES : 1.78 points ;; ------------------------------- ;; ;; ;; ------------------------------- Ties against EGALITARIAN ;; ------------------------------- EGALITARIAN : 3.0 points EYE - FOR - TWO - EYES : 3.0 points ;; ------------------------------- ;; ;; ;; ------------------------------- ;; Ties against EYE-FOR-EYE ;; ------------------------------- EYE - FOR - EYE : 3.0 points EYE - FOR - TWO - EYES : 3.0 points ;; ------------------------------- ;; ;; ;; ------------------------------- ;; Ties against EYE-FOR-TWO-EYES ;; ------------------------------- EYE - FOR - TWO - EYES : 3.0 points EYE - FOR - TWO - EYES : 3.0 points ;; ------------------------------- ;; ;; ;; EYE-FOR-TWO-EYES is a very "neutral" strategy. Usually it ties, and it never wins. It loses slighlty against NASTY , and loses slightly worse against SPASTIC . In this ;; way it's very similar to its close-cousin EYE-FOR-EYE, which similarly loses (slightly) against NASTY , ties or loses ( slightly ) against SPASTIC , and ties all the other strategies . ;; ;; Next let 's run timing results for the EYE - FOR - TWO - EYES procedure . ;; For the EGALITARIAN procedure , we will use the second ( faster ) definition . ;; ;; ---------------------------------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | EYE - FOR - TWO - EYES | ;; ------------------------------------------------------------------------------------------------------------ EYE - FOR - TWO - EYES | 19 | 14 | 14 | 256 | 11 | 12 | ;; ------------------------------------------------------------------------------------------------------------ ;; ;; In terms of perforamnce , EYE - FOR - TWO - EYES executes about as fast as all the other structures , with relatively fast performance against most strategies , except for EGALITARIAN , where the performance is slightly slower . ;; ;; ++++++++++++++++++++++++++++++++++++++++++++++ Problem 5 ;; ;; Write a procedure "make-eye-for-n-eyes". ;; ++++++++++++++++++++++++++++++++++++++++++++++ ;; ;; This procedure should take a number as input and return the appropriate "eye-for-eye"-like strategy. For example , ( make - eye - for - n - eyes 2 ) should return a strategy equivalent to " eye - for - two - eyes " . Use ;; this procedure to create a new strategy and test it against the other strategies. Describe the ;; observed behavior. ;; (define (make-eye-for-n-eyes n) ;; We need to return a two - argument procedure . ;; (lambda (my-history other-history) ;; ;; Extract current play, returning "c" if there are no more plays. ;; (define (current-play history) (if (empty-history? history) "c" (most-recent-play history))) ;; ;; Define iterative procedure for making "n" eyes. ;; (define (make-eye-for-n-eyes-iter k history) (cond ((= k 1) (current-play history)) (else (if (or (string=? "c" (current-play history)) (string=? "c" (make-eye-for-n-eyes-iter (- k 1) (rest-of-plays history)))) "c" "d")))) ;; ;; Invoke the iterative procedure. ;; (make-eye-for-n-eyes-iter n other-history))) ;; Let 's define strategies for 1 , 2 and 3 eyes , and see if they perform the way we anticipate : ;; (define one-eye (make-eye-for-n-eyes 1)) (define two-eye (make-eye-for-n-eyes 2)) (define three-eye (make-eye-for-n-eyes 3)) ;; Run the tests for " one - eye " : ;; (one-eye temp-my-1 (list "c")) ;; ==> "c" (one-eye temp-my-1 (list "d")) ;; ==> "d" (one-eye temp-my-2 (list "c" "c")) ;; ==> "c" (one-eye temp-my-2 (list "c" "d")) ;; ==> "c" (one-eye temp-my-2 (list "d" "c")) ;; ==> "d" (one-eye temp-my-2 (list "d" "d")) ;; ==> "d" (one-eye temp-my-3 (list "c" "c" "c")) ;; ==> "c" (one-eye temp-my-3 (list "c" "c" "d")) ;; ==> "c" (one-eye temp-my-3 (list "c" "d" "c")) ;; ==> "c" (one-eye temp-my-3 (list "c" "d" "d")) ;; ==> "c" (one-eye temp-my-3 (list "d" "c" "c")) ;; ==> "d" (one-eye temp-my-3 (list "d" "c" "d")) ;; ==> "d" (one-eye temp-my-3 (list "d" "d" "c")) ;; ==> "d" (one-eye temp-my-3 (list "d" "d" "d")) ;; ==> "d" ;; " one - eye " performs as we would expect " eye - for - eye " to perform . ;; ;; Run the tests for " two - eye " : ;; (two-eye temp-my-1 (list "c")) ;; ==> "c" (two-eye temp-my-1 (list "d")) ;; ==> "c" (two-eye temp-my-2 (list "c" "c")) ;; ==> "c" (two-eye temp-my-2 (list "c" "d")) ;; ==> "c" (two-eye temp-my-2 (list "d" "c")) ;; ==> "c" (two-eye temp-my-2 (list "d" "d")) ;; ==> "d" (two-eye temp-my-3 (list "c" "c" "c")) ;; ==> "c" (two-eye temp-my-3 (list "c" "c" "d")) ;; ==> "c" (two-eye temp-my-3 (list "c" "d" "c")) ;; ==> "c" (two-eye temp-my-3 (list "c" "d" "d")) ;; ==> "c" (two-eye temp-my-3 (list "d" "c" "c")) ;; ==> "c" (two-eye temp-my-3 (list "d" "c" "d")) ;; ==> "c" (two-eye temp-my-3 (list "d" "d" "c")) ;; ==> "d" (two-eye temp-my-3 (list "d" "d" "c")) ;; ==> "d" ;; " two - eye " performs as we would expect " eye - for - two - eyes " to perform . ;; ;; Run the tests for " three - eye " : ;; (three-eye temp-my-1 (list "c")) ;; ==> "c" (three-eye temp-my-1 (list "d")) ;; ==> "c" (three-eye temp-my-2 (list "c" "c")) ;; ==> "c" (three-eye temp-my-2 (list "c" "d")) ;; ==> "c" (three-eye temp-my-2 (list "d" "c")) ;; ==> "c" (three-eye temp-my-2 (list "d" "d")) ;; ==> "c" (three-eye temp-my-3 (list "c" "c" "c")) ;; ==> "c" (three-eye temp-my-3 (list "c" "c" "d")) ;; ==> "c" (three-eye temp-my-3 (list "c" "d" "c")) ;; ==> "c" (three-eye temp-my-3 (list "c" "d" "d")) ;; ==> "c" (three-eye temp-my-3 (list "d" "c" "c")) ;; ==> "c" (three-eye temp-my-3 (list "d" "c" "d")) ;; ==> "c" (three-eye temp-my-3 (list "d" "d" "c")) ;; ==> "c" (three-eye temp-my-3 (list "d" "d" "d")) ;; ==> "d" (three-eye temp-my-4 (list "c" "c" "c" "c")) ;; ==> "c" (three-eye temp-my-4 (list "c" "c" "c" "d")) ;; ==> "c" (three-eye temp-my-4 (list "c" "c" "d" "c")) ;; ==> "c" (three-eye temp-my-4 (list "c" "c" "d" "d")) ;; ==> "c" (three-eye temp-my-4 (list "c" "d" "c" "c")) ;; ==> "c" (three-eye temp-my-4 (list "c" "d" "c" "d")) ;; ==> "c" (three-eye temp-my-4 (list "c" "d" "d" "c")) ;; ==> "c" (three-eye temp-my-4 (list "c" "d" "d" "d")) ;; ==> "c" (three-eye temp-my-4 (list "d" "c" "c" "c")) ;; ==> "c" (three-eye temp-my-4 (list "d" "c" "c" "d")) ;; ==> "c" (three-eye temp-my-4 (list "d" "c" "d" "c")) ;; ==> "c" (three-eye temp-my-4 (list "d" "c" "d" "d")) ;; ==> "c" (three-eye temp-my-4 (list "d" "d" "c" "c")) ;; ==> "c" (three-eye temp-my-4 (list "d" "d" "c" "d")) ;; ==> "c" (three-eye temp-my-4 (list "d" "d" "d" "c")) ;; ==> "d" (three-eye temp-my-4 (list "d" "d" "d" "d")) ;; ==> "d" ;; " three - eye " performs as we would expect " eye - for - three - eyes " to perform . ;; ;; ;; How should "eye-for-n-eyes" perform as n increases? ;; At n=1 , we would expect perform identical to EYE - FOR - EYE . ;; ;; As n increases, we would expect the performance of "eye-for-n-eyes" to asymptotically approach the performance of PATSY . Let 's define " eye - for - n - eyes " strategies up to , and then n=20 and n=100 , and see how these compare and contrast with EYE - FOR - EYE and PATSY : ;; (define four-eye (make-eye-for-n-eyes 4)) (define five-eye (make-eye-for-n-eyes 5)) (define twenty-eye (make-eye-for-n-eyes 20)) (define hundred-eye (make-eye-for-n-eyes 100)) ;; ;; ------------------------------------------------------------------------------ | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;; -------------------------------------------------------------------------------------------- ;; EYE-FOR-EYE | Loses | Ties | Loses | Ties | Ties | | 0.99 points | 3.0 points | 2.16 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- ONE | Loses | Ties | Loses | Ties | Ties | | 0.99 points | 3.0 points | 2.14 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- ;; TWO | Loses | Ties | Loses | Ties | Ties | | 0.98 points | 3.0 points | 1.94 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- ;; THREE | Loses | Ties | Loses | Ties | Ties | | 0.97 points | 3.0 points | 1.74 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- ;; FOUR | Loses | Ties | Loses | Ties | Ties | | 0.96 points | 3.0 points | 1.57 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- FIVE | Loses | Ties | Loses | Ties | Ties | | 0.95 points | 3.0 points | 1.40 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- TWENTY | Loses | Ties | Loses | Ties | Ties | | 0.80 points | 3.0 points | 1.34 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- ;; HUNDRED | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.38 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- PATSY | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.41 points | 3.0 points | 3.0 points | ;; -------------------------------------------------------------------------------------------- ;; Note again , that SPASTIC is a stochastic strategy and will not generate strictly a strictly ;; "linear" responsive the way that the other strategies might. ;; ;; These strategies all perform along a "linear" progression as expected. With small "n" we see ;; behavior (roughly) similar to EYE-FOR-EYE. With large "n" we see behavior (roughly) similar to PATSY . ;; ;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Problem 6 ;; ;; Write a "make-rotating-strategy" procedure. ;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ;; ;; I don't know how to do this without using mutators and local assignment. ;; The implementation that follows uses these techniques: ;; (define (make-rotating-strategy strat0 strat1 freq0 freq1) ;; ;; We need to monitor how many times the strategy is executed: ;; (define (make-monitored f) (let ((count 0)) ;; We need to return a two - argument procedure , where ;; the arguments are "my-history" and "other-history". ;; Depending on where we are in the "count", this will ;; determine which strategy is executed. ;; (define (mf m1 m2) (let ((total (remainder count (+ freq0 freq1)))) (set! count (+ count 1)) (cond ((< total freq0) (f strat0 m1 m2)) (else (f strat1 m1 m2))))) mf)) ;; ;; Return the monitored game strategy: ;; (make-monitored (lambda (strategy my-history other-history) (strategy my-history other-history)))) ;; The simplest strategies to use for unit testing will be " nasty " and " " , since these two strategies always generate the same response . ;; (define rotating-1 (make-rotating-strategy nasty patsy 1 1)) ;; ;; Let's define a test harness, for running the unit tests. Neither "nasty" nor " " really looks at the history , so we can feed in " fake " histories ;; to generate results: ;; (define (test-rotating rotating) (rotating (list "x" "x") (list "x" "x"))) (test-rotating rotating-1) ;; ==> "d" (test-rotating rotating-1) ;; ==> "c" (test-rotating rotating-1) ;; ==> "d" (test-rotating rotating-1) ;; ==> "c" (test-rotating rotating-1) ;; ==> "d" (test-rotating rotating-1) ;; ==> "c" ;; ;; Let's define a new other rotation strategies, based on nasty and pasty: ;; (define rotating-2 (make-rotating-strategy patsy nasty 1 1)) (test-rotating rotating-2) ;; ==> "c" (test-rotating rotating-2) ;; ==> "d" (test-rotating rotating-2) ;; ==> "c" (test-rotating rotating-2) ;; ==> "d" (define rotating-3 (make-rotating-strategy nasty patsy 2 2)) (test-rotating rotating-3) ;; ==> "d" (test-rotating rotating-3) ;; ==> "d" (test-rotating rotating-3) ;; ==> "c" (test-rotating rotating-3) ;; ==> "c" (test-rotating rotating-3) ;; ==> "d" (test-rotating rotating-3) ;; ==> "d" (test-rotating rotating-3) ;; ==> "c" (test-rotating rotating-3) ;; ==> "c" (define rotating-4 (make-rotating-strategy nasty patsy 3 5)) (test-rotating rotating-4) ;; ==> "d" (test-rotating rotating-4) ;; ==> "d" (test-rotating rotating-4) ;; ==> "d" (test-rotating rotating-4) ;; ==> "c" (test-rotating rotating-4) ;; ==> "c" (test-rotating rotating-4) ;; ==> "c" (test-rotating rotating-4) ;; ==> "c" (test-rotating rotating-4) ;; ==> "c" (test-rotating rotating-4) ;; ==> "d" (test-rotating rotating-4) ;; ==> "d" (test-rotating rotating-4) ;; ==> "d" ;; ;; So far, so good. The rotating strategy seems to work as advertised. ;; ;; In terms of testing combinations, we could invent a very wide range of ;; combinations. So as to limit the scope, let's define a strategy that is " half nasty " , " half " , and see how that compares to the regular " nasty " and regular " " : ;; (define half-and-half (make-rotating-strategy nasty patsy 2 2)) ;; ;; ------------------------------------------------------------------------------- ;; | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE-FOR-EYE | ;; ------------------------------------------------------------------------------------------------ ;; NASTY | Ties | Wins | Wins | Wins | Wins | | 1.0 points | 5.0 points | 3.0 points | 1.04 points | 1.04 points | ;; ------------------------------------------------------------------------------------------------ ;; HALF-AND-HALF | Loses | Wins | Loses | Wins | Wins | | 0.5 points | 4.0 points | 2.11 points | 3.25 points | 2.28 points | ;; ------------------------------------------------------------------------------------------------ ;; PATSY | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.52 points | 3.0 points | 3.0 points | ;; ------------------------------------------------------------------------------------------------ ;; ;; +++++++++++++++++++++++++++++++++++++++++++++++++++ Problem 7 ;; ;; Write a new strategy "make-higher-order-spastic". ;; +++++++++++++++++++++++++++++++++++++++++++++++++++ ;; ;; Again, we use mutators and local assigment to keep track of which strategy we are invoking: ;; (define (make-higher-order-spastic strategies) ;; ;; We need to monitor how many times the strategy is executed: ;; (define (make-monitored f) (let ((count 0)) ;; We need to return a two - argument procedure , where ;; the arguments are "my-history" and "other-history". ;; Depending on where we are in the "count", this will ;; determine which strategy is executed. ;; (define (mf m1 m2) (let ((total (remainder count (length strategies)))) (set! count (+ count 1)) (let ((item (list-ref strategies total))) (f item m1 m2)))) mf)) ;; ;; Return the monitored strategy: ;; (make-monitored (lambda (strategy my-history other-history) (strategy my-history other-history)))) ;; The easiest way to test this is to use NASTY and PATSY , since these generate deterministic results : ;; (define NASTY-PATSY (make-higher-order-spastic (list NASTY PATSY))) ;; The " test - rotating " harness will work here as it did before ( for these two strategies , NASTY and PATSY ): ;; (test-rotating nasty-patsy) ;; ==> "d" (test-rotating nasty-patsy) ;; ==> "c" (test-rotating nasty-patsy) ;; ==> "d" (test-rotating nasty-patsy) ;; ==> "c" ;; Looks good . Let 's build a strategy called CHAOS that " samples " from all the five canonical strategies we had initially defined . We can also build a strategy called SUPER - SPASTIC , which takes a list of all SPASTIC strategies . Note that this should perform the same ( w / in stochastic limits ) as the regular SPASTIC . ;; (define CHAOS (make-higher-order-spastic (list NASTY PATSY SPASTIC EGALITARIAN EYE-FOR-EYE))) (define SUPER-SPASTIC (make-higher-order-spastic (list SPASTIC SPASTIC SPASTIC SPASTIC SPASTIC))) ;; Comparing how these strategies play against the five " canonical " strategies , we have : ;; ;; ;; ------------------------------------------------------------------------------ | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;; ----------------------------------------------------------------------------------------------- ;; NASTY | Ties | Wins | Wins | Wins | Wins | | 1.0 points | 5.0 points | 2.8 points | 1.04 points | 1.04 points | ;; ----------------------------------------------------------------------------------------------- NASTY - PATSY | Loses | Wins | Win / Lose | Ties | Ties | | 0.5 points | 4.0 points | ~2.4 points | 2.5 points | 2.5 points | ;; ----------------------------------------------------------------------------------------------- ;; PATSY | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.42 points | 3.0 points | 3.0 points | ;; ----------------------------------------------------------------------------------------------- ;; SPASTIC | Loses | Wins | Win/Lose | Win/Lose | Wins | | 0.53 points | 4.0 points | ~2.2 points | ~1.9 points | 2.3 points | ;; ----------------------------------------------------------------------------------------------- ;; SUPER-SPASTIC | Loses | Wins | Win/Lose | Win/Lose | Wins | | 0.52 points | 4.1 points | ~2.3 points | ~1.9 points | 2.4 points | ;; ----------------------------------------------------------------------------------------------- ;; CHAOS | Loses | Wins | Win/Lose | Win/Lose | Ties | | 0.71 points | 3.6 points | ~2.3 points | 3.5 points | 2.4 points | ;; ----------------------------------------------------------------------------------------------- ;; ;; ++++++++++++++++++++++++++++++++++++++++++++ Problem 8 ;; ;; Write a procedure "gentle". ;; ++++++++++++++++++++++++++++++++++++++++++++ (define (gentle strat gentleness-factor) (lambda (my-history other-history) (let ((result (strat my-history other-history))) (cond ((string=? result "d") (let ((test (random 1.0))) (if (< test gentleness-factor) "c" result))) (else result))))) ;; The " test - rotating " procedure still works OK as a test harness , if we model " gentle " using the NASTY strategy . ;; (define q1 (gentle NASTY 0.0)) (define q2 (gentle NASTY 0.5)) (define q3 (gentle NASTY 1.0)) ;; We expect q1 to perform just like NASTY , and we expect to perform just like PATSY . We expect q2 to perform 50 % like NASTY , and 50 % like PATSY , although the distribution will be stochastic . ;; (test-rotating q1) ;; ==> "d" (test-rotating q1) ;; ==> "d" (test-rotating q1) ;; ==> "d" (test-rotating q1) ;; ==> "d" (test-rotating q1) ;; ==> "d" (test-rotating q2) ;; ==> "d" (test-rotating q2) ;; ==> "c" (test-rotating q2) ;; ==> "c" (test-rotating q2) ;; ==> "c" (test-rotating q2) ;; ==> "d" (test-rotating q3) ;; ==> "c" (test-rotating q3) ;; ==> "c" (test-rotating q3) ;; ==> "c" (test-rotating q3) ;; ==> "c" (test-rotating q3) ;; ==> "c" ;; ;; So far, so good. GENTLE seems to perform as we anticipate. ;; ;; Now define the SLIGHTLY-GENTLE-NASTY and SLIGHTLY-GENTLE-EYE-FOR-EYE as defined in problem statement: ;; (define SLIGHTLY-GENTLE-NASTY (gentle NASTY 0.1)) (define SLIGHTLY-GENTLE-EYE-FOR-EYE (gentle EYE-FOR-EYE 0.1)) ;; ;; We obtain the following performance statistics, when playing against the other strategies: ;; ;; ;; ------------------------------------------------------------------------------ | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | ;; ------------------------------------------------------------------------------------------------------ NASTY | Ties | Wins | Wins | Wins | Wins | | 1.0 points | 5.0 points | 2.8 points | 1.04 points | 1.04 points | ;; ------------------------------------------------------------------------------------------------------ ;; SLIGHT-NASTY | Loses | Wins | Wins | Loses | Wins | | 0.93 points | 4.8 points | 2.6 points | 1.0 points | 1.3 points | ;; ------------------------------------------------------------------------------------------------------ ;; EYE-FOR-EYE | Loses | Ties | Ties/Loses | Ties | Wins | | 0.99 points | 3.0 points | 2.3 points | 3.0 points | 3.0 points | ;; ------------------------------------------------------------------------------------------------------ SLIGHTLY - EYE - FOR - EYE | Loses | Ties | Loses | Ties | Ties | | 0.88 points | 3.0 points | 2.2 points | 3.0 points | 3.0 points | ;; ------------------------------------------------------------------------------------------------------ ;; ;; ;; Note that the "slightly" strategies are stochastic, and so will not always produce exactly the same ;; results on subsequent play rounds. ;;
null
https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Projects-S2005/Project2/mit-scheme/game.scm
scheme
++++++++++++++++++++++++++++++++++++++++++++++++++ Definition of "extract-entry" ++++++++++++++++++++++++++++++++++++++++++++++++++ The *game-association-list* is defined as follows: We can extract a specific entry in this list by using the "list-ref" procedure. For example: ==> (("c" "d") (0 5)) and so on. To extract the entry associated with a specific play, we need to extract the "car" of the entry, and make sure that both elements of this "car" correspond to both elements of the argument play. We define our "extract-entry" procedure as follows: Returns "true" if the play matches the entry: Get references to each entry in the *game-association-list*: If we find a match, return that specific entry: We can test our procedure as follows: ==> (("c" "d") (0 5)) ==> () Similarly, since "get-point-list" is defined as: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Always "defect" Always "cooperate" ------------------------------------------------------------------------- ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ slightly different point values which vary from round to round. ---------------------------------------------------------------------------- --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- against itself, the results are (essentially) a draw, where it wins or loses by a slight random margin. Similarly, the results against EYE-FOR-EYE are usually neutral (i.e., a tie) will lose (quite badly). values which vary from round to round. Specifically, when playing against itself, obtaining nearly the same number of points. This state of affairs is labeled a "stochastic tie". --------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------------- EYE-FOR-EYE | Slight Loss | Tie | Tie or Slight Loss | Tie | Tie | -------------------------------------------------------------------------------------------------- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ So for each game play, if the "other-history" is of size k, the procedure executes in O(2*k) time. We are executing a total of n plays. That means the total time to execute all n plays is: T(n) = n * (n+1) In O-notation, this procedure will execute in O(n^2) time. still make a "linear" walk down the length of the "other-history" Hence, for each game play, if the "history" is of size k, the procedure executes in O(k) time. In other words, we expect the procedure to execute roughly twice We are executing a total of n plays. That means the total time to execute all n plays is: In O-notation, this procedure will execute in O(n^2) time. In other words, in O-notation, this procedure will executes in roughly the same order of magnitude time as the previous However, there is some (considerable) savings in this procedure, As a test, let's implement a "timed-play-loop" procedure that (a) runs more play sets; and (b) prints out timing statistics, so we can see whether program execution actually performs the way we would predict. Play-loop-iter procedure for executing the game play an arbitrary number of times Bracket execution loop for timing purposes and see which procedures are the slowest. The entries in the matrix correspond to the time (ticks) required for the ----------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- twice as quickly. Using the new definition, we obtain the following performance matrix: ----------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- As anticipated, the performance is still slow (i.e., O(n^2)), although the new procedure performs roughly twice as efficiently as the original procedure (as we anticipated). +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++ For reference, the original EYE-FOR-EYE strategy is defined as: plays of the opponent where cooperate. Let's run some unit tests, to make sure the procedure works the way we want. For this game strategy, "our" history does not enter into the calculation. We can pad our strategy with a random number "x": Run the actual unit tests: ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "d" ==> "d" ==> "d" Looks like the strategy works as advertised. Let's run the strategy against the other strategies, and compile the results: ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- ------------------------------- Ties against EYE-FOR-EYE ------------------------------- ------------------------------- ------------------------------- Ties against EYE-FOR-TWO-EYES ------------------------------- ------------------------------- EYE-FOR-TWO-EYES is a very "neutral" strategy. Usually it ties, and it never wins. way it's very similar to its close-cousin EYE-FOR-EYE, which similarly loses (slightly) ---------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------ ++++++++++++++++++++++++++++++++++++++++++++++ Write a procedure "make-eye-for-n-eyes". ++++++++++++++++++++++++++++++++++++++++++++++ This procedure should take a number as input and return the appropriate "eye-for-eye"-like strategy. this procedure to create a new strategy and test it against the other strategies. Describe the observed behavior. Extract current play, returning "c" if there are no more plays. Define iterative procedure for making "n" eyes. Invoke the iterative procedure. ==> "c" ==> "d" ==> "c" ==> "c" ==> "d" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "d" ==> "d" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "d" How should "eye-for-n-eyes" perform as n increases? As n increases, we would expect the performance of "eye-for-n-eyes" to asymptotically ------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------- EYE-FOR-EYE | Loses | Ties | Loses | Ties | Ties | -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- TWO | Loses | Ties | Loses | Ties | Ties | -------------------------------------------------------------------------------------------- THREE | Loses | Ties | Loses | Ties | Ties | -------------------------------------------------------------------------------------------- FOUR | Loses | Ties | Loses | Ties | Ties | -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- HUNDRED | Loses | Ties | Loses | Ties | Ties | -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- "linear" responsive the way that the other strategies might. These strategies all perform along a "linear" progression as expected. With small "n" we see behavior (roughly) similar to EYE-FOR-EYE. With large "n" we see behavior (roughly) similar to +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Write a "make-rotating-strategy" procedure. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ I don't know how to do this without using mutators and local assignment. The implementation that follows uses these techniques: We need to monitor how many times the strategy is executed: the arguments are "my-history" and "other-history". Depending on where we are in the "count", this will determine which strategy is executed. Return the monitored game strategy: Let's define a test harness, for running the unit tests. Neither "nasty" to generate results: ==> "d" ==> "c" ==> "d" ==> "c" ==> "d" ==> "c" Let's define a new other rotation strategies, based on nasty and pasty: ==> "c" ==> "d" ==> "c" ==> "d" ==> "d" ==> "d" ==> "c" ==> "c" ==> "d" ==> "d" ==> "c" ==> "c" ==> "d" ==> "d" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" ==> "d" ==> "d" ==> "d" So far, so good. The rotating strategy seems to work as advertised. In terms of testing combinations, we could invent a very wide range of combinations. So as to limit the scope, let's define a strategy that ------------------------------------------------------------------------------- | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE-FOR-EYE | ------------------------------------------------------------------------------------------------ NASTY | Ties | Wins | Wins | Wins | Wins | ------------------------------------------------------------------------------------------------ HALF-AND-HALF | Loses | Wins | Loses | Wins | Wins | ------------------------------------------------------------------------------------------------ PATSY | Loses | Ties | Loses | Ties | Ties | ------------------------------------------------------------------------------------------------ +++++++++++++++++++++++++++++++++++++++++++++++++++ Write a new strategy "make-higher-order-spastic". +++++++++++++++++++++++++++++++++++++++++++++++++++ Again, we use mutators and local assigment to keep track of which strategy we are invoking: We need to monitor how many times the strategy is executed: the arguments are "my-history" and "other-history". Depending on where we are in the "count", this will determine which strategy is executed. Return the monitored strategy: ==> "d" ==> "c" ==> "d" ==> "c" ------------------------------------------------------------------------------ ----------------------------------------------------------------------------------------------- NASTY | Ties | Wins | Wins | Wins | Wins | ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- PATSY | Loses | Ties | Loses | Ties | Ties | ----------------------------------------------------------------------------------------------- SPASTIC | Loses | Wins | Win/Lose | Win/Lose | Wins | ----------------------------------------------------------------------------------------------- SUPER-SPASTIC | Loses | Wins | Win/Lose | Win/Lose | Wins | ----------------------------------------------------------------------------------------------- CHAOS | Loses | Wins | Win/Lose | Win/Lose | Ties | ----------------------------------------------------------------------------------------------- ++++++++++++++++++++++++++++++++++++++++++++ Write a procedure "gentle". ++++++++++++++++++++++++++++++++++++++++++++ ==> "d" ==> "d" ==> "d" ==> "d" ==> "d" ==> "d" ==> "c" ==> "c" ==> "c" ==> "d" ==> "c" ==> "c" ==> "c" ==> "c" ==> "c" So far, so good. GENTLE seems to perform as we anticipate. Now define the SLIGHTLY-GENTLE-NASTY and SLIGHTLY-GENTLE-EYE-FOR-EYE as defined in problem statement: We obtain the following performance statistics, when playing against the other strategies: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ SLIGHT-NASTY | Loses | Wins | Wins | Loses | Wins | ------------------------------------------------------------------------------------------------------ EYE-FOR-EYE | Loses | Ties | Ties/Loses | Ties | Wins | ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ Note that the "slightly" strategies are stochastic, and so will not always produce exactly the same results on subsequent play rounds.
(load "prisoner.scm") Problem 1 (define *game-association-list* (list (list (list "c" "c") (list 3 3)) (list (list "c" "d") (list 0 5)) (list (list "d" "c") (list 5 0)) (list (list "d" "d") (list 1 1)))) (list-ref *game-association-list* 0) = = > ( ( " c " " c " ) ( 3 3 ) ) (list-ref *game-association-list* 1) (define (extract-entry play *game-association-list*) (define (compare play entry) (let ((test (car entry))) (and (string=? (car play) (car test)) (string=? (cadr play) (cadr test))))) (let ((first (list-ref *game-association-list* 0)) (second (list-ref *game-association-list* 1)) (third (list-ref *game-association-list* 2)) (fourth (list-ref *game-association-list* 3))) (cond ((compare play first) first) ((compare play second) second) ((compare play third) third) ((compare play fourth) fourth) (else '())))) (extract-entry (make-play "c" "c") *game-association-list*) = = > ( ( " c " " c " ) ( 3 3 ) ) (extract-entry (make-play "c" "d") *game-association-list*) (extract-entry (make-play "d" "c") *game-association-list*) = = > ( ( " d " " c " ) ( 5 0 ) ) (extract-entry (make-play "d" "d") *game-association-list*) = = > ( ( " d " " d " ) ( 1 1 ) ) (extract-entry (make-play "x" "x") *game-association-list*) (define (get-point-list game) (cadr (extract-entry game *game-association-list*))) (get-point-list (make-play "c" "c")) = = > ( 3 3 ) (get-point-list (make-play "c" "d")) = = > ( 0 5 ) (get-point-list (make-play "d" "c")) = = > ( 5 0 ) (get-point-list (make-play "d" "d")) = = > ( 1 1 ) Problem 2 Use " play - loop " to play games between the five strategies . For reference , the five strategies are defined as : (define (NASTY my-history other-history) "d") (define (PATSY my-history other-history) "c") " Defect " or " cooperate " with 50 - 50 chance (define (SPASTIC my-history other-history) (if (= (random 2) 0) "c" "d")) (define (EGALITARIAN my-history other-history) (define (count-instances-of test hist) (cond ((empty-history? hist) 0) ((string=? (most-recent-play hist) test) (+ (count-instances-of test (rest-of-plays hist)) 1)) (else (count-instances-of test (rest-of-plays hist))))) (let ((ds (count-instances-of "d" other-history)) (cs (count-instances-of "c" other-history))) (if (> ds cs) "d" "c"))) " Cooperate " on first round , otherwise return " eye for eye " (define (EYE-FOR-EYE my-history other-history) (if (empty-history? my-history) "c" (most-recent-play other-history))) NASTY is a highly " dominant " strategy . It never " loses " outright , at worst tying only when it plays against itself . Otherwise , NASTY is able to beat all the other strategies . When NASTY plays against the following opponents , we obtain the following results : | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | NASTY | Ties | Wins | Wins | Wins | Wins | | 1.0 points | 5.0 points | 2.88 points | 1.04 points | 1.04 points | Note that in all these plays , SPASTIC is a stochastic strategy and will generate PATSY never wins , and it loses badly against NASTY and SPASTIC . However , it ties with itself , EGALITARIAN and EYE - FOR - EYE . When PATSY plays against the following opponents , we obtain the following results : | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | PATSY | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.29 points | 3.0 points | 3.0 points | Despite being ostensibly " random " , the SPASTIC strategy fares quite well . When playing with an occasional very slighty win on the side of SPASTIC . SPASTIC wins decisively against PATSY , and loses against NASTY . The most interesting behavior is when SPASTIC plays EGALITARIAN . Usually ( roughly 70 % of the time ) , SPASTIC will win decisively , but occassionally ( roughly 30 % of the time ) it Note that SPASTIC is a stochastic strategy and will generate slightly different point SPASTIC will either win or lose , but only by a very narrow margin , both opponents When SPASTIC plays against the following opponents , we obtain the following results : | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | SPASTIC | Loses | Wins | " Stochastic Tie " | 70 % Wins | Tie or Slight Win | | 0.527 points | 4.1 points | 2.32 points | 2.77 points | 2.29 points | | | | | 30 % Loss | | | | | | 1.22 points | | EGALITARIAN almost always " ties " , or , even when " winning " or " losing " , does so only by a very narrow margin . The most interesting behavior comes with SPASTIC , where 50 % of the time , EGALITARIAN wins with a score of 2.47 , whereas 50 % of the time , EGALITARIAN loses with a score of 1.87 . When EGALITARIAN plays against the following opponents , we obtain the following results : | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | EGALITARIAN | Slight Loss | 50 % Wins | Tie | Tie | | 0.99 points | 3.0 points | 2.47 points | 3.0 points | 3.0 points | | | | 50 % Loses | | | | | | 1.87 points | | | Like EGALITARIAN , EYE - FOR - EYE also almost always " ties " , or , even when " winning " or " losing " , does so only by a very narrow margin . EYE - FOR - EYE will tie PATSY , EGALITARIAN and EYE - FOR - EYE ( itself ) . It will tie or slightly lose to SPASTIC , and will slightly lose to NASTY . | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | | 0.99 points | 3.0 points | 2.23 points | 3.0 points | 3.0 points | Problem 3 Explore more efficient ways to code EGALITARIAN . For reference , the original definition of EGALITARIAN was given as : (define (EGALITARIAN my-history other-history) (define (count-instances-of test hist) (cond ((empty-history? hist) 0) ((string=? (most-recent-play hist) test) (+ (count-instances-of test (rest-of-plays hist)) 1)) (else (count-instances-of test (rest-of-plays hist))))) (let ((ds (count-instances-of "d" other-history)) (cs (count-instances-of "c" other-history))) (if (> ds cs) "d" "c"))) For any one particular game play , the code here makes : In other words , when the history is of length 1 , the play executes in time 2 * 1 . When the history is of length 2 , the play executes in time 2 * 2 . When the history is of length k , the play executes in time 2*k . T(n ) = 2 * ( 1 + 2 + ... + n ) T(n ) = 2 * n * ( n + 1 ) / 2 's new definition of EGALITARIAN is given as : (define (EGALITARIAN my-history other-history) (define (majority-loop cs ds hist) (cond ((empty-history? hist) (if (> ds cs) "d" "c")) ((string=? (most-recent-play hist) "c") (majority-loop (+ 1 cs) ds (rest-of-plays hist))) (else (majority-loop cs (+ 1 ds) (rest-of-plays hist))))) (majority-loop 0 0 other-history)) Using this procedure , for any one particular game play , we list , but for each game play , we only make one linear walk down this list , not two . as fast as the previous EGALITARIAN procedure . T(n ) = 1 + 2 + .. + n T(n ) = n * ( n+1 ) / 2 procedure : it scales as n^2 , where n is the number of game plays . owing to the fact that each game play executes in roughly 1/2 the time that it took using the first procedure . (define (timed-play-loop strat0 strat1 times) (define (timed-play-loop-iter count history0 history1 limit) (cond ((= count limit) (print-out-results history0 history1 limit)) (else (let ((result0 (strat0 history0 history1)) (result1 (strat1 history1 history0))) (timed-play-loop-iter (+ count 1) (extend-history result0 history0) (extend-history result1 history1) limit))))) (let ((start (real-time-clock))) (timed-play-loop-iter 0 the-empty-history the-empty-history times) (let ((finish (real-time-clock))) (display "Timing: ") (display (- finish start))))) Let 's build a matrix of the time it takes to execute 500 game plays ( roughly 5 times more plays than in a normal round , using " play - loop " ) , 500 game plays to execute . The following matrix uses the " original " definition of the EGALITARIAN procedure : | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | | NASTY | 15 | 13 | 40 | 415 | 15 | | PATSY | 13 | 10 | 11 | 407 | 10 | | SPASTIC | 40 | 11 | 14 | 439 | 13 | | EGALITARIAN | 415 | 407 | 439 | 801 | 408 | | EYE - FOR - EYE | 15 | 10 | 13 | 408 | 10 | Clear EGALITARIAN takes much longer to execute than do the other strategies , requiring roughly 400 ticks to execute the 500 plays . Notice also that when playing against itself , EGALITARIAN requires roughly 2 * 400 = 800 ticks to execute the 500 plays . We anticipate that the new definition of the EGALITARIAN procedure will run roughly | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | | NASTY | 15 | 13 | 14 | 250 | 17 | | PATSY | 13 | 9 | 12 | 243 | 10 | | SPASTIC | 14 | 12 | 13 | 253 | 14 | | EGALITARIAN | 250 | 243 | 253 | 476 | 241 | | EYE - FOR - EYE | 17 | 10 | 14 | 241 | 10 | Problem 4 Write a new " eye - for - two - eyes " strategy . (define (EYE-FOR-EYE my-history other-history) (if (empty-history? my-history) "c" (most-recent-play other-history))) EYE - FOR - TWO - EYES will cooperate if either of the two most recent (define (EYE-FOR-TWO-EYES my-history other-history) (if (empty-history? other-history) "c" (let ((result1 (most-recent-play other-history))) (if (empty-history? (rest-of-plays other-history)) "c" (let ((result2 (most-recent-play (rest-of-plays other-history)))) (if (or (string=? result1 "c") (string=? result2 "c")) "c" "d")))))) (define temp-my-0 the-empty-history) (define temp-my-1 (list "x")) (define temp-my-2 (list "x" "x")) (define temp-my-3 (list "x" "x" "x")) (define temp-my-4 (list "x" "x" "x" "x")) (EYE-FOR-TWO-EYES temp-my-0 the-empty-history) (EYE-FOR-TWO-EYES temp-my-1 (list "c")) (EYE-FOR-TWO-EYES temp-my-1 (list "d")) (EYE-FOR-TWO-EYES temp-my-2 (list "c" "c")) (EYE-FOR-TWO-EYES temp-my-2 (list "c" "d")) (EYE-FOR-TWO-EYES temp-my-2 (list "d" "c")) (EYE-FOR-TWO-EYES temp-my-2 (list "d" "d")) (EYE-FOR-TWO-EYES temp-my-3 (list "c" "c" "c")) (EYE-FOR-TWO-EYES temp-my-3 (list "c" "c" "d")) (EYE-FOR-TWO-EYES temp-my-3 (list "c" "d" "c")) (EYE-FOR-TWO-EYES temp-my-3 (list "c" "d" "d")) (EYE-FOR-TWO-EYES temp-my-3 (list "d" "c" "c")) (EYE-FOR-TWO-EYES temp-my-3 (list "d" "c" "d")) (EYE-FOR-TWO-EYES temp-my-3 (list "d" "d" "c")) (EYE-FOR-TWO-EYES temp-my-3 (list "d" "d" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "c" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "c" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "d" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "c" "d" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "c" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "c" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "d" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "c" "d" "d" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "c" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "c" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "d" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "c" "d" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "c" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "c" "d")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "d" "c")) (EYE-FOR-TWO-EYES temp-my-4 (list "d" "d" "d" "d")) Loses against NASTY NASTY : 1.09 points EYE - FOR - TWO - EYES : 0.98 points Ties against PATSY PATSY : 3.0 points EYE - FOR - TWO - EYES : 3.0 points Loses against SPASTIC SPASTIC : 3.0 points EYE - FOR - TWO - EYES : 1.78 points Ties against EGALITARIAN EGALITARIAN : 3.0 points EYE - FOR - TWO - EYES : 3.0 points EYE - FOR - EYE : 3.0 points EYE - FOR - TWO - EYES : 3.0 points EYE - FOR - TWO - EYES : 3.0 points EYE - FOR - TWO - EYES : 3.0 points It loses slighlty against NASTY , and loses slightly worse against SPASTIC . In this against NASTY , ties or loses ( slightly ) against SPASTIC , and ties all the other strategies . Next let 's run timing results for the EYE - FOR - TWO - EYES procedure . For the EGALITARIAN procedure , we will use the second ( faster ) definition . | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | EYE - FOR - TWO - EYES | EYE - FOR - TWO - EYES | 19 | 14 | 14 | 256 | 11 | 12 | In terms of perforamnce , EYE - FOR - TWO - EYES executes about as fast as all the other structures , with relatively fast performance against most strategies , except for EGALITARIAN , where the performance is slightly slower . Problem 5 For example , ( make - eye - for - n - eyes 2 ) should return a strategy equivalent to " eye - for - two - eyes " . Use (define (make-eye-for-n-eyes n) We need to return a two - argument procedure . (lambda (my-history other-history) (define (current-play history) (if (empty-history? history) "c" (most-recent-play history))) (define (make-eye-for-n-eyes-iter k history) (cond ((= k 1) (current-play history)) (else (if (or (string=? "c" (current-play history)) (string=? "c" (make-eye-for-n-eyes-iter (- k 1) (rest-of-plays history)))) "c" "d")))) (make-eye-for-n-eyes-iter n other-history))) Let 's define strategies for 1 , 2 and 3 eyes , and see if they perform the way we anticipate : (define one-eye (make-eye-for-n-eyes 1)) (define two-eye (make-eye-for-n-eyes 2)) (define three-eye (make-eye-for-n-eyes 3)) Run the tests for " one - eye " : (one-eye temp-my-1 (list "c")) (one-eye temp-my-1 (list "d")) (one-eye temp-my-2 (list "c" "c")) (one-eye temp-my-2 (list "c" "d")) (one-eye temp-my-2 (list "d" "c")) (one-eye temp-my-2 (list "d" "d")) (one-eye temp-my-3 (list "c" "c" "c")) (one-eye temp-my-3 (list "c" "c" "d")) (one-eye temp-my-3 (list "c" "d" "c")) (one-eye temp-my-3 (list "c" "d" "d")) (one-eye temp-my-3 (list "d" "c" "c")) (one-eye temp-my-3 (list "d" "c" "d")) (one-eye temp-my-3 (list "d" "d" "c")) (one-eye temp-my-3 (list "d" "d" "d")) " one - eye " performs as we would expect " eye - for - eye " to perform . Run the tests for " two - eye " : (two-eye temp-my-1 (list "c")) (two-eye temp-my-1 (list "d")) (two-eye temp-my-2 (list "c" "c")) (two-eye temp-my-2 (list "c" "d")) (two-eye temp-my-2 (list "d" "c")) (two-eye temp-my-2 (list "d" "d")) (two-eye temp-my-3 (list "c" "c" "c")) (two-eye temp-my-3 (list "c" "c" "d")) (two-eye temp-my-3 (list "c" "d" "c")) (two-eye temp-my-3 (list "c" "d" "d")) (two-eye temp-my-3 (list "d" "c" "c")) (two-eye temp-my-3 (list "d" "c" "d")) (two-eye temp-my-3 (list "d" "d" "c")) (two-eye temp-my-3 (list "d" "d" "c")) " two - eye " performs as we would expect " eye - for - two - eyes " to perform . Run the tests for " three - eye " : (three-eye temp-my-1 (list "c")) (three-eye temp-my-1 (list "d")) (three-eye temp-my-2 (list "c" "c")) (three-eye temp-my-2 (list "c" "d")) (three-eye temp-my-2 (list "d" "c")) (three-eye temp-my-2 (list "d" "d")) (three-eye temp-my-3 (list "c" "c" "c")) (three-eye temp-my-3 (list "c" "c" "d")) (three-eye temp-my-3 (list "c" "d" "c")) (three-eye temp-my-3 (list "c" "d" "d")) (three-eye temp-my-3 (list "d" "c" "c")) (three-eye temp-my-3 (list "d" "c" "d")) (three-eye temp-my-3 (list "d" "d" "c")) (three-eye temp-my-3 (list "d" "d" "d")) (three-eye temp-my-4 (list "c" "c" "c" "c")) (three-eye temp-my-4 (list "c" "c" "c" "d")) (three-eye temp-my-4 (list "c" "c" "d" "c")) (three-eye temp-my-4 (list "c" "c" "d" "d")) (three-eye temp-my-4 (list "c" "d" "c" "c")) (three-eye temp-my-4 (list "c" "d" "c" "d")) (three-eye temp-my-4 (list "c" "d" "d" "c")) (three-eye temp-my-4 (list "c" "d" "d" "d")) (three-eye temp-my-4 (list "d" "c" "c" "c")) (three-eye temp-my-4 (list "d" "c" "c" "d")) (three-eye temp-my-4 (list "d" "c" "d" "c")) (three-eye temp-my-4 (list "d" "c" "d" "d")) (three-eye temp-my-4 (list "d" "d" "c" "c")) (three-eye temp-my-4 (list "d" "d" "c" "d")) (three-eye temp-my-4 (list "d" "d" "d" "c")) (three-eye temp-my-4 (list "d" "d" "d" "d")) " three - eye " performs as we would expect " eye - for - three - eyes " to perform . At n=1 , we would expect perform identical to EYE - FOR - EYE . approach the performance of PATSY . Let 's define " eye - for - n - eyes " strategies up to , and then n=20 and n=100 , and see how these compare and contrast with EYE - FOR - EYE and PATSY : (define four-eye (make-eye-for-n-eyes 4)) (define five-eye (make-eye-for-n-eyes 5)) (define twenty-eye (make-eye-for-n-eyes 20)) (define hundred-eye (make-eye-for-n-eyes 100)) | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | | 0.99 points | 3.0 points | 2.16 points | 3.0 points | 3.0 points | ONE | Loses | Ties | Loses | Ties | Ties | | 0.99 points | 3.0 points | 2.14 points | 3.0 points | 3.0 points | | 0.98 points | 3.0 points | 1.94 points | 3.0 points | 3.0 points | | 0.97 points | 3.0 points | 1.74 points | 3.0 points | 3.0 points | | 0.96 points | 3.0 points | 1.57 points | 3.0 points | 3.0 points | FIVE | Loses | Ties | Loses | Ties | Ties | | 0.95 points | 3.0 points | 1.40 points | 3.0 points | 3.0 points | TWENTY | Loses | Ties | Loses | Ties | Ties | | 0.80 points | 3.0 points | 1.34 points | 3.0 points | 3.0 points | | 0.0 points | 3.0 points | 1.38 points | 3.0 points | 3.0 points | PATSY | Loses | Ties | Loses | Ties | Ties | | 0.0 points | 3.0 points | 1.41 points | 3.0 points | 3.0 points | Note again , that SPASTIC is a stochastic strategy and will not generate strictly a strictly PATSY . Problem 6 (define (make-rotating-strategy strat0 strat1 freq0 freq1) (define (make-monitored f) (let ((count 0)) We need to return a two - argument procedure , where (define (mf m1 m2) (let ((total (remainder count (+ freq0 freq1)))) (set! count (+ count 1)) (cond ((< total freq0) (f strat0 m1 m2)) (else (f strat1 m1 m2))))) mf)) (make-monitored (lambda (strategy my-history other-history) (strategy my-history other-history)))) The simplest strategies to use for unit testing will be " nasty " and " " , since these two strategies always generate the same response . (define rotating-1 (make-rotating-strategy nasty patsy 1 1)) nor " " really looks at the history , so we can feed in " fake " histories (define (test-rotating rotating) (rotating (list "x" "x") (list "x" "x"))) (test-rotating rotating-1) (test-rotating rotating-1) (test-rotating rotating-1) (test-rotating rotating-1) (test-rotating rotating-1) (test-rotating rotating-1) (define rotating-2 (make-rotating-strategy patsy nasty 1 1)) (test-rotating rotating-2) (test-rotating rotating-2) (test-rotating rotating-2) (test-rotating rotating-2) (define rotating-3 (make-rotating-strategy nasty patsy 2 2)) (test-rotating rotating-3) (test-rotating rotating-3) (test-rotating rotating-3) (test-rotating rotating-3) (test-rotating rotating-3) (test-rotating rotating-3) (test-rotating rotating-3) (test-rotating rotating-3) (define rotating-4 (make-rotating-strategy nasty patsy 3 5)) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) (test-rotating rotating-4) is " half nasty " , " half " , and see how that compares to the regular " nasty " and regular " " : (define half-and-half (make-rotating-strategy nasty patsy 2 2)) | 1.0 points | 5.0 points | 3.0 points | 1.04 points | 1.04 points | | 0.5 points | 4.0 points | 2.11 points | 3.25 points | 2.28 points | | 0.0 points | 3.0 points | 1.52 points | 3.0 points | 3.0 points | Problem 7 (define (make-higher-order-spastic strategies) (define (make-monitored f) (let ((count 0)) We need to return a two - argument procedure , where (define (mf m1 m2) (let ((total (remainder count (length strategies)))) (set! count (+ count 1)) (let ((item (list-ref strategies total))) (f item m1 m2)))) mf)) (make-monitored (lambda (strategy my-history other-history) (strategy my-history other-history)))) The easiest way to test this is to use NASTY and PATSY , since these generate deterministic results : (define NASTY-PATSY (make-higher-order-spastic (list NASTY PATSY))) The " test - rotating " harness will work here as it did before ( for these two strategies , NASTY and PATSY ): (test-rotating nasty-patsy) (test-rotating nasty-patsy) (test-rotating nasty-patsy) (test-rotating nasty-patsy) Looks good . Let 's build a strategy called CHAOS that " samples " from all the five canonical strategies we had initially defined . We can also build a strategy called SUPER - SPASTIC , which takes a list of all SPASTIC strategies . Note that this should perform the same ( w / in stochastic limits ) as the regular SPASTIC . (define CHAOS (make-higher-order-spastic (list NASTY PATSY SPASTIC EGALITARIAN EYE-FOR-EYE))) (define SUPER-SPASTIC (make-higher-order-spastic (list SPASTIC SPASTIC SPASTIC SPASTIC SPASTIC))) Comparing how these strategies play against the five " canonical " strategies , we have : | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | | 1.0 points | 5.0 points | 2.8 points | 1.04 points | 1.04 points | NASTY - PATSY | Loses | Wins | Win / Lose | Ties | Ties | | 0.5 points | 4.0 points | ~2.4 points | 2.5 points | 2.5 points | | 0.0 points | 3.0 points | 1.42 points | 3.0 points | 3.0 points | | 0.53 points | 4.0 points | ~2.2 points | ~1.9 points | 2.3 points | | 0.52 points | 4.1 points | ~2.3 points | ~1.9 points | 2.4 points | | 0.71 points | 3.6 points | ~2.3 points | 3.5 points | 2.4 points | Problem 8 (define (gentle strat gentleness-factor) (lambda (my-history other-history) (let ((result (strat my-history other-history))) (cond ((string=? result "d") (let ((test (random 1.0))) (if (< test gentleness-factor) "c" result))) (else result))))) The " test - rotating " procedure still works OK as a test harness , if we model " gentle " using the NASTY strategy . (define q1 (gentle NASTY 0.0)) (define q2 (gentle NASTY 0.5)) (define q3 (gentle NASTY 1.0)) We expect q1 to perform just like NASTY , and we expect to perform just like PATSY . We expect q2 to perform 50 % like NASTY , and 50 % like PATSY , although the distribution will be stochastic . (test-rotating q1) (test-rotating q1) (test-rotating q1) (test-rotating q1) (test-rotating q1) (test-rotating q2) (test-rotating q2) (test-rotating q2) (test-rotating q2) (test-rotating q2) (test-rotating q3) (test-rotating q3) (test-rotating q3) (test-rotating q3) (test-rotating q3) (define SLIGHTLY-GENTLE-NASTY (gentle NASTY 0.1)) (define SLIGHTLY-GENTLE-EYE-FOR-EYE (gentle EYE-FOR-EYE 0.1)) | NASTY | PATSY | SPASTIC | EGALITARIAN | EYE - FOR - EYE | NASTY | Ties | Wins | Wins | Wins | Wins | | 1.0 points | 5.0 points | 2.8 points | 1.04 points | 1.04 points | | 0.93 points | 4.8 points | 2.6 points | 1.0 points | 1.3 points | | 0.99 points | 3.0 points | 2.3 points | 3.0 points | 3.0 points | SLIGHTLY - EYE - FOR - EYE | Loses | Ties | Loses | Ties | Ties | | 0.88 points | 3.0 points | 2.2 points | 3.0 points | 3.0 points |
a89680d61d145f640bca52ad40e1bd63f8424bcf3cc9fa024f9d14a932cfe429
Feuerlabs/yang
yang_codegen.erl
-module(yang_codegen). -export([module/3]). -include_lib("parse_trans/include/codegen.hrl"). module(YangF, ErlMod, Opts) -> case file:read_file(YangF) of {ok, Bin} -> YangOpts = proplists:get_value(yang, Opts, []), try yang_parser:deep_parse(YangF, YangOpts) of {ok, YangForms} -> module_(YangForms, Bin, ErlMod, lists:keydelete(yang, 1, Opts)); Error -> io:fwrite("Error parsing ~s: ~p~n", [YangF, Error]), Error catch Type:Catch -> io:fwrite("Caught ~p:~p~n", [Type,Catch]), {error, caught} end; Error1 -> io:fwrite("Error reading file ~s: ~p~n", [YangF, Error1]), Error1 end. module_([{module,_,M,Y}] = Yang, Src, ErlMod, Opts) -> Forms = [{attribute,1,module,ErlMod}, {attribute,2,export,[{module,0}, {prefix,0}, {revisions,0}, {contact,0}, {typedef,1}, {groupings, 0}, {grouping,1}, {rpcs, 0}, {rpc, 1}, {notifications, 0}, {notification, 1}, {yang, 0}, {src, 0}]}, module(M), prefix(Y), revisions(Y), contact(Y), typedefs(Y), groupings(Y), grouping_1(Y), rpcs(Y), rpc_1(Y), notifications(Y), notification_1(Y), yang(Yang), src(Src), {eof,1}], case compile:forms(Forms, Opts) of {ok, ModName, Bin} -> io:fwrite("loading binary (~p)~n", [ModName]), code:load_binary( ModName, "/tmp/" ++ atom_to_list(ModName) ++ ".beam", Bin); Other -> Other end. write_to_file(Forms, F) -> case file:open(F, [write]) of {ok, Fd} -> try io:fwrite(Fd, "~p~n", [Forms]) after file:close(Fd) end; Error -> Error end. module(M) -> codegen:gen_function( module, fun() -> {'$var', M} end). prefix(Y) -> Prefix = lists:keyfind(prefix, 1, Y), codegen:gen_function( prefix, fun() -> {'$var', Prefix} end). revisions(Y) -> Revs = [R || {revision,_,_,_} = R <- Y], codegen:gen_function( revisions, fun() -> {'$var', Revs} end). contact(Y) -> Contact = lists:keyfind(contact, 1, Y), codegen:gen_function( contact, fun() -> {'$var', Contact} end). typedefs(_Y) -> codegen:gen_function( typedef, fun(_) -> [] end). groupings(Y) -> Names = [Name || {grouping, _, Name, _} <- Y], codegen:gen_function( groupings, fun() -> {'$var', Names} end). grouping_1(Y) -> codegen:gen_function_alt( grouping, [fun({'$var', Name}) -> {'$var', Grp} end || {grouping,_,Name,_} = Grp <- Y], fun(_) -> error end). rpcs(Y) -> Names = [Name || {rpc,_,Name,_} <- Y], codegen:gen_function( rpcs, fun() -> {'$var', Names} end). rpc_1(Y) -> codegen:gen_function_alt( rpc, [fun({'$var', Name}) -> {'$var', RPC} end || {rpc,_,Name,_} = RPC <- Y], fun(_) -> error end). notifications(Y) -> Names = [Name || {notification,_,Name,_} <- Y], codegen:gen_function( notifications, fun() -> {'$var', Names} end). notification_1(Y) -> codegen:gen_function_alt( notification, [fun({'$var', Name}) -> {'$var', N} end || {notification,_,Name,_} = N <- Y], fun(_) -> error end). yang(_Y) -> codegen:gen_function( yang, fun() -> %% {'$var', Y} [] end). src(_Bin) -> codegen:gen_function( src, fun() -> { ' $ var ' , } [] end).
null
https://raw.githubusercontent.com/Feuerlabs/yang/92330c742cdd2a8e7ce07f99b34c0fe761806e82/src/yang_codegen.erl
erlang
{'$var', Y}
-module(yang_codegen). -export([module/3]). -include_lib("parse_trans/include/codegen.hrl"). module(YangF, ErlMod, Opts) -> case file:read_file(YangF) of {ok, Bin} -> YangOpts = proplists:get_value(yang, Opts, []), try yang_parser:deep_parse(YangF, YangOpts) of {ok, YangForms} -> module_(YangForms, Bin, ErlMod, lists:keydelete(yang, 1, Opts)); Error -> io:fwrite("Error parsing ~s: ~p~n", [YangF, Error]), Error catch Type:Catch -> io:fwrite("Caught ~p:~p~n", [Type,Catch]), {error, caught} end; Error1 -> io:fwrite("Error reading file ~s: ~p~n", [YangF, Error1]), Error1 end. module_([{module,_,M,Y}] = Yang, Src, ErlMod, Opts) -> Forms = [{attribute,1,module,ErlMod}, {attribute,2,export,[{module,0}, {prefix,0}, {revisions,0}, {contact,0}, {typedef,1}, {groupings, 0}, {grouping,1}, {rpcs, 0}, {rpc, 1}, {notifications, 0}, {notification, 1}, {yang, 0}, {src, 0}]}, module(M), prefix(Y), revisions(Y), contact(Y), typedefs(Y), groupings(Y), grouping_1(Y), rpcs(Y), rpc_1(Y), notifications(Y), notification_1(Y), yang(Yang), src(Src), {eof,1}], case compile:forms(Forms, Opts) of {ok, ModName, Bin} -> io:fwrite("loading binary (~p)~n", [ModName]), code:load_binary( ModName, "/tmp/" ++ atom_to_list(ModName) ++ ".beam", Bin); Other -> Other end. write_to_file(Forms, F) -> case file:open(F, [write]) of {ok, Fd} -> try io:fwrite(Fd, "~p~n", [Forms]) after file:close(Fd) end; Error -> Error end. module(M) -> codegen:gen_function( module, fun() -> {'$var', M} end). prefix(Y) -> Prefix = lists:keyfind(prefix, 1, Y), codegen:gen_function( prefix, fun() -> {'$var', Prefix} end). revisions(Y) -> Revs = [R || {revision,_,_,_} = R <- Y], codegen:gen_function( revisions, fun() -> {'$var', Revs} end). contact(Y) -> Contact = lists:keyfind(contact, 1, Y), codegen:gen_function( contact, fun() -> {'$var', Contact} end). typedefs(_Y) -> codegen:gen_function( typedef, fun(_) -> [] end). groupings(Y) -> Names = [Name || {grouping, _, Name, _} <- Y], codegen:gen_function( groupings, fun() -> {'$var', Names} end). grouping_1(Y) -> codegen:gen_function_alt( grouping, [fun({'$var', Name}) -> {'$var', Grp} end || {grouping,_,Name,_} = Grp <- Y], fun(_) -> error end). rpcs(Y) -> Names = [Name || {rpc,_,Name,_} <- Y], codegen:gen_function( rpcs, fun() -> {'$var', Names} end). rpc_1(Y) -> codegen:gen_function_alt( rpc, [fun({'$var', Name}) -> {'$var', RPC} end || {rpc,_,Name,_} = RPC <- Y], fun(_) -> error end). notifications(Y) -> Names = [Name || {notification,_,Name,_} <- Y], codegen:gen_function( notifications, fun() -> {'$var', Names} end). notification_1(Y) -> codegen:gen_function_alt( notification, [fun({'$var', Name}) -> {'$var', N} end || {notification,_,Name,_} = N <- Y], fun(_) -> error end). yang(_Y) -> codegen:gen_function( yang, fun() -> [] end). src(_Bin) -> codegen:gen_function( src, fun() -> { ' $ var ' , } [] end).
9ad8ba197d4ef9b1337fb1bcc7a3ac4570de120308b7ca245d6fa9ce5fe926b0
kushidesign/kushi
core.cljs
(ns kushi.ui.collapse.core (:require [kushi.core :refer (sx merge-attrs) :refer-macros (sx)] [clojure.string :as string] [kushi.ui.collapse.header :refer (collapse-header-contents)] [kushi.ui.core :refer (defcom opts+children)] [kushi.ui.dom :as dom])) TODO refactor this out (defcom collapse-body [:section (merge-attrs (sx 'kushi-collapse-body-wrapper :overflow--hidden) &attrs) [:div (sx 'kushi-collapse-body :bbe--1px:solid:transparent :padding-block--0.25em:0.5em) &children]]) (defn toggle-class-on-ancestor [node root-class class] (let [root (.closest node (str "." (name root-class)))] (when root (.toggle (.-classList root) (name class))))) (defn toggle-boolean-attribute [node attr] (let [aria-expanded? (.getAttribute node (name attr)) newv (if (= aria-expanded? "false") true false)] (.setAttribute node (name attr) newv))) (defn outer-height [el] (let [styles (js/window.getComputedStyle el) margin-top (js/parseFloat (.-marginTop styles)) margin-bottom (js/parseFloat (.-marginBottom styles)) ret (+ margin-top margin-bottom (js/Math.ceil (.-offsetHeight el)))] ret)) (defn other-expanded-node [accordian-node clicked-node] (when accordian-node (when-let [open-node (.querySelector accordian-node "section>div[aria-expanded='true'][role='button']")] (when-not (= open-node clicked-node) [open-node (-> open-node .-nextSibling)])))) (defn collapse-header [& args] (let [[opts attrs & children] (opts+children args) {:keys [icon-position icon-svg]} opts] (let [on-click #(let [node (.closest (-> % .-target) "[aria-expanded][role='button']") collapse (.-parentNode node) accordian* (dom/grandparent node) accordian (when (dom/has-class accordian* "kushi-accordian") accordian*) [open-node open-exp-parent] (other-expanded-node accordian node) exp-parent (-> node .-nextSibling) collapsed? (= "none" (.-display (.-style exp-parent))) _ (when collapsed? (set! exp-parent.style.display "block")) exp-inner (-> node .-nextSibling .-firstChild) exp-inner-h (outer-height exp-inner) aria-expanded? (dom/attribute-true? node :aria-expanded) height (str exp-inner-h "px") ->height (if aria-expanded? "0px" height) no-height? (and aria-expanded? (string/blank? exp-parent.style.height)) toggle-op (if aria-expanded? dom/remove-class dom/add-class)] (toggle-op collapse :kushi-collapse-expanded) (when no-height? (set! exp-parent.style.height height)) (js/window.requestAnimationFrame (fn [] (when open-exp-parent (set! open-exp-parent.style.height "0px") (toggle-boolean-attribute open-node :aria-expanded)) (set! exp-parent.style.height ->height) (toggle-boolean-attribute node :aria-expanded) (if-not collapsed? (js/setTimeout (fn [] (set! exp-parent.style.display "none")) 200) (js/setTimeout (fn [] (set! exp-parent.style.height "auto")) 210)))))] (into [:div (merge-attrs (sx 'kushi-collapse-header :.pointer {:class [:.flex-row-fs :.collapse-header] :style {:ai :center :padding-block :0.75em :transition :all:200ms:linear :+section:transition-property :height :+section:transition-timing-function "cubic-bezier(0.23, 1, 0.32, 1)" :+section:transition-duration :$kushi-collapse-transition-duration "&[aria-expanded='false']+section:height" :0px "&[aria-expanded='false']+section:>*:transition" :opacity:200ms:linear:10ms "&[aria-expanded='true']+section:>*:transition" :opacity:200ms:linear:200ms "&[aria-expanded='false']+section:>*:opacity" 0 "&[aria-expanded='true']+section:>*:opacity" 1} :tabIndex 0 :role :button :aria-expanded false :on-click on-click :onKeyDown #(when (or (= "Enter" (.-key %)) (= 13 (.-which %)) (= 13 (.-keyCode %))) (-> % .-target .click))}) attrs)] children)))) (defn collapse {:desc ["A section of content which can be collapsed and expanded."] :opts '[{:name label :type :string :default nil :desc "The text to display in the collapse header."} {:name label-expanded :type :string :default nil :desc "The text to display in the collapse header when expanded. Optional."} {:name mui-icon :type :string :default "add" :desc ["The [name of the Material Icon](+Icons) to use in the collapse header." "Optional."]} {:name mui-icon-expanded :type :string :default "remove" :desc ["The [name of the Material Icon](+Icons) to use in the collapse header when expanded." "Optional."]} {:name icon-position :type #{:start :end} :default :start :desc ["A value of `:start` will place the at the inline start of the header, preceding the label." "A value of `:end` will place the icon at the inline end of the header, opposite the label." "Optional."]} {:name icon-svg :type :boolean :default false :desc ["Pass a `mui-icon` in `svg` (hiccup) to use in place of the Google Fonts Material Icons font." "Must use `:viewBox` attribute with values such as `\"0 0 24 24\"`." "The `:width` and `:height` attributes of the `svg` do not need to be set."]} {:name expanded? :type :boolean :default false :desc ["When a value of `true` is passed, the collapse is initially rendered in an expanded state." "Optional"]} ]} [& args] (let [[opts attr & children] (opts+children args) {:keys [header-attrs body-attrs expanded? on-click icon-position]} opts] [:section (merge-attrs (sx 'kushi-collapse :.flex-col-fs (when expanded? :.kushi-collapse-expanded) :w--100% {:data-kushi-ui :collapse}) attr) [collapse-header (merge-attrs header-attrs (sx #_["[aria-expanded='false']+.kushi-collapse-body-wrapper:d" :none] {:on-click on-click :aria-expanded (if expanded? "true" "false") :-icon-position icon-position})) [collapse-header-contents opts]] ;; collapse body [:section (merge-attrs (sx 'kushi-collapse-body-wrapper :overflow--hidden {:disabled true}) body-attrs {:style {:display :none}}) (into [:div (sx 'kushi-collapse-body :bbe--1px:solid:transparent :padding-block--0.25em:0.5em)] children)]])) (defn accordian {:desc ["A wrapper for multiple instances of the `collapse` component." :br "When `collapse` components are children of the accordian component, they can only be expanded one at a time."]} [& args] (let [[opts attrs & children] (opts+children args) {:keys []} opts] (into [:div (merge-attrs {:class [:kushi-accordian]} attrs)] children)))
null
https://raw.githubusercontent.com/kushidesign/kushi/095f9852d426d0b58ec0cdc06fb278dbdf05353b/src/kushi/ui/collapse/core.cljs
clojure
collapse body
(ns kushi.ui.collapse.core (:require [kushi.core :refer (sx merge-attrs) :refer-macros (sx)] [clojure.string :as string] [kushi.ui.collapse.header :refer (collapse-header-contents)] [kushi.ui.core :refer (defcom opts+children)] [kushi.ui.dom :as dom])) TODO refactor this out (defcom collapse-body [:section (merge-attrs (sx 'kushi-collapse-body-wrapper :overflow--hidden) &attrs) [:div (sx 'kushi-collapse-body :bbe--1px:solid:transparent :padding-block--0.25em:0.5em) &children]]) (defn toggle-class-on-ancestor [node root-class class] (let [root (.closest node (str "." (name root-class)))] (when root (.toggle (.-classList root) (name class))))) (defn toggle-boolean-attribute [node attr] (let [aria-expanded? (.getAttribute node (name attr)) newv (if (= aria-expanded? "false") true false)] (.setAttribute node (name attr) newv))) (defn outer-height [el] (let [styles (js/window.getComputedStyle el) margin-top (js/parseFloat (.-marginTop styles)) margin-bottom (js/parseFloat (.-marginBottom styles)) ret (+ margin-top margin-bottom (js/Math.ceil (.-offsetHeight el)))] ret)) (defn other-expanded-node [accordian-node clicked-node] (when accordian-node (when-let [open-node (.querySelector accordian-node "section>div[aria-expanded='true'][role='button']")] (when-not (= open-node clicked-node) [open-node (-> open-node .-nextSibling)])))) (defn collapse-header [& args] (let [[opts attrs & children] (opts+children args) {:keys [icon-position icon-svg]} opts] (let [on-click #(let [node (.closest (-> % .-target) "[aria-expanded][role='button']") collapse (.-parentNode node) accordian* (dom/grandparent node) accordian (when (dom/has-class accordian* "kushi-accordian") accordian*) [open-node open-exp-parent] (other-expanded-node accordian node) exp-parent (-> node .-nextSibling) collapsed? (= "none" (.-display (.-style exp-parent))) _ (when collapsed? (set! exp-parent.style.display "block")) exp-inner (-> node .-nextSibling .-firstChild) exp-inner-h (outer-height exp-inner) aria-expanded? (dom/attribute-true? node :aria-expanded) height (str exp-inner-h "px") ->height (if aria-expanded? "0px" height) no-height? (and aria-expanded? (string/blank? exp-parent.style.height)) toggle-op (if aria-expanded? dom/remove-class dom/add-class)] (toggle-op collapse :kushi-collapse-expanded) (when no-height? (set! exp-parent.style.height height)) (js/window.requestAnimationFrame (fn [] (when open-exp-parent (set! open-exp-parent.style.height "0px") (toggle-boolean-attribute open-node :aria-expanded)) (set! exp-parent.style.height ->height) (toggle-boolean-attribute node :aria-expanded) (if-not collapsed? (js/setTimeout (fn [] (set! exp-parent.style.display "none")) 200) (js/setTimeout (fn [] (set! exp-parent.style.height "auto")) 210)))))] (into [:div (merge-attrs (sx 'kushi-collapse-header :.pointer {:class [:.flex-row-fs :.collapse-header] :style {:ai :center :padding-block :0.75em :transition :all:200ms:linear :+section:transition-property :height :+section:transition-timing-function "cubic-bezier(0.23, 1, 0.32, 1)" :+section:transition-duration :$kushi-collapse-transition-duration "&[aria-expanded='false']+section:height" :0px "&[aria-expanded='false']+section:>*:transition" :opacity:200ms:linear:10ms "&[aria-expanded='true']+section:>*:transition" :opacity:200ms:linear:200ms "&[aria-expanded='false']+section:>*:opacity" 0 "&[aria-expanded='true']+section:>*:opacity" 1} :tabIndex 0 :role :button :aria-expanded false :on-click on-click :onKeyDown #(when (or (= "Enter" (.-key %)) (= 13 (.-which %)) (= 13 (.-keyCode %))) (-> % .-target .click))}) attrs)] children)))) (defn collapse {:desc ["A section of content which can be collapsed and expanded."] :opts '[{:name label :type :string :default nil :desc "The text to display in the collapse header."} {:name label-expanded :type :string :default nil :desc "The text to display in the collapse header when expanded. Optional."} {:name mui-icon :type :string :default "add" :desc ["The [name of the Material Icon](+Icons) to use in the collapse header." "Optional."]} {:name mui-icon-expanded :type :string :default "remove" :desc ["The [name of the Material Icon](+Icons) to use in the collapse header when expanded." "Optional."]} {:name icon-position :type #{:start :end} :default :start :desc ["A value of `:start` will place the at the inline start of the header, preceding the label." "A value of `:end` will place the icon at the inline end of the header, opposite the label." "Optional."]} {:name icon-svg :type :boolean :default false :desc ["Pass a `mui-icon` in `svg` (hiccup) to use in place of the Google Fonts Material Icons font." "Must use `:viewBox` attribute with values such as `\"0 0 24 24\"`." "The `:width` and `:height` attributes of the `svg` do not need to be set."]} {:name expanded? :type :boolean :default false :desc ["When a value of `true` is passed, the collapse is initially rendered in an expanded state." "Optional"]} ]} [& args] (let [[opts attr & children] (opts+children args) {:keys [header-attrs body-attrs expanded? on-click icon-position]} opts] [:section (merge-attrs (sx 'kushi-collapse :.flex-col-fs (when expanded? :.kushi-collapse-expanded) :w--100% {:data-kushi-ui :collapse}) attr) [collapse-header (merge-attrs header-attrs (sx #_["[aria-expanded='false']+.kushi-collapse-body-wrapper:d" :none] {:on-click on-click :aria-expanded (if expanded? "true" "false") :-icon-position icon-position})) [collapse-header-contents opts]] [:section (merge-attrs (sx 'kushi-collapse-body-wrapper :overflow--hidden {:disabled true}) body-attrs {:style {:display :none}}) (into [:div (sx 'kushi-collapse-body :bbe--1px:solid:transparent :padding-block--0.25em:0.5em)] children)]])) (defn accordian {:desc ["A wrapper for multiple instances of the `collapse` component." :br "When `collapse` components are children of the accordian component, they can only be expanded one at a time."]} [& args] (let [[opts attrs & children] (opts+children args) {:keys []} opts] (into [:div (merge-attrs {:class [:kushi-accordian]} attrs)] children)))
2dac07357f820ee07cfd6ebe36f56948822cfc6b5c42b752321ac515e45806df
imrehg/ypsilon
draw.scm
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gdk draw) (export gdk_draw_arc gdk_draw_drawable gdk_draw_glyphs gdk_draw_glyphs_transformed gdk_draw_gray_image gdk_draw_image gdk_draw_indexed_image gdk_draw_layout gdk_draw_layout_line gdk_draw_layout_line_with_colors gdk_draw_layout_with_colors gdk_draw_line gdk_draw_lines gdk_draw_pixbuf gdk_draw_point gdk_draw_points gdk_draw_polygon gdk_draw_rectangle gdk_draw_rgb_32_image gdk_draw_rgb_32_image_dithalign gdk_draw_rgb_image gdk_draw_rgb_image_dithalign gdk_draw_segments gdk_draw_trapezoids) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgdk-x11-2.0.so.0") (on-sunos "libgdk-x11-2.0.so.0") (on-freebsd "libgdk-x11-2.0.so.0") (on-openbsd "libgdk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgdk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GDK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) void gdk_draw_arc ( GdkDrawable * drawable , GdkGC * gc , filled , , gint y , , , , gint ) (define-function void gdk_draw_arc (void* void* int int int int int int int)) void gdk_draw_drawable ( GdkDrawable * drawable , GdkGC * gc , GdkDrawable * src , , , , gint ydest , , ) (define-function void gdk_draw_drawable (void* void* void* int int int int int int)) void gdk_draw_glyphs ( GdkDrawable * drawable , GdkGC * gc , PangoFont * font , , gint y , PangoGlyphString * glyphs ) (define-function void gdk_draw_glyphs (void* void* void* int int void*)) void gdk_draw_glyphs_transformed ( GdkDrawable * drawable , GdkGC * gc , const PangoMatrix * matrix , PangoFont * font , , gint y , PangoGlyphString * glyphs ) (define-function void gdk_draw_glyphs_transformed (void* void* void* void* int int void*)) void gdk_draw_gray_image ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , ) (define-function void gdk_draw_gray_image (void* void* int int int int int void* int)) void gdk_draw_image ( GdkDrawable * drawable , GdkGC * gc , GdkImage * image , , , , gint ydest , , ) (define-function void gdk_draw_image (void* void* void* int int int int int int)) void ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , , GdkRgbCmap * cmap ) (define-function void gdk_draw_indexed_image (void* void* int int int int int void* int void*)) void gdk_draw_layout ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayout * layout ) (define-function void gdk_draw_layout (void* void* int int void*)) void gdk_draw_layout_line ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayoutLine * line ) (define-function void gdk_draw_layout_line (void* void* int int void*)) void gdk_draw_layout_line_with_colors ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayoutLine * line , const GdkColor * foreground , const GdkColor * background ) (define-function void gdk_draw_layout_line_with_colors (void* void* int int void* void* void*)) void gdk_draw_layout_with_colors ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayout * layout , const GdkColor * foreground , const GdkColor * background ) (define-function void gdk_draw_layout_with_colors (void* void* int int void* void* void*)) void gdk_draw_line ( GdkDrawable * drawable , GdkGC * gc , gint x1 _ , y1 _ , gint x2 _ , ) (define-function void gdk_draw_line (void* void* int int int int)) void gdk_draw_lines ( GdkDrawable * drawable , GdkGC * gc , const GdkPoint * points , ) (define-function void gdk_draw_lines (void* void* void* int)) void gdk_draw_pixbuf ( GdkDrawable * drawable , GdkGC * gc , const GdkPixbuf * pixbuf , , gint src_y , gint dest_x , , , , GdkRgbDither dither , , ) (define-function void gdk_draw_pixbuf (void* void* void* int int int int int int int int int)) void gdk_draw_point ( GdkDrawable * drawable , GdkGC * gc , , ) (define-function void gdk_draw_point (void* void* int int)) void gdk_draw_points ( GdkDrawable * drawable , GdkGC * gc , const GdkPoint * points , ) (define-function void gdk_draw_points (void* void* void* int)) void gdk_draw_polygon ( GdkDrawable * drawable , GdkGC * gc , filled , const GdkPoint * points , ) (define-function void gdk_draw_polygon (void* void* int void* int)) void gdk_draw_rectangle ( GdkDrawable * drawable , GdkGC * gc , filled , , gint y , , ) (define-function void gdk_draw_rectangle (void* void* int int int int int)) void gdk_draw_rgb_32_image ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , ) (define-function void gdk_draw_rgb_32_image (void* void* int int int int int void* int)) void gdk_draw_rgb_32_image_dithalign ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , , , ) (define-function void gdk_draw_rgb_32_image_dithalign (void* void* int int int int int void* int int int)) void gdk_draw_rgb_image ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , const * rgb_buf , ) (define-function void gdk_draw_rgb_image (void* void* int int int int int void* int)) void gdk_draw_rgb_image_dithalign ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , const * rgb_buf , , , ) (define-function void gdk_draw_rgb_image_dithalign (void* void* int int int int int void* int int int)) void gdk_draw_segments ( GdkDrawable * drawable , GdkGC * gc , const GdkSegment * , ) (define-function void gdk_draw_segments (void* void* void* int)) void gdk_draw_trapezoids ( GdkDrawable * drawable , GdkGC * gc , const GdkTrapezoid * trapezoids , gint n_trapezoids ) (define-function void gdk_draw_trapezoids (void* void* void* int)) ) ;[end]
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/sitelib/ypsilon/gdk/draw.scm
scheme
[end]
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gdk draw) (export gdk_draw_arc gdk_draw_drawable gdk_draw_glyphs gdk_draw_glyphs_transformed gdk_draw_gray_image gdk_draw_image gdk_draw_indexed_image gdk_draw_layout gdk_draw_layout_line gdk_draw_layout_line_with_colors gdk_draw_layout_with_colors gdk_draw_line gdk_draw_lines gdk_draw_pixbuf gdk_draw_point gdk_draw_points gdk_draw_polygon gdk_draw_rectangle gdk_draw_rgb_32_image gdk_draw_rgb_32_image_dithalign gdk_draw_rgb_image gdk_draw_rgb_image_dithalign gdk_draw_segments gdk_draw_trapezoids) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgdk-x11-2.0.so.0") (on-sunos "libgdk-x11-2.0.so.0") (on-freebsd "libgdk-x11-2.0.so.0") (on-openbsd "libgdk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgdk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GDK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) void gdk_draw_arc ( GdkDrawable * drawable , GdkGC * gc , filled , , gint y , , , , gint ) (define-function void gdk_draw_arc (void* void* int int int int int int int)) void gdk_draw_drawable ( GdkDrawable * drawable , GdkGC * gc , GdkDrawable * src , , , , gint ydest , , ) (define-function void gdk_draw_drawable (void* void* void* int int int int int int)) void gdk_draw_glyphs ( GdkDrawable * drawable , GdkGC * gc , PangoFont * font , , gint y , PangoGlyphString * glyphs ) (define-function void gdk_draw_glyphs (void* void* void* int int void*)) void gdk_draw_glyphs_transformed ( GdkDrawable * drawable , GdkGC * gc , const PangoMatrix * matrix , PangoFont * font , , gint y , PangoGlyphString * glyphs ) (define-function void gdk_draw_glyphs_transformed (void* void* void* void* int int void*)) void gdk_draw_gray_image ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , ) (define-function void gdk_draw_gray_image (void* void* int int int int int void* int)) void gdk_draw_image ( GdkDrawable * drawable , GdkGC * gc , GdkImage * image , , , , gint ydest , , ) (define-function void gdk_draw_image (void* void* void* int int int int int int)) void ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , , GdkRgbCmap * cmap ) (define-function void gdk_draw_indexed_image (void* void* int int int int int void* int void*)) void gdk_draw_layout ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayout * layout ) (define-function void gdk_draw_layout (void* void* int int void*)) void gdk_draw_layout_line ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayoutLine * line ) (define-function void gdk_draw_layout_line (void* void* int int void*)) void gdk_draw_layout_line_with_colors ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayoutLine * line , const GdkColor * foreground , const GdkColor * background ) (define-function void gdk_draw_layout_line_with_colors (void* void* int int void* void* void*)) void gdk_draw_layout_with_colors ( GdkDrawable * drawable , GdkGC * gc , , gint y , PangoLayout * layout , const GdkColor * foreground , const GdkColor * background ) (define-function void gdk_draw_layout_with_colors (void* void* int int void* void* void*)) void gdk_draw_line ( GdkDrawable * drawable , GdkGC * gc , gint x1 _ , y1 _ , gint x2 _ , ) (define-function void gdk_draw_line (void* void* int int int int)) void gdk_draw_lines ( GdkDrawable * drawable , GdkGC * gc , const GdkPoint * points , ) (define-function void gdk_draw_lines (void* void* void* int)) void gdk_draw_pixbuf ( GdkDrawable * drawable , GdkGC * gc , const GdkPixbuf * pixbuf , , gint src_y , gint dest_x , , , , GdkRgbDither dither , , ) (define-function void gdk_draw_pixbuf (void* void* void* int int int int int int int int int)) void gdk_draw_point ( GdkDrawable * drawable , GdkGC * gc , , ) (define-function void gdk_draw_point (void* void* int int)) void gdk_draw_points ( GdkDrawable * drawable , GdkGC * gc , const GdkPoint * points , ) (define-function void gdk_draw_points (void* void* void* int)) void gdk_draw_polygon ( GdkDrawable * drawable , GdkGC * gc , filled , const GdkPoint * points , ) (define-function void gdk_draw_polygon (void* void* int void* int)) void gdk_draw_rectangle ( GdkDrawable * drawable , GdkGC * gc , filled , , gint y , , ) (define-function void gdk_draw_rectangle (void* void* int int int int int)) void gdk_draw_rgb_32_image ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , ) (define-function void gdk_draw_rgb_32_image (void* void* int int int int int void* int)) void gdk_draw_rgb_32_image_dithalign ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , * buf , , , ) (define-function void gdk_draw_rgb_32_image_dithalign (void* void* int int int int int void* int int int)) void gdk_draw_rgb_image ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , const * rgb_buf , ) (define-function void gdk_draw_rgb_image (void* void* int int int int int void* int)) void gdk_draw_rgb_image_dithalign ( GdkDrawable * drawable , GdkGC * gc , , gint y , , , , const * rgb_buf , , , ) (define-function void gdk_draw_rgb_image_dithalign (void* void* int int int int int void* int int int)) void gdk_draw_segments ( GdkDrawable * drawable , GdkGC * gc , const GdkSegment * , ) (define-function void gdk_draw_segments (void* void* void* int)) void gdk_draw_trapezoids ( GdkDrawable * drawable , GdkGC * gc , const GdkTrapezoid * trapezoids , gint n_trapezoids ) (define-function void gdk_draw_trapezoids (void* void* void* int))
eb8a34172870ef8700e62ed762dcf474b116090c998251616ffe787dc25edd67
census-instrumentation/opencensus-erlang
oc_span_ctx_SUITE.erl
%%% --------------------------------------------------------------------------- %%% @doc %%% @end %%% --------------------------------------------------------------------------- -module(oc_span_ctx_SUITE). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include("opencensus.hrl"). -define(W3C_HEADERS(TraceParent, TraceState), [{<<"traceparent">>, TraceParent}, {<<"tracestate">>, TraceState}]). -define(B3_HEADERS(TraceId, SpanId, Sampled), [{<<"X-B3-TraceId">>, TraceId}, {<<"X-B3-SpanId">>, SpanId}, {<<"X-B3-Sampled">>, Sampled}]). all() -> [encode_decode, decode_with_extra_junk, w3c_encode_decode_headers, b3_encode_decode_headers, tracestate]. init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_testcase(_, Config) -> Config. end_per_testcase(_, _Config) -> ok. TraceId : 85409434994488837557643013731547696719 %% SpanId: 7017280452245743464 %% Enabled: true -define(EXAMPLE_BIN, <<0, 0, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 1, 97, 98, 99, 100, 101, 102, 103, 104, 2, 1>>). reencode(Binary) -> Decoded = oc_propagation_binary:decode(Binary), Encoded = oc_propagation_binary:encode(Decoded), Encoded. encode_decode(_Config) -> Encoded = reencode(?EXAMPLE_BIN), ?assertMatch(?EXAMPLE_BIN, Encoded), InvalidBothIdsBinary = <<0:8, 0:8, 0:128, 1:8, 0:64, 2:8, 1>>, ?assertEqual(undefined, oc_propagation_binary:decode(InvalidBothIdsBinary)), InvalidTraceIdBinary = <<0:8, 0:8, 0:128, 1:8, 1:64, 2:8, 1>>, ?assertEqual(undefined, oc_propagation_binary:decode(InvalidTraceIdBinary)), InvalidSpanIdBinary = <<0:8, 0:8, 1:128, 1:8, 0:64, 2:8, 1>>, ?assertEqual(undefined, oc_propagation_binary:decode(InvalidSpanIdBinary)). decode_with_extra_junk(_Config) -> Binary = ?EXAMPLE_BIN, BinaryWithJunk = <<Binary/binary, 23, 4, 5>>, Encoded = reencode(BinaryWithJunk), ?assertMatch(Binary, Encoded). w3c_encode_decode_headers(_Config) -> TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 %% Enabled: true Header = <<"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01">>, Decoded = oc_propagation_http_tracecontext:decode(Header), Encoded = oc_propagation_http_tracecontext:encode(Decoded), ?assertEqual(Header, list_to_binary(Encoded)), ?assertEqual(Decoded, oc_propagation_http_tracecontext:decode(Encoded)), TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 %% Enabled: false DisabledHeader = <<"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00">>, DisabledDecoded = oc_propagation_http_tracecontext:decode(DisabledHeader), DisabledEncoded = oc_propagation_http_tracecontext:encode(DisabledDecoded), ?assertEqual(DisabledHeader, list_to_binary(DisabledEncoded)), ?assertEqual(DisabledDecoded, oc_propagation_http_tracecontext:decode(DisabledEncoded)), ?assertEqual(0, DisabledDecoded#span_ctx.trace_options), Headers = ?W3C_HEADERS(<<"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01">>, <<"congo=congosFirstPosition,rojo=rojosFirstPosition">>), SpanCtx = oc_propagation_http_tracecontext:from_headers(Headers), EncodedHeaders = oc_propagation_http_tracecontext:to_headers(SpanCtx), ?assertMatch(SpanCtx, oc_propagation_http_tracecontext:from_headers(EncodedHeaders)), %% Decode invalid headers ?assertEqual(undefined, oc_propagation_http_tracecontext:from_headers([])), InvalidSpanIdHeader = <<"00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-00">>, ?assertEqual(undefined, oc_propagation_http_tracecontext:decode(InvalidSpanIdHeader)), InvalidTraceIdHeader = <<"00-00000000000000000000000000000000-00f067aa0ba902b7-00">>, ?assertEqual(undefined, oc_propagation_http_tracecontext:decode(InvalidTraceIdHeader)), InvalidBothIdsHeader = <<"00-00000000000000000000000000000000-0000000000000000-00">>, ?assertEqual(undefined, oc_propagation_http_tracecontext:decode(InvalidBothIdsHeader)), NoCtx = undefined, NoCtxEncoded = oc_propagation_http_tracecontext:to_headers(NoCtx), ?assertEqual(NoCtx, oc_propagation_http_tracecontext:from_headers(NoCtxEncoded)), %% Encode invalid trace contexts InvalidTC = #span_ctx{trace_id = 0, span_id = 0, trace_options = false}, ?assertEqual([], oc_propagation_http_tracecontext:to_headers(InvalidTC)), InvalidTraceIdTC = #span_ctx{trace_id = 85409434994488837557643013731547696719, span_id = 0, trace_options = true}, ?assertEqual([], oc_propagation_http_tracecontext:to_headers(InvalidTraceIdTC)), InvalidSpanIdTC = #span_ctx{trace_id = 0, span_id = 7017280452245743464, trace_options = false}, ?assertEqual([], oc_propagation_http_tracecontext:to_headers(InvalidSpanIdTC)). b3_encode_decode_headers(_Config) -> TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 %% Enabled: true Headers = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba902b7">>, <<"1">>), Decoded = oc_propagation_http_b3:from_headers(Headers), Encoded = oc_propagation_http_b3:to_headers(Decoded), compare_b3_headers(Encoded, Headers), ?assertEqual(Decoded, oc_propagation_http_b3:from_headers(Encoded)), TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 %% Enabled: false DisabledHeaders = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba902b7">>, <<"0">>), DisabledDecoded = oc_propagation_http_b3:from_headers(DisabledHeaders), DisabledEncoded = oc_propagation_http_b3:to_headers(DisabledDecoded), compare_b3_headers(DisabledEncoded, DisabledHeaders), ?assertEqual(DisabledDecoded, oc_propagation_http_b3:from_headers(DisabledEncoded)), ?assertEqual(0, DisabledDecoded#span_ctx.trace_options), %% Decode invalid headers ?assertEqual(undefined, oc_propagation_http_b3:from_headers([])), InvalidBase16 = ?B3_HEADERS(<<"zbf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba902b7">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidBase16)), InvalidSpanIdLength = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba90">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidSpanIdLength)), InvalidSpanIdHeader = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"0000000000000">>, <<"1">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidSpanIdHeader)), InvalidTraceIdHeader = ?B3_HEADERS(<<"00000000000000000000000000000000">>, <<"00f067aa0ba90">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidTraceIdHeader)), InvalidBothIdsHeader = ?B3_HEADERS(<<"00000000000000000000000000000000">>, <<"0000000000000">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidBothIdsHeader)), NoCtx = undefined, NoCtxEncoded = oc_propagation_http_b3:to_headers(NoCtx), ?assertEqual(NoCtx, oc_propagation_http_b3:from_headers(NoCtxEncoded)), %% Encode invalid trace contexts InvalidTC = #span_ctx{trace_id = 0, span_id = 0, trace_options = false}, ?assertEqual([], oc_propagation_http_b3:to_headers(InvalidTC)), InvalidTraceIdTC = #span_ctx{trace_id = 85409434994488837557643013731547696719, span_id = 0, trace_options = true}, ?assertEqual([], oc_propagation_http_b3:to_headers(InvalidTraceIdTC)), InvalidSpanIdTC = #span_ctx{trace_id = 0, span_id = 7017280452245743464, trace_options = false}, ?assertEqual([], oc_propagation_http_b3:to_headers(InvalidSpanIdTC)). compare_b3_headers(Encoded, Orig) -> lists:all(fun({Key, Value}) -> string:equal(Value, element(2, lists:keyfind(Key, 1, Orig))) end, Encoded). tracestate(_Config) -> %% fail on empty key ?assertMatch(undefined, oc_tracestate:new(undefined, [{"", "emptykey"}])), %% fail on too long key ?assertMatch(undefined, oc_tracestate:new(undefined, [{lists:flatten(lists:duplicate(257, "k")), "value"}])), %% fail on too long value ?assertMatch(undefined, oc_tracestate:new(undefined, [{"key", lists:flatten(lists:duplicate(257, "v"))}])), Entries = [{"congo", "congosFirstPosition"}, {"rojo", "rojosFirstPosition"}], TS0 = oc_tracestate:new(undefined, Entries), TS = oc_tracestate:new(TS0, [{"congo", "congosSecondPosition"}]), %% order matters ?assertMatch([{"rojo", "rojosFirstPosition"}, {"congo", "congosSecondPosition"}], TS#tracestate.entries), %% return undefined if any entry is invalid ?assertMatch(undefined, oc_tracestate:new(TS0, [{"congo", "congosSecondPosition"}, {"rojo", <<1234>>}])).
null
https://raw.githubusercontent.com/census-instrumentation/opencensus-erlang/7fb276ff73d677c00458922c9180df634f45e018/test/oc_span_ctx_SUITE.erl
erlang
--------------------------------------------------------------------------- @doc @end --------------------------------------------------------------------------- SpanId: 7017280452245743464 Enabled: true Enabled: true Enabled: false Decode invalid headers Encode invalid trace contexts Enabled: true Enabled: false Decode invalid headers Encode invalid trace contexts fail on empty key fail on too long key fail on too long value order matters return undefined if any entry is invalid
-module(oc_span_ctx_SUITE). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include("opencensus.hrl"). -define(W3C_HEADERS(TraceParent, TraceState), [{<<"traceparent">>, TraceParent}, {<<"tracestate">>, TraceState}]). -define(B3_HEADERS(TraceId, SpanId, Sampled), [{<<"X-B3-TraceId">>, TraceId}, {<<"X-B3-SpanId">>, SpanId}, {<<"X-B3-Sampled">>, Sampled}]). all() -> [encode_decode, decode_with_extra_junk, w3c_encode_decode_headers, b3_encode_decode_headers, tracestate]. init_per_suite(Config) -> Config. end_per_suite(_Config) -> ok. init_per_testcase(_, Config) -> Config. end_per_testcase(_, _Config) -> ok. TraceId : 85409434994488837557643013731547696719 -define(EXAMPLE_BIN, <<0, 0, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 1, 97, 98, 99, 100, 101, 102, 103, 104, 2, 1>>). reencode(Binary) -> Decoded = oc_propagation_binary:decode(Binary), Encoded = oc_propagation_binary:encode(Decoded), Encoded. encode_decode(_Config) -> Encoded = reencode(?EXAMPLE_BIN), ?assertMatch(?EXAMPLE_BIN, Encoded), InvalidBothIdsBinary = <<0:8, 0:8, 0:128, 1:8, 0:64, 2:8, 1>>, ?assertEqual(undefined, oc_propagation_binary:decode(InvalidBothIdsBinary)), InvalidTraceIdBinary = <<0:8, 0:8, 0:128, 1:8, 1:64, 2:8, 1>>, ?assertEqual(undefined, oc_propagation_binary:decode(InvalidTraceIdBinary)), InvalidSpanIdBinary = <<0:8, 0:8, 1:128, 1:8, 0:64, 2:8, 1>>, ?assertEqual(undefined, oc_propagation_binary:decode(InvalidSpanIdBinary)). decode_with_extra_junk(_Config) -> Binary = ?EXAMPLE_BIN, BinaryWithJunk = <<Binary/binary, 23, 4, 5>>, Encoded = reencode(BinaryWithJunk), ?assertMatch(Binary, Encoded). w3c_encode_decode_headers(_Config) -> TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 Header = <<"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01">>, Decoded = oc_propagation_http_tracecontext:decode(Header), Encoded = oc_propagation_http_tracecontext:encode(Decoded), ?assertEqual(Header, list_to_binary(Encoded)), ?assertEqual(Decoded, oc_propagation_http_tracecontext:decode(Encoded)), TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 DisabledHeader = <<"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00">>, DisabledDecoded = oc_propagation_http_tracecontext:decode(DisabledHeader), DisabledEncoded = oc_propagation_http_tracecontext:encode(DisabledDecoded), ?assertEqual(DisabledHeader, list_to_binary(DisabledEncoded)), ?assertEqual(DisabledDecoded, oc_propagation_http_tracecontext:decode(DisabledEncoded)), ?assertEqual(0, DisabledDecoded#span_ctx.trace_options), Headers = ?W3C_HEADERS(<<"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01">>, <<"congo=congosFirstPosition,rojo=rojosFirstPosition">>), SpanCtx = oc_propagation_http_tracecontext:from_headers(Headers), EncodedHeaders = oc_propagation_http_tracecontext:to_headers(SpanCtx), ?assertMatch(SpanCtx, oc_propagation_http_tracecontext:from_headers(EncodedHeaders)), ?assertEqual(undefined, oc_propagation_http_tracecontext:from_headers([])), InvalidSpanIdHeader = <<"00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-00">>, ?assertEqual(undefined, oc_propagation_http_tracecontext:decode(InvalidSpanIdHeader)), InvalidTraceIdHeader = <<"00-00000000000000000000000000000000-00f067aa0ba902b7-00">>, ?assertEqual(undefined, oc_propagation_http_tracecontext:decode(InvalidTraceIdHeader)), InvalidBothIdsHeader = <<"00-00000000000000000000000000000000-0000000000000000-00">>, ?assertEqual(undefined, oc_propagation_http_tracecontext:decode(InvalidBothIdsHeader)), NoCtx = undefined, NoCtxEncoded = oc_propagation_http_tracecontext:to_headers(NoCtx), ?assertEqual(NoCtx, oc_propagation_http_tracecontext:from_headers(NoCtxEncoded)), InvalidTC = #span_ctx{trace_id = 0, span_id = 0, trace_options = false}, ?assertEqual([], oc_propagation_http_tracecontext:to_headers(InvalidTC)), InvalidTraceIdTC = #span_ctx{trace_id = 85409434994488837557643013731547696719, span_id = 0, trace_options = true}, ?assertEqual([], oc_propagation_http_tracecontext:to_headers(InvalidTraceIdTC)), InvalidSpanIdTC = #span_ctx{trace_id = 0, span_id = 7017280452245743464, trace_options = false}, ?assertEqual([], oc_propagation_http_tracecontext:to_headers(InvalidSpanIdTC)). b3_encode_decode_headers(_Config) -> TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 Headers = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba902b7">>, <<"1">>), Decoded = oc_propagation_http_b3:from_headers(Headers), Encoded = oc_propagation_http_b3:to_headers(Decoded), compare_b3_headers(Encoded, Headers), ?assertEqual(Decoded, oc_propagation_http_b3:from_headers(Encoded)), TraceId : 4bf92f3577b34da6a3ce929d0e0e4736 SpanId : 00f067aa0ba902b7 DisabledHeaders = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba902b7">>, <<"0">>), DisabledDecoded = oc_propagation_http_b3:from_headers(DisabledHeaders), DisabledEncoded = oc_propagation_http_b3:to_headers(DisabledDecoded), compare_b3_headers(DisabledEncoded, DisabledHeaders), ?assertEqual(DisabledDecoded, oc_propagation_http_b3:from_headers(DisabledEncoded)), ?assertEqual(0, DisabledDecoded#span_ctx.trace_options), ?assertEqual(undefined, oc_propagation_http_b3:from_headers([])), InvalidBase16 = ?B3_HEADERS(<<"zbf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba902b7">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidBase16)), InvalidSpanIdLength = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"00f067aa0ba90">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidSpanIdLength)), InvalidSpanIdHeader = ?B3_HEADERS(<<"4bf92f3577b34da6a3ce929d0e0e4736">>, <<"0000000000000">>, <<"1">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidSpanIdHeader)), InvalidTraceIdHeader = ?B3_HEADERS(<<"00000000000000000000000000000000">>, <<"00f067aa0ba90">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidTraceIdHeader)), InvalidBothIdsHeader = ?B3_HEADERS(<<"00000000000000000000000000000000">>, <<"0000000000000">>, <<"0">>), ?assertEqual(undefined, oc_propagation_http_b3:from_headers(InvalidBothIdsHeader)), NoCtx = undefined, NoCtxEncoded = oc_propagation_http_b3:to_headers(NoCtx), ?assertEqual(NoCtx, oc_propagation_http_b3:from_headers(NoCtxEncoded)), InvalidTC = #span_ctx{trace_id = 0, span_id = 0, trace_options = false}, ?assertEqual([], oc_propagation_http_b3:to_headers(InvalidTC)), InvalidTraceIdTC = #span_ctx{trace_id = 85409434994488837557643013731547696719, span_id = 0, trace_options = true}, ?assertEqual([], oc_propagation_http_b3:to_headers(InvalidTraceIdTC)), InvalidSpanIdTC = #span_ctx{trace_id = 0, span_id = 7017280452245743464, trace_options = false}, ?assertEqual([], oc_propagation_http_b3:to_headers(InvalidSpanIdTC)). compare_b3_headers(Encoded, Orig) -> lists:all(fun({Key, Value}) -> string:equal(Value, element(2, lists:keyfind(Key, 1, Orig))) end, Encoded). tracestate(_Config) -> ?assertMatch(undefined, oc_tracestate:new(undefined, [{"", "emptykey"}])), ?assertMatch(undefined, oc_tracestate:new(undefined, [{lists:flatten(lists:duplicate(257, "k")), "value"}])), ?assertMatch(undefined, oc_tracestate:new(undefined, [{"key", lists:flatten(lists:duplicate(257, "v"))}])), Entries = [{"congo", "congosFirstPosition"}, {"rojo", "rojosFirstPosition"}], TS0 = oc_tracestate:new(undefined, Entries), TS = oc_tracestate:new(TS0, [{"congo", "congosSecondPosition"}]), ?assertMatch([{"rojo", "rojosFirstPosition"}, {"congo", "congosSecondPosition"}], TS#tracestate.entries), ?assertMatch(undefined, oc_tracestate:new(TS0, [{"congo", "congosSecondPosition"}, {"rojo", <<1234>>}])).
96d50efd6d946410f01ccb0e0fe1cefe8f32c612eae8d7f83cafa9bc8bcd0bb8
raptazure/chocolate
UsefulEquivalence.hs
module UsefulEquivalence (validUsefulEquivalences) where import Logic (logEquiv1, logEquiv2, logEquiv3, (<=>), (==>)) validUsefulEquivalences :: Bool validUsefulEquivalences = form1 && form2a && form2b && form3a && form3b && form4a && form4b && form4c && form5a && form5b && form6 && form7a && form7b && form8 && form9a && form9b -- have a try to apply hlint hints :) -- law of double negation form1 :: Bool form1 = logEquiv1 id (\p -> not (not p)) -- laws of idempotence form2a :: Bool form2a = logEquiv1 id (\p -> p && p) form2b :: Bool form2b = logEquiv1 id (\p -> p || p) form3a :: Bool form3a = logEquiv2 (\p q -> p ==> q) (\p q -> not p || q) form3b :: Bool form3b = logEquiv2 (\p q -> not (p ==> q)) (\p q -> p && (not q)) -- laws of contraposition form4a :: Bool form4a = logEquiv2 (\p q -> not p ==> not q) (\p q -> q ==> p) form4b :: Bool form4b = logEquiv2 (\p q -> p ==> not q) (\p q -> q ==> not p) form4c :: Bool form4c = logEquiv2 (\p q -> not p ==> q) (\p q -> not q ==> p) form5a :: Bool form5a = logEquiv2 (\p q -> p <=> q) (\p q -> (p ==> q) && (q ==> p)) form5b :: Bool form5b = logEquiv2 (\p q -> (p && q) || (not p && not q)) (\p q -> (p && q) || (not p && not q)) -- law of commutativity form6 :: Bool form6 = logEquiv2 (\p q -> p && q) (\p q -> q && p) laws form7a :: Bool form7a = logEquiv2 (\p q -> not (p && q)) (\p q -> not p || not q) form7b :: Bool form7b = logEquiv2 (\p q -> not (p || q)) (\p q -> not p && not q) -- laws of associativity form8 :: Bool form8 = logEquiv3 (\p q r -> p && (q && r)) (\p q r -> (p && q) && r) -- distribution laws form9a :: Bool form9a = logEquiv3 (\p q r -> p && (q || r)) (\p q r -> (p || q) && (p || r)) form9b :: Bool form9b = logEquiv3 (\p q r -> p || (q && r)) (\p q r -> (p && q) || (p && r))
null
https://raw.githubusercontent.com/raptazure/chocolate/48a7aaebb0d36aff639d6aa583536595ff034c22/src/UsefulEquivalence.hs
haskell
have a try to apply hlint hints :) law of double negation laws of idempotence laws of contraposition law of commutativity laws of associativity distribution laws
module UsefulEquivalence (validUsefulEquivalences) where import Logic (logEquiv1, logEquiv2, logEquiv3, (<=>), (==>)) validUsefulEquivalences :: Bool validUsefulEquivalences = form1 && form2a && form2b && form3a && form3b && form4a && form4b && form4c && form5a && form5b && form6 && form7a && form7b && form8 && form9a && form9b form1 :: Bool form1 = logEquiv1 id (\p -> not (not p)) form2a :: Bool form2a = logEquiv1 id (\p -> p && p) form2b :: Bool form2b = logEquiv1 id (\p -> p || p) form3a :: Bool form3a = logEquiv2 (\p q -> p ==> q) (\p q -> not p || q) form3b :: Bool form3b = logEquiv2 (\p q -> not (p ==> q)) (\p q -> p && (not q)) form4a :: Bool form4a = logEquiv2 (\p q -> not p ==> not q) (\p q -> q ==> p) form4b :: Bool form4b = logEquiv2 (\p q -> p ==> not q) (\p q -> q ==> not p) form4c :: Bool form4c = logEquiv2 (\p q -> not p ==> q) (\p q -> not q ==> p) form5a :: Bool form5a = logEquiv2 (\p q -> p <=> q) (\p q -> (p ==> q) && (q ==> p)) form5b :: Bool form5b = logEquiv2 (\p q -> (p && q) || (not p && not q)) (\p q -> (p && q) || (not p && not q)) form6 :: Bool form6 = logEquiv2 (\p q -> p && q) (\p q -> q && p) laws form7a :: Bool form7a = logEquiv2 (\p q -> not (p && q)) (\p q -> not p || not q) form7b :: Bool form7b = logEquiv2 (\p q -> not (p || q)) (\p q -> not p && not q) form8 :: Bool form8 = logEquiv3 (\p q r -> p && (q && r)) (\p q r -> (p && q) && r) form9a :: Bool form9a = logEquiv3 (\p q r -> p && (q || r)) (\p q r -> (p || q) && (p || r)) form9b :: Bool form9b = logEquiv3 (\p q r -> p || (q && r)) (\p q r -> (p && q) || (p && r))
401fbb2c9d9a3d9bd10c1e4e9da92b28757d969c9744481d0b3dc5dc12065aa8
noteed/mojito
SystemCT1999.hs
# LANGUAGE GeneralizedNewtypeDeriving , FlexibleContexts # SystemCT from Camarao 1999 , -- Type Inference for Overloading without -- Restrictions, Declarations or Annotations -- -- Based on Cardelli.hs. module Language.Mojito.Inference.SystemCT1999.SystemCT1999 where import Data.List (groupBy, union, (\\)) import Data.Maybe (mapMaybe) import Data.Function (on) import Control.Monad.Except import Control.Monad.Identity import Control.Monad.State import Control.Monad.Writer import Language.Mojito.Syntax.Expr import Language.Mojito.Syntax.Types import Language.Mojito.Syntax.ExprBuilder import Language.Mojito.Prelude.Types import Language.Mojito.Inference.Context import Language.Mojito.Inference.Substitution import Language.Mojito.Inference.Unification import Language.Mojito.Inference.SystemCT1999.Note import Language.Mojito.Inference.SystemCT1999.Inferencer import Language.Mojito.Inference.SystemCT1999.LCG ---------------------------------------------------------------------- -- main functions ---------------------------------------------------------------------- -- Infers the typing of an expression in a context. This returns some logs, the state -- of the inference and either the typing or an error. infer :: [Simple] -> Expr Int -> Context -> ((Either String (Constrained,Context), [Note]), Inferencer) infer ts e g = runIdentity $ runStateT (runWriterT $ runExceptT $ runInf $ pp e g) (inferencer { tiTypes = ts }) TODO use infer + duplicate ' instead infer' :: [Simple] -> Expr Int -> Context -> ((Either String (Expr Simple), [Note]), Inferencer) infer' ts e g = runIdentity $ runStateT (runWriterT $ runExceptT $ runInf $ go) (inferencer { tiTypes = ts }) where go = do (c,g') <- pp e g case kgs c g' of [] -> throwError "no type." [t] -> do ty <- gets tiTypings s <- gets tiSubstitution return $ duplicate ty s e t _ -> throwError "more than one type." TODO delete this function or put it in some helper module readInferedExpr :: [Simple] -> Context -> String -> Expr Simple readInferedExpr ts g str = case readExpr str of Left err -> error err Right e -> case infer' ts e g of ((Left err,_),_) -> error err ((Right e',_),_) -> e' duplicate' :: MonadError String m => Inferencer -> Expr Int -> Constrained -> Context -> m (Expr Simple) duplicate' inf e c g = case kgs c g of [] -> throwError "no type." [t] -> do let ty = tiTypings inf let s = tiSubstitution inf return $ duplicate ty s e t _ -> throwError "more than one type." makeDefaultTypes :: Substitution -> [(Int,(Constrained,Context))] -> [(Int,Simple)] makeDefaultTypes s ts = map f ts where f (k,(t,g)) = let (Constrained k' t',g') = (s `subs` t,s `subs'` g) bigs = satc k' g' in (k, h $ map (`subs` t') bigs) h [] = error "no type" h [t] = t h tt = error $ "TODO implement some default type mechanism: " ++ concatMap showSimple tt giveTypes :: Expr Int -> Substitution -> [(Int,(Constrained,Context))] -> Expr [Simple] giveTypes e s ts = fmap f e where f k = case lookup k ts of Nothing -> error $ "no typing for node " ++ show k Just (t,g) -> let (Constrained k' t',g') = (s `subs` t,s `subs'` g) bigs = satc k' g' in map (`subs` t') bigs giveTypes' :: Expr Int -> Substitution -> [(Int, (Constrained, Context))] -> Expr [Simple] giveTypes' e s ts = fmap l' e where (ts',ks) = unzip $ map f ts -- mapping i/simple and mapping simple/(constrains,context) f (i,(t,g)) = let Constrained k' t' = s `subs` t g' = s `subs'` g in ((i,t'),(t',(k',g'))) ks' :: [[(Simple,([Constraint],Context))]] ks' = groupBy ((==) `on` fst) ks -- grouping simple/(constraints,context) h :: [(Simple,([Constraint],Context))] -> (Simple,[Substitution]) h xs@((t',_):_) = (t', grp $ unzip $ map snd xs) h _ = error "unexpected" grp (uk,ug) = let ug' = unionContexts ug uk' = foldl union [] uk in satc uk' ug' ss = map h ks' l i = do t <- lookup i ts' bigs <- lookup t ss return $ map (`subs` t) bigs l' i = case l i of Nothing -> error "giveTypes'" Just r -> r inferTypes :: [Simple] -> Context -> String -> Expr [Simple] inferTypes ts g str = case readExpr str of Left err -> error err Right e -> case infer ts e g of ((Left err,_),_) -> error err ((Right _,_),i) -> giveTypes e (tiSubstitution i) (tiTypings i) inferTypes' :: [Simple] -> Context -> String -> Expr [Simple] inferTypes' ts g str = case readExpr str of Left err -> error err Right e -> case infer ts e g of ((Left err,_),_) -> error err ((Right _,_),i) -> giveTypes' e (tiSubstitution i) (tiTypings i) giveDefaultTypes :: Expr [Simple] -> Expr Simple giveDefaultTypes e = fmap f e where f [] = error "no type" f [t] = t f tt = error $ "TODO implement some default type mechanism: " ++ concatMap showSimple tt ---------------------------------------------------------------------- -- system-ct type-inference specific helper functions ---------------------------------------------------------------------- ambiguous :: [String] -> [Constraint] -> [String] -> Bool ambiguous v1 k v = not (null v') && all (`elem` v1) v' where v' = tv k \\ tv (restr' k v) unresolved :: [Constraint] -> Context -> [Constraint] unresolved [] _ = [] unresolved (Constraint o t : k) g = k' `union` unresolved k g where k' = case satc [Constraint o t] g of [s] -> unresolved (subs s k) g _ -> [Constraint o t] rhoc :: MonadError String m => Type -> [Type] -> m () rhoc _ [] = return () rhoc s ss = do let t = simple s checkClosed s' = unless (null $ tv s') $ throwError $ "the previous type " ++ show s' ++ " is not closed." checkUnification s' = unless (isLeft $ unify t $ simple s') $ throwError $ "the new type " ++ show s ++ " unifies with previous type " ++ show s' ++ "." checkAll s' = checkClosed s' >> checkUnification s' unless (null ss) $ do unless (null $ tv s) $ throwError $ "the new type " ++ show s ++ " is not closed." mapM_ checkAll ss satc :: [Constraint] -> Context -> [Substitution] satc [] _ = [idSubstitution] FIXME , not in the paper satc [Constraint o t] g = mapMaybe f kt where f (ki,ti) = case unify t ti of Right s -> if not . null $ satc (s `subs` ki) g then Just s else Nothing Left _ -> Nothing kt = map (\(Type _ (Constrained k t')) -> (k,t')) (g `types` o) satc (k:ks) g = [comp "satc" sij si | si <- satc [k] g, sij <- satc (si `subs` ks) g] -- [[("a",TyCon "int32"),("b",TyCon "flt32")], -- [("a",TyCon "flt32"),("b",TyCon "int32")]] satcTest1 :: [Substitution] satcTest1 = satc ks g where g = Context [("f", Type [] $ Constrained [] $ int32 `fun` flt32), ("f", Type [] $ Constrained [] $ flt32 `fun` int32), ("x", Type [] $ Constrained [] $ int32), ("x", Type [] $ Constrained [] $ flt32)] ks = [Constraint "f" $ TyVar "a" `fun` TyVar "b", Constraint "x" $ TyVar "a"] -- Given a constrained type and a context, returns the possible simple types. FIXME this should make sure all constraints are satisfied ? kgs :: Constrained -> Context -> [Simple] kgs (Constrained k t) g = map (`subs` t) (satc k g) kgs' :: [(Int,(Constrained,Context))] -> Substitution -> Int -> [Simple] kgs' ty s k = case lookup k ty of Nothing -> error "kgs': Should not happen." Just (k1,g1) -> kgs (s `subs` k1) (s `subs'` g1) ---------------------------------------------------------------------- -- 'duplicate' turns each implicitely overloaded symbols into a -- definition for each of its types. ---------------------------------------------------------------------- duplicate :: [(Int, (Constrained, Context))] -> Substitution -> Expr Int -> Simple -> Expr Simple duplicate ty s_ e t = case e of Id _ x -> Id t x FltLit _ l -> FltLit t l IntLit _ l -> IntLit t l StrLit _ l -> StrLit t l Let _ (Def o e1) e2 -> let e2' = duplicate ty s e2 t kgs_ = kgs' ty s (unExpr e1) in case kgs_ of [] -> error "no type." [t'] -> let e1' = duplicate ty s e1 t' in Let t (Def o e1') e2' ts -> let e1s = map (duplicate ty s e1) ts in duplicateLet t o e1s e2' Let _ _ _ -> error "unhandeled Let expression" Case _ e1 alts -> let kgs_ = kgs' ty s (unExpr e1) in case kgs_ of [] -> error "no type." [t'] -> let alts' = map (duplicateAlt ty s t' t) alts e1' = duplicate ty s e1 t' in Case t e1' alts' _ -> error "more than one type." Fun _ u e1 -> case t of TyApp (TyCon "->" `TyApp` _) t1 -> let e1' = duplicate ty s e1 t1 in Fun t u e1' _ -> error "not a fun type." App _ e1 e2 -> -- discover t2 for which e1 has type t2 -> t let kgs_ = kgs' ty s (unExpr e1) in case kgs_ of [] -> error "no type." ts -> let t2 = domForType t ts e1'= duplicate ty s e1 (t2 `fun` t) e2' = duplicate ty s e2 t2 in App t e1' e2' HasType _ e1 t' -> duplicate ty s e1 t' If _ e1 e2 e3 -> let e1' = duplicate ty s e1 bool e2' = duplicate ty s e2 t e3' = duplicate ty s e3 t in If t e1' e2' e3' where s = case lookup (unExpr e) ty of Nothing -> error "duplicate: Should not happen." Just (Constrained _ t1_, _) -> case unify (s_ `subs` t1_) t of Left err -> error $ "duplicate: Should not happen: " ++ err Right s' -> comp "duplicate" s' s_ duplicateLet :: k -> String -> [Expr k] -> Expr k -> Expr k duplicateLet _ _ [] e2 = e2 duplicateLet t o (e1:es) e2 = Let t (Def o e1) $ duplicateLet t o es e2 duplicateAlt :: [(Int,(Constrained,Context))] -> Substitution -> Simple -> Simple -> Alternative Int -> Alternative Simple duplicateAlt ty s t1 t2 (Alternative p e) = let p' = duplicatePat ty s p t1 e' = duplicate ty s e t2 in Alternative p' e' duplicatePat :: [(Int,(Constrained,Context))] -> Substitution -> Pattern Int -> Simple -> Pattern Simple duplicatePat _ _ (PatVar _ v) t = PatVar t v duplicatePat _ _ (PatCon _ _ c []) t = PatCon t t c [] duplicatePat ty s (PatCon _ k c ps) t@(t' `TyApp` _) = let [ts] = kgs' ty s k ps' = map (uncurry $ duplicatePat ty s) $ zip ps (init $ fargs ts) in PatCon t t' c ps' duplicatePat _ _ p t = error $ "duplicatePat: unexpected " ++ show p ++ ", " ++ showSimple t domForType :: Simple -> [Simple] -> Simple domForType t [] = error $ "no type has the form _ -> " ++ showSimple t ++ "." domForType t ((TyApp (TyCon "->" `TyApp` t2) t'):_) | t == t' = t2 domForType t ((TyApp (TyCon "->" `TyApp` t2) t'):ts) = case unify t t' of Right s -> s `subs` t2 Left _ -> domForType t ts ---------------------------------------------------------------------- -- ---------------------------------------------------------------------- -- Checks if the given type is available. isTypeInScope :: MonadState Inferencer m => Simple -> m Bool isTypeInScope t = do let vs = tv t vs' <- mapM (fmap TyVar . fresh) (tv t) let t' = subs (fromList $ zip vs vs') t ts <- gets tiTypes return $ (not . null $ filter (isRight . unify t') ts) && all (`elem` tc' ts) (tc t) -- Checks if the given value constructor is available. isConstructorInScope :: MonadState Inferencer m => String -> m Bool isConstructorInScope _ = do error "TODO isConstructorInScope" ---------------------------------------------------------------------- -- ---------------------------------------------------------------------- -- Not really pt: - If no type for x in g , then a new type variable is returned -- with a singleton context. - When there is one type , the quantified variables are renamed . pt :: String -> Context -> Inf (Constrained,Context) pt x g = do case g `types` x of [] -> do a <- fmap TyVar (fresh "a") let a' = Constrained [] a ret = (a', Context [(x, Type [] $ a')]) note $ " pt " + + x + + showContext g + + " = " + + ( \(i , j ) - > showConstrained i + + showContext j ) ret return ret [t] -> do c <- refresh t let ret = (c, g) note $ " pt " + + x + + showContext g + + " = " + + ( \(i , j ) - > showConstrained i + + showContext j ) ret return ret ti -> do x' <- fresh "b" let g' = tsubs x x' g t <- lcg ti let ret = (Constrained [Constraint x' t] t, g') note $ " pt " + + x + + showContext g + + " = " + + ( \(i , j ) - > showConstrained i + + showContext j ) ret return ret -- term variable substitution on contexts tsubs :: String -> String -> Context -> Context tsubs x x' gs = Context [if a == x then (x',b) else (a,b) | (a,b) <- ctxAssoc gs] ---------------------------------------------------------------------- -- Type inference ---------------------------------------------------------------------- pp :: Expr Int -> Context -> Inf (Constrained,Context) pp e g = (\(a,b) -> do a' <- substitute a b' <- substitute' b return (a',b')) =<< case e of Id key x -> do (t1, g1) <- pt x g recordType key t1 g1 tell [NId key x g (t1, g1)] return (t1, g1) FltLit key x -> do (t1, g1) <- do c <- refresh $ typed flt32 -- mimic what pt does return (c, g) recordType key t1 g1 TODO not an I d return (t1, g1) IntLit key x -> do (t1, g1) <- do c <- refresh $ typed int32 -- mimic what pt does return (c, g) recordType key t1 g1 TODO not an I d return (t1, g1) StrLit key x -> do (t1, g1) <- do c <- refresh $ typed string -- mimic what pt does return (c, g) recordType key t1 g1 TODO not an I d return (t1, g1) Let key (Def o e1) e2 -> do (c1_, g1_) <- pp e1 g gext <- letExtend g o (close c1_ g) (Constrained k2 t2, g2) <- pp e2 (unionContexts [gext, g1_]) -- Adding g1 is not in the type rules but I believe it should g1 <- substitute' g1_ Constrained k1 _ <- substitute c1_ let c = combine "Let" g (k1 `union` k2) (unionContexts [g1, g2]) t2 case c of Nothing -> do tell [NLet key o e1 e2 g Nothing] throwError $ unlines [ "k1 and k2 cannot be satisfied in g1 and g2", "k1:", showConstraints k1, "k2:", showConstraints k2, "g1:", showContext g1, "g2:", showContext g2 ] Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NLet key o e1 e2 g (Just (ret,g'))] return (ret, g') Let _ _ _ -> do error "Unhandeled Let expression" -- to type -- case e1 of -- pi -> ei 1 . type e1 2 . type pi - > ei -- like lambdas where each variable in the pattern is introduced, -- type the pi like applications, -- type the ei, -- unify e1 and the pi, -- unify the ei -- or : type pi -> ei like a lambda with multiple vars and give it -- a single funtion type ti and unify the ti. Case key e1 alts -> do (c1_, g1_) <- pp e1 g cgs_ <- mapM (ppAlt g) alts Constrained k1_ t1_ <- substitute c1_ cgs' <- mapM (\(a,b) -> do { a' <- substitute a ; b' <- substitute' b ; return (a',b') }) cgs_ a <- fmap TyVar (fresh "l") s <- unify' (zip (repeat $ t1_ `fun` a) $ map (smpl . fst) cgs') compose "Case" s cgs <- mapM (\(a_,b) -> do { a' <- substitute a_ ; b' <- substitute' b ; return (a',b') }) cgs' g1 <- substitute' g1_ k1 <- substitute k1_ ty <- substitute a let uk = foldl (\b (c,_) -> b `union` cstr c) [] cgs ug = Context $ foldl (\ c (_,b) -> c `union` ctxAssoc b) [] cgs let c = combine "Case" g (k1 `union` uk) (unionContexts [g1, ug]) ty case c of Nothing -> do throwError "uk cannot be satisfied in ug" Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' return (ret, g') Fun key u e1 - > do ( Constrained k t , g ' _ ) < - pp e1 g case lookup u $ ctxAssoc g ' _ of Just ( Type [ ] ( Constrained [ ] t ' ) ) - > do let ret = Constrained k ( t ' ` fun ` t ) g ' = Context $ filter ( /= ( u , Type [ ] ( Constrained [ ] t ' ) ) ) ( _ ) recordType key ret g ' tell [ NFun key u e1 g ( ret , ' ) ] return ( ret , ' ) Nothing - > do a < - fresh " i " let ret = Constrained k ( a ` fun ` t ) recordType key ret g ' _ tell [ NFun key u e1 g ( ret , ' _ ) ] return ( ret , ' _ ) _ - > error " unexpected type " Fun key u e1 -> do (Constrained k t, g'_) <- pp e1 g case lookup u $ ctxAssoc g'_ of Just (Type [] (Constrained [] t')) -> do let ret = Constrained k (t' `fun` t) g' = Context $ filter (/= (u,Type [] (Constrained [] t'))) (ctxAssoc g'_) recordType key ret g' tell [NFun key u e1 g (ret,g')] return (ret, g') Nothing -> do a <- fresh "i" let ret = Constrained k (a `fun` t) recordType key ret g'_ tell [NFun key u e1 g (ret,g'_)] return (ret, g'_) _ -> error "unexpected type" -} Fun key u e1 -> do t' <- fmap TyVar (fresh "i") let gext = lamExtend g u (typed t') (Constrained k t, g'_) <- pp e1 gext t'' <- substitute t' let ret = Constrained k (t'' `fun` t) g' = Context $ filter ((/= u) . fst) (ctxAssoc g'_) recordType key ret g' tell [NFun key u e1 g (ret,g')] return (ret, g') App key e1 e2 -> do (c1_, g1_) <- pp e1 g (Constrained k2_ t2, g2_) <- pp e2 g Constrained k1_ t1_ <- substitute c1_ a <- fmap TyVar (fresh "j") -- note $ "_unify " ++ showSimple t1 ++ " " ++ showSimple (t2 `fun` TyVar a) ++ " " ++ show (tv' g) -- let s = case _unify t1 (t2 `fun` TyVar a) (tv' g) of -- FIXME This should use _unify ('Unify' in the paper) but I don't know exactly what it is. s <- unify t1_ (t2 `fun` a) compose "App" s k1 <- substitute k1_ g1 <- substitute' g1_ k2 <- substitute k2_ g2 <- substitute' g2_ ty <- substitute a let c = combine "App2" g (k1 `union` k2) (unionContexts [g1, g2]) ty case c of Nothing -> do tell [NApp key e1 e2 g Nothing] throwError $ unlines [ "k1 and k2 cannot be satisfied in g1 and g2", "k1:", showConstraints k1, "k2:", showConstraints k2, "g1:", showContext g1, "g2:", showContext g2 ] Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NApp key e1 e2 g (Just (ret,g'))] return (ret, g') HasType key e1 t -> do b <- isTypeInScope t when (not b) $ throwError $ "the type " ++ showSimple t ++ " is not in scope." (Constrained k1_ t1_, g1_) <- pp e1 g s <- unify t1_ t compose "HasType" s g1 <- substitute' g1_ k1 <- substitute k1_ let c = combine "HasType" g k1 g1 t case c of Nothing -> do tell [NHasType key e1 t g Nothing] throwError "k1 and k2 cannot be satisfied in g'" Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NHasType key e1 t g (Just (ret,g'))] return (ret, g') If key e1 e2 e3 -> do FIXME constraints do not participate to the global substitution ( same in App and Let ) (c2_, g2_) <- pp e2 g (Constrained k3 t3, g3) <- pp e3 g Constrained k2_ t2_ <- substitute c2_ s <- unify t2_ t3 compose "If" s g2 <- substitute' g2_ k2 <- substitute k2_ let c = combine "If" g (k2 `union` k3) (unionContexts [g2, g3]) t3 case c of Nothing -> do tell [NIf key e1 e2 e3 g Nothing] throwError "k1 and k2 cannot be satisfied in g'" Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NIf key e1 e2 e3 g (Just (ret,g'))] return (ret, g') ppAlt :: Context -> Alternative Int -> Inf (Constrained,Context) ppAlt g (Alternative p e) = do let pvs = map fst $ patVars p pe = patExpr p ts <- replicateM (length pvs) (fmap TyVar (fresh "k")) let gext = foldl lamExtend' g (zip pvs (map typed ts)) (c1_, g1_) <- pp pe gext (Constrained k2 t2, g2) <- pp e gext Constrained k1 t1 <- substitute c1_ g1 <- substitute' g1_ let c = combine "ppAlt" g (k1 `union` k2) (unionContexts [g1, g2]) (t1 `fun` t2) case c of Nothing -> do throwError "k1 and k2 cannot be satisfied in g'" Just (ret, g', sg) -> do compose "combine:" sg let fg' = Context $ filter (not . (`elem` pvs) . fst) (ctxAssoc g') return (ret, fg') letExtend :: MonadError String m => Context -> String -> Type -> m Context letExtend g o t = do rhoc t (g `types` o) `catchError` (\e -> throwError $ "Can't overload " ++ o ++ ": " ++ e) return $ Context $ ctxAssoc g `union` [(o,t)] lamExtend :: Context -> String -> Type -> Context lamExtend g u t = Context $ (u,t) : filter ((/= u) . fst) (ctxAssoc g) lamExtend' :: Context -> (String, Type) -> Context lamExtend' g (u,t) = lamExtend g u t Returns Nothing if k1 and k2 can not be satisfied in g1 and . FIXME the g , ' used in unresolved and tv ' are not correct I think w.r.t . to -- the algorithm in the paper. combine :: String -> Context -> [Constraint] -> Context -> Simple -> Maybe (Constrained, Context, Substitution) combine msg g uk ug ty = do let bigs = satc uk ug if null bigs then Nothing else let sg = intersectSubs bigs --`restrict` (tv uk \\ tv' g) -- not in the algorithm t = sg `subs` ty k = unresolved (sg `subs` uk) ug FIXME is this what tv(t , ) means ? ret = Constrained (k `restr'` (tv t `union` tv' g)) t in Just (ret, ug, sg) ---------------------------------------------------------------------- -- Report ---------------------------------------------------------------------- -- maximal type, minimal context, notes data Report = Report { rCode :: String , rExpr :: Expr Int , rInitialContext :: Context , rType :: Constrained , rContext :: Context , rTypings :: [(Int, (Constrained,Context))] , rSubstitution :: Substitution , rNotes :: [Note] } | NoReport { rCode :: String , rError :: String , rNotes :: [Note] } report :: [Simple] -> Context -> String -> Report report ts g str = case readExpr str of Left err -> NoReport str err [] Right e -> case infer ts e g of ((Left err,n),_) -> NoReport str err n ((Right (t,c),n),s) -> let tgs = tiTypings s sub = tiSubstitution s in Report str e g t c tgs sub n ---------------------------------------------------------------------- -- utility code ---------------------------------------------------------------------- isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft _ = False isRight :: Either a b -> Bool isRight (Left _) = False isRight _ = True
null
https://raw.githubusercontent.com/noteed/mojito/893d1d826d969b0db7bbc8884df3b417db151d14/Language/Mojito/Inference/SystemCT1999/SystemCT1999.hs
haskell
Type Inference for Overloading without Restrictions, Declarations or Annotations Based on Cardelli.hs. -------------------------------------------------------------------- main functions -------------------------------------------------------------------- Infers the typing of an expression in a context. This returns some logs, the state of the inference and either the typing or an error. mapping i/simple and mapping simple/(constrains,context) grouping simple/(constraints,context) -------------------------------------------------------------------- system-ct type-inference specific helper functions -------------------------------------------------------------------- [[("a",TyCon "int32"),("b",TyCon "flt32")], [("a",TyCon "flt32"),("b",TyCon "int32")]] Given a constrained type and a context, returns the possible simple types. -------------------------------------------------------------------- 'duplicate' turns each implicitely overloaded symbols into a definition for each of its types. -------------------------------------------------------------------- discover t2 for which e1 has type t2 -> t -------------------------------------------------------------------- -------------------------------------------------------------------- Checks if the given type is available. Checks if the given value constructor is available. -------------------------------------------------------------------- -------------------------------------------------------------------- Not really pt: with a singleton context. term variable substitution on contexts -------------------------------------------------------------------- Type inference -------------------------------------------------------------------- mimic what pt does mimic what pt does mimic what pt does Adding g1 is not in the type rules but I believe it should to type case e1 of pi -> ei like lambdas where each variable in the pattern is introduced, type the pi like applications, type the ei, unify e1 and the pi, unify the ei or : type pi -> ei like a lambda with multiple vars and give it a single funtion type ti and unify the ti. note $ "_unify " ++ showSimple t1 ++ " " ++ showSimple (t2 `fun` TyVar a) ++ " " ++ show (tv' g) let s = case _unify t1 (t2 `fun` TyVar a) (tv' g) of FIXME This should use _unify ('Unify' in the paper) but I don't know exactly what it is. the algorithm in the paper. `restrict` (tv uk \\ tv' g) -- not in the algorithm -------------------------------------------------------------------- Report -------------------------------------------------------------------- maximal type, minimal context, notes -------------------------------------------------------------------- utility code --------------------------------------------------------------------
# LANGUAGE GeneralizedNewtypeDeriving , FlexibleContexts # SystemCT from Camarao 1999 , module Language.Mojito.Inference.SystemCT1999.SystemCT1999 where import Data.List (groupBy, union, (\\)) import Data.Maybe (mapMaybe) import Data.Function (on) import Control.Monad.Except import Control.Monad.Identity import Control.Monad.State import Control.Monad.Writer import Language.Mojito.Syntax.Expr import Language.Mojito.Syntax.Types import Language.Mojito.Syntax.ExprBuilder import Language.Mojito.Prelude.Types import Language.Mojito.Inference.Context import Language.Mojito.Inference.Substitution import Language.Mojito.Inference.Unification import Language.Mojito.Inference.SystemCT1999.Note import Language.Mojito.Inference.SystemCT1999.Inferencer import Language.Mojito.Inference.SystemCT1999.LCG infer :: [Simple] -> Expr Int -> Context -> ((Either String (Constrained,Context), [Note]), Inferencer) infer ts e g = runIdentity $ runStateT (runWriterT $ runExceptT $ runInf $ pp e g) (inferencer { tiTypes = ts }) TODO use infer + duplicate ' instead infer' :: [Simple] -> Expr Int -> Context -> ((Either String (Expr Simple), [Note]), Inferencer) infer' ts e g = runIdentity $ runStateT (runWriterT $ runExceptT $ runInf $ go) (inferencer { tiTypes = ts }) where go = do (c,g') <- pp e g case kgs c g' of [] -> throwError "no type." [t] -> do ty <- gets tiTypings s <- gets tiSubstitution return $ duplicate ty s e t _ -> throwError "more than one type." TODO delete this function or put it in some helper module readInferedExpr :: [Simple] -> Context -> String -> Expr Simple readInferedExpr ts g str = case readExpr str of Left err -> error err Right e -> case infer' ts e g of ((Left err,_),_) -> error err ((Right e',_),_) -> e' duplicate' :: MonadError String m => Inferencer -> Expr Int -> Constrained -> Context -> m (Expr Simple) duplicate' inf e c g = case kgs c g of [] -> throwError "no type." [t] -> do let ty = tiTypings inf let s = tiSubstitution inf return $ duplicate ty s e t _ -> throwError "more than one type." makeDefaultTypes :: Substitution -> [(Int,(Constrained,Context))] -> [(Int,Simple)] makeDefaultTypes s ts = map f ts where f (k,(t,g)) = let (Constrained k' t',g') = (s `subs` t,s `subs'` g) bigs = satc k' g' in (k, h $ map (`subs` t') bigs) h [] = error "no type" h [t] = t h tt = error $ "TODO implement some default type mechanism: " ++ concatMap showSimple tt giveTypes :: Expr Int -> Substitution -> [(Int,(Constrained,Context))] -> Expr [Simple] giveTypes e s ts = fmap f e where f k = case lookup k ts of Nothing -> error $ "no typing for node " ++ show k Just (t,g) -> let (Constrained k' t',g') = (s `subs` t,s `subs'` g) bigs = satc k' g' in map (`subs` t') bigs giveTypes' :: Expr Int -> Substitution -> [(Int, (Constrained, Context))] -> Expr [Simple] giveTypes' e s ts = fmap l' e where f (i,(t,g)) = let Constrained k' t' = s `subs` t g' = s `subs'` g in ((i,t'),(t',(k',g'))) ks' :: [[(Simple,([Constraint],Context))]] h :: [(Simple,([Constraint],Context))] -> (Simple,[Substitution]) h xs@((t',_):_) = (t', grp $ unzip $ map snd xs) h _ = error "unexpected" grp (uk,ug) = let ug' = unionContexts ug uk' = foldl union [] uk in satc uk' ug' ss = map h ks' l i = do t <- lookup i ts' bigs <- lookup t ss return $ map (`subs` t) bigs l' i = case l i of Nothing -> error "giveTypes'" Just r -> r inferTypes :: [Simple] -> Context -> String -> Expr [Simple] inferTypes ts g str = case readExpr str of Left err -> error err Right e -> case infer ts e g of ((Left err,_),_) -> error err ((Right _,_),i) -> giveTypes e (tiSubstitution i) (tiTypings i) inferTypes' :: [Simple] -> Context -> String -> Expr [Simple] inferTypes' ts g str = case readExpr str of Left err -> error err Right e -> case infer ts e g of ((Left err,_),_) -> error err ((Right _,_),i) -> giveTypes' e (tiSubstitution i) (tiTypings i) giveDefaultTypes :: Expr [Simple] -> Expr Simple giveDefaultTypes e = fmap f e where f [] = error "no type" f [t] = t f tt = error $ "TODO implement some default type mechanism: " ++ concatMap showSimple tt ambiguous :: [String] -> [Constraint] -> [String] -> Bool ambiguous v1 k v = not (null v') && all (`elem` v1) v' where v' = tv k \\ tv (restr' k v) unresolved :: [Constraint] -> Context -> [Constraint] unresolved [] _ = [] unresolved (Constraint o t : k) g = k' `union` unresolved k g where k' = case satc [Constraint o t] g of [s] -> unresolved (subs s k) g _ -> [Constraint o t] rhoc :: MonadError String m => Type -> [Type] -> m () rhoc _ [] = return () rhoc s ss = do let t = simple s checkClosed s' = unless (null $ tv s') $ throwError $ "the previous type " ++ show s' ++ " is not closed." checkUnification s' = unless (isLeft $ unify t $ simple s') $ throwError $ "the new type " ++ show s ++ " unifies with previous type " ++ show s' ++ "." checkAll s' = checkClosed s' >> checkUnification s' unless (null ss) $ do unless (null $ tv s) $ throwError $ "the new type " ++ show s ++ " is not closed." mapM_ checkAll ss satc :: [Constraint] -> Context -> [Substitution] satc [] _ = [idSubstitution] FIXME , not in the paper satc [Constraint o t] g = mapMaybe f kt where f (ki,ti) = case unify t ti of Right s -> if not . null $ satc (s `subs` ki) g then Just s else Nothing Left _ -> Nothing kt = map (\(Type _ (Constrained k t')) -> (k,t')) (g `types` o) satc (k:ks) g = [comp "satc" sij si | si <- satc [k] g, sij <- satc (si `subs` ks) g] satcTest1 :: [Substitution] satcTest1 = satc ks g where g = Context [("f", Type [] $ Constrained [] $ int32 `fun` flt32), ("f", Type [] $ Constrained [] $ flt32 `fun` int32), ("x", Type [] $ Constrained [] $ int32), ("x", Type [] $ Constrained [] $ flt32)] ks = [Constraint "f" $ TyVar "a" `fun` TyVar "b", Constraint "x" $ TyVar "a"] FIXME this should make sure all constraints are satisfied ? kgs :: Constrained -> Context -> [Simple] kgs (Constrained k t) g = map (`subs` t) (satc k g) kgs' :: [(Int,(Constrained,Context))] -> Substitution -> Int -> [Simple] kgs' ty s k = case lookup k ty of Nothing -> error "kgs': Should not happen." Just (k1,g1) -> kgs (s `subs` k1) (s `subs'` g1) duplicate :: [(Int, (Constrained, Context))] -> Substitution -> Expr Int -> Simple -> Expr Simple duplicate ty s_ e t = case e of Id _ x -> Id t x FltLit _ l -> FltLit t l IntLit _ l -> IntLit t l StrLit _ l -> StrLit t l Let _ (Def o e1) e2 -> let e2' = duplicate ty s e2 t kgs_ = kgs' ty s (unExpr e1) in case kgs_ of [] -> error "no type." [t'] -> let e1' = duplicate ty s e1 t' in Let t (Def o e1') e2' ts -> let e1s = map (duplicate ty s e1) ts in duplicateLet t o e1s e2' Let _ _ _ -> error "unhandeled Let expression" Case _ e1 alts -> let kgs_ = kgs' ty s (unExpr e1) in case kgs_ of [] -> error "no type." [t'] -> let alts' = map (duplicateAlt ty s t' t) alts e1' = duplicate ty s e1 t' in Case t e1' alts' _ -> error "more than one type." Fun _ u e1 -> case t of TyApp (TyCon "->" `TyApp` _) t1 -> let e1' = duplicate ty s e1 t1 in Fun t u e1' _ -> error "not a fun type." App _ e1 e2 -> let kgs_ = kgs' ty s (unExpr e1) in case kgs_ of [] -> error "no type." ts -> let t2 = domForType t ts e1'= duplicate ty s e1 (t2 `fun` t) e2' = duplicate ty s e2 t2 in App t e1' e2' HasType _ e1 t' -> duplicate ty s e1 t' If _ e1 e2 e3 -> let e1' = duplicate ty s e1 bool e2' = duplicate ty s e2 t e3' = duplicate ty s e3 t in If t e1' e2' e3' where s = case lookup (unExpr e) ty of Nothing -> error "duplicate: Should not happen." Just (Constrained _ t1_, _) -> case unify (s_ `subs` t1_) t of Left err -> error $ "duplicate: Should not happen: " ++ err Right s' -> comp "duplicate" s' s_ duplicateLet :: k -> String -> [Expr k] -> Expr k -> Expr k duplicateLet _ _ [] e2 = e2 duplicateLet t o (e1:es) e2 = Let t (Def o e1) $ duplicateLet t o es e2 duplicateAlt :: [(Int,(Constrained,Context))] -> Substitution -> Simple -> Simple -> Alternative Int -> Alternative Simple duplicateAlt ty s t1 t2 (Alternative p e) = let p' = duplicatePat ty s p t1 e' = duplicate ty s e t2 in Alternative p' e' duplicatePat :: [(Int,(Constrained,Context))] -> Substitution -> Pattern Int -> Simple -> Pattern Simple duplicatePat _ _ (PatVar _ v) t = PatVar t v duplicatePat _ _ (PatCon _ _ c []) t = PatCon t t c [] duplicatePat ty s (PatCon _ k c ps) t@(t' `TyApp` _) = let [ts] = kgs' ty s k ps' = map (uncurry $ duplicatePat ty s) $ zip ps (init $ fargs ts) in PatCon t t' c ps' duplicatePat _ _ p t = error $ "duplicatePat: unexpected " ++ show p ++ ", " ++ showSimple t domForType :: Simple -> [Simple] -> Simple domForType t [] = error $ "no type has the form _ -> " ++ showSimple t ++ "." domForType t ((TyApp (TyCon "->" `TyApp` t2) t'):_) | t == t' = t2 domForType t ((TyApp (TyCon "->" `TyApp` t2) t'):ts) = case unify t t' of Right s -> s `subs` t2 Left _ -> domForType t ts isTypeInScope :: MonadState Inferencer m => Simple -> m Bool isTypeInScope t = do let vs = tv t vs' <- mapM (fmap TyVar . fresh) (tv t) let t' = subs (fromList $ zip vs vs') t ts <- gets tiTypes return $ (not . null $ filter (isRight . unify t') ts) && all (`elem` tc' ts) (tc t) isConstructorInScope :: MonadState Inferencer m => String -> m Bool isConstructorInScope _ = do error "TODO isConstructorInScope" - If no type for x in g , then a new type variable is returned - When there is one type , the quantified variables are renamed . pt :: String -> Context -> Inf (Constrained,Context) pt x g = do case g `types` x of [] -> do a <- fmap TyVar (fresh "a") let a' = Constrained [] a ret = (a', Context [(x, Type [] $ a')]) note $ " pt " + + x + + showContext g + + " = " + + ( \(i , j ) - > showConstrained i + + showContext j ) ret return ret [t] -> do c <- refresh t let ret = (c, g) note $ " pt " + + x + + showContext g + + " = " + + ( \(i , j ) - > showConstrained i + + showContext j ) ret return ret ti -> do x' <- fresh "b" let g' = tsubs x x' g t <- lcg ti let ret = (Constrained [Constraint x' t] t, g') note $ " pt " + + x + + showContext g + + " = " + + ( \(i , j ) - > showConstrained i + + showContext j ) ret return ret tsubs :: String -> String -> Context -> Context tsubs x x' gs = Context [if a == x then (x',b) else (a,b) | (a,b) <- ctxAssoc gs] pp :: Expr Int -> Context -> Inf (Constrained,Context) pp e g = (\(a,b) -> do a' <- substitute a b' <- substitute' b return (a',b')) =<< case e of Id key x -> do (t1, g1) <- pt x g recordType key t1 g1 tell [NId key x g (t1, g1)] return (t1, g1) FltLit key x -> do return (c, g) recordType key t1 g1 TODO not an I d return (t1, g1) IntLit key x -> do return (c, g) recordType key t1 g1 TODO not an I d return (t1, g1) StrLit key x -> do return (c, g) recordType key t1 g1 TODO not an I d return (t1, g1) Let key (Def o e1) e2 -> do (c1_, g1_) <- pp e1 g gext <- letExtend g o (close c1_ g) g1 <- substitute' g1_ Constrained k1 _ <- substitute c1_ let c = combine "Let" g (k1 `union` k2) (unionContexts [g1, g2]) t2 case c of Nothing -> do tell [NLet key o e1 e2 g Nothing] throwError $ unlines [ "k1 and k2 cannot be satisfied in g1 and g2", "k1:", showConstraints k1, "k2:", showConstraints k2, "g1:", showContext g1, "g2:", showContext g2 ] Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NLet key o e1 e2 g (Just (ret,g'))] return (ret, g') Let _ _ _ -> do error "Unhandeled Let expression" 1 . type e1 2 . type pi - > ei Case key e1 alts -> do (c1_, g1_) <- pp e1 g cgs_ <- mapM (ppAlt g) alts Constrained k1_ t1_ <- substitute c1_ cgs' <- mapM (\(a,b) -> do { a' <- substitute a ; b' <- substitute' b ; return (a',b') }) cgs_ a <- fmap TyVar (fresh "l") s <- unify' (zip (repeat $ t1_ `fun` a) $ map (smpl . fst) cgs') compose "Case" s cgs <- mapM (\(a_,b) -> do { a' <- substitute a_ ; b' <- substitute' b ; return (a',b') }) cgs' g1 <- substitute' g1_ k1 <- substitute k1_ ty <- substitute a let uk = foldl (\b (c,_) -> b `union` cstr c) [] cgs ug = Context $ foldl (\ c (_,b) -> c `union` ctxAssoc b) [] cgs let c = combine "Case" g (k1 `union` uk) (unionContexts [g1, ug]) ty case c of Nothing -> do throwError "uk cannot be satisfied in ug" Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' return (ret, g') Fun key u e1 - > do ( Constrained k t , g ' _ ) < - pp e1 g case lookup u $ ctxAssoc g ' _ of Just ( Type [ ] ( Constrained [ ] t ' ) ) - > do let ret = Constrained k ( t ' ` fun ` t ) g ' = Context $ filter ( /= ( u , Type [ ] ( Constrained [ ] t ' ) ) ) ( _ ) recordType key ret g ' tell [ NFun key u e1 g ( ret , ' ) ] return ( ret , ' ) Nothing - > do a < - fresh " i " let ret = Constrained k ( a ` fun ` t ) recordType key ret g ' _ tell [ NFun key u e1 g ( ret , ' _ ) ] return ( ret , ' _ ) _ - > error " unexpected type " Fun key u e1 -> do (Constrained k t, g'_) <- pp e1 g case lookup u $ ctxAssoc g'_ of Just (Type [] (Constrained [] t')) -> do let ret = Constrained k (t' `fun` t) g' = Context $ filter (/= (u,Type [] (Constrained [] t'))) (ctxAssoc g'_) recordType key ret g' tell [NFun key u e1 g (ret,g')] return (ret, g') Nothing -> do a <- fresh "i" let ret = Constrained k (a `fun` t) recordType key ret g'_ tell [NFun key u e1 g (ret,g'_)] return (ret, g'_) _ -> error "unexpected type" -} Fun key u e1 -> do t' <- fmap TyVar (fresh "i") let gext = lamExtend g u (typed t') (Constrained k t, g'_) <- pp e1 gext t'' <- substitute t' let ret = Constrained k (t'' `fun` t) g' = Context $ filter ((/= u) . fst) (ctxAssoc g'_) recordType key ret g' tell [NFun key u e1 g (ret,g')] return (ret, g') App key e1 e2 -> do (c1_, g1_) <- pp e1 g (Constrained k2_ t2, g2_) <- pp e2 g Constrained k1_ t1_ <- substitute c1_ a <- fmap TyVar (fresh "j") s <- unify t1_ (t2 `fun` a) compose "App" s k1 <- substitute k1_ g1 <- substitute' g1_ k2 <- substitute k2_ g2 <- substitute' g2_ ty <- substitute a let c = combine "App2" g (k1 `union` k2) (unionContexts [g1, g2]) ty case c of Nothing -> do tell [NApp key e1 e2 g Nothing] throwError $ unlines [ "k1 and k2 cannot be satisfied in g1 and g2", "k1:", showConstraints k1, "k2:", showConstraints k2, "g1:", showContext g1, "g2:", showContext g2 ] Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NApp key e1 e2 g (Just (ret,g'))] return (ret, g') HasType key e1 t -> do b <- isTypeInScope t when (not b) $ throwError $ "the type " ++ showSimple t ++ " is not in scope." (Constrained k1_ t1_, g1_) <- pp e1 g s <- unify t1_ t compose "HasType" s g1 <- substitute' g1_ k1 <- substitute k1_ let c = combine "HasType" g k1 g1 t case c of Nothing -> do tell [NHasType key e1 t g Nothing] throwError "k1 and k2 cannot be satisfied in g'" Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NHasType key e1 t g (Just (ret,g'))] return (ret, g') If key e1 e2 e3 -> do FIXME constraints do not participate to the global substitution ( same in App and Let ) (c2_, g2_) <- pp e2 g (Constrained k3 t3, g3) <- pp e3 g Constrained k2_ t2_ <- substitute c2_ s <- unify t2_ t3 compose "If" s g2 <- substitute' g2_ k2 <- substitute k2_ let c = combine "If" g (k2 `union` k3) (unionContexts [g2, g3]) t3 case c of Nothing -> do tell [NIf key e1 e2 e3 g Nothing] throwError "k1 and k2 cannot be satisfied in g'" Just (ret, g', sg) -> do compose "combine:" sg recordType key ret g' tell [NIf key e1 e2 e3 g (Just (ret,g'))] return (ret, g') ppAlt :: Context -> Alternative Int -> Inf (Constrained,Context) ppAlt g (Alternative p e) = do let pvs = map fst $ patVars p pe = patExpr p ts <- replicateM (length pvs) (fmap TyVar (fresh "k")) let gext = foldl lamExtend' g (zip pvs (map typed ts)) (c1_, g1_) <- pp pe gext (Constrained k2 t2, g2) <- pp e gext Constrained k1 t1 <- substitute c1_ g1 <- substitute' g1_ let c = combine "ppAlt" g (k1 `union` k2) (unionContexts [g1, g2]) (t1 `fun` t2) case c of Nothing -> do throwError "k1 and k2 cannot be satisfied in g'" Just (ret, g', sg) -> do compose "combine:" sg let fg' = Context $ filter (not . (`elem` pvs) . fst) (ctxAssoc g') return (ret, fg') letExtend :: MonadError String m => Context -> String -> Type -> m Context letExtend g o t = do rhoc t (g `types` o) `catchError` (\e -> throwError $ "Can't overload " ++ o ++ ": " ++ e) return $ Context $ ctxAssoc g `union` [(o,t)] lamExtend :: Context -> String -> Type -> Context lamExtend g u t = Context $ (u,t) : filter ((/= u) . fst) (ctxAssoc g) lamExtend' :: Context -> (String, Type) -> Context lamExtend' g (u,t) = lamExtend g u t Returns Nothing if k1 and k2 can not be satisfied in g1 and . FIXME the g , ' used in unresolved and tv ' are not correct I think w.r.t . to combine :: String -> Context -> [Constraint] -> Context -> Simple -> Maybe (Constrained, Context, Substitution) combine msg g uk ug ty = do let bigs = satc uk ug if null bigs then Nothing else t = sg `subs` ty k = unresolved (sg `subs` uk) ug FIXME is this what tv(t , ) means ? ret = Constrained (k `restr'` (tv t `union` tv' g)) t in Just (ret, ug, sg) data Report = Report { rCode :: String , rExpr :: Expr Int , rInitialContext :: Context , rType :: Constrained , rContext :: Context , rTypings :: [(Int, (Constrained,Context))] , rSubstitution :: Substitution , rNotes :: [Note] } | NoReport { rCode :: String , rError :: String , rNotes :: [Note] } report :: [Simple] -> Context -> String -> Report report ts g str = case readExpr str of Left err -> NoReport str err [] Right e -> case infer ts e g of ((Left err,n),_) -> NoReport str err n ((Right (t,c),n),s) -> let tgs = tiTypings s sub = tiSubstitution s in Report str e g t c tgs sub n isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft _ = False isRight :: Either a b -> Bool isRight (Left _) = False isRight _ = True
da7c7728f4f7baf6a0be5c5405eaca3e85b59ff9c6ad59730bb3c39849b15d19
WorksHub/client
views.cljs
(ns wh.views (:require ["smoothscroll-polyfill"] [clojure.walk :as walk] [reagent.core :as r] [wh.common.subs] [wh.components.banner :as banner] [wh.components.error.subs :as error-subs] [wh.components.error.views :refer [global-status-box]] [wh.components.footer :as footer] [wh.components.icons :refer [icon]] [wh.components.loader :refer [loader]] [wh.components.navbar.navbar :as navbar] [wh.logged-in.apply.views :as apply-views] [wh.pages.router :refer [current-page]] [wh.subs :as subs :refer [<sub]] [wh.user.views :as user-views])) (defn version-mismatch [] [:div.version-mismatch [icon "codi"] [:h1 "Sorry to interrupt you..."] [:p "...but we've just released a new version of our platform and we need you to reload the page so you can use it."] [:button.button.button--medium {:on-click #(js/window.location.reload true)} "Reload"]]) (defn main-panel [] (let [page (<sub [:wh.pages.core/page]) user-type (<sub [:user/type]) ;; specify links on the menu that should be restricted restricted-links (when-not (<sub [:company/has-permission? :can_see_applications]) #{:company-applications}) params (<sub [:wh/page-params]) query-params (walk/keywordize-keys (<sub [:wh/query-params])) logged-in? (<sub [:user/logged-in?]) vertical (<sub [:wh/vertical])] (if (<sub [::subs/version-mismatch]) [version-mismatch] [:div.main-panel [user-views/consent-popup] [apply-views/overlay-apply] [banner/banner {:page page :logged-in? logged-in?}] [navbar/top-bar {:env (<sub [:wh/env]) :vertical vertical :logged-in? logged-in? :params params :query-params query-params :page page :user-type user-type :restricted-links restricted-links}] [:div.page-container (when (<sub [::error-subs/message]) [global-status-box]) (if (and (not (<sub [::subs/ssr-page?])) (<sub [::subs/loading?])) [:div.main-wrapper [:div.loader-wrapper [loader]]] [current-page]) (when (<sub [::subs/show-footer?]) [footer/footer vertical logged-in?])]]))) (defonce remove-all-bsl-locks-when-app-loads (js/disableNoScroll))
null
https://raw.githubusercontent.com/WorksHub/client/bfee3d5aced3ceb9d4f59a8fa7a4ac4226cd1726/client/src/wh/views.cljs
clojure
specify links on the menu that should be restricted
(ns wh.views (:require ["smoothscroll-polyfill"] [clojure.walk :as walk] [reagent.core :as r] [wh.common.subs] [wh.components.banner :as banner] [wh.components.error.subs :as error-subs] [wh.components.error.views :refer [global-status-box]] [wh.components.footer :as footer] [wh.components.icons :refer [icon]] [wh.components.loader :refer [loader]] [wh.components.navbar.navbar :as navbar] [wh.logged-in.apply.views :as apply-views] [wh.pages.router :refer [current-page]] [wh.subs :as subs :refer [<sub]] [wh.user.views :as user-views])) (defn version-mismatch [] [:div.version-mismatch [icon "codi"] [:h1 "Sorry to interrupt you..."] [:p "...but we've just released a new version of our platform and we need you to reload the page so you can use it."] [:button.button.button--medium {:on-click #(js/window.location.reload true)} "Reload"]]) (defn main-panel [] (let [page (<sub [:wh.pages.core/page]) user-type (<sub [:user/type]) restricted-links (when-not (<sub [:company/has-permission? :can_see_applications]) #{:company-applications}) params (<sub [:wh/page-params]) query-params (walk/keywordize-keys (<sub [:wh/query-params])) logged-in? (<sub [:user/logged-in?]) vertical (<sub [:wh/vertical])] (if (<sub [::subs/version-mismatch]) [version-mismatch] [:div.main-panel [user-views/consent-popup] [apply-views/overlay-apply] [banner/banner {:page page :logged-in? logged-in?}] [navbar/top-bar {:env (<sub [:wh/env]) :vertical vertical :logged-in? logged-in? :params params :query-params query-params :page page :user-type user-type :restricted-links restricted-links}] [:div.page-container (when (<sub [::error-subs/message]) [global-status-box]) (if (and (not (<sub [::subs/ssr-page?])) (<sub [::subs/loading?])) [:div.main-wrapper [:div.loader-wrapper [loader]]] [current-page]) (when (<sub [::subs/show-footer?]) [footer/footer vertical logged-in?])]]))) (defonce remove-all-bsl-locks-when-app-loads (js/disableNoScroll))
faff5e98a0b09d5f8ec6c1a0bb639bb4d07f48796a79e8bbeee34d17016b029f
janestreet/core_kernel
color_256.mli
* Support for 256 - color handling on terminals / consoles . Note that the functions [ of_rgb6_exn ] and [ of_rgb6 ] return values within the 6x6x6 color - cube space , even though equivalent duplicates exist in the first 16 and last 24 colors ( a " best - fit - equivalent " function could be added some day , if there ever becomes a requirement for it -- see note 2 below ) . NOTE 1 : the color - cube is not linear in terms of RGB levels , but is " shifted " towards brighter values ( as opposed to a logarithmic or other mapping ) . Visually , the " rgb6 " values 0 to 5 ( used in [ of_rgb6_exn ] and encoded in the 256 - color palette values ) map into RGB levels as follows : { v Cube - val : 0 1 2 3 4 5 v + -----------+----+----+----+----+ RGB : 0 95 135 175 215 255 v } The floating - point values used in [ of_rgb ] are { e not } weighted in the same way , but are rounded to the nearest cube - value -- a value of 0.5 ( 50 % or 127.5/255 ) would result in a color - cube value of 2 , for example . Any level less than 0.187 ( approx . ) maps to 0 ( black ) and greater than 0.921 to 5 ( white ) . NOTE 2 : is is { e not } recommended to use the 256 - color palette for representing the 16 ( 8 * 2 ) ' primary ' colors . The standard [ ` Black ] , [ ` Blue ] , etc . attributes are recommended for these . functions [of_rgb6_exn] and [of_rgb6] return values within the 6x6x6 color-cube space, even though equivalent duplicates exist in the first 16 and last 24 colors (a "best-fit-equivalent" function could be added some day, if there ever becomes a requirement for it -- see note 2 below). NOTE 1: the color-cube is not linear in terms of RGB levels, but is "shifted" towards brighter values (as opposed to a logarithmic or other mapping). Visually, the "rgb6" values 0 to 5 (used in [of_rgb6_exn] and encoded in the 256-color palette values) map into RGB levels as follows: {v Cube-val: 0 1 2 3 4 5 v +-----------+----+----+----+----+ RGB: 0 95 135 175 215 255 v} The floating-point values used in [of_rgb] are {e not} weighted in the same way, but are rounded to the nearest cube-value -- a value of 0.5 (50% or 127.5/255) would result in a color-cube value of 2, for example. Any level less than 0.187 (approx.) maps to 0 (black) and greater than 0.921 to 5 (white). NOTE 2: is is {e not} recommended to use the 256-color palette for representing the 16 (8 * 2) 'primary' colors. The standard [`Black], [`Blue], etc. attributes are recommended for these. *) type t [@@deriving sexp_of, compare, hash, equal] val to_int : t -> int val of_int_exn : int -> t * Takes an RGB triple with values in the range [ 0,5 ] ( inclusive ) and returns the appropriate 256 - color palette value . Will throw an exception if any of the inputs are out - of - range . Note that the input values are weighted as described above . the appropriate 256-color palette value. Will throw an exception if any of the inputs are out-of-range. Note that the input values are weighted as described above. *) val of_rgb6_exn : int * int * int -> t * Takes an RGB triple with float values in the closed ( inclusive ) interval [ 0,1 ] and returns the nearest ( rounded ) 256 - color palette value . Out - of - bound values are clamped to the range . The inputs are { e not } weighted , unlike [ of_rgb6_exn ] as described above . [0,1] and returns the nearest (rounded) 256-color palette value. Out-of-bound values are clamped to the range. The inputs are {e not} weighted, unlike [of_rgb6_exn] as described above. *) val of_rgb : float * float * float -> t * Takes an RGB triple with integer values in the closed ( inclusive ) range [ 0,255 ] and returns the nearest ( rounded ) 256 - color palette color - cube value . Out - of - bound values are clamped to the range . The inputs are { e not } weighted , unlike [ of_rgb6_exn ] as described above . [0,255] and returns the nearest (rounded) 256-color palette color-cube value. Out-of-bound values are clamped to the range. The inputs are {e not} weighted, unlike [of_rgb6_exn] as described above. *) val of_rgb_8bit : int * int * int -> t * Takes an RGB triple with integer values in the closed ( inclusive ) range [ 0,1000 ] and returns the nearest ( rounded ) 256 - color palette color - cube value . Out - of - bound values are clamped to the range . The inputs are { e not } weighted , unlike [ of_rgb6_exn ] as described above . [0,1000] and returns the nearest (rounded) 256-color palette color-cube value. Out-of-bound values are clamped to the range. The inputs are {e not} weighted, unlike [of_rgb6_exn] as described above. *) val of_rgb_int1k : int * int * int -> t * Takes a grayscale level from [ 0 - 23 ] ( inclusive , not - black - to - not - white ) and returns the appropriate 256 - color palette value . Will throw an exception if the input value is out - of - range . and returns the appropriate 256-color palette value. Will throw an exception if the input value is out-of-range. *) val of_gray24_exn : int -> t * Takes a color palette value and returns , for color - cube and grayscale palette values , an approximated [ ` RGB ] triple with each component in the range [ 0,1 ] ; for the first 16 values , [ ` Primary ] followed by the specific palette index is returned , as these are not consistently defined . palette values, an approximated [`RGB] triple with each component in the range [0,1]; for the first 16 values, [`Primary] followed by the specific palette index is returned, as these are not consistently defined. *) val to_rgb : t -> [> `Primary of int | `RGB of float * float * float ] * Takes a color palette value and returns a hex - encoded RGB 24 - bit triplet , with a leading ' # ' . I.e. " # 000000 " through " # ffffff " . The values returned for the first 16 ( primary ) colors follow the Windows Console scheme , as documented here : . with a leading '#'. I.e. "#000000" through "#ffffff". The values returned for the first 16 (primary) colors follow the Windows Console scheme, as documented here: . *) val to_rgb_hex24 : t -> string * Takes a color palette value and returns an approximate luminance value in the closed interval [ 0,1 ] . in the closed interval [0,1]. *) val to_luma : t -> float * Takes a color palette value and returns a triple of RGB integers in the closed interval [ 0,255 ] . the closed interval [0,255]. *) val to_rgb_8bit : t -> int * int * int (** Takes a color palette value and returns a triple of RGB integers in the closed interval [0,1000]. *) val to_rgb_int1k : t -> int * int * int * Takes a color palette value and returns a triple of RGB integers in the closed interval [ 0,5 ] . For color - cube palette values , this simply un - does [ of_rgb6_exn ] . For others , it will return the closest matching value in the color - cube . the closed interval [0,5]. For color-cube palette values, this simply un-does [of_rgb6_exn]. For others, it will return the closest matching value in the color-cube. *) val to_rgb6 : t -> int * int * int module Stable : sig module V1 : sig type nonrec t = t [@@deriving sexp, compare, hash, equal] end end
null
https://raw.githubusercontent.com/janestreet/core_kernel/b4746470fccd26e4bb7b021d25c6d54faa95a656/ansi_kernel/src/color_256.mli
ocaml
* Takes a color palette value and returns a triple of RGB integers in the closed interval [0,1000].
* Support for 256 - color handling on terminals / consoles . Note that the functions [ of_rgb6_exn ] and [ of_rgb6 ] return values within the 6x6x6 color - cube space , even though equivalent duplicates exist in the first 16 and last 24 colors ( a " best - fit - equivalent " function could be added some day , if there ever becomes a requirement for it -- see note 2 below ) . NOTE 1 : the color - cube is not linear in terms of RGB levels , but is " shifted " towards brighter values ( as opposed to a logarithmic or other mapping ) . Visually , the " rgb6 " values 0 to 5 ( used in [ of_rgb6_exn ] and encoded in the 256 - color palette values ) map into RGB levels as follows : { v Cube - val : 0 1 2 3 4 5 v + -----------+----+----+----+----+ RGB : 0 95 135 175 215 255 v } The floating - point values used in [ of_rgb ] are { e not } weighted in the same way , but are rounded to the nearest cube - value -- a value of 0.5 ( 50 % or 127.5/255 ) would result in a color - cube value of 2 , for example . Any level less than 0.187 ( approx . ) maps to 0 ( black ) and greater than 0.921 to 5 ( white ) . NOTE 2 : is is { e not } recommended to use the 256 - color palette for representing the 16 ( 8 * 2 ) ' primary ' colors . The standard [ ` Black ] , [ ` Blue ] , etc . attributes are recommended for these . functions [of_rgb6_exn] and [of_rgb6] return values within the 6x6x6 color-cube space, even though equivalent duplicates exist in the first 16 and last 24 colors (a "best-fit-equivalent" function could be added some day, if there ever becomes a requirement for it -- see note 2 below). NOTE 1: the color-cube is not linear in terms of RGB levels, but is "shifted" towards brighter values (as opposed to a logarithmic or other mapping). Visually, the "rgb6" values 0 to 5 (used in [of_rgb6_exn] and encoded in the 256-color palette values) map into RGB levels as follows: {v Cube-val: 0 1 2 3 4 5 v +-----------+----+----+----+----+ RGB: 0 95 135 175 215 255 v} The floating-point values used in [of_rgb] are {e not} weighted in the same way, but are rounded to the nearest cube-value -- a value of 0.5 (50% or 127.5/255) would result in a color-cube value of 2, for example. Any level less than 0.187 (approx.) maps to 0 (black) and greater than 0.921 to 5 (white). NOTE 2: is is {e not} recommended to use the 256-color palette for representing the 16 (8 * 2) 'primary' colors. The standard [`Black], [`Blue], etc. attributes are recommended for these. *) type t [@@deriving sexp_of, compare, hash, equal] val to_int : t -> int val of_int_exn : int -> t * Takes an RGB triple with values in the range [ 0,5 ] ( inclusive ) and returns the appropriate 256 - color palette value . Will throw an exception if any of the inputs are out - of - range . Note that the input values are weighted as described above . the appropriate 256-color palette value. Will throw an exception if any of the inputs are out-of-range. Note that the input values are weighted as described above. *) val of_rgb6_exn : int * int * int -> t * Takes an RGB triple with float values in the closed ( inclusive ) interval [ 0,1 ] and returns the nearest ( rounded ) 256 - color palette value . Out - of - bound values are clamped to the range . The inputs are { e not } weighted , unlike [ of_rgb6_exn ] as described above . [0,1] and returns the nearest (rounded) 256-color palette value. Out-of-bound values are clamped to the range. The inputs are {e not} weighted, unlike [of_rgb6_exn] as described above. *) val of_rgb : float * float * float -> t * Takes an RGB triple with integer values in the closed ( inclusive ) range [ 0,255 ] and returns the nearest ( rounded ) 256 - color palette color - cube value . Out - of - bound values are clamped to the range . The inputs are { e not } weighted , unlike [ of_rgb6_exn ] as described above . [0,255] and returns the nearest (rounded) 256-color palette color-cube value. Out-of-bound values are clamped to the range. The inputs are {e not} weighted, unlike [of_rgb6_exn] as described above. *) val of_rgb_8bit : int * int * int -> t * Takes an RGB triple with integer values in the closed ( inclusive ) range [ 0,1000 ] and returns the nearest ( rounded ) 256 - color palette color - cube value . Out - of - bound values are clamped to the range . The inputs are { e not } weighted , unlike [ of_rgb6_exn ] as described above . [0,1000] and returns the nearest (rounded) 256-color palette color-cube value. Out-of-bound values are clamped to the range. The inputs are {e not} weighted, unlike [of_rgb6_exn] as described above. *) val of_rgb_int1k : int * int * int -> t * Takes a grayscale level from [ 0 - 23 ] ( inclusive , not - black - to - not - white ) and returns the appropriate 256 - color palette value . Will throw an exception if the input value is out - of - range . and returns the appropriate 256-color palette value. Will throw an exception if the input value is out-of-range. *) val of_gray24_exn : int -> t * Takes a color palette value and returns , for color - cube and grayscale palette values , an approximated [ ` RGB ] triple with each component in the range [ 0,1 ] ; for the first 16 values , [ ` Primary ] followed by the specific palette index is returned , as these are not consistently defined . palette values, an approximated [`RGB] triple with each component in the range [0,1]; for the first 16 values, [`Primary] followed by the specific palette index is returned, as these are not consistently defined. *) val to_rgb : t -> [> `Primary of int | `RGB of float * float * float ] * Takes a color palette value and returns a hex - encoded RGB 24 - bit triplet , with a leading ' # ' . I.e. " # 000000 " through " # ffffff " . The values returned for the first 16 ( primary ) colors follow the Windows Console scheme , as documented here : . with a leading '#'. I.e. "#000000" through "#ffffff". The values returned for the first 16 (primary) colors follow the Windows Console scheme, as documented here: . *) val to_rgb_hex24 : t -> string * Takes a color palette value and returns an approximate luminance value in the closed interval [ 0,1 ] . in the closed interval [0,1]. *) val to_luma : t -> float * Takes a color palette value and returns a triple of RGB integers in the closed interval [ 0,255 ] . the closed interval [0,255]. *) val to_rgb_8bit : t -> int * int * int val to_rgb_int1k : t -> int * int * int * Takes a color palette value and returns a triple of RGB integers in the closed interval [ 0,5 ] . For color - cube palette values , this simply un - does [ of_rgb6_exn ] . For others , it will return the closest matching value in the color - cube . the closed interval [0,5]. For color-cube palette values, this simply un-does [of_rgb6_exn]. For others, it will return the closest matching value in the color-cube. *) val to_rgb6 : t -> int * int * int module Stable : sig module V1 : sig type nonrec t = t [@@deriving sexp, compare, hash, equal] end end
8909a1983ddfb83e24612a97efbaf6bbddcc12ad18ac594696e67ffed2a6f32c
mentat-collective/emmy
permute_test.cljc
#_"SPDX-License-Identifier: GPL-3.0" (ns emmy.util.permute-test (:require [clojure.test :refer [is deftest testing]] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [emmy.generic :as g] [emmy.util.permute :as p])) (deftest misc-tests (testing "permutations" (is (= '((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)) (p/permutations [1 2 3]))) (is (= [[]] (p/permutations []))) (checking "permutation laws" 100 [xs (gen/vector gen/keyword 3)] (let [perms (p/permutations xs) elems (distinct (map set perms))] (is (every? #(= (count %) 3) perms) "every permutation has the same number of elements.") (is (= 1 (count elems)) "They all have the same enties..") (is (= (set xs) (first elems)) "equal to the original.")))) (testing "combinations" (checking "empty input always returns empty output" 100 [p (gen/fmap inc gen/nat)] (is (= [] (p/combinations [] p)))) (checking "p == 0 always returns a singleton with the empty set." 100 [xs (gen/vector gen/any-equatable)] (is (= [[]] (p/combinations xs 0)))) (is (= '((a b c) (a b d) (a b e) (a c d) (a c e) (a d e) (b c d) (b c e) (b d e) (c d e)) (p/combinations '[a b c d e] 3)))) (testing "cartesian-product" (is (= '((a c) (b c) (a d) (b d)) (p/cartesian-product [['a 'b] ['c 'd]]))) (is (= '(()) (p/cartesian-product [])) "base case.")) (testing "list-interchanges, permutation-sequence" (let [xs ['a 'b 'c 'd 'e] changes (map #(p/list-interchanges % xs) (p/permutation-sequence xs))] (is (every? true? (for [[a b] (partition 2 changes)] (= 1 (g/abs (- b a))))) "p/permutation-sequence generates a sequence of permutations that each differ from the previous by a single transposition."))) (testing "permutation-parity" (is (= 1 (p/permutation-parity [1 2 3] [1 2 3])) "Same elements returns 1 (even parity)") (is (= 0 (p/permutation-parity [1 2 3] [1 2 3 3])) "Same elements but different length gives 0.") (let [xs ['a 'b 'c 'd 'e 'f] parities (map #(p/permutation-parity % xs) (p/permutation-sequence xs))] (is (= (take (count parities) (cycle [1 -1])) parities) "parity cycles between 1 and -1."))) (checking "permutation-parity laws" 100 [xs (gen/shuffle (range 6))] (let [sorted (sort xs)] (is (= 1 (p/permutation-parity sorted)) "sorted lists have parity == 1") (let [changes (p/permutation-interchanges xs)] (is (= (if (odd? changes) -1 1) (p/permutation-parity xs)) "given odd interchanges, permutation-parity returns -1, else 1. Never 0 in the single-arg case.")))) (checking "permutation-interchanges" 100 [xs (gen/vector gen/nat 6)] (is (= (p/list-interchanges xs (sort xs)) (p/permutation-interchanges xs)))) (testing "permute unit" (is (= [] (p/permute [] []))) (is (= [0 1 3 2] (p/permute [3 0 1 2] [1 3 2 0])))) (checking "permute" 100 [xs (gen/shuffle (range 6))] (let [sorted (sort xs)] (is (= xs (p/permute xs sorted)) "applying a permutation to a sorted list returns the permutation.") (is (= xs (p/permute sorted xs)) "applying the sorted list to the permutation acts as id."))) (testing "sort-and-permute" (is (= [[0 2 0 0 1 2 0 0] [0 0 0 0 0 1 2 2] [0 0 0 0 0 1 2 2] [0 2 0 0 1 2 0 0]] (p/sort-and-permute [0 2 0 0 1 2 0 0] < (fn [unsorted sorted permuter unpermuter] [unsorted sorted (permuter unsorted) (unpermuter sorted)]))))) (testing "subpermute" (is (= ['a 'e 'd 'b 'c] (p/subpermute {1 4, 4 2, 2 3, 3 1} '[a b c d e])))) (checking "number-of-permutations" 100 [xs (gen/let [n (gen/choose 0 6)] (gen/vector gen/nat n))] (is (= (p/number-of-permutations (count xs)) (count (p/permutations xs))))) (checking "number-of-combinations" 100 [[xs k] (gen/let [n (gen/choose 1 6)] (gen/tuple (gen/vector gen/nat n) (gen/choose 0 n)))] (is (= (p/number-of-combinations (count xs) k) (count (p/combinations xs k))))) (checking "multichoose" 100 [n gen/nat k (gen/fmap inc gen/nat)] (is (= (p/multichoose n k) (p/number-of-combinations (+ n k -1) k)) "Definition from "))) (deftest permutation-test (testing "permutation-sequence" (is (thrown? #?(:clj Exception :cljs js/Error) (p/permutation-sequence 0))) (is (= '[[a]] (p/permutation-sequence '[a]))) (is (= '[[a b] [b a]] (p/permutation-sequence '(a b)))) (is (= [[0 1 2] [0 2 1] [2 0 1] [2 1 0] [1 2 0] [1 0 2]] (p/permutation-sequence [0 1 2]))) (is (= [[[0 1 2] 1] [[0 2 1] -1] [[2 0 1] 1] [[2 1 0] -1] [[1 2 0] 1] [[1 0 2] -1]] (map vector (p/permutation-sequence (range 3)) (cycle [1 -1])))) (is (= [[0 1 2 3] [0 1 3 2] [0 3 1 2] [3 0 1 2] [3 0 2 1] [0 3 2 1] [0 2 3 1] [0 2 1 3] [2 0 1 3] [2 0 3 1] [2 3 0 1] [3 2 0 1] [3 2 1 0] [2 3 1 0] [2 1 3 0] [2 1 0 3] [1 2 0 3] [1 2 3 0] [1 3 2 0] [3 1 2 0] [3 1 0 2] [1 3 0 2] [1 0 3 2] [1 0 2 3]] (p/permutation-sequence (range 4))))))
null
https://raw.githubusercontent.com/mentat-collective/emmy/535b237a8e3fd7067b9c0ade8b2a4b3419f9f132/test/emmy/util/permute_test.cljc
clojure
#_"SPDX-License-Identifier: GPL-3.0" (ns emmy.util.permute-test (:require [clojure.test :refer [is deftest testing]] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [emmy.generic :as g] [emmy.util.permute :as p])) (deftest misc-tests (testing "permutations" (is (= '((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)) (p/permutations [1 2 3]))) (is (= [[]] (p/permutations []))) (checking "permutation laws" 100 [xs (gen/vector gen/keyword 3)] (let [perms (p/permutations xs) elems (distinct (map set perms))] (is (every? #(= (count %) 3) perms) "every permutation has the same number of elements.") (is (= 1 (count elems)) "They all have the same enties..") (is (= (set xs) (first elems)) "equal to the original.")))) (testing "combinations" (checking "empty input always returns empty output" 100 [p (gen/fmap inc gen/nat)] (is (= [] (p/combinations [] p)))) (checking "p == 0 always returns a singleton with the empty set." 100 [xs (gen/vector gen/any-equatable)] (is (= [[]] (p/combinations xs 0)))) (is (= '((a b c) (a b d) (a b e) (a c d) (a c e) (a d e) (b c d) (b c e) (b d e) (c d e)) (p/combinations '[a b c d e] 3)))) (testing "cartesian-product" (is (= '((a c) (b c) (a d) (b d)) (p/cartesian-product [['a 'b] ['c 'd]]))) (is (= '(()) (p/cartesian-product [])) "base case.")) (testing "list-interchanges, permutation-sequence" (let [xs ['a 'b 'c 'd 'e] changes (map #(p/list-interchanges % xs) (p/permutation-sequence xs))] (is (every? true? (for [[a b] (partition 2 changes)] (= 1 (g/abs (- b a))))) "p/permutation-sequence generates a sequence of permutations that each differ from the previous by a single transposition."))) (testing "permutation-parity" (is (= 1 (p/permutation-parity [1 2 3] [1 2 3])) "Same elements returns 1 (even parity)") (is (= 0 (p/permutation-parity [1 2 3] [1 2 3 3])) "Same elements but different length gives 0.") (let [xs ['a 'b 'c 'd 'e 'f] parities (map #(p/permutation-parity % xs) (p/permutation-sequence xs))] (is (= (take (count parities) (cycle [1 -1])) parities) "parity cycles between 1 and -1."))) (checking "permutation-parity laws" 100 [xs (gen/shuffle (range 6))] (let [sorted (sort xs)] (is (= 1 (p/permutation-parity sorted)) "sorted lists have parity == 1") (let [changes (p/permutation-interchanges xs)] (is (= (if (odd? changes) -1 1) (p/permutation-parity xs)) "given odd interchanges, permutation-parity returns -1, else 1. Never 0 in the single-arg case.")))) (checking "permutation-interchanges" 100 [xs (gen/vector gen/nat 6)] (is (= (p/list-interchanges xs (sort xs)) (p/permutation-interchanges xs)))) (testing "permute unit" (is (= [] (p/permute [] []))) (is (= [0 1 3 2] (p/permute [3 0 1 2] [1 3 2 0])))) (checking "permute" 100 [xs (gen/shuffle (range 6))] (let [sorted (sort xs)] (is (= xs (p/permute xs sorted)) "applying a permutation to a sorted list returns the permutation.") (is (= xs (p/permute sorted xs)) "applying the sorted list to the permutation acts as id."))) (testing "sort-and-permute" (is (= [[0 2 0 0 1 2 0 0] [0 0 0 0 0 1 2 2] [0 0 0 0 0 1 2 2] [0 2 0 0 1 2 0 0]] (p/sort-and-permute [0 2 0 0 1 2 0 0] < (fn [unsorted sorted permuter unpermuter] [unsorted sorted (permuter unsorted) (unpermuter sorted)]))))) (testing "subpermute" (is (= ['a 'e 'd 'b 'c] (p/subpermute {1 4, 4 2, 2 3, 3 1} '[a b c d e])))) (checking "number-of-permutations" 100 [xs (gen/let [n (gen/choose 0 6)] (gen/vector gen/nat n))] (is (= (p/number-of-permutations (count xs)) (count (p/permutations xs))))) (checking "number-of-combinations" 100 [[xs k] (gen/let [n (gen/choose 1 6)] (gen/tuple (gen/vector gen/nat n) (gen/choose 0 n)))] (is (= (p/number-of-combinations (count xs) k) (count (p/combinations xs k))))) (checking "multichoose" 100 [n gen/nat k (gen/fmap inc gen/nat)] (is (= (p/multichoose n k) (p/number-of-combinations (+ n k -1) k)) "Definition from "))) (deftest permutation-test (testing "permutation-sequence" (is (thrown? #?(:clj Exception :cljs js/Error) (p/permutation-sequence 0))) (is (= '[[a]] (p/permutation-sequence '[a]))) (is (= '[[a b] [b a]] (p/permutation-sequence '(a b)))) (is (= [[0 1 2] [0 2 1] [2 0 1] [2 1 0] [1 2 0] [1 0 2]] (p/permutation-sequence [0 1 2]))) (is (= [[[0 1 2] 1] [[0 2 1] -1] [[2 0 1] 1] [[2 1 0] -1] [[1 2 0] 1] [[1 0 2] -1]] (map vector (p/permutation-sequence (range 3)) (cycle [1 -1])))) (is (= [[0 1 2 3] [0 1 3 2] [0 3 1 2] [3 0 1 2] [3 0 2 1] [0 3 2 1] [0 2 3 1] [0 2 1 3] [2 0 1 3] [2 0 3 1] [2 3 0 1] [3 2 0 1] [3 2 1 0] [2 3 1 0] [2 1 3 0] [2 1 0 3] [1 2 0 3] [1 2 3 0] [1 3 2 0] [3 1 2 0] [3 1 0 2] [1 3 0 2] [1 0 3 2] [1 0 2 3]] (p/permutation-sequence (range 4))))))
4af195878ca5544bdcd9020817c9aba2325f2105604d2159270bf39e396ae3f4
tommaisey/aeon
prelude.scm
( negate 3 ) (define negate (lambda (n) (- n))) (define enum-from-difference-to (lambda (f i x k) (cond ((= i k) (list1 k)) ((f i k) nil) (else (cons i (enum-from-difference-to f (+ i x) x k)))))) ;; enumFromThenTo :: a -> a -> a -> [a] (define enum-from-then-to (lambda (i j k) (let ((x (- j i))) (enum-from-difference-to (if (> x 0) > <) i x k)))) ;; enumFromTo :: a -> a -> [a] (define enum-from-to (lambda (i j) (enum-from-then-to i (succ i) j))) ;; even :: (Integral a) => a -> Bool ;; (define even even?) ;; odd :: (Integral a) => a -> Bool ;; (define odd odd?) ;; pred :: a -> a (define pred (lambda (x) (- x 1))) signum : : a = > a - > a (define signum (lambda (x) (cond ((> x 0) 1) ((< x 0) -1) (else 0)))) ;; succ :: a -> a (define succ (lambda (x) (+ x 1)))
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rhs/src/prelude.scm
scheme
enumFromThenTo :: a -> a -> a -> [a] enumFromTo :: a -> a -> [a] even :: (Integral a) => a -> Bool (define even even?) odd :: (Integral a) => a -> Bool (define odd odd?) pred :: a -> a succ :: a -> a
( negate 3 ) (define negate (lambda (n) (- n))) (define enum-from-difference-to (lambda (f i x k) (cond ((= i k) (list1 k)) ((f i k) nil) (else (cons i (enum-from-difference-to f (+ i x) x k)))))) (define enum-from-then-to (lambda (i j k) (let ((x (- j i))) (enum-from-difference-to (if (> x 0) > <) i x k)))) (define enum-from-to (lambda (i j) (enum-from-then-to i (succ i) j))) (define pred (lambda (x) (- x 1))) signum : : a = > a - > a (define signum (lambda (x) (cond ((> x 0) 1) ((< x 0) -1) (else 0)))) (define succ (lambda (x) (+ x 1)))
a1e6bdb3514cfe374d3fbc76322ef7d6f269fabe5b3ca7f126cb9b7131122de8
sebastiw/otc
otc_m2pa_codec_tests.erl
-module(otc_m2pa_codec_tests). -include_lib("eunit/include/eunit.hrl"). empty_user_data_test() -> Bin = <<16#01, 16#00, 16#0b, 16#01, 16#00, 16#00, 16#00, 16#10, 16#00, 16#00, 16#00, 16#01, 16#00, 16#00, 16#00, 16#00>>, Exp = #{backward_sequence_number => 1, forward_sequence_number => 0, message_class => m2pa, message_type => user_data }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_out_of_service_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#09>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => out_of_service, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_alignment_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#01>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => alignment, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_proving_normal_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#02>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => proving_normal, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_ready_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#04>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => ready, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin).
null
https://raw.githubusercontent.com/sebastiw/otc/2ce29e3178152e2130572c6485f0ed52d5360416/test/otc_m2pa_codec_tests.erl
erlang
-module(otc_m2pa_codec_tests). -include_lib("eunit/include/eunit.hrl"). empty_user_data_test() -> Bin = <<16#01, 16#00, 16#0b, 16#01, 16#00, 16#00, 16#00, 16#10, 16#00, 16#00, 16#00, 16#01, 16#00, 16#00, 16#00, 16#00>>, Exp = #{backward_sequence_number => 1, forward_sequence_number => 0, message_class => m2pa, message_type => user_data }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_out_of_service_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#09>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => out_of_service, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_alignment_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#01>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => alignment, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_proving_normal_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#02>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => proving_normal, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin). link_status_ready_test() -> Bin = <<16#01, 16#00, 16#0b, 16#02, 16#00, 16#00, 16#00, 16#14, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#ff, 16#ff, 16#ff, 16#00, 16#00, 16#00, 16#04>>, Exp = #{backward_sequence_number => 16777215, forward_sequence_number => 16777215, link_status => ready, message_class => m2pa, message_type => link_status }, Val = otc_m2pa:decode(Bin), ?assertEqual(Exp, Val), NewBin = otc_m2pa:encode(Val), ?assertEqual(Bin, NewBin).
44c811df5ef24c11fdd5909c95960ad572c7d541261a467c0389b002d8d4cb96
modular-macros/ocaml-macros
parsecmmaux.mli
(* Auxiliary functions for parsing *) val bind_ident: string -> Ident.t val find_ident: string -> Ident.t val unbind_ident: Ident.t -> unit type error = Unbound of string exception Error of error val report_error: error -> unit
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/asmcomp/parsecmmaux.mli
ocaml
Auxiliary functions for parsing
val bind_ident: string -> Ident.t val find_ident: string -> Ident.t val unbind_ident: Ident.t -> unit type error = Unbound of string exception Error of error val report_error: error -> unit
9af62140603d8b9a3e537047ce455e92d98044401f63357ca40fcd21ef711dd1
kit-clj/kit
repl.clj
(ns kit.edge.utils.repl (:require [clojure.core.server :as socket] [clojure.tools.logging :as log] [integrant.core :as ig])) (defmethod ig/prep-key :repl/server [_ config] (merge {:name "main"} config)) (defmethod ig/init-key :repl/server [_ {:keys [port host name] :as config}] (try (socket/start-server {:address host :port port :name name :accept 'clojure.core.server/repl}) (log/info "REPL server started on host:" host "port:" port) (catch Exception e (log/error "failed to start the REPL server on host:" host "port:" port) (throw e))) config) (defmethod ig/halt-key! :repl/server [_ config] (socket/stop-server (:name config)) (log/info "REPL server stopped"))
null
https://raw.githubusercontent.com/kit-clj/kit/320b920dcf25c33130f33b0e1cd55ff13f3157f6/libs/kit-repl/src/kit/edge/utils/repl.clj
clojure
(ns kit.edge.utils.repl (:require [clojure.core.server :as socket] [clojure.tools.logging :as log] [integrant.core :as ig])) (defmethod ig/prep-key :repl/server [_ config] (merge {:name "main"} config)) (defmethod ig/init-key :repl/server [_ {:keys [port host name] :as config}] (try (socket/start-server {:address host :port port :name name :accept 'clojure.core.server/repl}) (log/info "REPL server started on host:" host "port:" port) (catch Exception e (log/error "failed to start the REPL server on host:" host "port:" port) (throw e))) config) (defmethod ig/halt-key! :repl/server [_ config] (socket/stop-server (:name config)) (log/info "REPL server stopped"))
fe8e78bb1c46361d12c754101f3b521657f3b59771161219d7d34ad39234b438
scymtym/clim.flamegraph
trace-recording.lisp
(cl:defpackage #:clim.flamegraph.examples.recording (:use #:cl) (:local-nicknames (#:model #:clim.flamegraph.model) (#:recording #:clim.flamegraph.recording)) (:export #:call-with-recording #:with-recording)) (cl:in-package #:clim.flamegraph.examples.recording) (defun call-with-recording (thunk &key specifications record-blockers? record-io? include-recording-threads? include-recording-functions? (sample-rate .01) depth-limit min-duration) (let* ((specifications (append (when record-blockers? '(:blockers)) (when record-io? '(:io)) specifications)) (sources (list (make-instance 'clim.flamegraph.backend.advice::source :specification specifications :sample-rate sample-rate :depth-limit depth-limit :min-duration (or min-duration 0)) (make-instance 'clim.flamegraph.backend.sb-sprof::source ;; :thread-test (lambda (thread) ...) :name-test (lambda (name) (not (and (symbolp name) (search "SWANK" (package-name (symbol-package name))))))) #+sbcl (make-instance 'clim.flamegraph.backend.sb-memory::source))) (recorder (recording:make-recorder :standard :sources sources)) (run (recording:make-run recorder))) (unwind-protect (recording:call-with-recording-into thunk run recorder) (let ((result (make-instance 'model::standard-run :traces (recording::data run)))) ( clouseau : inspect result : new - process t ) (when (boundp '*frame*) (clim.flamegraph.application::add-run (symbol-value '*frame*) result)) result)))) (defmacro with-recording ((&rest args &key &allow-other-keys) &body body) `(call-with-recording (lambda () ,@body) ,@args)) (defvar *frame* (clim.flamegraph.application:launch :new-process t)) #+example (with-recording (:record-blockers? t) (loop :repeat 10 :do (sleep 1)))
null
https://raw.githubusercontent.com/scymtym/clim.flamegraph/03b5e4f08b53af86a98afa975a8e7a29d0ddd3a7/examples/trace-recording.lisp
lisp
:thread-test (lambda (thread) ...)
(cl:defpackage #:clim.flamegraph.examples.recording (:use #:cl) (:local-nicknames (#:model #:clim.flamegraph.model) (#:recording #:clim.flamegraph.recording)) (:export #:call-with-recording #:with-recording)) (cl:in-package #:clim.flamegraph.examples.recording) (defun call-with-recording (thunk &key specifications record-blockers? record-io? include-recording-threads? include-recording-functions? (sample-rate .01) depth-limit min-duration) (let* ((specifications (append (when record-blockers? '(:blockers)) (when record-io? '(:io)) specifications)) (sources (list (make-instance 'clim.flamegraph.backend.advice::source :specification specifications :sample-rate sample-rate :depth-limit depth-limit :min-duration (or min-duration 0)) (make-instance 'clim.flamegraph.backend.sb-sprof::source :name-test (lambda (name) (not (and (symbolp name) (search "SWANK" (package-name (symbol-package name))))))) #+sbcl (make-instance 'clim.flamegraph.backend.sb-memory::source))) (recorder (recording:make-recorder :standard :sources sources)) (run (recording:make-run recorder))) (unwind-protect (recording:call-with-recording-into thunk run recorder) (let ((result (make-instance 'model::standard-run :traces (recording::data run)))) ( clouseau : inspect result : new - process t ) (when (boundp '*frame*) (clim.flamegraph.application::add-run (symbol-value '*frame*) result)) result)))) (defmacro with-recording ((&rest args &key &allow-other-keys) &body body) `(call-with-recording (lambda () ,@body) ,@args)) (defvar *frame* (clim.flamegraph.application:launch :new-process t)) #+example (with-recording (:record-blockers? t) (loop :repeat 10 :do (sleep 1)))
23e588bf0ada1a70125b1747a9bc7f20742a053afc1041785c6ab7684eafcfcf
UU-ComputerScience/js-asteroids
data_export_plain.hs
import Language.UHC.JS.ECMA.String import Language.UHC.JS.Primitives import Language.UHC.JS.Assorted So this would be somewhat of a decent idea . The thing is , though , that we 'd still be doing runtime conversion . If we 're going to be stuck with that anyway , we might just as well just have a primitive JS function to do this for us . We 'd still need to wrap the functions in an object , though . Would we need some facility to turn the datatype into an object first ? I do n't think so ; we 'd just have to evaluate the datatype and then call on it . In fact , we might as well embed the evaluation in and do the evaluation inside . We would then import it with type ` a - > JSPtr b ` . So , in short : the original object export approach wo n't be good enough . In common usecases , one stores callbacks in an object . These callbacks need to be of type JSFunPtr ( ... ) . The only way to obtain something of that type is to wrap a function using a wrapper , which is a dynamic process . Converting a Haskell datatype is therefor also defered to runtime . In fact , the entire process is very similar to a function wrapper . One could call it an object wrapper . So this would be somewhat of a decent idea. The thing is, though, that we'd still be doing runtime conversion. If we're going to be stuck with that anyway, we might just as well just have a primitive JS function to do this for us. We'd still need to wrap the functions in an object, though. Would we need some facility to turn the datatype into an object first? I don't think so; we'd just have to evaluate the datatype and then call primToPlainObj on it. In fact, we might as well embed the evaluation in primToPlainObj and do the evaluation inside. We would then import it with type `a -> JSPtr b`. So, in short: the original object export approach won't be good enough. In common usecases, one stores callbacks in an object. These callbacks need to be of type JSFunPtr (...). The only way to obtain something of that type is to wrap a function using a wrapper, which is a dynamic process. Converting a Haskell datatype is therefor also defered to runtime. In fact, the entire process is very similar to a function wrapper. One could call it an object wrapper. -} main = do putStrLn "data_export" add' <- mkMath add bptr <- mkBook (myBook add') print $ getCount bptr myFun bptr getCount :: JSBook -> Int getCount = getAttr "count" data BookPtr type JSBook = JSPtr BookPtr data Book = Book { title :: JSString , author :: JSString , count :: Int , stuff :: String , doMath :: JSFunPtr (Int -> Int -> IO ()) } add :: Int -> Int -> IO () add x y = print $ y + x TODO -- The current problem is that we need to do something like this: -- -- main = do -- add' <- mkMath add -- let b = myBook add' -- ... -- where myBook add' = Book "" "" 1 "" add' -- -- but the current object export cannot deal with exporting functions. How -- do we fix this? -- -- Perhaps we need a mechanism similar to wrapper and dynamic, which -- dynamically creates a plain object from a datatype: -- foreign import " { } " mkJSObj : : a - > JSPtr b -- where ` a ` must be a data value . If so , we should remove it from the FEL -- and parse it as a token instead. Though, that would require modifying _ every _ FFI backend . Lets leave it in the FEL anyway . -- myBook f = Book (stringToJSString "story") (stringToJSString "me") 123 "foo" f foreign export " myBook " myBook : : Book foreign export " { myBook } " myBook : : Book foreign import jscript " myBook ( ) " myBookPtr : : JSBook foreign import " { myBook } " myBookPtr : : JSBook mkBook :: Book -> IO JSBook mkBook = mkObj foreign import jscript "myFun(%1)" myFun :: JSBook -> IO () foreign import jscript "{}" mkObj :: a -> IO (JSPtr b) foreign import jscript "wrapper" mkMath :: (Int -> Int -> IO ()) -> IO (JSFunPtr (Int -> Int -> IO ()))
null
https://raw.githubusercontent.com/UU-ComputerScience/js-asteroids/b7015d8ad4aa57ff30f2631e0945462f6e1ef47a/uhc-js/tests/works/data_export_plain/data_export_plain.hs
haskell
The current problem is that we need to do something like this: main = do add' <- mkMath add let b = myBook add' ... where myBook add' = Book "" "" 1 "" add' but the current object export cannot deal with exporting functions. How do we fix this? Perhaps we need a mechanism similar to wrapper and dynamic, which dynamically creates a plain object from a datatype: and parse it as a token instead. Though, that would require modifying
import Language.UHC.JS.ECMA.String import Language.UHC.JS.Primitives import Language.UHC.JS.Assorted So this would be somewhat of a decent idea . The thing is , though , that we 'd still be doing runtime conversion . If we 're going to be stuck with that anyway , we might just as well just have a primitive JS function to do this for us . We 'd still need to wrap the functions in an object , though . Would we need some facility to turn the datatype into an object first ? I do n't think so ; we 'd just have to evaluate the datatype and then call on it . In fact , we might as well embed the evaluation in and do the evaluation inside . We would then import it with type ` a - > JSPtr b ` . So , in short : the original object export approach wo n't be good enough . In common usecases , one stores callbacks in an object . These callbacks need to be of type JSFunPtr ( ... ) . The only way to obtain something of that type is to wrap a function using a wrapper , which is a dynamic process . Converting a Haskell datatype is therefor also defered to runtime . In fact , the entire process is very similar to a function wrapper . One could call it an object wrapper . So this would be somewhat of a decent idea. The thing is, though, that we'd still be doing runtime conversion. If we're going to be stuck with that anyway, we might just as well just have a primitive JS function to do this for us. We'd still need to wrap the functions in an object, though. Would we need some facility to turn the datatype into an object first? I don't think so; we'd just have to evaluate the datatype and then call primToPlainObj on it. In fact, we might as well embed the evaluation in primToPlainObj and do the evaluation inside. We would then import it with type `a -> JSPtr b`. So, in short: the original object export approach won't be good enough. In common usecases, one stores callbacks in an object. These callbacks need to be of type JSFunPtr (...). The only way to obtain something of that type is to wrap a function using a wrapper, which is a dynamic process. Converting a Haskell datatype is therefor also defered to runtime. In fact, the entire process is very similar to a function wrapper. One could call it an object wrapper. -} main = do putStrLn "data_export" add' <- mkMath add bptr <- mkBook (myBook add') print $ getCount bptr myFun bptr getCount :: JSBook -> Int getCount = getAttr "count" data BookPtr type JSBook = JSPtr BookPtr data Book = Book { title :: JSString , author :: JSString , count :: Int , stuff :: String , doMath :: JSFunPtr (Int -> Int -> IO ()) } add :: Int -> Int -> IO () add x y = print $ y + x TODO foreign import " { } " mkJSObj : : a - > JSPtr b where ` a ` must be a data value . If so , we should remove it from the FEL _ every _ FFI backend . Lets leave it in the FEL anyway . myBook f = Book (stringToJSString "story") (stringToJSString "me") 123 "foo" f foreign export " myBook " myBook : : Book foreign export " { myBook } " myBook : : Book foreign import jscript " myBook ( ) " myBookPtr : : JSBook foreign import " { myBook } " myBookPtr : : JSBook mkBook :: Book -> IO JSBook mkBook = mkObj foreign import jscript "myFun(%1)" myFun :: JSBook -> IO () foreign import jscript "{}" mkObj :: a -> IO (JSPtr b) foreign import jscript "wrapper" mkMath :: (Int -> Int -> IO ()) -> IO (JSFunPtr (Int -> Int -> IO ()))
30adad51bc694f20e284846f6ec85925c32fdd69e181fbb0ffb929fcfb72e5b3
glguy/advent2017
Day16.hs
# Language DataKinds , NumDecimals , ScopedTypeVariables , OverloadedStrings # | Module : Main Description : Day 16 solution Copyright : ( c ) , 2017 License : ISC Maintainer : Day 16 defines a language of renaming and permutations and asks us to iterate the program one billion times ! The key to this solution is that ' stimes ' can used repeated squaring to efficiently compute the result of multiplication by a large factor . There are two kind of dance moves : permutation of positions , and renamings of dancers . These two kinds of moves commute with each other . Both renamings and permutations can efficiently compose , so we represent a dance as a single renaming and a single permutation . This representation means that our dance combination operation ( ' < > ' ) is associative , as required for dances to be a ' Monoid ' because the component permutations themselves support an associative composition . Module : Main Description : Day 16 solution Copyright : (c) Eric Mertens, 2017 License : ISC Maintainer : Day 16 defines a language of renaming and permutations and asks us to iterate the program one billion times! The key to this solution is that 'stimes' can used repeated squaring to efficiently compute the result of multiplication by a large factor. There are two kind of dance moves: permutation of positions, and renamings of dancers. These two kinds of moves commute with each other. Both renamings and permutations can efficiently compose, so we represent a dance as a single renaming and a single permutation. This representation means that our dance combination operation ('<>') is associative, as required for dances to be a 'Monoid' because the component permutations themselves support an associative composition. -} module Main where import Advent (Parser, getParsedInput, number) import Advent.Permutation (Permutation, rotateRight, runPermutation, swap) import Data.Semigroup (Semigroup, (<>), Dual(..), sconcat, stimes) import Data.Char (chr, ord) import GHC.TypeLits (KnownNat) import Text.Megaparsec (choice, sepBy) import Text.Megaparsec.Char (letterChar) -- $setup -- >>> :set -XDataKinds | Print the solutions to both parts of the day 16 problem . The input -- file can be overridden via command-line arguments. main :: IO () main = do dance :: Dance 16 <- getParsedInput 16 parseDance putStrLn (runDance dance) putStrLn (runDance (stimes 1e9 dance)) -- | Parse an input string as a dance. parseDance :: KnownNat n => Parser (Dance n) parseDance = mconcat <$> sepBy parseDanceStep "," -- | Parse a single step in a dance. parseDanceStep :: KnownNat n => Parser (Dance n) parseDanceStep = choice [ spinDance <$ "s" <*> number , swapDance <$ "x" <*> number <* "/" <*> number , partDance <$ "p" <*> letterChar <* "/" <*> letterChar ] | Map the numbers starting at @0@ to the letters starting at -- > > > intToLetter < $ > [ 0 .. 3 ] -- "abcd" intToLetter :: Int -> Char intToLetter i = chr (i + ord 'a') | Map the letters starting at @a@ to the numbers starting at @0@. -- -- >>> letterToInt <$> ['a'..'d'] -- [0,1,2,3] letterToInt :: Char -> Int letterToInt c = ord c - ord 'a' -- | A dance is a renaming of dancers and a permutation of their positions type Dance n = (Dual (Permutation n), Permutation n) -- ^ renaming, permutation -- | Compute the final position of the dancers given a dance where -- dancers start in order. -- > > > let example = spinDance 1 < > swapDance 3 4 < > partDance ' e ' ' b ' : : Dance 5 -- >>> runDance example -- "baedc" > > > runDance ( stimes 2 example ) -- "ceadb" runDance :: KnownNat n => Dance n -> String runDance (Dual r, p) = runPermutation intToLetter (r <> p) -- | The spin dance where all dancers move some number of positions -- to the right. -- > > > runDance ( spinDance 0 : : Dance 3 ) " abc " > > > runDance ( spinDance 1 : : Dance 3 ) -- "cab" spinDance :: KnownNat n => Int -> Dance n spinDance n = (mempty, rotateRight n) | The swap dance where dancers in the two positions trade places . -- > > > runDance ( swapDance 0 1 : : Dance 3 ) -- "bac" > > > runDance ( swapDance 0 1 < > swapDance 1 2 : : Dance 3 ) -- "bca" swapDance :: KnownNat n => Int -> Int -> Dance n swapDance x y = (mempty, swap x y) | The parter dance where the two named dancers changes positions . -- > > > runDance ( partDance ' a ' ' b ' : : Dance 3 ) -- "bac" > > > runDance ( partDance ' a ' ' b ' < > partDance ' a ' ' c ' : : Dance 3 ) -- "bca" partDance :: KnownNat n => Char -> Char -> Dance n partDance x y = (Dual (swap (letterToInt x) (letterToInt y)), mempty)
null
https://raw.githubusercontent.com/glguy/advent2017/fed4592b076d255297dbddf2a183c70d6d0acfa4/execs/Day16.hs
haskell
$setup >>> :set -XDataKinds file can be overridden via command-line arguments. | Parse an input string as a dance. | Parse a single step in a dance. "abcd" >>> letterToInt <$> ['a'..'d'] [0,1,2,3] | A dance is a renaming of dancers and a permutation of their positions ^ renaming, permutation | Compute the final position of the dancers given a dance where dancers start in order. >>> runDance example "baedc" "ceadb" | The spin dance where all dancers move some number of positions to the right. "cab" "bac" "bca" "bac" "bca"
# Language DataKinds , NumDecimals , ScopedTypeVariables , OverloadedStrings # | Module : Main Description : Day 16 solution Copyright : ( c ) , 2017 License : ISC Maintainer : Day 16 defines a language of renaming and permutations and asks us to iterate the program one billion times ! The key to this solution is that ' stimes ' can used repeated squaring to efficiently compute the result of multiplication by a large factor . There are two kind of dance moves : permutation of positions , and renamings of dancers . These two kinds of moves commute with each other . Both renamings and permutations can efficiently compose , so we represent a dance as a single renaming and a single permutation . This representation means that our dance combination operation ( ' < > ' ) is associative , as required for dances to be a ' Monoid ' because the component permutations themselves support an associative composition . Module : Main Description : Day 16 solution Copyright : (c) Eric Mertens, 2017 License : ISC Maintainer : Day 16 defines a language of renaming and permutations and asks us to iterate the program one billion times! The key to this solution is that 'stimes' can used repeated squaring to efficiently compute the result of multiplication by a large factor. There are two kind of dance moves: permutation of positions, and renamings of dancers. These two kinds of moves commute with each other. Both renamings and permutations can efficiently compose, so we represent a dance as a single renaming and a single permutation. This representation means that our dance combination operation ('<>') is associative, as required for dances to be a 'Monoid' because the component permutations themselves support an associative composition. -} module Main where import Advent (Parser, getParsedInput, number) import Advent.Permutation (Permutation, rotateRight, runPermutation, swap) import Data.Semigroup (Semigroup, (<>), Dual(..), sconcat, stimes) import Data.Char (chr, ord) import GHC.TypeLits (KnownNat) import Text.Megaparsec (choice, sepBy) import Text.Megaparsec.Char (letterChar) | Print the solutions to both parts of the day 16 problem . The input main :: IO () main = do dance :: Dance 16 <- getParsedInput 16 parseDance putStrLn (runDance dance) putStrLn (runDance (stimes 1e9 dance)) parseDance :: KnownNat n => Parser (Dance n) parseDance = mconcat <$> sepBy parseDanceStep "," parseDanceStep :: KnownNat n => Parser (Dance n) parseDanceStep = choice [ spinDance <$ "s" <*> number , swapDance <$ "x" <*> number <* "/" <*> number , partDance <$ "p" <*> letterChar <* "/" <*> letterChar ] | Map the numbers starting at @0@ to the letters starting at > > > intToLetter < $ > [ 0 .. 3 ] intToLetter :: Int -> Char intToLetter i = chr (i + ord 'a') | Map the letters starting at @a@ to the numbers starting at @0@. letterToInt :: Char -> Int letterToInt c = ord c - ord 'a' > > > let example = spinDance 1 < > swapDance 3 4 < > partDance ' e ' ' b ' : : Dance 5 > > > runDance ( stimes 2 example ) runDance :: KnownNat n => Dance n -> String runDance (Dual r, p) = runPermutation intToLetter (r <> p) > > > runDance ( spinDance 0 : : Dance 3 ) " abc " > > > runDance ( spinDance 1 : : Dance 3 ) spinDance :: KnownNat n => Int -> Dance n spinDance n = (mempty, rotateRight n) | The swap dance where dancers in the two positions trade places . > > > runDance ( swapDance 0 1 : : Dance 3 ) > > > runDance ( swapDance 0 1 < > swapDance 1 2 : : Dance 3 ) swapDance :: KnownNat n => Int -> Int -> Dance n swapDance x y = (mempty, swap x y) | The parter dance where the two named dancers changes positions . > > > runDance ( partDance ' a ' ' b ' : : Dance 3 ) > > > runDance ( partDance ' a ' ' b ' < > partDance ' a ' ' c ' : : Dance 3 ) partDance :: KnownNat n => Char -> Char -> Dance n partDance x y = (Dual (swap (letterToInt x) (letterToInt y)), mempty)
1388da149595a8ef7cff7dbadf7b12f9dd548ad36b6d84de1cdb73bdff3b4b74
diagrams/diagrams-lib
PolyTest.hs
# LANGUAGE NoMonomorphismRestriction # import Diagrams.Backend.Cairo.CmdLine import Diagrams.Prelude import Diagrams.TwoD.Polygons d = stroke . close $ fromVertices ( polyPoints with { polyStar = StarFun succ } ) vs = take 10 $ iterate (rotateBy (1/20 :: CircleFrac)) unitX mkR v = (mconcat . mconcat $ p) <> fromVertices [origin, origin .+^ v] where p = map (zipWith lc (red : repeat black)) $ (map (map stroke)) (explodePath (polygon (with & polyOrient .~ OrientTo v ))) d = hcat' with {sep = 0.5} (map mkR vs) # lw 0.05 s = stroke $ starPoly (StarSkip 5) (polygon (with & polyType .~ PolyPolar (repeat (tau/15 :: Rad)) (take 15 (cycle [6,7,8])) )) main = defaultMain (pad 1.1 s)
null
https://raw.githubusercontent.com/diagrams/diagrams-lib/6f66ce6bd5aed81d8a1330c143ea012724dbac3c/test/PolyTest.hs
haskell
# LANGUAGE NoMonomorphismRestriction # import Diagrams.Backend.Cairo.CmdLine import Diagrams.Prelude import Diagrams.TwoD.Polygons d = stroke . close $ fromVertices ( polyPoints with { polyStar = StarFun succ } ) vs = take 10 $ iterate (rotateBy (1/20 :: CircleFrac)) unitX mkR v = (mconcat . mconcat $ p) <> fromVertices [origin, origin .+^ v] where p = map (zipWith lc (red : repeat black)) $ (map (map stroke)) (explodePath (polygon (with & polyOrient .~ OrientTo v ))) d = hcat' with {sep = 0.5} (map mkR vs) # lw 0.05 s = stroke $ starPoly (StarSkip 5) (polygon (with & polyType .~ PolyPolar (repeat (tau/15 :: Rad)) (take 15 (cycle [6,7,8])) )) main = defaultMain (pad 1.1 s)
7d614c588393b8c84e754c74348ed74b0c52af5dfa6958bab90f839d736ea877
Cumulus/Cumulus
templates_common.mli
Copyright ( c ) 2012 Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . Copyright (c) 2012 Enguerrand Decorne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) val string_input_box : ?a:Html5_types.input_attrib Eliom_content.Html5.F.attrib list -> input_type:[< `Button | `Checkbox | `Color | `Date | `Datetime | `Datetime_local | `Email | `File | `Hidden | `Image | `Month | `Number | `Password | `Radio | `Range | `Reset | `Search | `Submit | `Tel | `Text | `Time | `Url | `Week ] -> ?name:[< string Eliom_parameter.setoneradio ] Eliom_parameter.param_name -> ?value:string -> unit -> [> Html5_types.input ] Eliom_content.Html5.elt val submit_input : ?a:Html5_types.input_attrib Eliom_content.Html5.F.attrib list -> ?name:[< string Eliom_parameter.setoneradio ] Eliom_parameter.param_name -> ?value:string -> unit -> [> Html5_types.input ] Eliom_content.Html5.elt val links_of_tags : string list -> [> `A of [> `PCDATA ] | `PCDATA ] Eliom_content.Html5.F.elt list module Markdown : module type of MarkdownHTML.Make_html5(struct include Eliom_content.Html5.F.Raw module Svg = Eliom_content.Svg.F.Raw end)
null
https://raw.githubusercontent.com/Cumulus/Cumulus/3b6de05d76c57d528e052aa382f98e40354cf581/src/templates_common.mli
ocaml
Copyright ( c ) 2012 Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . Copyright (c) 2012 Enguerrand Decorne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) val string_input_box : ?a:Html5_types.input_attrib Eliom_content.Html5.F.attrib list -> input_type:[< `Button | `Checkbox | `Color | `Date | `Datetime | `Datetime_local | `Email | `File | `Hidden | `Image | `Month | `Number | `Password | `Radio | `Range | `Reset | `Search | `Submit | `Tel | `Text | `Time | `Url | `Week ] -> ?name:[< string Eliom_parameter.setoneradio ] Eliom_parameter.param_name -> ?value:string -> unit -> [> Html5_types.input ] Eliom_content.Html5.elt val submit_input : ?a:Html5_types.input_attrib Eliom_content.Html5.F.attrib list -> ?name:[< string Eliom_parameter.setoneradio ] Eliom_parameter.param_name -> ?value:string -> unit -> [> Html5_types.input ] Eliom_content.Html5.elt val links_of_tags : string list -> [> `A of [> `PCDATA ] | `PCDATA ] Eliom_content.Html5.F.elt list module Markdown : module type of MarkdownHTML.Make_html5(struct include Eliom_content.Html5.F.Raw module Svg = Eliom_content.Svg.F.Raw end)
2ba82b8183129a1727642515275a09b7ba762e0f4e01c80518cbdcc73d7b34f6
DavidAlphaFox/RabbitMQ
rabbit_heartbeat.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% 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. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% %% 通过一个进程不断获取Socket进出流量来判断是否需要心跳 -module(rabbit_heartbeat). -export([start/6, start/7]). -export([start_heartbeat_sender/4, start_heartbeat_receiver/4, pause_monitor/1, resume_monitor/1]). -export([system_continue/3, system_terminate/4, system_code_change/4]). -include("rabbit.hrl"). %%---------------------------------------------------------------------------- -ifdef(use_specs). -export_type([heartbeaters/0]). -type(heartbeaters() :: {rabbit_types:maybe(pid()), rabbit_types:maybe(pid())}). -type(heartbeat_callback() :: fun (() -> any())). -spec(start/6 :: (pid(), rabbit_net:socket(), non_neg_integer(), heartbeat_callback(), non_neg_integer(), heartbeat_callback()) -> heartbeaters()). -spec(start/7 :: (pid(), rabbit_net:socket(), rabbit_types:proc_name(), non_neg_integer(), heartbeat_callback(), non_neg_integer(), heartbeat_callback()) -> heartbeaters()). -spec(start_heartbeat_sender/4 :: (rabbit_net:socket(), non_neg_integer(), heartbeat_callback(), rabbit_types:proc_type_and_name()) -> rabbit_types:ok(pid())). -spec(start_heartbeat_receiver/4 :: (rabbit_net:socket(), non_neg_integer(), heartbeat_callback(), rabbit_types:proc_type_and_name()) -> rabbit_types:ok(pid())). -spec(pause_monitor/1 :: (heartbeaters()) -> 'ok'). -spec(resume_monitor/1 :: (heartbeaters()) -> 'ok'). -spec(system_code_change/4 :: (_,_,_,_) -> {'ok',_}). -spec(system_continue/3 :: (_,_,{_, _}) -> any()). -spec(system_terminate/4 :: (_,_,_,_) -> none()). -endif. %%---------------------------------------------------------------------------- start(SupPid, Sock, SendTimeoutSec, SendFun, ReceiveTimeoutSec, ReceiveFun) -> start(SupPid, Sock, unknown, SendTimeoutSec, SendFun, ReceiveTimeoutSec, ReceiveFun). start(SupPid, Sock, Identity, SendTimeoutSec, SendFun, ReceiveTimeoutSec, ReceiveFun) -> {ok, Sender} = start_heartbeater(SendTimeoutSec, SupPid, Sock, SendFun, heartbeat_sender, start_heartbeat_sender, Identity), {ok, Receiver} = start_heartbeater(ReceiveTimeoutSec, SupPid, Sock, ReceiveFun, heartbeat_receiver, start_heartbeat_receiver, Identity), {Sender, Receiver}. start_heartbeat_sender(Sock, TimeoutSec, SendFun, Identity) -> %% the 'div 2' is there so that we don't end up waiting for nearly 2 * TimeoutSec before sending a heartbeat in the boundary case %% where the last message was sent just after a heartbeat. heartbeater({Sock, TimeoutSec * 1000 div 2, send_oct, 0, fun () -> SendFun(), continue end}, Identity). start_heartbeat_receiver(Sock, TimeoutSec, ReceiveFun, Identity) -> %% we check for incoming data every interval, and time out after two checks with no change . As a result we will time out between 2 and 3 intervals after the last data has been received . heartbeater({Sock, TimeoutSec * 1000, recv_oct, 1, fun () -> ReceiveFun(), stop end}, Identity). pause_monitor({_Sender, none}) -> ok; pause_monitor({_Sender, Receiver}) -> Receiver ! pause, ok. resume_monitor({_Sender, none}) -> ok; resume_monitor({_Sender, Receiver}) -> Receiver ! resume, ok. system_continue(_Parent, Deb, {Params, State}) -> heartbeater(Params, Deb, State). system_terminate(Reason, _Parent, _Deb, _State) -> exit(Reason). system_code_change(Misc, _Module, _OldVsn, _Extra) -> {ok, Misc}. %%---------------------------------------------------------------------------- start_heartbeater(0, _SupPid, _Sock, _TimeoutFun, _Name, _Callback, _Identity) -> {ok, none}; start_heartbeater(TimeoutSec, SupPid, Sock, TimeoutFun, Name, Callback, Identity) -> supervisor2:start_child( SupPid, {Name, {rabbit_heartbeat, Callback, [Sock, TimeoutSec, TimeoutFun, {Name, Identity}]}, transient, ?MAX_WAIT, worker, [rabbit_heartbeat]}). heartbeater(Params, Identity) -> Deb = sys:debug_options([]), {ok, proc_lib:spawn_link(fun () -> rabbit_misc:store_proc_name(Identity), heartbeater(Params, Deb, {0, 0}) end)}. heartbeater({Sock, TimeoutMillisec, StatName, Threshold, Handler} = Params, Deb, {StatVal, SameCount} = State) -> Recurse = fun (State1) -> heartbeater(Params, Deb, State1) end, System = fun (From, Req) -> sys:handle_system_msg( Req, From, self(), ?MODULE, Deb, {Params, State}) end, receive pause -> receive resume -> Recurse({0, 0}); {system, From, Req} -> System(From, Req); Other -> exit({unexpected_message, Other}) end; {system, From, Req} -> System(From, Req); Other -> exit({unexpected_message, Other}) after TimeoutMillisec -> case rabbit_net:getstat(Sock, [StatName]) of {ok, [{StatName, NewStatVal}]} -> if NewStatVal =/= StatVal -> Recurse({NewStatVal, 0}); SameCount < Threshold -> Recurse({NewStatVal, SameCount + 1}); true -> case Handler() of stop -> ok; continue -> Recurse({NewStatVal, 0}) end end; {error, einval} -> %% the socket is dead, most likely because the %% connection is being shut down -> terminate ok; {error, Reason} -> exit({cannot_get_socket_stats, Reason}) end end.
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/src/rabbit_heartbeat.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License 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. 通过一个进程不断获取Socket进出流量来判断是否需要心跳 ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- the 'div 2' is there so that we don't end up waiting for nearly where the last message was sent just after a heartbeat. we check for incoming data every interval, and time out after ---------------------------------------------------------------------------- the socket is dead, most likely because the connection is being shut down -> terminate
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_heartbeat). -export([start/6, start/7]). -export([start_heartbeat_sender/4, start_heartbeat_receiver/4, pause_monitor/1, resume_monitor/1]). -export([system_continue/3, system_terminate/4, system_code_change/4]). -include("rabbit.hrl"). -ifdef(use_specs). -export_type([heartbeaters/0]). -type(heartbeaters() :: {rabbit_types:maybe(pid()), rabbit_types:maybe(pid())}). -type(heartbeat_callback() :: fun (() -> any())). -spec(start/6 :: (pid(), rabbit_net:socket(), non_neg_integer(), heartbeat_callback(), non_neg_integer(), heartbeat_callback()) -> heartbeaters()). -spec(start/7 :: (pid(), rabbit_net:socket(), rabbit_types:proc_name(), non_neg_integer(), heartbeat_callback(), non_neg_integer(), heartbeat_callback()) -> heartbeaters()). -spec(start_heartbeat_sender/4 :: (rabbit_net:socket(), non_neg_integer(), heartbeat_callback(), rabbit_types:proc_type_and_name()) -> rabbit_types:ok(pid())). -spec(start_heartbeat_receiver/4 :: (rabbit_net:socket(), non_neg_integer(), heartbeat_callback(), rabbit_types:proc_type_and_name()) -> rabbit_types:ok(pid())). -spec(pause_monitor/1 :: (heartbeaters()) -> 'ok'). -spec(resume_monitor/1 :: (heartbeaters()) -> 'ok'). -spec(system_code_change/4 :: (_,_,_,_) -> {'ok',_}). -spec(system_continue/3 :: (_,_,{_, _}) -> any()). -spec(system_terminate/4 :: (_,_,_,_) -> none()). -endif. start(SupPid, Sock, SendTimeoutSec, SendFun, ReceiveTimeoutSec, ReceiveFun) -> start(SupPid, Sock, unknown, SendTimeoutSec, SendFun, ReceiveTimeoutSec, ReceiveFun). start(SupPid, Sock, Identity, SendTimeoutSec, SendFun, ReceiveTimeoutSec, ReceiveFun) -> {ok, Sender} = start_heartbeater(SendTimeoutSec, SupPid, Sock, SendFun, heartbeat_sender, start_heartbeat_sender, Identity), {ok, Receiver} = start_heartbeater(ReceiveTimeoutSec, SupPid, Sock, ReceiveFun, heartbeat_receiver, start_heartbeat_receiver, Identity), {Sender, Receiver}. start_heartbeat_sender(Sock, TimeoutSec, SendFun, Identity) -> 2 * TimeoutSec before sending a heartbeat in the boundary case heartbeater({Sock, TimeoutSec * 1000 div 2, send_oct, 0, fun () -> SendFun(), continue end}, Identity). start_heartbeat_receiver(Sock, TimeoutSec, ReceiveFun, Identity) -> two checks with no change . As a result we will time out between 2 and 3 intervals after the last data has been received . heartbeater({Sock, TimeoutSec * 1000, recv_oct, 1, fun () -> ReceiveFun(), stop end}, Identity). pause_monitor({_Sender, none}) -> ok; pause_monitor({_Sender, Receiver}) -> Receiver ! pause, ok. resume_monitor({_Sender, none}) -> ok; resume_monitor({_Sender, Receiver}) -> Receiver ! resume, ok. system_continue(_Parent, Deb, {Params, State}) -> heartbeater(Params, Deb, State). system_terminate(Reason, _Parent, _Deb, _State) -> exit(Reason). system_code_change(Misc, _Module, _OldVsn, _Extra) -> {ok, Misc}. start_heartbeater(0, _SupPid, _Sock, _TimeoutFun, _Name, _Callback, _Identity) -> {ok, none}; start_heartbeater(TimeoutSec, SupPid, Sock, TimeoutFun, Name, Callback, Identity) -> supervisor2:start_child( SupPid, {Name, {rabbit_heartbeat, Callback, [Sock, TimeoutSec, TimeoutFun, {Name, Identity}]}, transient, ?MAX_WAIT, worker, [rabbit_heartbeat]}). heartbeater(Params, Identity) -> Deb = sys:debug_options([]), {ok, proc_lib:spawn_link(fun () -> rabbit_misc:store_proc_name(Identity), heartbeater(Params, Deb, {0, 0}) end)}. heartbeater({Sock, TimeoutMillisec, StatName, Threshold, Handler} = Params, Deb, {StatVal, SameCount} = State) -> Recurse = fun (State1) -> heartbeater(Params, Deb, State1) end, System = fun (From, Req) -> sys:handle_system_msg( Req, From, self(), ?MODULE, Deb, {Params, State}) end, receive pause -> receive resume -> Recurse({0, 0}); {system, From, Req} -> System(From, Req); Other -> exit({unexpected_message, Other}) end; {system, From, Req} -> System(From, Req); Other -> exit({unexpected_message, Other}) after TimeoutMillisec -> case rabbit_net:getstat(Sock, [StatName]) of {ok, [{StatName, NewStatVal}]} -> if NewStatVal =/= StatVal -> Recurse({NewStatVal, 0}); SameCount < Threshold -> Recurse({NewStatVal, SameCount + 1}); true -> case Handler() of stop -> ok; continue -> Recurse({NewStatVal, 0}) end end; {error, einval} -> ok; {error, Reason} -> exit({cannot_get_socket_stats, Reason}) end end.
736afc4b35af80302ce23d8c3614678f964668b4145d6ebcc1ea794ce5fa50a5
soegaard/remacs
status-line.rkt
#lang racket/base (provide status-line-hook status-line-time status-line-coloring-time status-line-command-time status-line-render-time status-line-show-paren-time) ;;; ;;; STATUS LINE ;;; ; Each frame (GUI window) has a status line - a horizontal line at ; the bottom of the frame (under the displayed buffer). The status ; line is used to display information on the current buffer. ; The default information displayed is: ; - name of the current buffer ; - the row and column of the point ; - the position of the point ; - the current major mode ; - the time used to run the last commands (measured in milliseconds) (require racket/format "buffer-locals.rkt" "mark.rkt" "mode.rkt" "parameters.rkt" "representation.rkt") ; The variable the-time keeps track of the time used by the last command. (define the-time 0) (define (status-line-time t) (set! the-time t)) (define the-render-time 0) (define (status-line-render-time t) (set! the-render-time t)) (define the-coloring-time 0) (define (status-line-coloring-time t) (set! the-coloring-time t)) (define the-command-time 0) (define (status-line-command-time t) (set! the-command-time t)) (define the-show-paren-time 0) (define (status-line-show-paren-time t) (set! the-show-paren-time t)) (define (position pos) (if (mark? pos) (mark-position pos) pos)) ; The default function used to compute status line information (define (status-line-hook) (define w (current-window)) (define b (window-buffer w)) (define point (buffer-point b)) (cond [b (define save-status (if (buffer-modified? b) "***" "---")) (define line? (local line-number-mode?)) (define col? (local column-number-mode?)) (define-values (row col) (if (and (<= (buffer-length b) (local line-number-display-limit))) (mark-row+column point) (values "-" "-"))) (define line+col (cond [(and line? col?) (~a "(" row "," col ")")] [line? (~a "L" row)] [col? (~a "C" col)] [else ""])) (~a save-status " " "Buffer: " (buffer-name) " " line+col " " "Position: " (mark-position point) " " "Length: " (buffer-length b) " " "Mode: " "(" (get-mode-name) ")" " " "Time: " the-time " " "Command Time:" the-command-time " " "Render Time: " the-render-time " " "Coloring Time: " the-coloring-time " " "Show Paren Time: " the-show-paren-time ; " " "Window: " (position (window-start-mark w)) "-" ; (position (window-end-mark w)) )] [else "No current buffer"]))
null
https://raw.githubusercontent.com/soegaard/remacs/8681b3acfe93335e2bc2133c6f144af9e0a1289e/status-line.rkt
racket
STATUS LINE Each frame (GUI window) has a status line - a horizontal line at the bottom of the frame (under the displayed buffer). The status line is used to display information on the current buffer. The default information displayed is: - name of the current buffer - the row and column of the point - the position of the point - the current major mode - the time used to run the last commands (measured in milliseconds) The variable the-time keeps track of the time used by the last command. The default function used to compute status line information " " "Window: " (position (window-start-mark w)) "-" (position (window-end-mark w))
#lang racket/base (provide status-line-hook status-line-time status-line-coloring-time status-line-command-time status-line-render-time status-line-show-paren-time) (require racket/format "buffer-locals.rkt" "mark.rkt" "mode.rkt" "parameters.rkt" "representation.rkt") (define the-time 0) (define (status-line-time t) (set! the-time t)) (define the-render-time 0) (define (status-line-render-time t) (set! the-render-time t)) (define the-coloring-time 0) (define (status-line-coloring-time t) (set! the-coloring-time t)) (define the-command-time 0) (define (status-line-command-time t) (set! the-command-time t)) (define the-show-paren-time 0) (define (status-line-show-paren-time t) (set! the-show-paren-time t)) (define (position pos) (if (mark? pos) (mark-position pos) pos)) (define (status-line-hook) (define w (current-window)) (define b (window-buffer w)) (define point (buffer-point b)) (cond [b (define save-status (if (buffer-modified? b) "***" "---")) (define line? (local line-number-mode?)) (define col? (local column-number-mode?)) (define-values (row col) (if (and (<= (buffer-length b) (local line-number-display-limit))) (mark-row+column point) (values "-" "-"))) (define line+col (cond [(and line? col?) (~a "(" row "," col ")")] [line? (~a "L" row)] [col? (~a "C" col)] [else ""])) (~a save-status " " "Buffer: " (buffer-name) " " line+col " " "Position: " (mark-position point) " " "Length: " (buffer-length b) " " "Mode: " "(" (get-mode-name) ")" " " "Time: " the-time " " "Command Time:" the-command-time " " "Render Time: " the-render-time " " "Coloring Time: " the-coloring-time " " "Show Paren Time: " the-show-paren-time )] [else "No current buffer"]))
28093c26c23008476dca46a1b7f0cca7925418eb0066384695e0883488fa2d88
haskell/ghcide
Main.hs
Copyright ( c ) 2019 The DAML Authors . All rights reserved . SPDX - License - Identifier : Apache-2.0 GHC no longer exports def in GHC 8.6 and above # LANGUAGE TemplateHaskell # module Main(main) where import Arguments import Control.Concurrent.Extra import Control.Monad.Extra import Control.Lens ( (^.) ) import Data.Default import Data.List.Extra import Data.Maybe import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Version import Development.IDE.Core.Debouncer import Development.IDE.Core.FileStore import Development.IDE.Core.OfInterest import Development.IDE.Core.Service import Development.IDE.Core.Rules import Development.IDE.Core.Shake import Development.IDE.Core.RuleTypes import Development.IDE.LSP.Protocol import Development.IDE.Types.Location import Development.IDE.Types.Diagnostics import Development.IDE.Types.Options import Development.IDE.Types.Logger import Development.IDE.Plugin import Development.IDE.Plugin.Completions as Completions import Development.IDE.Plugin.CodeAction as CodeAction import Development.IDE.Plugin.Test as Test import Development.IDE.Session (loadSession) import qualified Language.Haskell.LSP.Core as LSP import Language.Haskell.LSP.Messages import Language.Haskell.LSP.Types import Language.Haskell.LSP.Types.Lens (params, initializationOptions) import Development.IDE.LSP.LanguageServer import qualified System.Directory.Extra as IO import System.Environment import System.IO import System.Info import System.Exit import System.FilePath import System.Time.Extra import Paths_ghcide import Development.GitRev import qualified Data.HashMap.Strict as HashMap import qualified Data.Aeson as J import HIE.Bios.Cradle import Development.IDE (action) import Text.Printf import Development.IDE.Core.Tracing import Development.IDE.Types.Shake (Key(Key)) ghcideVersion :: IO String ghcideVersion = do path <- getExecutablePath let gitHashSection = case $(gitHash) of x | x == "UNKNOWN" -> "" x -> " (GIT hash: " <> x <> ")" return $ "ghcide version: " <> showVersion version <> " (GHC: " <> showVersion compilerVersion <> ") (PATH: " <> path <> ")" <> gitHashSection main :: IO () main = do -- WARNING: If you write to stdout before runLanguageServer -- then the language server will not work Arguments{..} <- getArguments if argsVersion then ghcideVersion >>= putStrLn >> exitSuccess else hPutStrLn stderr {- see WARNING above -} =<< ghcideVersion -- lock to avoid overlapping output on stdout lock <- newLock let logger p = Logger $ \pri msg -> when (pri >= p) $ withLock lock $ T.putStrLn $ T.pack ("[" ++ upper (show pri) ++ "] ") <> msg whenJust argsCwd IO.setCurrentDirectory dir <- IO.getCurrentDirectory command <- makeLspCommandId "typesignature.add" let plugins = Completions.plugin <> CodeAction.plugin <> if argsTesting then Test.plugin else mempty onInitialConfiguration :: InitializeRequest -> Either T.Text LspConfig onInitialConfiguration x = case x ^. params . initializationOptions of Nothing -> Right defaultLspConfig Just v -> case J.fromJSON v of J.Error err -> Left $ T.pack err J.Success a -> Right a onConfigurationChange = const $ Left "Updating Not supported" options = def { LSP.executeCommandCommands = Just [command] , LSP.completionTriggerCharacters = Just "." } if argLSP then do t <- offsetTime hPutStrLn stderr "Starting LSP server..." hPutStrLn stderr "If you are seeing this in a terminal, you probably should have run ghcide WITHOUT the --lsp option!" runLanguageServer options (pluginHandler plugins) onInitialConfiguration onConfigurationChange $ \getLspId event vfs caps wProg wIndefProg getConfig rootPath -> do t <- t hPutStrLn stderr $ "Started LSP server in " ++ showDuration t sessionLoader <- loadSession $ fromMaybe dir rootPath config <- fromMaybe defaultLspConfig <$> getConfig let options = (defaultIdeOptions sessionLoader) { optReportProgress = clientSupportsProgress caps , optShakeProfiling = argsShakeProfiling , optOTMemoryProfiling = IdeOTMemoryProfiling argsOTMemoryProfiling , optTesting = IdeTesting argsTesting , optThreads = argsThreads , optCheckParents = checkParents config , optCheckProject = checkProject config } logLevel = if argsVerbose then minBound else Info debouncer <- newAsyncDebouncer let rules = do -- install the main and ghcide-plugin rules mainRule pluginRules plugins -- install the kick action, which triggers a typecheck on every -- Shake database restart, i.e. on every user edit. unless argsDisableKick $ action kick initialise caps rules getLspId event wProg wIndefProg (logger logLevel) debouncer options vfs else do GHC produces messages with UTF8 in them , so make sure the terminal does n't error hSetEncoding stdout utf8 hSetEncoding stderr utf8 putStrLn $ "Ghcide setup tester in " ++ dir ++ "." putStrLn "Report bugs at " putStrLn $ "\nStep 1/4: Finding files to test in " ++ dir files <- expandFiles (argFiles ++ ["." | null argFiles]) LSP works with absolute file paths , so try and behave similarly files <- nubOrd <$> mapM IO.canonicalizePath files putStrLn $ "Found " ++ show (length files) ++ " files" putStrLn "\nStep 2/4: Looking for hie.yaml files that control setup" cradles <- mapM findCradle files let ucradles = nubOrd cradles let n = length ucradles putStrLn $ "Found " ++ show n ++ " cradle" ++ ['s' | n /= 1] when (n > 0) $ putStrLn $ " (" ++ intercalate ", " (catMaybes ucradles) ++ ")" putStrLn "\nStep 3/4: Initializing the IDE" vfs <- makeVFSHandle debouncer <- newAsyncDebouncer let dummyWithProg _ _ f = f (const (pure ())) sessionLoader <- loadSession dir let options = (defaultIdeOptions sessionLoader) { optShakeProfiling = argsShakeProfiling -- , optOTMemoryProfiling = IdeOTMemoryProfiling argsOTMemoryProfiling , optTesting = IdeTesting argsTesting , optThreads = argsThreads , optCheckParents = NeverCheck , optCheckProject = CheckProject False } logLevel = if argsVerbose then minBound else Info ide <- initialise def mainRule (pure $ IdInt 0) (showEvent lock) dummyWithProg (const (const id)) (logger logLevel) debouncer options vfs putStrLn "\nStep 4/4: Type checking the files" setFilesOfInterest ide $ HashMap.fromList $ map ((, OnDisk) . toNormalizedFilePath') files results <- runAction "User TypeCheck" ide $ uses TypeCheck (map toNormalizedFilePath' files) _results <- runAction "GetHie" ide $ uses GetHieAst (map toNormalizedFilePath' files) _results <- runAction "GenerateCore" ide $ uses GenerateCore (map toNormalizedFilePath' files) let (worked, failed) = partition fst $ zip (map isJust results) files when (failed /= []) $ putStr $ unlines $ "Files that failed:" : map ((++) " * " . snd) failed let nfiles xs = let n = length xs in if n == 1 then "1 file" else show n ++ " files" putStrLn $ "\nCompleted (" ++ nfiles worked ++ " worked, " ++ nfiles failed ++ " failed)" when argsOTMemoryProfiling $ do let valuesRef = state $ shakeExtras ide values <- readVar valuesRef let consoleObserver Nothing = return $ \size -> printf "Total: %.2fMB\n" (fromIntegral @Int @Double size / 1e6) consoleObserver (Just k) = return $ \size -> printf " - %s: %.2fKB\n" (show k) (fromIntegral @Int @Double size / 1e3) printf "# Shake value store contents(%d):\n" (length values) let keys = nub $ Key GhcSession : Key GhcSessionDeps : [ k | (_,k) <- HashMap.keys values, k /= Key GhcSessionIO] ++ [Key GhcSessionIO] measureMemory (logger logLevel) [keys] consoleObserver valuesRef unless (null failed) (exitWith $ ExitFailure (length failed)) # ANN main ( " HLint : ignore Use nubOrd " : : String ) # expandFiles :: [FilePath] -> IO [FilePath] expandFiles = concatMapM $ \x -> do b <- IO.doesFileExist x if b then return [x] else do let recurse "." = True skip .git etc recurse x = takeFileName x `notElem` ["dist","dist-newstyle"] -- cabal directories files <- filter (\x -> takeExtension x `elem` [".hs",".lhs"]) <$> IO.listFilesInside (return . recurse) x when (null files) $ fail $ "Couldn't find any .hs/.lhs files inside directory: " ++ x return files | Print an LSP event . showEvent :: Lock -> FromServerMessage -> IO () showEvent _ (EventFileDiagnostics _ []) = return () showEvent lock (EventFileDiagnostics (toNormalizedFilePath' -> file) diags) = withLock lock $ T.putStrLn $ showDiagnosticsColored $ map (file,ShowDiag,) diags showEvent lock e = withLock lock $ print e
null
https://raw.githubusercontent.com/haskell/ghcide/3ef4ef99c4b9cde867d29180c32586947df64b9e/exe/Main.hs
haskell
WARNING: If you write to stdout before runLanguageServer then the language server will not work see WARNING above lock to avoid overlapping output on stdout install the main and ghcide-plugin rules install the kick action, which triggers a typecheck on every Shake database restart, i.e. on every user edit. , optOTMemoryProfiling = IdeOTMemoryProfiling argsOTMemoryProfiling cabal directories
Copyright ( c ) 2019 The DAML Authors . All rights reserved . SPDX - License - Identifier : Apache-2.0 GHC no longer exports def in GHC 8.6 and above # LANGUAGE TemplateHaskell # module Main(main) where import Arguments import Control.Concurrent.Extra import Control.Monad.Extra import Control.Lens ( (^.) ) import Data.Default import Data.List.Extra import Data.Maybe import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Version import Development.IDE.Core.Debouncer import Development.IDE.Core.FileStore import Development.IDE.Core.OfInterest import Development.IDE.Core.Service import Development.IDE.Core.Rules import Development.IDE.Core.Shake import Development.IDE.Core.RuleTypes import Development.IDE.LSP.Protocol import Development.IDE.Types.Location import Development.IDE.Types.Diagnostics import Development.IDE.Types.Options import Development.IDE.Types.Logger import Development.IDE.Plugin import Development.IDE.Plugin.Completions as Completions import Development.IDE.Plugin.CodeAction as CodeAction import Development.IDE.Plugin.Test as Test import Development.IDE.Session (loadSession) import qualified Language.Haskell.LSP.Core as LSP import Language.Haskell.LSP.Messages import Language.Haskell.LSP.Types import Language.Haskell.LSP.Types.Lens (params, initializationOptions) import Development.IDE.LSP.LanguageServer import qualified System.Directory.Extra as IO import System.Environment import System.IO import System.Info import System.Exit import System.FilePath import System.Time.Extra import Paths_ghcide import Development.GitRev import qualified Data.HashMap.Strict as HashMap import qualified Data.Aeson as J import HIE.Bios.Cradle import Development.IDE (action) import Text.Printf import Development.IDE.Core.Tracing import Development.IDE.Types.Shake (Key(Key)) ghcideVersion :: IO String ghcideVersion = do path <- getExecutablePath let gitHashSection = case $(gitHash) of x | x == "UNKNOWN" -> "" x -> " (GIT hash: " <> x <> ")" return $ "ghcide version: " <> showVersion version <> " (GHC: " <> showVersion compilerVersion <> ") (PATH: " <> path <> ")" <> gitHashSection main :: IO () main = do Arguments{..} <- getArguments if argsVersion then ghcideVersion >>= putStrLn >> exitSuccess lock <- newLock let logger p = Logger $ \pri msg -> when (pri >= p) $ withLock lock $ T.putStrLn $ T.pack ("[" ++ upper (show pri) ++ "] ") <> msg whenJust argsCwd IO.setCurrentDirectory dir <- IO.getCurrentDirectory command <- makeLspCommandId "typesignature.add" let plugins = Completions.plugin <> CodeAction.plugin <> if argsTesting then Test.plugin else mempty onInitialConfiguration :: InitializeRequest -> Either T.Text LspConfig onInitialConfiguration x = case x ^. params . initializationOptions of Nothing -> Right defaultLspConfig Just v -> case J.fromJSON v of J.Error err -> Left $ T.pack err J.Success a -> Right a onConfigurationChange = const $ Left "Updating Not supported" options = def { LSP.executeCommandCommands = Just [command] , LSP.completionTriggerCharacters = Just "." } if argLSP then do t <- offsetTime hPutStrLn stderr "Starting LSP server..." hPutStrLn stderr "If you are seeing this in a terminal, you probably should have run ghcide WITHOUT the --lsp option!" runLanguageServer options (pluginHandler plugins) onInitialConfiguration onConfigurationChange $ \getLspId event vfs caps wProg wIndefProg getConfig rootPath -> do t <- t hPutStrLn stderr $ "Started LSP server in " ++ showDuration t sessionLoader <- loadSession $ fromMaybe dir rootPath config <- fromMaybe defaultLspConfig <$> getConfig let options = (defaultIdeOptions sessionLoader) { optReportProgress = clientSupportsProgress caps , optShakeProfiling = argsShakeProfiling , optOTMemoryProfiling = IdeOTMemoryProfiling argsOTMemoryProfiling , optTesting = IdeTesting argsTesting , optThreads = argsThreads , optCheckParents = checkParents config , optCheckProject = checkProject config } logLevel = if argsVerbose then minBound else Info debouncer <- newAsyncDebouncer let rules = do mainRule pluginRules plugins unless argsDisableKick $ action kick initialise caps rules getLspId event wProg wIndefProg (logger logLevel) debouncer options vfs else do GHC produces messages with UTF8 in them , so make sure the terminal does n't error hSetEncoding stdout utf8 hSetEncoding stderr utf8 putStrLn $ "Ghcide setup tester in " ++ dir ++ "." putStrLn "Report bugs at " putStrLn $ "\nStep 1/4: Finding files to test in " ++ dir files <- expandFiles (argFiles ++ ["." | null argFiles]) LSP works with absolute file paths , so try and behave similarly files <- nubOrd <$> mapM IO.canonicalizePath files putStrLn $ "Found " ++ show (length files) ++ " files" putStrLn "\nStep 2/4: Looking for hie.yaml files that control setup" cradles <- mapM findCradle files let ucradles = nubOrd cradles let n = length ucradles putStrLn $ "Found " ++ show n ++ " cradle" ++ ['s' | n /= 1] when (n > 0) $ putStrLn $ " (" ++ intercalate ", " (catMaybes ucradles) ++ ")" putStrLn "\nStep 3/4: Initializing the IDE" vfs <- makeVFSHandle debouncer <- newAsyncDebouncer let dummyWithProg _ _ f = f (const (pure ())) sessionLoader <- loadSession dir let options = (defaultIdeOptions sessionLoader) { optShakeProfiling = argsShakeProfiling , optTesting = IdeTesting argsTesting , optThreads = argsThreads , optCheckParents = NeverCheck , optCheckProject = CheckProject False } logLevel = if argsVerbose then minBound else Info ide <- initialise def mainRule (pure $ IdInt 0) (showEvent lock) dummyWithProg (const (const id)) (logger logLevel) debouncer options vfs putStrLn "\nStep 4/4: Type checking the files" setFilesOfInterest ide $ HashMap.fromList $ map ((, OnDisk) . toNormalizedFilePath') files results <- runAction "User TypeCheck" ide $ uses TypeCheck (map toNormalizedFilePath' files) _results <- runAction "GetHie" ide $ uses GetHieAst (map toNormalizedFilePath' files) _results <- runAction "GenerateCore" ide $ uses GenerateCore (map toNormalizedFilePath' files) let (worked, failed) = partition fst $ zip (map isJust results) files when (failed /= []) $ putStr $ unlines $ "Files that failed:" : map ((++) " * " . snd) failed let nfiles xs = let n = length xs in if n == 1 then "1 file" else show n ++ " files" putStrLn $ "\nCompleted (" ++ nfiles worked ++ " worked, " ++ nfiles failed ++ " failed)" when argsOTMemoryProfiling $ do let valuesRef = state $ shakeExtras ide values <- readVar valuesRef let consoleObserver Nothing = return $ \size -> printf "Total: %.2fMB\n" (fromIntegral @Int @Double size / 1e6) consoleObserver (Just k) = return $ \size -> printf " - %s: %.2fKB\n" (show k) (fromIntegral @Int @Double size / 1e3) printf "# Shake value store contents(%d):\n" (length values) let keys = nub $ Key GhcSession : Key GhcSessionDeps : [ k | (_,k) <- HashMap.keys values, k /= Key GhcSessionIO] ++ [Key GhcSessionIO] measureMemory (logger logLevel) [keys] consoleObserver valuesRef unless (null failed) (exitWith $ ExitFailure (length failed)) # ANN main ( " HLint : ignore Use nubOrd " : : String ) # expandFiles :: [FilePath] -> IO [FilePath] expandFiles = concatMapM $ \x -> do b <- IO.doesFileExist x if b then return [x] else do let recurse "." = True skip .git etc files <- filter (\x -> takeExtension x `elem` [".hs",".lhs"]) <$> IO.listFilesInside (return . recurse) x when (null files) $ fail $ "Couldn't find any .hs/.lhs files inside directory: " ++ x return files | Print an LSP event . showEvent :: Lock -> FromServerMessage -> IO () showEvent _ (EventFileDiagnostics _ []) = return () showEvent lock (EventFileDiagnostics (toNormalizedFilePath' -> file) diags) = withLock lock $ T.putStrLn $ showDiagnosticsColored $ map (file,ShowDiag,) diags showEvent lock e = withLock lock $ print e
c4aebd71e19e8dcd9aee13203ec6fa73cab67bcf0e7ceeee6cd34f4d66b7f6e2
rmculpepper/crypto
digest.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 ffi/unsafe "../common/digest.rkt" "ffi.rkt") (provide sodium-blake2-digest-impl% sodium-sha256-digest-impl% sodium-sha512-digest-impl%) (define (make-ctx size) (malloc size 'atomic-interior)) (define sodium-blake2-digest-impl% (class digest-impl% (super-new) (inherit sanity-check get-size) (define/override (key-size-ok? size) (<= (crypto_generichash_blake2b_keybytes_min) size (crypto_generichash_blake2b_keybytes_max))) (define/override (-new-ctx key) (define ctx (make-ctx (crypto_generichash_blake2b_statebytes))) (crypto_generichash_blake2b_init ctx (or key #"") (get-size)) (new sodium-blake2b-digest-ctx% (impl this) (ctx ctx))) (define/override (new-hmac-ctx key) (new rkt-hmac-ctx% (impl this) (key key))) )) (define sodium-blake2b-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_generichash_blake2b_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_generichash_blake2b_final ctx buf)) (define/override (-copy) (define size (crypto_generichash_blake2b_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-blake2b-digest-ctx% (impl impl) (ctx ctx2))) )) ;; ---- (define sodium-sha256-digest-impl% (class digest-impl% (super-new) (inherit sanity-check get-size) (define/override (-new-ctx key) (define ctx (make-ctx (crypto_hash_sha256_statebytes))) (crypto_hash_sha256_init ctx) (new sodium-sha256-digest-ctx% (impl this) (ctx ctx))) (define/override (new-hmac-ctx key) (define ctx (make-ctx (crypto_auth_hmacsha256_statebytes))) (crypto_auth_hmacsha256_init ctx key (bytes-length key)) (new sodium-hmac-sha256-digest-ctx% (impl this) (ctx ctx))) )) (define sodium-sha256-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_hash_sha256_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_hash_sha256_final ctx buf)) (define/override (-copy) (define size (crypto_hash_sha256_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-sha256-digest-ctx% (impl impl) (ctx ctx2))) )) (define sodium-hmac-sha256-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_auth_hmacsha256_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_auth_hmacsha256_final ctx buf)) (define/override (-copy) (define size (crypto_auth_hmacsha256_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-hmac-sha256-digest-ctx% (impl impl) (ctx ctx2))) )) ;; ---- (define sodium-sha512-digest-impl% (class digest-impl% (super-new) (inherit sanity-check get-size) (define/override (-new-ctx key) (define ctx (make-ctx (crypto_hash_sha512_statebytes))) (crypto_hash_sha512_init ctx) (new sodium-sha512-digest-ctx% (impl this) (ctx ctx))) (define/override (new-hmac-ctx key) (define ctx (make-ctx (crypto_auth_hmacsha512_statebytes))) (crypto_auth_hmacsha512_init ctx key (bytes-length key)) (new sodium-hmac-sha512-digest-ctx% (impl this) (ctx ctx))) )) (define sodium-sha512-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_hash_sha512_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_hash_sha512_final ctx buf)) (define/override (-copy) (define size (crypto_hash_sha512_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-sha512-digest-ctx% (impl impl) (ctx ctx2))) )) (define sodium-hmac-sha512-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_auth_hmacsha512_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_auth_hmacsha512_final ctx buf)) (define/override (-copy) (define size (crypto_auth_hmacsha512_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-hmac-sha512-digest-ctx% (impl impl) (ctx ctx2))) ))
null
https://raw.githubusercontent.com/rmculpepper/crypto/fec745e8af7e3f4d5eaf83407dde2817de4c2eb0/crypto-lib/private/sodium/digest.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 ffi/unsafe "../common/digest.rkt" "ffi.rkt") (provide sodium-blake2-digest-impl% sodium-sha256-digest-impl% sodium-sha512-digest-impl%) (define (make-ctx size) (malloc size 'atomic-interior)) (define sodium-blake2-digest-impl% (class digest-impl% (super-new) (inherit sanity-check get-size) (define/override (key-size-ok? size) (<= (crypto_generichash_blake2b_keybytes_min) size (crypto_generichash_blake2b_keybytes_max))) (define/override (-new-ctx key) (define ctx (make-ctx (crypto_generichash_blake2b_statebytes))) (crypto_generichash_blake2b_init ctx (or key #"") (get-size)) (new sodium-blake2b-digest-ctx% (impl this) (ctx ctx))) (define/override (new-hmac-ctx key) (new rkt-hmac-ctx% (impl this) (key key))) )) (define sodium-blake2b-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_generichash_blake2b_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_generichash_blake2b_final ctx buf)) (define/override (-copy) (define size (crypto_generichash_blake2b_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-blake2b-digest-ctx% (impl impl) (ctx ctx2))) )) (define sodium-sha256-digest-impl% (class digest-impl% (super-new) (inherit sanity-check get-size) (define/override (-new-ctx key) (define ctx (make-ctx (crypto_hash_sha256_statebytes))) (crypto_hash_sha256_init ctx) (new sodium-sha256-digest-ctx% (impl this) (ctx ctx))) (define/override (new-hmac-ctx key) (define ctx (make-ctx (crypto_auth_hmacsha256_statebytes))) (crypto_auth_hmacsha256_init ctx key (bytes-length key)) (new sodium-hmac-sha256-digest-ctx% (impl this) (ctx ctx))) )) (define sodium-sha256-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_hash_sha256_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_hash_sha256_final ctx buf)) (define/override (-copy) (define size (crypto_hash_sha256_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-sha256-digest-ctx% (impl impl) (ctx ctx2))) )) (define sodium-hmac-sha256-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_auth_hmacsha256_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_auth_hmacsha256_final ctx buf)) (define/override (-copy) (define size (crypto_auth_hmacsha256_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-hmac-sha256-digest-ctx% (impl impl) (ctx ctx2))) )) (define sodium-sha512-digest-impl% (class digest-impl% (super-new) (inherit sanity-check get-size) (define/override (-new-ctx key) (define ctx (make-ctx (crypto_hash_sha512_statebytes))) (crypto_hash_sha512_init ctx) (new sodium-sha512-digest-ctx% (impl this) (ctx ctx))) (define/override (new-hmac-ctx key) (define ctx (make-ctx (crypto_auth_hmacsha512_statebytes))) (crypto_auth_hmacsha512_init ctx key (bytes-length key)) (new sodium-hmac-sha512-digest-ctx% (impl this) (ctx ctx))) )) (define sodium-sha512-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_hash_sha512_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_hash_sha512_final ctx buf)) (define/override (-copy) (define size (crypto_hash_sha512_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-sha512-digest-ctx% (impl impl) (ctx ctx2))) )) (define sodium-hmac-sha512-digest-ctx% (class digest-ctx% (init-field ctx) (inherit-field impl) (super-new) (define/override (-update buf start end) (crypto_auth_hmacsha512_update ctx (ptr-add buf start) (- end start))) (define/override (-final! buf) (crypto_auth_hmacsha512_final ctx buf)) (define/override (-copy) (define size (crypto_auth_hmacsha512_statebytes)) (define ctx2 (make-ctx size)) (memmove ctx2 ctx size) (new sodium-hmac-sha512-digest-ctx% (impl impl) (ctx ctx2))) ))
6b58e4fd4ad12178277b01204d52a9b9eeb32220733a189ab17ed576ae4e4fb6
FranklinChen/hugs98-plus-Sep2006
WASHFlags.hs
module WASHFlags where -- flags0 = FLAGS { generateBT = False } data FLAGS = FLAGS { generateBT :: Bool }
null
https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/Cabal/tests/wash2hs/hs/WASHFlags.hs
haskell
module WASHFlags where flags0 = FLAGS { generateBT = False } data FLAGS = FLAGS { generateBT :: Bool }
a8c2056ae2c3e1eb51890f2b70f3138f6dfed82e3c89242700eef049b0b635bd
wlitwin/graphv
graphv_anim.ml
module Ease = Ease type repeat = | Count of int | Infinite type direction = | Forward | Mirror of direction | Backward (* TODO - maybe give info about repeats *) type reason = | Done | Canceled type kind = Serial of bool * anim list | Parallel of bool * anim list | Leaf and anim = { delay : float; duration : float (* option *); repeat : repeat; repeat_delay : float; update : float -> unit; complete : (int -> reason -> unit) option; direction : direction option; kind : kind; ease : Ease.t option; } let invert_direction = function | Some (Mirror Backward) -> Some (Mirror Forward) | Some (Mirror Forward) -> Some (Mirror Backward) | Some Forward -> Some Backward | Some Backward -> Some Forward | None -> Some Backward | Some (Mirror (Mirror _)) -> assert false ;; let get_repeat (desc : anim) = match desc.repeat with | Infinite -> 1 | (Count times) -> times ;; let calc_duration (desc : anim) = let repeat = float (get_repeat desc) in desc.delay +. (desc.duration +. desc.repeat_delay)*.repeat ;; let rec invert_desc desc = let kind = match desc.kind with | Leaf -> Leaf | Serial (b, lst) -> Serial (b, List.map invert_desc lst) | Parallel (b, lst) -> Parallel (b, List.map invert_desc lst) in { desc with kind; direction = invert_direction desc.direction } ;; let rec has_infinite desc = if desc.repeat = Infinite then true else ( match desc.kind with | Leaf -> false | Serial (_, lst) | Parallel (_, lst) -> List.exists has_infinite lst ) ;; let has_infinite_lst = List.exists has_infinite let filter_infinite_serial lst = let seen = ref false in List.filter (fun desc -> if !seen then false else ( seen := has_infinite desc; keep the first infinite ) ) lst ;; let mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration update kind = { delay = Option.value ~default:0. delay; ease; repeat = Option.value ~default:(Count 1) repeat; repeat_delay = Option.value ~default:0. repeat_delay; direction; kind; complete; update; duration; } let create ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration update = mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration update Leaf ;; let propagate_ease lst = function | None -> lst | Some ease -> let rec replace = function | { ease=None; _ } as r -> {r with ease=Some ease; kind = match r.kind with | Leaf -> Leaf | Serial (b, lst) -> Serial (b, List.map replace lst) | Parallel (b, lst) -> Parallel (b, List.map replace lst) } | anim -> anim in List.map replace lst ;; let propagate_direction lst = function | None -> lst | Some direction -> let rec replace = function | { direction=None; _ } as r -> {r with direction=Some direction; kind = match r.kind with | Leaf -> Leaf | Serial (b, lst) -> Serial (b, List.map replace lst) | Parallel (b, lst) -> Parallel (b, List.map replace lst) } | anim -> anim in List.map replace lst ;; let serial ?delay ?ease ?complete ?repeat ?repeat_delay ?direction (lst : anim list) = let inf = has_infinite_lst lst in let lst = filter_infinite_serial lst in let duration = List.fold_left (fun total anim -> total +. calc_duration anim ) 0. lst in (* Propagate our repeat to children if not none *) let lst = propagate_direction lst direction in let lst = propagate_ease lst ease in mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration ignore (Serial (inf, lst)) ;; let parallel ?delay ?ease ?complete ?repeat ?repeat_delay ?direction (lst : anim list) = let inf = has_infinite_lst lst in let duration = List.fold_left (fun max_d anim -> Float.max max_d (calc_duration anim) ) Float.min_float lst in let lst = propagate_direction lst direction in let lst = propagate_ease lst ease in mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration ignore (Parallel (inf, lst)) ;; module Driver = struct type concrete = { id : int; delay : float; duration : float; mutable elapsed : float; mutable repeat : repeat; mutable direction : direction; repeat_delay : float; ease :Ease.t; update : float -> unit; complete : int -> reason -> unit; } let anim_of_description id offset (d : anim) : concrete = { id; delay = offset +. d.delay; duration = d.duration; elapsed = 0.; repeat = d.repeat; repeat_delay = d.repeat_delay; direction = Option.value ~default:Forward d.direction; ease = Option.value ~default:Ease.linear d.ease; update = d.update; complete = Option.value ~default:(fun _ _ -> ()) d.complete; } type elt = { time : float; order : int; concrete : concrete; } module PQ = MoreLabels.Set.Make(struct type t = elt let compare t1 t2 = let c = Float.compare t1.time t2.time in if c = 0 then ( let c = Int.compare t1.concrete.id t2.concrete.id in if c = 0 then Int.compare t1.order t2.order else c ) else c end) type t = { mutable time : float; mutable queue : PQ.t; mutable active : concrete list; mutable next_id : int; mutable next_uniq : int; } let create () = { time = 0.; queue = PQ.empty; active = []; next_id = 0; next_uniq = 0; } let get_next_uniq t = let id = t.next_uniq in t.next_uniq <- t.next_uniq + 1; id ;; let make_entry t c = { time = t.time +. c.delay; concrete=c; order = get_next_uniq t; } let get_next_id t = let id = t.next_id in t.next_id <- t.next_id + 1; id ;; let enqueue_anim (t : t) (anim : concrete) = let entry = make_entry t anim in anim.elapsed <- 0.; t.queue <- PQ.add entry t.queue ;; let add_basic (t : t) id offset desc = let anim = anim_of_description id offset desc in enqueue_anim t anim ;; let get_end (desc : anim) = let duration = desc.duration in desc.delay +. duration ;; let is_mirror : anim -> bool = function | {direction = Some (Mirror _); _} -> true | _ -> false ;; let has_repeat = function | Infinite -> true | (Count x) -> x >= 0 ;; let rec add_completer_if_needed (t : t) id offset (inf : bool) (anim : anim) = (* We repeat if our child is not infinite or we are infinite *) if not inf && has_repeat anim.repeat then ( let complete id reason = Option.iter (fun c -> c id reason) anim.complete; let requeue anim = let anim = if is_mirror anim then invert_desc anim else anim in let anim = { anim with delay = anim.repeat_delay } in add t id 0. anim in match anim.repeat with | Infinite -> requeue anim | Count x -> if x > 1 then ( requeue {anim with repeat = Count (x-1)} ) in let dummy = mk_desc ~delay:(get_end anim) ~complete:complete 0. ignore Leaf in add t id offset dummy ); and add (t : t) (id : int) (delay : float) (anim : anim) = match anim.kind with | Leaf -> add_basic t id delay anim | Parallel (inf, lst) -> let offset = delay +. anim.delay in List.iter (add t id offset) lst; add_completer_if_needed t id offset inf anim | Serial (inf, lst) -> let offset = delay +. anim.delay in begin match anim.direction with | None | Some Forward | Some (Mirror Forward) -> List.fold_left (fun offset anim -> add t id offset anim; offset +. calc_duration anim ) offset lst |> ignore | Some Backward | Some (Mirror Backward) -> List.fold_right (fun anim offset -> add t id offset anim; offset +. calc_duration anim ) lst offset |> ignore | _ -> assert false end; add_completer_if_needed t id offset inf anim ;; let start (t : t) (anim : anim) : int = let id = get_next_id t in add t id 0. anim; id ;; let start_ (t : t) (anim : anim) : unit = start t anim |> ignore let rec check_queue (t : t) (dt : float) = match PQ.min_elt_opt t.queue with | None -> () | Some elem -> if elem.time <= (t.time +. dt) then ( let c = elem.concrete in (* no +. dt because we add it later *) c.elapsed <- t.time -. elem.time; (* should go after to do updates in the proper order *) t.active <- (*c :: t.active;*) List.append t.active [c]; t.queue <- PQ.remove elem t.queue; check_queue t dt ) ;; let swap_mirror (anim : concrete) = match anim.direction with | Mirror Backward -> anim.direction <- Mirror Forward | Mirror Forward -> anim.direction <- Mirror Backward | _ -> () ;; let check_repeat_and_requeue (t : t) (anim : concrete) = swap_mirror anim; match anim.repeat with | Infinite -> enqueue_anim t anim | Count times -> if times > 1 then ( anim.repeat <- Count (times-1); enqueue_anim t anim ) ;; let update_animation (t : t) (dt : float) (anim : concrete) = anim.elapsed <- Float.min (anim.elapsed +. dt) anim.duration; let l = anim.ease (anim.elapsed /. anim.duration) in let l = if anim.direction = Backward || (anim.direction = Mirror Backward) then (1. -. l) else l in anim.update l; if anim.elapsed >= anim.duration then ( anim.complete anim.id Done; check_repeat_and_requeue t anim; None ) else ( Some anim ) ;; let is_list_empty = function | [] -> true | _ -> false ;; let is_empty (t : t) = is_list_empty t.active && PQ.is_empty t.queue ;; let tick (t : t) (dt : float) = check_queue t dt; t.time <- t.time +. dt; t.active <- List.filter_map (fun (anim : concrete) -> update_animation t dt anim ) t.active ; ;; let check_if_empty_and_reset (t : t) = if is_empty t then ( Maybe do n't set this to 0 ? if things depend on a fixed timestamp , this could cause jumps . as in , always add 0.016 , then cancel_all , we 're now at 0 instead of some remainder on a fixed timestamp, this could cause jumps. as in, always add 0.016, then cancel_all, we're now at 0 instead of some remainder *) t.time <- 0.; t.next_id <- 0; ) ;; let cancel (t : t) (id : int) = t.active <- List.filter (fun anim -> if anim.id = id then ( anim.complete anim.id Canceled; false ) else true ) t.active; t.queue <- PQ.filter ~f:(fun elem -> if elem.concrete.id = id then ( elem.concrete.complete id Canceled; false ) else true ) t.queue; check_if_empty_and_reset t; ;; let cancel_all (t : t) = t.time <- 0.; t.next_id <- 0; List.iter (fun anim -> anim.complete anim.id Canceled) t.active; PQ.iter ~f:(fun elem -> elem.concrete.complete elem.concrete.id Canceled) t.queue; t.active <- []; t.queue <- PQ.empty; ;; let active_count (t : t) = List.length t.active let pending_count (t : t) = PQ.cardinal t.queue end let lerp a b t = (a *. (1.0 -. t)) +. (b *. t) ;;
null
https://raw.githubusercontent.com/wlitwin/graphv/1416fe1daaedc411e8b54e5458d6005d2d3678b5/graphv_anim/lib/graphv_anim.ml
ocaml
TODO - maybe give info about repeats option Propagate our repeat to children if not none We repeat if our child is not infinite or we are infinite no +. dt because we add it later should go after to do updates in the proper order c :: t.active;
module Ease = Ease type repeat = | Count of int | Infinite type direction = | Forward | Mirror of direction | Backward type reason = | Done | Canceled type kind = Serial of bool * anim list | Parallel of bool * anim list | Leaf and anim = { delay : float; repeat : repeat; repeat_delay : float; update : float -> unit; complete : (int -> reason -> unit) option; direction : direction option; kind : kind; ease : Ease.t option; } let invert_direction = function | Some (Mirror Backward) -> Some (Mirror Forward) | Some (Mirror Forward) -> Some (Mirror Backward) | Some Forward -> Some Backward | Some Backward -> Some Forward | None -> Some Backward | Some (Mirror (Mirror _)) -> assert false ;; let get_repeat (desc : anim) = match desc.repeat with | Infinite -> 1 | (Count times) -> times ;; let calc_duration (desc : anim) = let repeat = float (get_repeat desc) in desc.delay +. (desc.duration +. desc.repeat_delay)*.repeat ;; let rec invert_desc desc = let kind = match desc.kind with | Leaf -> Leaf | Serial (b, lst) -> Serial (b, List.map invert_desc lst) | Parallel (b, lst) -> Parallel (b, List.map invert_desc lst) in { desc with kind; direction = invert_direction desc.direction } ;; let rec has_infinite desc = if desc.repeat = Infinite then true else ( match desc.kind with | Leaf -> false | Serial (_, lst) | Parallel (_, lst) -> List.exists has_infinite lst ) ;; let has_infinite_lst = List.exists has_infinite let filter_infinite_serial lst = let seen = ref false in List.filter (fun desc -> if !seen then false else ( seen := has_infinite desc; keep the first infinite ) ) lst ;; let mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration update kind = { delay = Option.value ~default:0. delay; ease; repeat = Option.value ~default:(Count 1) repeat; repeat_delay = Option.value ~default:0. repeat_delay; direction; kind; complete; update; duration; } let create ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration update = mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration update Leaf ;; let propagate_ease lst = function | None -> lst | Some ease -> let rec replace = function | { ease=None; _ } as r -> {r with ease=Some ease; kind = match r.kind with | Leaf -> Leaf | Serial (b, lst) -> Serial (b, List.map replace lst) | Parallel (b, lst) -> Parallel (b, List.map replace lst) } | anim -> anim in List.map replace lst ;; let propagate_direction lst = function | None -> lst | Some direction -> let rec replace = function | { direction=None; _ } as r -> {r with direction=Some direction; kind = match r.kind with | Leaf -> Leaf | Serial (b, lst) -> Serial (b, List.map replace lst) | Parallel (b, lst) -> Parallel (b, List.map replace lst) } | anim -> anim in List.map replace lst ;; let serial ?delay ?ease ?complete ?repeat ?repeat_delay ?direction (lst : anim list) = let inf = has_infinite_lst lst in let lst = filter_infinite_serial lst in let duration = List.fold_left (fun total anim -> total +. calc_duration anim ) 0. lst in let lst = propagate_direction lst direction in let lst = propagate_ease lst ease in mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration ignore (Serial (inf, lst)) ;; let parallel ?delay ?ease ?complete ?repeat ?repeat_delay ?direction (lst : anim list) = let inf = has_infinite_lst lst in let duration = List.fold_left (fun max_d anim -> Float.max max_d (calc_duration anim) ) Float.min_float lst in let lst = propagate_direction lst direction in let lst = propagate_ease lst ease in mk_desc ?delay ?ease ?complete ?repeat ?repeat_delay ?direction duration ignore (Parallel (inf, lst)) ;; module Driver = struct type concrete = { id : int; delay : float; duration : float; mutable elapsed : float; mutable repeat : repeat; mutable direction : direction; repeat_delay : float; ease :Ease.t; update : float -> unit; complete : int -> reason -> unit; } let anim_of_description id offset (d : anim) : concrete = { id; delay = offset +. d.delay; duration = d.duration; elapsed = 0.; repeat = d.repeat; repeat_delay = d.repeat_delay; direction = Option.value ~default:Forward d.direction; ease = Option.value ~default:Ease.linear d.ease; update = d.update; complete = Option.value ~default:(fun _ _ -> ()) d.complete; } type elt = { time : float; order : int; concrete : concrete; } module PQ = MoreLabels.Set.Make(struct type t = elt let compare t1 t2 = let c = Float.compare t1.time t2.time in if c = 0 then ( let c = Int.compare t1.concrete.id t2.concrete.id in if c = 0 then Int.compare t1.order t2.order else c ) else c end) type t = { mutable time : float; mutable queue : PQ.t; mutable active : concrete list; mutable next_id : int; mutable next_uniq : int; } let create () = { time = 0.; queue = PQ.empty; active = []; next_id = 0; next_uniq = 0; } let get_next_uniq t = let id = t.next_uniq in t.next_uniq <- t.next_uniq + 1; id ;; let make_entry t c = { time = t.time +. c.delay; concrete=c; order = get_next_uniq t; } let get_next_id t = let id = t.next_id in t.next_id <- t.next_id + 1; id ;; let enqueue_anim (t : t) (anim : concrete) = let entry = make_entry t anim in anim.elapsed <- 0.; t.queue <- PQ.add entry t.queue ;; let add_basic (t : t) id offset desc = let anim = anim_of_description id offset desc in enqueue_anim t anim ;; let get_end (desc : anim) = let duration = desc.duration in desc.delay +. duration ;; let is_mirror : anim -> bool = function | {direction = Some (Mirror _); _} -> true | _ -> false ;; let has_repeat = function | Infinite -> true | (Count x) -> x >= 0 ;; let rec add_completer_if_needed (t : t) id offset (inf : bool) (anim : anim) = if not inf && has_repeat anim.repeat then ( let complete id reason = Option.iter (fun c -> c id reason) anim.complete; let requeue anim = let anim = if is_mirror anim then invert_desc anim else anim in let anim = { anim with delay = anim.repeat_delay } in add t id 0. anim in match anim.repeat with | Infinite -> requeue anim | Count x -> if x > 1 then ( requeue {anim with repeat = Count (x-1)} ) in let dummy = mk_desc ~delay:(get_end anim) ~complete:complete 0. ignore Leaf in add t id offset dummy ); and add (t : t) (id : int) (delay : float) (anim : anim) = match anim.kind with | Leaf -> add_basic t id delay anim | Parallel (inf, lst) -> let offset = delay +. anim.delay in List.iter (add t id offset) lst; add_completer_if_needed t id offset inf anim | Serial (inf, lst) -> let offset = delay +. anim.delay in begin match anim.direction with | None | Some Forward | Some (Mirror Forward) -> List.fold_left (fun offset anim -> add t id offset anim; offset +. calc_duration anim ) offset lst |> ignore | Some Backward | Some (Mirror Backward) -> List.fold_right (fun anim offset -> add t id offset anim; offset +. calc_duration anim ) lst offset |> ignore | _ -> assert false end; add_completer_if_needed t id offset inf anim ;; let start (t : t) (anim : anim) : int = let id = get_next_id t in add t id 0. anim; id ;; let start_ (t : t) (anim : anim) : unit = start t anim |> ignore let rec check_queue (t : t) (dt : float) = match PQ.min_elt_opt t.queue with | None -> () | Some elem -> if elem.time <= (t.time +. dt) then ( let c = elem.concrete in c.elapsed <- t.time -. elem.time; t.queue <- PQ.remove elem t.queue; check_queue t dt ) ;; let swap_mirror (anim : concrete) = match anim.direction with | Mirror Backward -> anim.direction <- Mirror Forward | Mirror Forward -> anim.direction <- Mirror Backward | _ -> () ;; let check_repeat_and_requeue (t : t) (anim : concrete) = swap_mirror anim; match anim.repeat with | Infinite -> enqueue_anim t anim | Count times -> if times > 1 then ( anim.repeat <- Count (times-1); enqueue_anim t anim ) ;; let update_animation (t : t) (dt : float) (anim : concrete) = anim.elapsed <- Float.min (anim.elapsed +. dt) anim.duration; let l = anim.ease (anim.elapsed /. anim.duration) in let l = if anim.direction = Backward || (anim.direction = Mirror Backward) then (1. -. l) else l in anim.update l; if anim.elapsed >= anim.duration then ( anim.complete anim.id Done; check_repeat_and_requeue t anim; None ) else ( Some anim ) ;; let is_list_empty = function | [] -> true | _ -> false ;; let is_empty (t : t) = is_list_empty t.active && PQ.is_empty t.queue ;; let tick (t : t) (dt : float) = check_queue t dt; t.time <- t.time +. dt; t.active <- List.filter_map (fun (anim : concrete) -> update_animation t dt anim ) t.active ; ;; let check_if_empty_and_reset (t : t) = if is_empty t then ( Maybe do n't set this to 0 ? if things depend on a fixed timestamp , this could cause jumps . as in , always add 0.016 , then cancel_all , we 're now at 0 instead of some remainder on a fixed timestamp, this could cause jumps. as in, always add 0.016, then cancel_all, we're now at 0 instead of some remainder *) t.time <- 0.; t.next_id <- 0; ) ;; let cancel (t : t) (id : int) = t.active <- List.filter (fun anim -> if anim.id = id then ( anim.complete anim.id Canceled; false ) else true ) t.active; t.queue <- PQ.filter ~f:(fun elem -> if elem.concrete.id = id then ( elem.concrete.complete id Canceled; false ) else true ) t.queue; check_if_empty_and_reset t; ;; let cancel_all (t : t) = t.time <- 0.; t.next_id <- 0; List.iter (fun anim -> anim.complete anim.id Canceled) t.active; PQ.iter ~f:(fun elem -> elem.concrete.complete elem.concrete.id Canceled) t.queue; t.active <- []; t.queue <- PQ.empty; ;; let active_count (t : t) = List.length t.active let pending_count (t : t) = PQ.cardinal t.queue end let lerp a b t = (a *. (1.0 -. t)) +. (b *. t) ;;
4620ff5944eee664c421cc903c2685876b4bc879c0c9dab62a5e09e343386137
Incubaid/baardskeerder
baardskeerder.ml
* This file is part of Baardskeerder . * * Copyright ( C ) 2011 Incubaid BVBA * * Baardskeerder 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 . * * Baardskeerder 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 Baardskeerder . If not , see < / > . * This file is part of Baardskeerder. * * Copyright (C) 2011 Incubaid BVBA * * Baardskeerder 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. * * Baardskeerder 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 Baardskeerder. If not, see </>. *) include Base include Pack module Logs = struct module Flog = Flog.Flog module Flog0 = Flog0.Flog0 end module Stores = struct module Memory = Store.Memory module Sync = Store.Sync module Lwt = Store.Lwt end module Baardskeerder (LF: functor(S: Bs_internal.STORE) -> Log.LOG with type 'a m = 'a S.m) = functor(S: Bs_internal.STORE) -> struct module L = LF(S) module D = Tree.DB(L) module X = Dbx.DBX(L) module C = Catchup.Catchup(L) module PrL = Prefix.Prefix(L) type t = L.t type tx = X.tx let init fn = L.init ~d:6 fn Time.zero let make = L.make let close = L.close let with_tx log f = X.with_tx log (fun v -> f v) let log_update log ?(diff=true) f = X.log_update log ~diff f let last_update log = X.last_update log let commit_last log = X.commit_last log let catchup log i0 f a0 = C.catchup i0 f a0 log let get_latest t k = ((D.get t k): (v,k) result L.m) let key_count_latest t = D.key_count t let range_latest t first finc last linc max = D.range t first finc last linc max let range_entries_latest t first finc last linc max = D.range_entries t first finc last linc max let rev_range_entries_latest t first finc last linc max = D.rev_range_entries t first finc last linc max let prefix_keys_latest t prefix max = PrL.prefix_keys_latest t prefix max let get tx k = X.get tx k let set tx k v = X.set tx k v let delete tx k = X.delete tx k let delete_prefix tx k = X.delete_prefix tx k let range tx first finc last linc max = X.range tx first finc last linc max let range_entries tx first finc last linc max = X.range_entries tx first finc last linc max let rev_range_entries tx first finc last linc max = X.rev_range_entries tx first finc last linc max let prefix_keys tx prefix max = X.prefix_keys tx prefix max let set_metadata t s = L.set_metadata t s let get_metadata t = L.get_metadata t let unset_metadata t = L.unset_metadata t end module SB = Baardskeerder(Logs.Flog0)(Stores.Sync) include SB
null
https://raw.githubusercontent.com/Incubaid/baardskeerder/3975cb7f0e92e1f35eeab17beeb906344e43dae0/src/baardskeerder.ml
ocaml
* This file is part of Baardskeerder . * * Copyright ( C ) 2011 Incubaid BVBA * * Baardskeerder 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 . * * Baardskeerder 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 Baardskeerder . If not , see < / > . * This file is part of Baardskeerder. * * Copyright (C) 2011 Incubaid BVBA * * Baardskeerder 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. * * Baardskeerder 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 Baardskeerder. If not, see </>. *) include Base include Pack module Logs = struct module Flog = Flog.Flog module Flog0 = Flog0.Flog0 end module Stores = struct module Memory = Store.Memory module Sync = Store.Sync module Lwt = Store.Lwt end module Baardskeerder (LF: functor(S: Bs_internal.STORE) -> Log.LOG with type 'a m = 'a S.m) = functor(S: Bs_internal.STORE) -> struct module L = LF(S) module D = Tree.DB(L) module X = Dbx.DBX(L) module C = Catchup.Catchup(L) module PrL = Prefix.Prefix(L) type t = L.t type tx = X.tx let init fn = L.init ~d:6 fn Time.zero let make = L.make let close = L.close let with_tx log f = X.with_tx log (fun v -> f v) let log_update log ?(diff=true) f = X.log_update log ~diff f let last_update log = X.last_update log let commit_last log = X.commit_last log let catchup log i0 f a0 = C.catchup i0 f a0 log let get_latest t k = ((D.get t k): (v,k) result L.m) let key_count_latest t = D.key_count t let range_latest t first finc last linc max = D.range t first finc last linc max let range_entries_latest t first finc last linc max = D.range_entries t first finc last linc max let rev_range_entries_latest t first finc last linc max = D.rev_range_entries t first finc last linc max let prefix_keys_latest t prefix max = PrL.prefix_keys_latest t prefix max let get tx k = X.get tx k let set tx k v = X.set tx k v let delete tx k = X.delete tx k let delete_prefix tx k = X.delete_prefix tx k let range tx first finc last linc max = X.range tx first finc last linc max let range_entries tx first finc last linc max = X.range_entries tx first finc last linc max let rev_range_entries tx first finc last linc max = X.rev_range_entries tx first finc last linc max let prefix_keys tx prefix max = X.prefix_keys tx prefix max let set_metadata t s = L.set_metadata t s let get_metadata t = L.get_metadata t let unset_metadata t = L.unset_metadata t end module SB = Baardskeerder(Logs.Flog0)(Stores.Sync) include SB
f728222059422dcc3f20b6b3e1f3425865cd125bb6608c409dad798bcc539b4f
tfausak/json-feed
JsonFeed.hs
# LANGUAGE DeriveGeneric # -- | <> module JsonFeed ( parseFeed, renderFeed, -- * Types Feed (..), Author (..), Item (..), Attachment (..), Hub (..), -- * Wrappers Html (..), Mime (..), Url (..), ) where import Data.Aeson (FromJSON, ToJSON, Value) import qualified Data.Aeson as Json (eitherDecode, encode) import Data.Aeson.Types (Options) import qualified Data.Aeson.Types as Json import Data.ByteString.Lazy (ByteString) import qualified Data.List as List import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time (UTCTime) import GHC.Generics (Generic) import Network.Mime (MimeType) import Network.URI (URI) import qualified Network.URI as Uri import Numeric.Natural (Natural) import Text.HTML.TagSoup (Tag) import qualified Text.HTML.TagSoup as Html parseFeed :: ByteString -> Either String Feed parseFeed = Json.eitherDecode renderFeed :: Feed -> ByteString renderFeed = Json.encode data Feed = Feed { -- | The feed author. The author object has several members. These are all optional --- but if you provide an author object , then at least one is -- required. feedAuthor :: Maybe Author, -- | Provides more detail, beyond the title, on what the feed is about. A -- feed reader may display this text. feedDescription :: Maybe Text, -- | Says whether or not the feed is finished --- that is, whether or not it -- will ever update again. A feed for a temporary event, such as an instance of the Olympics , could expire . If the value is ' True ' , then it 's expired . -- Any other value, or the absence of 'feedExpired', means the feed may -- continue to update. feedExpired :: Maybe Bool, -- | The URL of an image for the feed suitable to be used in a source list. It should be square and relatively small , but not smaller than 64 x 64 ( so -- that it can look good on retina displays). As with 'feedIcon', this image -- should use transparency where appropriate, since it may be rendered on a -- non-white background. feedFavicon :: Maybe Url, -- | The URL of the feed, and serves as the unique identifier for the feed. -- As with 'feedHomePageUrl', this should be considered required for feeds on -- the public web. feedFeedUrl :: Maybe Url, -- | The URL of the resource that the feed describes. This resource may or -- may not actually be a "home" page, but it should be an HTML page. If a -- feed is published on the public web, this should be considered as -- required. But it may not make sense in the case of a file created on a -- desktop computer, when that file is not shared or is shared only -- privately. feedHomePageUrl :: Maybe Url, -- | Describes endpoints that can be used to subscribe to real-time -- notifications from the publisher of this feed. Each object has a type and -- URL, both of which are required. feedHubs :: Maybe [Hub], -- | The URL of an image for the feed suitable to be used in a timeline, much -- the way an avatar might be used. It should be square and relatively large --- such as 512 x 512 --- so that it can be scaled - down and so that it can -- look good on retina displays. It should use transparency where -- appropriate, since it may be rendered on a non-white background. feedIcon :: Maybe Url, -- | An array of objects that describe each object in the list. feedItems :: [Item], -- | The URL of a feed that provides the next /n/ items, where /n/ is -- determined by the publisher. This allows for pagination, but with the -- expectation that reader software is not required to use it and probably -- won't use it very often. 'feedNextUrl' must not be the same as -- 'feedFeedUrl', and it must not be the same as a previous 'feedNextUrl' (to -- avoid infinite loops). feedNextUrl :: Maybe Url, -- | The name of the feed, which will often correspond to the name of the -- website (blog, for instance), though not necessarily. feedTitle :: Text, -- | A description of the purpose of the feed. This is for the use of people -- looking at the raw JSON, and should be ignored by feed readers. feedUserComment :: Maybe Text, -- | The URL of the version of the format the feed uses. feedVersion :: Url } deriving (Eq, Generic, Show) instance FromJSON Feed where parseJSON = Json.genericParseJSON (jsonOptions "feed") instance ToJSON Feed where toJSON = Json.genericToJSON (jsonOptions "feed") data Author = Author { -- | The URL for an image for the author. As with icon, it should be square and relatively large --- such as 512 x 512 --- and should use transparency -- where appropriate, since it may be rendered on a non-white background. authorAvatar :: Maybe Url, -- | The author's name. authorName :: Maybe Text, -- | The URL of a site owned by the author. It could be a blog, micro-blog, -- Twitter account, and so on. Ideally the linked-to page provides a way to -- contact the author, but that's not required. The URL could be a @mailto:@ -- link, though we suspect that will be rare. authorUrl :: Maybe Url } deriving (Eq, Generic, Show) instance FromJSON Author where parseJSON value = do author <- Json.genericParseJSON (jsonOptions "author") value case (authorAvatar author, authorName author, authorUrl author) of (Nothing, Nothing, Nothing) -> fail ("invalid Author: " <> show author) _ -> pure author instance ToJSON Author where toJSON = Json.genericToJSON (jsonOptions "author") data Item = Item { -- | Lists related resources. Podcasts, for instance, would include an -- attachment that's an audio or video file. itemAttachments :: Maybe [Attachment], -- | Has the same structure as the top-level 'feedAuthor'. If not specified -- in an item, then the top-level author, if present, is the author of the -- item. itemAuthor :: Maybe Author, -- | The URL of an image to use as a banner. Some blogging systems (such as -- Medium) display a different banner image chosen to go with each post, but -- that image wouldn't otherwise appear in the content_html. A feed reader -- with a detail view may choose to show this banner image at the top of the -- detail view, possibly with the title overlaid. itemBannerImage :: Maybe Url, -- | 'itemContentHtml' and 'itemContentText' are each optional strings --- -- but one or both must be present. This is the HTML or plain text of the -- item. Important: the only place HTML is allowed in this format is in -- 'itemContentHtml'. A Twitter-like service might use 'itemContentText', -- while a blog might use 'itemContentHtml'. Use whichever makes sense for -- your resource. (It doesn't even have to be the same for each item in a -- feed.) itemContentHtml :: Maybe Html, -- | See 'itemContentHtml'. itemContentText :: Maybe Text, | Specifies the modification date in RFC 3339 format . itemDateModified :: Maybe UTCTime, | Specifies the date in RFC 3339 format . ( Example : -- @2010-02-07T14:04:00-05:00@.) itemDatePublished :: Maybe UTCTime, -- | The URL of a page elsewhere. This is especially useful for linkblogs. If -- 'itemUrl' links to where you're talking about a thing, then -- 'itemExternalUrl' links to the thing you're talking about. itemExternalUrl :: Maybe Url, -- | Unique for the item in the feed over time. If an item is ever updated, -- the ID should be unchanged. New items should never use a previously-used -- ID. If an ID is presented as a number or other type, a JSON Feed reader -- must coerce it to a string. Ideally, the ID is the full URL of the -- resource described by the item, since URLs make great unique identifiers. itemId :: Value, -- | The URL of the main image for the item. This image may also appear in -- the 'itemContentHtml' --- if so, it's a hint to the feed reader that this -- is the main, featured image. Feed readers may use the image as a preview -- (probably resized as a thumbnail and placed in a timeline). itemImage :: Maybe Url, | A plain text sentence or two describing the item . This might be -- presented in a timeline, for instance, where a detail view would display -- all of 'itemContentHtml' or 'itemContentText'. itemSummary :: Maybe Text, -- | Can have any plain text values you want. Tags tend to be just one word, -- but they may be anything. Note: they are not the equivalent of Twitter -- hashtags. Some blogging systems and other feed formats call these -- categories. itemTags :: Maybe [Text], -- | Plain text. Microblog items in particular may omit titles. itemTitle :: Maybe Text, -- | The URL of the resource described by the item. It's the permalink. This -- may be the same as the ID --- but should be present regardless. itemUrl :: Maybe Url } deriving (Eq, Generic, Show) instance FromJSON Item where parseJSON value = do item <- Json.genericParseJSON (jsonOptions "item") value case (itemContentHtml item, itemContentText item) of (Nothing, Nothing) -> fail ("invalid Item: " <> show item) _ -> pure item instance ToJSON Item where toJSON = Json.genericToJSON (jsonOptions "item") data Attachment = Attachment { -- | Specifies how long it takes to listen to or watch, when played at normal -- speed. attachmentDurationInSeconds :: Maybe Natural, | Specifies the type of the attachment , such as @audio / mpeg@. attachmentMimeType :: Mime, -- | Specifies how large the file is. attachmentSizeInBytes :: Maybe Natural, -- | Is a name for the attachment. Important: if there are multiple attachments , and two or more have the exact same title ( when title is -- present), then they are considered as alternate representations of the -- same thing. In this way a podcaster, for instance, might provide an audio -- recording in different formats. attachmentTitle :: Maybe Text, -- | Specifies the location of the attachment. attachmentUrl :: Url } deriving (Eq, Generic, Show) instance FromJSON Attachment where parseJSON = Json.genericParseJSON (jsonOptions "attachment") instance ToJSON Attachment where toJSON = Json.genericToJSON (jsonOptions "attachment") data Hub = Hub { hubType :: Text, hubUrl :: Url } deriving (Eq, Generic, Show) instance FromJSON Hub where parseJSON = Json.genericParseJSON (jsonOptions "hub") instance ToJSON Hub where toJSON = Json.genericToJSON (jsonOptions "hub") newtype Html = Html { htmlValue :: [Tag Text] } deriving (Eq, Show) instance FromJSON Html where parseJSON = Json.withText "Html" (\text -> pure Html {htmlValue = Html.parseTags text}) instance ToJSON Html where toJSON html = Json.String (Html.renderTags (htmlValue html)) newtype Mime = Mime { mimeValue :: MimeType } deriving (Eq, Show) instance FromJSON Mime where parseJSON = Json.withText "Mime" (\text -> pure Mime {mimeValue = Text.encodeUtf8 text}) instance ToJSON Mime where toJSON mime = Json.String (Text.decodeUtf8 (mimeValue mime)) newtype Url = Url { urlValue :: URI } deriving (Eq, Show) instance FromJSON Url where parseJSON = Json.withText "Url" ( \text -> case Uri.parseURI (Text.unpack text) of Just uri -> pure Url {urlValue = uri} Nothing -> fail ("invalid Url: " <> show text) ) instance ToJSON Url where toJSON url = Json.String (Text.pack (show (urlValue url))) jsonOptions :: String -> Options jsonOptions prefix = Json.defaultOptions {Json.fieldLabelModifier = fieldLabelModifier prefix} fieldLabelModifier :: String -> String -> String fieldLabelModifier prefix string = Json.camelTo2 '_' (unsafeDropPrefix prefix string) unsafeDropPrefix :: String -> String -> String unsafeDropPrefix prefix string = case dropPrefix prefix string of Just suffix -> suffix Nothing -> error ( unwords ["unsafeDropPrefix:", show prefix, "is not a prefix of", show string] ) dropPrefix :: String -> String -> Maybe String dropPrefix prefix string = if prefix `List.isPrefixOf` string then Just (drop (length prefix) string) else Nothing
null
https://raw.githubusercontent.com/tfausak/json-feed/7a2f5a2d672cbf208703ae15d40f568671ebb67f/source/library/JsonFeed.hs
haskell
| <> * Types * Wrappers | The feed author. The author object has several members. These are all - but if you provide an author object , then at least one is required. | Provides more detail, beyond the title, on what the feed is about. A feed reader may display this text. | Says whether or not the feed is finished --- that is, whether or not it will ever update again. A feed for a temporary event, such as an instance Any other value, or the absence of 'feedExpired', means the feed may continue to update. | The URL of an image for the feed suitable to be used in a source list. that it can look good on retina displays). As with 'feedIcon', this image should use transparency where appropriate, since it may be rendered on a non-white background. | The URL of the feed, and serves as the unique identifier for the feed. As with 'feedHomePageUrl', this should be considered required for feeds on the public web. | The URL of the resource that the feed describes. This resource may or may not actually be a "home" page, but it should be an HTML page. If a feed is published on the public web, this should be considered as required. But it may not make sense in the case of a file created on a desktop computer, when that file is not shared or is shared only privately. | Describes endpoints that can be used to subscribe to real-time notifications from the publisher of this feed. Each object has a type and URL, both of which are required. | The URL of an image for the feed suitable to be used in a timeline, much the way an avatar might be used. It should be square and relatively large - such as 512 x 512 --- so that it can be scaled - down and so that it can look good on retina displays. It should use transparency where appropriate, since it may be rendered on a non-white background. | An array of objects that describe each object in the list. | The URL of a feed that provides the next /n/ items, where /n/ is determined by the publisher. This allows for pagination, but with the expectation that reader software is not required to use it and probably won't use it very often. 'feedNextUrl' must not be the same as 'feedFeedUrl', and it must not be the same as a previous 'feedNextUrl' (to avoid infinite loops). | The name of the feed, which will often correspond to the name of the website (blog, for instance), though not necessarily. | A description of the purpose of the feed. This is for the use of people looking at the raw JSON, and should be ignored by feed readers. | The URL of the version of the format the feed uses. | The URL for an image for the author. As with icon, it should be square - such as 512 x 512 --- and should use transparency where appropriate, since it may be rendered on a non-white background. | The author's name. | The URL of a site owned by the author. It could be a blog, micro-blog, Twitter account, and so on. Ideally the linked-to page provides a way to contact the author, but that's not required. The URL could be a @mailto:@ link, though we suspect that will be rare. | Lists related resources. Podcasts, for instance, would include an attachment that's an audio or video file. | Has the same structure as the top-level 'feedAuthor'. If not specified in an item, then the top-level author, if present, is the author of the item. | The URL of an image to use as a banner. Some blogging systems (such as Medium) display a different banner image chosen to go with each post, but that image wouldn't otherwise appear in the content_html. A feed reader with a detail view may choose to show this banner image at the top of the detail view, possibly with the title overlaid. | 'itemContentHtml' and 'itemContentText' are each optional strings --- but one or both must be present. This is the HTML or plain text of the item. Important: the only place HTML is allowed in this format is in 'itemContentHtml'. A Twitter-like service might use 'itemContentText', while a blog might use 'itemContentHtml'. Use whichever makes sense for your resource. (It doesn't even have to be the same for each item in a feed.) | See 'itemContentHtml'. @2010-02-07T14:04:00-05:00@.) | The URL of a page elsewhere. This is especially useful for linkblogs. If 'itemUrl' links to where you're talking about a thing, then 'itemExternalUrl' links to the thing you're talking about. | Unique for the item in the feed over time. If an item is ever updated, the ID should be unchanged. New items should never use a previously-used ID. If an ID is presented as a number or other type, a JSON Feed reader must coerce it to a string. Ideally, the ID is the full URL of the resource described by the item, since URLs make great unique identifiers. | The URL of the main image for the item. This image may also appear in the 'itemContentHtml' --- if so, it's a hint to the feed reader that this is the main, featured image. Feed readers may use the image as a preview (probably resized as a thumbnail and placed in a timeline). presented in a timeline, for instance, where a detail view would display all of 'itemContentHtml' or 'itemContentText'. | Can have any plain text values you want. Tags tend to be just one word, but they may be anything. Note: they are not the equivalent of Twitter hashtags. Some blogging systems and other feed formats call these categories. | Plain text. Microblog items in particular may omit titles. | The URL of the resource described by the item. It's the permalink. This may be the same as the ID --- but should be present regardless. | Specifies how long it takes to listen to or watch, when played at normal speed. | Specifies how large the file is. | Is a name for the attachment. Important: if there are multiple present), then they are considered as alternate representations of the same thing. In this way a podcaster, for instance, might provide an audio recording in different formats. | Specifies the location of the attachment.
# LANGUAGE DeriveGeneric # module JsonFeed ( parseFeed, renderFeed, Feed (..), Author (..), Item (..), Attachment (..), Hub (..), Html (..), Mime (..), Url (..), ) where import Data.Aeson (FromJSON, ToJSON, Value) import qualified Data.Aeson as Json (eitherDecode, encode) import Data.Aeson.Types (Options) import qualified Data.Aeson.Types as Json import Data.ByteString.Lazy (ByteString) import qualified Data.List as List import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time (UTCTime) import GHC.Generics (Generic) import Network.Mime (MimeType) import Network.URI (URI) import qualified Network.URI as Uri import Numeric.Natural (Natural) import Text.HTML.TagSoup (Tag) import qualified Text.HTML.TagSoup as Html parseFeed :: ByteString -> Either String Feed parseFeed = Json.eitherDecode renderFeed :: Feed -> ByteString renderFeed = Json.encode data Feed = Feed feedAuthor :: Maybe Author, feedDescription :: Maybe Text, of the Olympics , could expire . If the value is ' True ' , then it 's expired . feedExpired :: Maybe Bool, It should be square and relatively small , but not smaller than 64 x 64 ( so feedFavicon :: Maybe Url, feedFeedUrl :: Maybe Url, feedHomePageUrl :: Maybe Url, feedHubs :: Maybe [Hub], feedIcon :: Maybe Url, feedItems :: [Item], feedNextUrl :: Maybe Url, feedTitle :: Text, feedUserComment :: Maybe Text, feedVersion :: Url } deriving (Eq, Generic, Show) instance FromJSON Feed where parseJSON = Json.genericParseJSON (jsonOptions "feed") instance ToJSON Feed where toJSON = Json.genericToJSON (jsonOptions "feed") data Author = Author authorAvatar :: Maybe Url, authorName :: Maybe Text, authorUrl :: Maybe Url } deriving (Eq, Generic, Show) instance FromJSON Author where parseJSON value = do author <- Json.genericParseJSON (jsonOptions "author") value case (authorAvatar author, authorName author, authorUrl author) of (Nothing, Nothing, Nothing) -> fail ("invalid Author: " <> show author) _ -> pure author instance ToJSON Author where toJSON = Json.genericToJSON (jsonOptions "author") data Item = Item itemAttachments :: Maybe [Attachment], itemAuthor :: Maybe Author, itemBannerImage :: Maybe Url, itemContentHtml :: Maybe Html, itemContentText :: Maybe Text, | Specifies the modification date in RFC 3339 format . itemDateModified :: Maybe UTCTime, | Specifies the date in RFC 3339 format . ( Example : itemDatePublished :: Maybe UTCTime, itemExternalUrl :: Maybe Url, itemId :: Value, itemImage :: Maybe Url, | A plain text sentence or two describing the item . This might be itemSummary :: Maybe Text, itemTags :: Maybe [Text], itemTitle :: Maybe Text, itemUrl :: Maybe Url } deriving (Eq, Generic, Show) instance FromJSON Item where parseJSON value = do item <- Json.genericParseJSON (jsonOptions "item") value case (itemContentHtml item, itemContentText item) of (Nothing, Nothing) -> fail ("invalid Item: " <> show item) _ -> pure item instance ToJSON Item where toJSON = Json.genericToJSON (jsonOptions "item") data Attachment = Attachment attachmentDurationInSeconds :: Maybe Natural, | Specifies the type of the attachment , such as @audio / mpeg@. attachmentMimeType :: Mime, attachmentSizeInBytes :: Maybe Natural, attachments , and two or more have the exact same title ( when title is attachmentTitle :: Maybe Text, attachmentUrl :: Url } deriving (Eq, Generic, Show) instance FromJSON Attachment where parseJSON = Json.genericParseJSON (jsonOptions "attachment") instance ToJSON Attachment where toJSON = Json.genericToJSON (jsonOptions "attachment") data Hub = Hub { hubType :: Text, hubUrl :: Url } deriving (Eq, Generic, Show) instance FromJSON Hub where parseJSON = Json.genericParseJSON (jsonOptions "hub") instance ToJSON Hub where toJSON = Json.genericToJSON (jsonOptions "hub") newtype Html = Html { htmlValue :: [Tag Text] } deriving (Eq, Show) instance FromJSON Html where parseJSON = Json.withText "Html" (\text -> pure Html {htmlValue = Html.parseTags text}) instance ToJSON Html where toJSON html = Json.String (Html.renderTags (htmlValue html)) newtype Mime = Mime { mimeValue :: MimeType } deriving (Eq, Show) instance FromJSON Mime where parseJSON = Json.withText "Mime" (\text -> pure Mime {mimeValue = Text.encodeUtf8 text}) instance ToJSON Mime where toJSON mime = Json.String (Text.decodeUtf8 (mimeValue mime)) newtype Url = Url { urlValue :: URI } deriving (Eq, Show) instance FromJSON Url where parseJSON = Json.withText "Url" ( \text -> case Uri.parseURI (Text.unpack text) of Just uri -> pure Url {urlValue = uri} Nothing -> fail ("invalid Url: " <> show text) ) instance ToJSON Url where toJSON url = Json.String (Text.pack (show (urlValue url))) jsonOptions :: String -> Options jsonOptions prefix = Json.defaultOptions {Json.fieldLabelModifier = fieldLabelModifier prefix} fieldLabelModifier :: String -> String -> String fieldLabelModifier prefix string = Json.camelTo2 '_' (unsafeDropPrefix prefix string) unsafeDropPrefix :: String -> String -> String unsafeDropPrefix prefix string = case dropPrefix prefix string of Just suffix -> suffix Nothing -> error ( unwords ["unsafeDropPrefix:", show prefix, "is not a prefix of", show string] ) dropPrefix :: String -> String -> Maybe String dropPrefix prefix string = if prefix `List.isPrefixOf` string then Just (drop (length prefix) string) else Nothing
303ad9ce0a7a039c8bde55255c0f6fde29225a97d9642f51c52d75970ff75347
brendanhay/semver
SemVer.hs
-- | -- Module : Data.SemVer Copyright : ( c ) 2014 - 2020 < > License : This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . A copy of the MPL can be found in the LICENSE file or -- you can obtain it at /. Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC extensions ) -- An implementation of the Semantic Versioning specification located at -- <>. -- -- A canonical 'Version' type and functions representing behaviour as outlined -- in the specification are defined alongside additional lenses, traversals, -- common manipulations, and serialisation primitives. module Data.SemVer ( -- * Version Version, -- ** Constructors version, initial, -- ** Lenses major, minor, patch, release, metadata, -- ** Incrementing -- $incrementing incrementMajor, incrementMinor, incrementPatch, -- ** Predicates isDevelopment, isPublic, -- ** Encoding toString, toText, toLazyText, toBuilder, -- ** Decoding fromText, fromLazyText, parser, -- * Identifiers Identifier, -- ** Constructors numeric, textual, -- ** Prisms _Numeric, _Textual, ) where import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as Parsec import qualified Data.SemVer.Delimited as Delimited import Data.SemVer.Internal import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as Text.Lazy import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as Text.Builder -- | Smart constructor fully specifying all available version components. version :: -- | Major version component. Int -> -- | Minor version component. Int -> -- | Patch version component. Int -> -- | Release identifiers. [Identifier] -> -- | Metadata identifiers. [Identifier] -> Version version = Version # INLINEABLE version # -- | A default 'Version' which can be used to signify initial development. -- Note : Equivalent to @0.0.0@ initial :: Version initial = version 0 0 0 [] [] -- | Lens for the major version component. major :: Functor f => (Int -> f Int) -> Version -> f Version major f x = (\y -> x {_versionMajor = y}) <$> f (_versionMajor x) # INLINEABLE major # -- | Lens for minor version component. minor :: Functor f => (Int -> f Int) -> Version -> f Version minor f x = (\y -> x {_versionMinor = y}) <$> f (_versionMinor x) # INLINEABLE minor # -- | Lens for the patch version component. patch :: Functor f => (Int -> f Int) -> Version -> f Version patch f x = (\y -> x {_versionPatch = y}) <$> f (_versionPatch x) # INLINEABLE patch # -- | Lens for the list of release identifiers. release :: Functor f => ([Identifier] -> f [Identifier]) -> Version -> f Version release f x = (\y -> x {_versionRelease = y}) <$> f (_versionRelease x) # INLINEABLE release # -- | Lens for the list of metadata identifiers. metadata :: Functor f => ([Identifier] -> f [Identifier]) -> Version -> f Version metadata f x = (\y -> x {_versionMeta = y}) <$> f (_versionMeta x) # INLINEABLE metadata # -- $incrementing -- -- The following increment functions are used to ensure that the related -- version components are reset according to the specification. -- -- See the individual function documentation for specifics regarding each -- version component. | Increment the major component of a ' Version ' by 1 , resetting the minor -- and patch components. -- -- * Major version X (X.y.z | X > 0) MUST be incremented if any backwards -- incompatible changes are introduced to the public API. -- -- * It MAY include minor and patch level changes. -- -- * Patch and minor version MUST be reset to 0 when major version -- is incremented. incrementMajor :: Version -> Version incrementMajor v = v { _versionMajor = _versionMajor v + 1, _versionMinor = 0, _versionPatch = 0 } # INLINEABLE incrementMajor # | Increment the minor component of a ' Version ' by 1 , resetting the -- patch component. -- -- * Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards -- compatible functionality is introduced to the public API. -- -- * It MUST be incremented if any public API functionality is marked -- as deprecated. -- -- * It MAY be incremented if substantial new functionality or improvements -- are introduced within the private code. -- -- * It MAY include patch level changes. -- -- * Patch version MUST be reset to 0 when minor version is incremented. incrementMinor :: Version -> Version incrementMinor v = v { _versionMinor = _versionMinor v + 1, _versionPatch = 0 } # INLINEABLE incrementMinor # | Increment the patch component of a ' Version ' by 1 . -- -- * Patch version Z (x.y.Z | x > 0) MUST be incremented if only backwards -- compatible bug fixes are introduced. -- -- * A bug fix is defined as an internal change that fixes incorrect behavior. incrementPatch :: Version -> Version incrementPatch v = v { _versionPatch = _versionPatch v + 1 } # INLINEABLE incrementPatch # -- | Check if the 'Version' is considered unstable. -- * Major version zero ( 0.y.z ) is for initial development . -- -- * Anything may change at any time. -- -- * The public API should not be considered stable. isDevelopment :: Version -> Bool isDevelopment = (== 0) . _versionMajor # INLINEABLE isDevelopment # -- | Check if the 'Version' is considered stable. -- -- Version 1.0.0 defines the public API. The way in which the version number -- is incremented after this release is dependent on this public API and how -- it changes. isPublic :: Version -> Bool isPublic = (>= 1) . _versionMajor # INLINEABLE isPublic # -- | Convert a 'Version' to it's readable 'String' representation. -- -- Note: This is optimised for cases where you require 'String' output, and -- as such is faster than the semantically equivalent @unpack . toLazyText@. toString :: Version -> String toString = toMonoid (: []) show Text.unpack Delimited.semantic {-# INLINEABLE toString #-} -- | Convert a 'Version' to a strict 'Text' representation. -- -- Note: Equivalent to @toStrict . toLazyText@ toText :: Version -> Text toText = Text.Lazy.toStrict . toLazyText # INLINEABLE toText # -- | Convert a 'Version' to a 'Text.Lazy.Text' representation. -- -- Note: This uses a lower 'Builder' buffer size optimised for commonly -- found version formats. If you have particuarly long version numbers using ' toBuilder ' and ' Text . Builder.toLazyTextWith ' to control the buffer size -- is recommended. toLazyText :: Version -> Text.Lazy.Text toLazyText = Text.Builder.toLazyTextWith 24 . toBuilder # INLINEABLE toLazyText # -- | Convert a 'Version' to a 'Builder'. toBuilder :: Version -> Builder toBuilder = Delimited.toBuilder Delimited.semantic # INLINEABLE toBuilder # | Parse a ' Version ' from ' Text ' , returning an attoparsec error message -- in the 'Left' case on failure. fromText :: Text -> Either String Version fromText = Parsec.parseOnly parser # INLINEABLE fromText # | Parse a ' Version ' from ' Text . Lazy . Text ' , returning an attoparsec error message -- in the 'Left' case on failure. -- Note : The underlying attoparsec ' ' is based on ' Text ' and this is equivalent to @fromText . toStrict@ fromLazyText :: Text.Lazy.Text -> Either String Version fromLazyText = fromText . Text.Lazy.toStrict # INLINEABLE fromLazyText # | A greedy attoparsec ' ' which requires the entire ' Text ' -- input to match. parser :: Parser Version parser = Delimited.parser Delimited.semantic True # INLINEABLE parser # -- | Safely construct a numeric identifier. numeric :: Int -> Identifier numeric = INum # INLINEABLE numeric # -- | Construct an identifier from the given 'Text', returning 'Nothing' if -- neither a numeric or valid textual input is supplied. textual :: Text -> Maybe Identifier textual = either (const Nothing) (Just . IText) . Parsec.parseOnly (textualParser Parsec.endOfInput <* Parsec.endOfInput) # INLINEABLE textual # -- | A prism into the numeric branch of an 'Identifier'. _Numeric :: Applicative f => (Int -> f Int) -> Identifier -> f Identifier _Numeric f (INum x) = INum <$> f x _Numeric _ x = pure x {-# INLINEABLE _Numeric #-} -- | A prism into the textual branch of an 'Identifier'. _Textual :: Applicative f => (Text -> f Text) -> Identifier -> f (Maybe Identifier) _Textual f (IText x) = textual <$> f x _Textual _ x = pure (Just x) {-# INLINEABLE _Textual #-}
null
https://raw.githubusercontent.com/brendanhay/semver/7bc42dd298e0d98e119486ceab4f74042d46b004/lib/Data/SemVer.hs
haskell
| Module : Data.SemVer you can obtain it at /. Stability : experimental <>. A canonical 'Version' type and functions representing behaviour as outlined in the specification are defined alongside additional lenses, traversals, common manipulations, and serialisation primitives. * Version ** Constructors ** Lenses ** Incrementing $incrementing ** Predicates ** Encoding ** Decoding * Identifiers ** Constructors ** Prisms | Smart constructor fully specifying all available version components. | Major version component. | Minor version component. | Patch version component. | Release identifiers. | Metadata identifiers. | A default 'Version' which can be used to signify initial development. | Lens for the major version component. | Lens for minor version component. | Lens for the patch version component. | Lens for the list of release identifiers. | Lens for the list of metadata identifiers. $incrementing The following increment functions are used to ensure that the related version components are reset according to the specification. See the individual function documentation for specifics regarding each version component. and patch components. * Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API. * It MAY include minor and patch level changes. * Patch and minor version MUST be reset to 0 when major version is incremented. patch component. * Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. * It MUST be incremented if any public API functionality is marked as deprecated. * It MAY be incremented if substantial new functionality or improvements are introduced within the private code. * It MAY include patch level changes. * Patch version MUST be reset to 0 when minor version is incremented. * Patch version Z (x.y.Z | x > 0) MUST be incremented if only backwards compatible bug fixes are introduced. * A bug fix is defined as an internal change that fixes incorrect behavior. | Check if the 'Version' is considered unstable. * Anything may change at any time. * The public API should not be considered stable. | Check if the 'Version' is considered stable. Version 1.0.0 defines the public API. The way in which the version number is incremented after this release is dependent on this public API and how it changes. | Convert a 'Version' to it's readable 'String' representation. Note: This is optimised for cases where you require 'String' output, and as such is faster than the semantically equivalent @unpack . toLazyText@. # INLINEABLE toString # | Convert a 'Version' to a strict 'Text' representation. Note: Equivalent to @toStrict . toLazyText@ | Convert a 'Version' to a 'Text.Lazy.Text' representation. Note: This uses a lower 'Builder' buffer size optimised for commonly found version formats. If you have particuarly long version numbers is recommended. | Convert a 'Version' to a 'Builder'. in the 'Left' case on failure. in the 'Left' case on failure. input to match. | Safely construct a numeric identifier. | Construct an identifier from the given 'Text', returning 'Nothing' if neither a numeric or valid textual input is supplied. | A prism into the numeric branch of an 'Identifier'. # INLINEABLE _Numeric # | A prism into the textual branch of an 'Identifier'. # INLINEABLE _Textual #
Copyright : ( c ) 2014 - 2020 < > License : This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . A copy of the MPL can be found in the LICENSE file or Maintainer : < > Portability : non - portable ( GHC extensions ) An implementation of the Semantic Versioning specification located at module Data.SemVer Version, version, initial, major, minor, patch, release, metadata, incrementMajor, incrementMinor, incrementPatch, isDevelopment, isPublic, toString, toText, toLazyText, toBuilder, fromText, fromLazyText, parser, Identifier, numeric, textual, _Numeric, _Textual, ) where import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as Parsec import qualified Data.SemVer.Delimited as Delimited import Data.SemVer.Internal import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as Text.Lazy import Data.Text.Lazy.Builder (Builder) import qualified Data.Text.Lazy.Builder as Text.Builder version :: Int -> Int -> Int -> [Identifier] -> [Identifier] -> Version version = Version # INLINEABLE version # Note : Equivalent to @0.0.0@ initial :: Version initial = version 0 0 0 [] [] major :: Functor f => (Int -> f Int) -> Version -> f Version major f x = (\y -> x {_versionMajor = y}) <$> f (_versionMajor x) # INLINEABLE major # minor :: Functor f => (Int -> f Int) -> Version -> f Version minor f x = (\y -> x {_versionMinor = y}) <$> f (_versionMinor x) # INLINEABLE minor # patch :: Functor f => (Int -> f Int) -> Version -> f Version patch f x = (\y -> x {_versionPatch = y}) <$> f (_versionPatch x) # INLINEABLE patch # release :: Functor f => ([Identifier] -> f [Identifier]) -> Version -> f Version release f x = (\y -> x {_versionRelease = y}) <$> f (_versionRelease x) # INLINEABLE release # metadata :: Functor f => ([Identifier] -> f [Identifier]) -> Version -> f Version metadata f x = (\y -> x {_versionMeta = y}) <$> f (_versionMeta x) # INLINEABLE metadata # | Increment the major component of a ' Version ' by 1 , resetting the minor incrementMajor :: Version -> Version incrementMajor v = v { _versionMajor = _versionMajor v + 1, _versionMinor = 0, _versionPatch = 0 } # INLINEABLE incrementMajor # | Increment the minor component of a ' Version ' by 1 , resetting the incrementMinor :: Version -> Version incrementMinor v = v { _versionMinor = _versionMinor v + 1, _versionPatch = 0 } # INLINEABLE incrementMinor # | Increment the patch component of a ' Version ' by 1 . incrementPatch :: Version -> Version incrementPatch v = v { _versionPatch = _versionPatch v + 1 } # INLINEABLE incrementPatch # * Major version zero ( 0.y.z ) is for initial development . isDevelopment :: Version -> Bool isDevelopment = (== 0) . _versionMajor # INLINEABLE isDevelopment # isPublic :: Version -> Bool isPublic = (>= 1) . _versionMajor # INLINEABLE isPublic # toString :: Version -> String toString = toMonoid (: []) show Text.unpack Delimited.semantic toText :: Version -> Text toText = Text.Lazy.toStrict . toLazyText # INLINEABLE toText # using ' toBuilder ' and ' Text . Builder.toLazyTextWith ' to control the buffer size toLazyText :: Version -> Text.Lazy.Text toLazyText = Text.Builder.toLazyTextWith 24 . toBuilder # INLINEABLE toLazyText # toBuilder :: Version -> Builder toBuilder = Delimited.toBuilder Delimited.semantic # INLINEABLE toBuilder # | Parse a ' Version ' from ' Text ' , returning an attoparsec error message fromText :: Text -> Either String Version fromText = Parsec.parseOnly parser # INLINEABLE fromText # | Parse a ' Version ' from ' Text . Lazy . Text ' , returning an attoparsec error message Note : The underlying attoparsec ' ' is based on ' Text ' and this is equivalent to @fromText . toStrict@ fromLazyText :: Text.Lazy.Text -> Either String Version fromLazyText = fromText . Text.Lazy.toStrict # INLINEABLE fromLazyText # | A greedy attoparsec ' ' which requires the entire ' Text ' parser :: Parser Version parser = Delimited.parser Delimited.semantic True # INLINEABLE parser # numeric :: Int -> Identifier numeric = INum # INLINEABLE numeric # textual :: Text -> Maybe Identifier textual = either (const Nothing) (Just . IText) . Parsec.parseOnly (textualParser Parsec.endOfInput <* Parsec.endOfInput) # INLINEABLE textual # _Numeric :: Applicative f => (Int -> f Int) -> Identifier -> f Identifier _Numeric f (INum x) = INum <$> f x _Numeric _ x = pure x _Textual :: Applicative f => (Text -> f Text) -> Identifier -> f (Maybe Identifier) _Textual f (IText x) = textual <$> f x _Textual _ x = pure (Just x)
d9339567fa43f699071dbefedf28c50ff4954dac8bcd0ad4fcf0539bb7750e85
serokell/tztime
Tree.hs
SPDX - FileCopyrightText : 2022 > -- SPDX - License - Identifier : MPL-2.0 # OPTIONS_GHC -Wno - missing - kind - signatures # # OPTIONS_GHC -F -pgmF tasty - discover -optF --tree - display --generated - module -optF Tree #
null
https://raw.githubusercontent.com/serokell/tztime/d2f7bcffb2be491c04c9e41086bc2918bf2485d6/test/Tree.hs
haskell
tree - display --generated - module -optF Tree #
SPDX - FileCopyrightText : 2022 > SPDX - License - Identifier : MPL-2.0 # OPTIONS_GHC -Wno - missing - kind - signatures #
87e5b9deb36f6267fad83ac4c1d7bef97b0c397e4a781e26b836c325c81d2bc9
cedlemo/OCaml-GI-ctypes-bindings-generator
Progress_bar_private.ml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Progress_bar_private"
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Progress_bar_private.ml
ocaml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Progress_bar_private"
fb6c34e4c7aa1945b532701d0dbcabb621453822e2439c58537e41a88b77c19f
open-company/open-company-web
media_video_modal.cljs
(ns oc.web.components.ui.media-video-modal (:require [rum.core :as rum] [cuerdas.core :as string] [org.martinklepsch.derivatives :as drv] [dommy.core :as dommy :refer-macros (sel1)] [oc.web.dispatcher :as dis] [oc.web.lib.utils :as utils] [oc.web.mixins.ui :refer (first-render-mixin)])) (def media-video-modal-height 153) (def youtube-regexp "https?://(?:www\\.|m\\.)*(?:youtube\\.com|youtu\\.be)/watch/?\\?(?:(?:time_continue|t)=\\d+s?&)?v=([a-zA-Z0-9_-]{11}).*") (def youtube-short-regexp "https?://(?:www\\.|m\\.)*(?:youtube\\.com|youtu\\.be)/([a-zA-Z0-9_-]{11}/?)") ; (def vimeo-regexp (str "(?:http|https)?:\\/\\/(?:www\\.)?vimeo.com\\/" "(?:channels\\/(?:\\w+\\/)?|groups\\/(?:[?:^\\/]*)" "\\/videos\\/|)(\\d+)(?:|\\/\\?)")) (def loom-regexp (str "(?:http|https)?:\\/\\/(?:www\\.)?(?:useloom|loom).com\\/share\\/" "([a-zA-Z0-9_-]*/?)")) (defn get-video-data [url] (let [yr (js/RegExp youtube-regexp "ig") yr2 (js/RegExp youtube-short-regexp "ig") vr (js/RegExp vimeo-regexp "ig") loomr (js/RegExp loom-regexp "ig") y-groups (.exec yr url) y2-groups (.exec yr2 url) v-groups (.exec vr url) loom-groups (.exec loomr url)] {:id (cond (nth y-groups 1) (nth y-groups 1) (nth y2-groups 1) (nth y2-groups 1) (nth v-groups 1) (nth v-groups 1) (nth loom-groups 1) (nth loom-groups 1)) :type (cond (or (nth y-groups 1) (nth y2-groups 1)) :youtube (nth v-groups 1) :vimeo (nth loom-groups 1) :loom)})) (defn- get-vimeo-thumbnail-success [s video res] (let [resp (aget res 0) thumbnail (aget resp "thumbnail_medium") video-data (assoc video :thumbnail thumbnail) dismiss-modal-cb (:dismiss-cb (first (:rum/args s)))] (dis/dispatch! [:input [:media-input :media-video] video-data]) (dismiss-modal-cb))) (def _retry (atom 0)) (declare get-vimeo-thumbnail) (defn- get-vimeo-thumbnail-retry [s video] ;; Increment the retry count (if (< (swap! _retry inc) 3) Retry at most 3 times to load the video details (get-vimeo-thumbnail s video) ;; Add the video without thumbnail (do (dis/dispatch! [:input [:media-input :media-video] video]) (let [dismiss-modal-cb (:dismiss-cb (first (:rum/args s)))] (dismiss-modal-cb))))) (defn- get-vimeo-thumbnail [s video] (.ajax js/$ #js {:method "GET" :url (str "/" (:id video) ".json") :success #(get-vimeo-thumbnail-success s video %) :error #(get-vimeo-thumbnail-retry s video)})) (defn valid-video-url? [url] (let [trimmed-url (string/trim url) yr (js/RegExp youtube-regexp "ig") yr2 (js/RegExp youtube-short-regexp "ig") vr (js/RegExp vimeo-regexp "ig") loomr (js/RegExp loom-regexp "ig")] (when (seq trimmed-url) (or (.match trimmed-url yr) (.match trimmed-url yr2) (.match trimmed-url vr) (.match trimmed-url loomr))))) (defn video-add-click [s] (let [video-data (get-video-data @(::video-url s)) dismiss-modal-cb (:dismiss-cb (first (:rum/args s)))] (if (= :vimeo (:type video-data)) (get-vimeo-thumbnail s video-data) (do (dis/dispatch! [:input [:media-input :media-video] video-data]) (dismiss-modal-cb))))) (rum/defcs media-video-modal < rum/reactive ;; Locals (rum/local false ::dismiss) (rum/local "" ::video-url) (rum/local false ::video-url-focused) (rum/local 0 ::offset-top) ;; Derivatives (drv/drv :current-user-data) first-render-mixin {:will-mount (fn [s] (let [outer-container-selector (:outer-container-selector (first (:rum/args s)))] (when-let [picker-el (sel1 (concat outer-container-selector [:div.medium-editor-media-picker]))] (reset! (::offset-top s) (.-offsetTop picker-el)))) s) :did-mount (fn [s] (when-let [video-field (rum/ref-node s "video-input")] (.focus video-field)) s)} [s {:keys [fullscreen dismiss-cb outer-container-selector offset-element-selector]}] (let [current-user-data (drv/react s :current-user-data) valid-url (valid-video-url? @(::video-url s)) scrolling-element (if fullscreen (sel1 outer-container-selector) (.-scrollingElement js/document)) win-height (or (.-clientHeight (.-documentElement js/document)) (.-innerHeight js/window)) top-offset-limit (.-offsetTop (sel1 offset-element-selector)) scroll-top (.-scrollTop scrolling-element) top-position (max 0 @(::offset-top s)) relative-position (+ top-position top-offset-limit (* scroll-top -1) media-video-modal-height) adjusted-position (if (> relative-position win-height) (max 0 (- top-position (- relative-position win-height) 16)) top-position)] [:div.media-video-modal-container {:class (when @(::video-url-focused s) "video-url-focused") :style {:top (str adjusted-position "px")}} [:div.media-video-modal-title "Embed video"] [:input.media-video-modal-input.oc-input {:type "text" :value @(::video-url s) :ref "video-input" :on-change #(reset! (::video-url s) (.. % -target -value)) :on-focus #(reset! (::video-url-focused s) true) :on-key-press (fn [e] (when (and valid-url (= (.-key e) "Enter")) (video-add-click s))) :on-blur #(when (clojure.string/blank? @(::video-url s)) (reset! (::video-url-focused s) false)) :placeholder "Paste the video link…"}] [:button.mlb-reset.embed-video-bt {:class (when-not valid-url "disabled") :on-click #(when valid-url (video-add-click s))} "Embed video"] [:div.media-video-description "Works with Loom, Youtube, and Vimeo"]]))
null
https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/components/ui/media_video_modal.cljs
clojure
Increment the retry count Add the video without thumbnail Locals Derivatives
(ns oc.web.components.ui.media-video-modal (:require [rum.core :as rum] [cuerdas.core :as string] [org.martinklepsch.derivatives :as drv] [dommy.core :as dommy :refer-macros (sel1)] [oc.web.dispatcher :as dis] [oc.web.lib.utils :as utils] [oc.web.mixins.ui :refer (first-render-mixin)])) (def media-video-modal-height 153) (def youtube-regexp "https?://(?:www\\.|m\\.)*(?:youtube\\.com|youtu\\.be)/watch/?\\?(?:(?:time_continue|t)=\\d+s?&)?v=([a-zA-Z0-9_-]{11}).*") (def youtube-short-regexp "https?://(?:www\\.|m\\.)*(?:youtube\\.com|youtu\\.be)/([a-zA-Z0-9_-]{11}/?)") (def vimeo-regexp (str "(?:http|https)?:\\/\\/(?:www\\.)?vimeo.com\\/" "(?:channels\\/(?:\\w+\\/)?|groups\\/(?:[?:^\\/]*)" "\\/videos\\/|)(\\d+)(?:|\\/\\?)")) (def loom-regexp (str "(?:http|https)?:\\/\\/(?:www\\.)?(?:useloom|loom).com\\/share\\/" "([a-zA-Z0-9_-]*/?)")) (defn get-video-data [url] (let [yr (js/RegExp youtube-regexp "ig") yr2 (js/RegExp youtube-short-regexp "ig") vr (js/RegExp vimeo-regexp "ig") loomr (js/RegExp loom-regexp "ig") y-groups (.exec yr url) y2-groups (.exec yr2 url) v-groups (.exec vr url) loom-groups (.exec loomr url)] {:id (cond (nth y-groups 1) (nth y-groups 1) (nth y2-groups 1) (nth y2-groups 1) (nth v-groups 1) (nth v-groups 1) (nth loom-groups 1) (nth loom-groups 1)) :type (cond (or (nth y-groups 1) (nth y2-groups 1)) :youtube (nth v-groups 1) :vimeo (nth loom-groups 1) :loom)})) (defn- get-vimeo-thumbnail-success [s video res] (let [resp (aget res 0) thumbnail (aget resp "thumbnail_medium") video-data (assoc video :thumbnail thumbnail) dismiss-modal-cb (:dismiss-cb (first (:rum/args s)))] (dis/dispatch! [:input [:media-input :media-video] video-data]) (dismiss-modal-cb))) (def _retry (atom 0)) (declare get-vimeo-thumbnail) (defn- get-vimeo-thumbnail-retry [s video] (if (< (swap! _retry inc) 3) Retry at most 3 times to load the video details (get-vimeo-thumbnail s video) (do (dis/dispatch! [:input [:media-input :media-video] video]) (let [dismiss-modal-cb (:dismiss-cb (first (:rum/args s)))] (dismiss-modal-cb))))) (defn- get-vimeo-thumbnail [s video] (.ajax js/$ #js {:method "GET" :url (str "/" (:id video) ".json") :success #(get-vimeo-thumbnail-success s video %) :error #(get-vimeo-thumbnail-retry s video)})) (defn valid-video-url? [url] (let [trimmed-url (string/trim url) yr (js/RegExp youtube-regexp "ig") yr2 (js/RegExp youtube-short-regexp "ig") vr (js/RegExp vimeo-regexp "ig") loomr (js/RegExp loom-regexp "ig")] (when (seq trimmed-url) (or (.match trimmed-url yr) (.match trimmed-url yr2) (.match trimmed-url vr) (.match trimmed-url loomr))))) (defn video-add-click [s] (let [video-data (get-video-data @(::video-url s)) dismiss-modal-cb (:dismiss-cb (first (:rum/args s)))] (if (= :vimeo (:type video-data)) (get-vimeo-thumbnail s video-data) (do (dis/dispatch! [:input [:media-input :media-video] video-data]) (dismiss-modal-cb))))) (rum/defcs media-video-modal < rum/reactive (rum/local false ::dismiss) (rum/local "" ::video-url) (rum/local false ::video-url-focused) (rum/local 0 ::offset-top) (drv/drv :current-user-data) first-render-mixin {:will-mount (fn [s] (let [outer-container-selector (:outer-container-selector (first (:rum/args s)))] (when-let [picker-el (sel1 (concat outer-container-selector [:div.medium-editor-media-picker]))] (reset! (::offset-top s) (.-offsetTop picker-el)))) s) :did-mount (fn [s] (when-let [video-field (rum/ref-node s "video-input")] (.focus video-field)) s)} [s {:keys [fullscreen dismiss-cb outer-container-selector offset-element-selector]}] (let [current-user-data (drv/react s :current-user-data) valid-url (valid-video-url? @(::video-url s)) scrolling-element (if fullscreen (sel1 outer-container-selector) (.-scrollingElement js/document)) win-height (or (.-clientHeight (.-documentElement js/document)) (.-innerHeight js/window)) top-offset-limit (.-offsetTop (sel1 offset-element-selector)) scroll-top (.-scrollTop scrolling-element) top-position (max 0 @(::offset-top s)) relative-position (+ top-position top-offset-limit (* scroll-top -1) media-video-modal-height) adjusted-position (if (> relative-position win-height) (max 0 (- top-position (- relative-position win-height) 16)) top-position)] [:div.media-video-modal-container {:class (when @(::video-url-focused s) "video-url-focused") :style {:top (str adjusted-position "px")}} [:div.media-video-modal-title "Embed video"] [:input.media-video-modal-input.oc-input {:type "text" :value @(::video-url s) :ref "video-input" :on-change #(reset! (::video-url s) (.. % -target -value)) :on-focus #(reset! (::video-url-focused s) true) :on-key-press (fn [e] (when (and valid-url (= (.-key e) "Enter")) (video-add-click s))) :on-blur #(when (clojure.string/blank? @(::video-url s)) (reset! (::video-url-focused s) false)) :placeholder "Paste the video link…"}] [:button.mlb-reset.embed-video-bt {:class (when-not valid-url "disabled") :on-click #(when valid-url (video-add-click s))} "Embed video"] [:div.media-video-description "Works with Loom, Youtube, and Vimeo"]]))
636a17266d35565dc8d9b00fe518c78019042f720ac593cf15772e0fadc3ea2a
tnelson/Forge
error-test-paren.rkt
#lang forge --$ (pre-declare-sig A) --$ (declare-sig A) --$ (pred p (some (join A A))) --$ (run "foo" (p))
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/examples/errors/error-test-paren.rkt
racket
#lang forge --$ (pre-declare-sig A) --$ (declare-sig A) --$ (pred p (some (join A A))) --$ (run "foo" (p))
e68c6c4efc13c57cfaf3a51390457fabd0c114209527488e70a5863d058cac92
NorfairKing/smos
TestImport.hs
module TestImport ( module X, ) where import Control.Monad as X import Data.ByteString as X (ByteString) import Data.GenValidity as X import Data.GenValidity.Containers as X () import Data.GenValidity.HashMap as X () import Data.GenValidity.Text as X () import Data.GenValidity.Time as X () import Data.Maybe as X import Data.Text as X (Text) import GHC.Generics as X hiding (Selector) import Path as X import Path.IO as X import System.Exit as X import Test.QuickCheck as X import Test.Syd as X import Test.Syd.Validity as X import Test.Syd.Validity.Aeson as X import Prelude as X hiding (head, init, last, tail)
null
https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos/test/TestImport.hs
haskell
module TestImport ( module X, ) where import Control.Monad as X import Data.ByteString as X (ByteString) import Data.GenValidity as X import Data.GenValidity.Containers as X () import Data.GenValidity.HashMap as X () import Data.GenValidity.Text as X () import Data.GenValidity.Time as X () import Data.Maybe as X import Data.Text as X (Text) import GHC.Generics as X hiding (Selector) import Path as X import Path.IO as X import System.Exit as X import Test.QuickCheck as X import Test.Syd as X import Test.Syd.Validity as X import Test.Syd.Validity.Aeson as X import Prelude as X hiding (head, init, last, tail)
3c1c1ca592c9fb22c70170cada463eaaf9a32c6082f6f0eb559cac26f821fc54
rtoy/cmucl
boot4.lisp
(in-package "VM") Add some new constants for the Sparc backend . #+sparc (progn (defconstant fixnum-tag-bits (1- lowtag-bits) "Number of tag bits used for a fixnum") (defconstant fixnum-tag-mask (1- (ash 1 fixnum-tag-bits)) "Mask to get the fixnum tag") (defconstant positive-fixnum-bits (- word-bits fixnum-tag-bits 1) "Maximum number of bits in a positive fixnum") )
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/bootfiles/18c/boot4.lisp
lisp
(in-package "VM") Add some new constants for the Sparc backend . #+sparc (progn (defconstant fixnum-tag-bits (1- lowtag-bits) "Number of tag bits used for a fixnum") (defconstant fixnum-tag-mask (1- (ash 1 fixnum-tag-bits)) "Mask to get the fixnum tag") (defconstant positive-fixnum-bits (- word-bits fixnum-tag-bits 1) "Maximum number of bits in a positive fixnum") )
772cc633a1868502f60916f3fdd5f1e71b5692d19322d7338805f10ab024c918
freckle/stackctl
Core.hs
module Stackctl.AWS.Core ( AwsEnv , HasAwsEnv(..) , awsEnvDiscover , awsSimple , awsSend , awsPaginate , awsAwait , awsAssumeRole -- * Modifiers on 'AwsEnv' , awsWithin , awsTimeout -- * 'Amazonka' extensions , AccountId(..) -- * 'Amazonka'/'ResourceT' re-exports , Region(..) , FromText(..) , ToText(..) , MonadResource ) where import Stackctl.Prelude hiding (timeout) import Amazonka hiding (LogLevel(..)) import qualified Amazonka as AWS import Amazonka.Auth.Keys (fromSession) import Amazonka.STS.AssumeRole import Conduit (ConduitM) import Control.Monad.Logger (defaultLoc, toLogStr) import Control.Monad.Trans.Resource (MonadResource) import Stackctl.AWS.Orphans () newtype AwsEnv = AwsEnv { unAwsEnv :: Env } unL :: Lens' AwsEnv Env unL = lens unAwsEnv $ \x y -> x { unAwsEnv = y } awsEnvDiscover :: MonadLoggerIO m => m AwsEnv awsEnvDiscover = do env <- liftIO $ newEnv discover AwsEnv <$> configureLogging env configureLogging :: MonadLoggerIO m => Env -> m Env configureLogging env = do loggerIO <- askLoggerIO pure $ env { AWS.envLogger = \level msg -> do loggerIO TODO : there may be a way to get a CallStack / Loc "Amazonka" (case level of AWS.Info -> LevelInfo AWS.Error -> LevelError AWS.Debug -> LevelDebug AWS.Trace -> LevelOther "trace" ) (toLogStr msg) } class HasAwsEnv env where awsEnvL :: Lens' env AwsEnv instance HasAwsEnv AwsEnv where awsEnvL = id awsSimple :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSRequest a) => Text -> a -> (AWSResponse a -> Maybe b) -> m b awsSimple name req post = do resp <- awsSend req maybe (throwString err) pure $ post resp where err = unpack name <> " successful, but processing the response failed" awsSend :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSRequest a) => a -> m (AWSResponse a) awsSend req = do AwsEnv env <- view awsEnvL send env req awsPaginate :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSPager a) => a -> ConduitM () (AWSResponse a) m () awsPaginate req = do AwsEnv env <- view awsEnvL paginateEither env req >>= hoistEither hoistEither :: MonadIO m => Either Error a -> m a hoistEither = either (liftIO . throwIO) pure awsAwait :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSRequest a) => Wait a -> a -> m Accept awsAwait w req = do AwsEnv env <- view awsEnvL await env w req awsAssumeRole :: (MonadResource m, MonadReader env m, HasAwsEnv env) => Text ^ Role ARN -> Text -- ^ Session name -> m a -- ^ Action to run as the assumed role -> m a awsAssumeRole role sessionName f = do let req = newAssumeRole role sessionName assumeEnv <- awsSimple "sts:AssumeRole" req $ \resp -> do creds <- resp ^. assumeRoleResponse_credentials token <- creds ^. authSessionToken let accessKeyId = creds ^. authAccessKeyId secretAccessKey = creds ^. authSecretAccessKey pure $ fromSession accessKeyId secretAccessKey token local (awsEnvL . unL %~ assumeEnv) f awsWithin :: (MonadReader env m, HasAwsEnv env) => Region -> m a -> m a awsWithin r = local $ over (awsEnvL . unL) (within r) awsTimeout :: (MonadReader env m, HasAwsEnv env) => Seconds -> m a -> m a awsTimeout t = local $ over (awsEnvL . unL) (timeout t) newtype AccountId = AccountId { unAccountId :: Text } deriving newtype (Eq, Ord, Show, ToJSON)
null
https://raw.githubusercontent.com/freckle/stackctl/b6673a6fcfefb1be5a034e23a74c4c88c0fb8eeb/src/Stackctl/AWS/Core.hs
haskell
* Modifiers on 'AwsEnv' * 'Amazonka' extensions * 'Amazonka'/'ResourceT' re-exports ^ Session name ^ Action to run as the assumed role
module Stackctl.AWS.Core ( AwsEnv , HasAwsEnv(..) , awsEnvDiscover , awsSimple , awsSend , awsPaginate , awsAwait , awsAssumeRole , awsWithin , awsTimeout , AccountId(..) , Region(..) , FromText(..) , ToText(..) , MonadResource ) where import Stackctl.Prelude hiding (timeout) import Amazonka hiding (LogLevel(..)) import qualified Amazonka as AWS import Amazonka.Auth.Keys (fromSession) import Amazonka.STS.AssumeRole import Conduit (ConduitM) import Control.Monad.Logger (defaultLoc, toLogStr) import Control.Monad.Trans.Resource (MonadResource) import Stackctl.AWS.Orphans () newtype AwsEnv = AwsEnv { unAwsEnv :: Env } unL :: Lens' AwsEnv Env unL = lens unAwsEnv $ \x y -> x { unAwsEnv = y } awsEnvDiscover :: MonadLoggerIO m => m AwsEnv awsEnvDiscover = do env <- liftIO $ newEnv discover AwsEnv <$> configureLogging env configureLogging :: MonadLoggerIO m => Env -> m Env configureLogging env = do loggerIO <- askLoggerIO pure $ env { AWS.envLogger = \level msg -> do loggerIO TODO : there may be a way to get a CallStack / Loc "Amazonka" (case level of AWS.Info -> LevelInfo AWS.Error -> LevelError AWS.Debug -> LevelDebug AWS.Trace -> LevelOther "trace" ) (toLogStr msg) } class HasAwsEnv env where awsEnvL :: Lens' env AwsEnv instance HasAwsEnv AwsEnv where awsEnvL = id awsSimple :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSRequest a) => Text -> a -> (AWSResponse a -> Maybe b) -> m b awsSimple name req post = do resp <- awsSend req maybe (throwString err) pure $ post resp where err = unpack name <> " successful, but processing the response failed" awsSend :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSRequest a) => a -> m (AWSResponse a) awsSend req = do AwsEnv env <- view awsEnvL send env req awsPaginate :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSPager a) => a -> ConduitM () (AWSResponse a) m () awsPaginate req = do AwsEnv env <- view awsEnvL paginateEither env req >>= hoistEither hoistEither :: MonadIO m => Either Error a -> m a hoistEither = either (liftIO . throwIO) pure awsAwait :: (MonadResource m, MonadReader env m, HasAwsEnv env, AWSRequest a) => Wait a -> a -> m Accept awsAwait w req = do AwsEnv env <- view awsEnvL await env w req awsAssumeRole :: (MonadResource m, MonadReader env m, HasAwsEnv env) => Text ^ Role ARN -> Text -> m a -> m a awsAssumeRole role sessionName f = do let req = newAssumeRole role sessionName assumeEnv <- awsSimple "sts:AssumeRole" req $ \resp -> do creds <- resp ^. assumeRoleResponse_credentials token <- creds ^. authSessionToken let accessKeyId = creds ^. authAccessKeyId secretAccessKey = creds ^. authSecretAccessKey pure $ fromSession accessKeyId secretAccessKey token local (awsEnvL . unL %~ assumeEnv) f awsWithin :: (MonadReader env m, HasAwsEnv env) => Region -> m a -> m a awsWithin r = local $ over (awsEnvL . unL) (within r) awsTimeout :: (MonadReader env m, HasAwsEnv env) => Seconds -> m a -> m a awsTimeout t = local $ over (awsEnvL . unL) (timeout t) newtype AccountId = AccountId { unAccountId :: Text } deriving newtype (Eq, Ord, Show, ToJSON)
75303e5ac586681cb4d87d1adee5cb4b47831ec720d8a88d7fa32cd55ecaaa1a
lazy-cat-io/metaverse
electron.cljs
(ns metaverse.runner.electron (:require ["electron" :refer [app dialog screen shell nativeImage crashReporter globalShortcut safeStorage ipcMain ipcRenderer contextBridge] :rename {BrowserWindow browserWindow ipcRenderer ipcRenderer Menu menu Tray tray}] ["electron-store" :as store])) (def ^{:tag js/electron.app} App app) (def ^{:tag js/electron.BrowserWindow} BrowserWindow browserWindow) (def ^{:tag js/electron.contextBridge} ContextBridge contextBridge) (def ^{:tag js/electron.crashReporter} CrashReporter crashReporter) (def ^{:tag js/electron.dialog} Dialog dialog) (def ^{:tag js/electron.globalShortcut} GlobalShortcut globalShortcut) (def ^{:tag js/electron.ipcMain} IpcMain ipcMain) (def ^{:tag js/electron.ipcRenderer} IpcRenderer ipcRenderer) (def ^{:tag js/electron.Menu} Menu menu) (def ^{:tag js/electron.nativeImage} NativeImage nativeImage) (def ^{:tag js/electron.safeStorage} SafeStorage safeStorage) (def ^{:tag js/electron.screen} Screen screen) (def ^{:tag js/electron.shell} Shell shell) (def ^{:tag js/ElectronStore} Store store) (def ^{:tag js/electron.Tray} Tray tray)
null
https://raw.githubusercontent.com/lazy-cat-io/metaverse/2e5754967ac0e4219197da3ff6937b666d2d26fa/src/main/clojure/metaverse/runner/electron.cljs
clojure
(ns metaverse.runner.electron (:require ["electron" :refer [app dialog screen shell nativeImage crashReporter globalShortcut safeStorage ipcMain ipcRenderer contextBridge] :rename {BrowserWindow browserWindow ipcRenderer ipcRenderer Menu menu Tray tray}] ["electron-store" :as store])) (def ^{:tag js/electron.app} App app) (def ^{:tag js/electron.BrowserWindow} BrowserWindow browserWindow) (def ^{:tag js/electron.contextBridge} ContextBridge contextBridge) (def ^{:tag js/electron.crashReporter} CrashReporter crashReporter) (def ^{:tag js/electron.dialog} Dialog dialog) (def ^{:tag js/electron.globalShortcut} GlobalShortcut globalShortcut) (def ^{:tag js/electron.ipcMain} IpcMain ipcMain) (def ^{:tag js/electron.ipcRenderer} IpcRenderer ipcRenderer) (def ^{:tag js/electron.Menu} Menu menu) (def ^{:tag js/electron.nativeImage} NativeImage nativeImage) (def ^{:tag js/electron.safeStorage} SafeStorage safeStorage) (def ^{:tag js/electron.screen} Screen screen) (def ^{:tag js/electron.shell} Shell shell) (def ^{:tag js/ElectronStore} Store store) (def ^{:tag js/electron.Tray} Tray tray)
0fee276eafc6b6f71b2ec28ef1b01f0f09db1895a4747f0cbed23338f77058a8
camlp5/camlp5
reloc.mli
(* camlp5r *) (* reloc.mli,v *) Copyright ( c ) INRIA 2007 - 2017 val expr : (MLast.loc -> MLast.loc) -> int -> MLast.expr -> MLast.expr;; val longid : (MLast.loc -> MLast.loc) -> int -> MLast.longid -> MLast.longid;; val longid_lident : (MLast.loc -> MLast.loc) -> int -> MLast.longid_lident -> MLast.longid_lident;; val patt : (MLast.loc -> MLast.loc) -> int -> MLast.patt -> MLast.patt;; val ctyp : (MLast.loc -> MLast.loc) -> int -> MLast.ctyp -> MLast.ctyp;; val sig_item : (MLast.loc -> MLast.loc) -> int -> MLast.sig_item -> MLast.sig_item;; val str_item : (MLast.loc -> MLast.loc) -> int -> MLast.str_item -> MLast.str_item;; (* Equality over syntax trees *) val eq_longid : MLast.longid -> MLast.longid -> bool;; val eq_longid_lident : MLast.longid_lident -> MLast.longid_lident -> bool;; val eq_expr : MLast.expr -> MLast.expr -> bool;; val eq_patt : MLast.patt -> MLast.patt -> bool;; val eq_ctyp : MLast.ctyp -> MLast.ctyp -> bool;; val eq_str_item : MLast.str_item -> MLast.str_item -> bool;; val eq_sig_item : MLast.sig_item -> MLast.sig_item -> bool;; val eq_module_expr : MLast.module_expr -> MLast.module_expr -> bool;; val eq_module_type : MLast.module_type -> MLast.module_type -> bool;; val eq_class_sig_item : MLast.class_sig_item -> MLast.class_sig_item -> bool;; val eq_class_str_item : MLast.class_str_item -> MLast.class_str_item -> bool;; val eq_class_type : MLast.class_type -> MLast.class_type -> bool;; val eq_class_expr : MLast.class_expr -> MLast.class_expr -> bool;;
null
https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/ocaml_src/main/reloc.mli
ocaml
camlp5r reloc.mli,v Equality over syntax trees
Copyright ( c ) INRIA 2007 - 2017 val expr : (MLast.loc -> MLast.loc) -> int -> MLast.expr -> MLast.expr;; val longid : (MLast.loc -> MLast.loc) -> int -> MLast.longid -> MLast.longid;; val longid_lident : (MLast.loc -> MLast.loc) -> int -> MLast.longid_lident -> MLast.longid_lident;; val patt : (MLast.loc -> MLast.loc) -> int -> MLast.patt -> MLast.patt;; val ctyp : (MLast.loc -> MLast.loc) -> int -> MLast.ctyp -> MLast.ctyp;; val sig_item : (MLast.loc -> MLast.loc) -> int -> MLast.sig_item -> MLast.sig_item;; val str_item : (MLast.loc -> MLast.loc) -> int -> MLast.str_item -> MLast.str_item;; val eq_longid : MLast.longid -> MLast.longid -> bool;; val eq_longid_lident : MLast.longid_lident -> MLast.longid_lident -> bool;; val eq_expr : MLast.expr -> MLast.expr -> bool;; val eq_patt : MLast.patt -> MLast.patt -> bool;; val eq_ctyp : MLast.ctyp -> MLast.ctyp -> bool;; val eq_str_item : MLast.str_item -> MLast.str_item -> bool;; val eq_sig_item : MLast.sig_item -> MLast.sig_item -> bool;; val eq_module_expr : MLast.module_expr -> MLast.module_expr -> bool;; val eq_module_type : MLast.module_type -> MLast.module_type -> bool;; val eq_class_sig_item : MLast.class_sig_item -> MLast.class_sig_item -> bool;; val eq_class_str_item : MLast.class_str_item -> MLast.class_str_item -> bool;; val eq_class_type : MLast.class_type -> MLast.class_type -> bool;; val eq_class_expr : MLast.class_expr -> MLast.class_expr -> bool;;
a8bd578a9636b65de280ce2f28c897e7fb7f1a9b3c8507c960f92b7af6b9652d
ontodev/howl
project.clj
(def project-version "0.3.0-SNAPSHOT") (defproject howl project-version :description "Tools for processing HOWL format" :url "" :license {:name "Simplified BSD License" :url "-2-Clause"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/clojurescript "1.8.40"] [com.lucasbradstreet/instaparse-cljs "1.4.1.1"] [org.clojure/tools.cli "0.3.3"] [org.clojure/data.json "0.2.6"] [edn-ld "0.2.2"]] :plugins [[lein-cljsbuild "1.1.3"] [lein-project-version "0.1.0"] [lein-cljfmt "0.5.3"]] :main howl.cli :aot [howl.cli] :manifest {"Implementation-Version" ~project-version} :cljsbuild {:builds [{:source-paths ["src"] :compiler {:optimizations :advanced :output-dir "target" :output-to "target/howl.js" :pretty-print true}}]})
null
https://raw.githubusercontent.com/ontodev/howl/0880c903a0f603324309153586f720860d1e7d89/project.clj
clojure
(def project-version "0.3.0-SNAPSHOT") (defproject howl project-version :description "Tools for processing HOWL format" :url "" :license {:name "Simplified BSD License" :url "-2-Clause"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/clojurescript "1.8.40"] [com.lucasbradstreet/instaparse-cljs "1.4.1.1"] [org.clojure/tools.cli "0.3.3"] [org.clojure/data.json "0.2.6"] [edn-ld "0.2.2"]] :plugins [[lein-cljsbuild "1.1.3"] [lein-project-version "0.1.0"] [lein-cljfmt "0.5.3"]] :main howl.cli :aot [howl.cli] :manifest {"Implementation-Version" ~project-version} :cljsbuild {:builds [{:source-paths ["src"] :compiler {:optimizations :advanced :output-dir "target" :output-to "target/howl.js" :pretty-print true}}]})
4e533afd1e2fc7e3d6e26b2e972a691bce643af73fa4db52a4570382d1cbb46f
TrustInSoft/tis-interpreter
eval_behaviors.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Cil_types open Cil open Value_util open Eval_annots module AB = Eval_annots.ActiveBehaviors * Evaluate the assigns [ assigns ] of [ kf ] ( for one or more behaviors ) in the state [ with_formals ] . [ per_behavior ] indicates that the assigns clause is computed separately for each behavior . It is used to control the emission of warnings . in the state [with_formals]. [per_behavior] indicates that the assigns clause is computed separately for each behavior. It is used to control the emission of warnings. *) let compute_assigns kf assigns return_used sclob ~with_formals ~per_behavior = let with_alarms = CilE.warn_none_mode in let vi = Kernel_function.get_vi kf in if (not (Cvalue.Model.is_reachable with_formals)) || Cil.hasAttribute "noreturn" vi.vattr then None, Cvalue.Model.bottom else let returned_value, with_formals = Library_functions.returned_value kf with_formals in let returned_value = ref returned_value in let env = Eval_terms.env_assigns with_formals in let pp_eval_error fmt e = if e <> Eval_terms.CAlarm then Format.fprintf fmt "@ (%a)" Eval_terms.pretty_logic_evaluation_error e in (* Treat one assign ... \from ... clause. Update [state] accordingly, as well as [returned_value] and [sclob] *) let treat_assign state ({it_content = out}, ins as asgn) = Evaluate the contents of one element of the from clause , topify them , and add them to the current state of the evaluation in acc and add them to the current state of the evaluation in acc *) if Value_parameters.InterpreterMode.get() then begin warning_once_current "Assign in extern function call. Stopping.%t" Value_util.pp_callstack; raise Db.Value.Aborted end; let one_from_contents acc { it_content = t } = let r = Eval_terms.eval_term ~with_alarms env t in Cvalue.V.join acc (Cvalue.V.topify_arith_origin r.Eval_terms.eover) in (* evaluation of the entire from clause *) let froms_contents = match ins with | FromAny -> Cvalue.V.top_int | From l -> try let filter x = not(List.mem "indirect" x.it_content.term_name) in let direct = List.filter filter l in List.fold_left one_from_contents Cvalue.V.top_int direct with Eval_terms.LogicEvalError e -> warning_once_current "cannot interpret@ 'from' clause@ \ '%a'@ of function %a%a" Printer.pp_from asgn Kernel_function.pretty kf pp_eval_error e; Cvalue.V.top in Treat one location coming from the evaluation of [ out ] let treat_output_loc acc loc = let valid = Locations.valid_part ~for_writing:true loc in if Locations.is_bottom_loc valid then (if (not (Locations.is_bottom_loc loc)) then (Value_parameters.warning ~current:true ~once:true "@[Completely invalid destination@ for assigns@ clause %a.@ \ Ignoring.@]" Printer.pp_term out); acc) else ( Locals_scoping.remember_if_locals_in_value sclob loc froms_contents; let state' = snd (Cvalue.Model.add_binding ~exact:false acc loc froms_contents) in if Cvalue.Model.equal Cvalue.Model.top state' then ( Value_parameters.error ~once:true ~current:true "Cannot@ handle@ assigns@ for %a,@ location@ is@ too@ imprecise@ \ (%a).@ Assuming@ it@ is@ not@ assigned,@ but@ be@ aware@ this\ @ is@ incorrect." Printer.pp_term out Locations.pretty loc; acc) else state') in (* Treat the output part of the assigns clause *) if Logic_utils.is_result out then ( (* Special case for \result *) returned_value := Cvalue.V.join froms_contents !returned_value; state ) else try (* TODO: warn about errors during evaluation *) let loc = Eval_terms.eval_tlval_as_location ~with_alarms env out in treat_output_loc state loc with | Eval_terms.LogicEvalError e -> warning_once_current "cannot interpret assigns %a@ in function %a%a; effects will be \ ignored" Printer.pp_term out Kernel_function.pretty kf pp_eval_error e; state in (* Treat all the assigns for the function *) let state = match assigns with | WritesAny -> (* No need to warn for missing assigns when evaluating a behavior, we can always use those of the default behavior as a fallback. *) if not per_behavior then warning_once_current "Cannot handle empty assigns clause. Assuming assigns \\nothing: be aware this is probably incorrect."; with_formals | Writes l -> Warn for clauses without \from let no_from = List.filter (fun (_, from) -> from = FromAny) l in (match no_from with | (out, _) :: _ as l -> let source = fst out.it_content.term_loc in Value_parameters.warning ~source ~once:true "@[no \\from part@ for clause '%a' of@ function %a@]" Printer.pp_assigns (Writes l) Kernel_function.pretty kf | [] -> () ); Warn in case the ' assigns \result ' clause is missing (if return_used then let for_result (out, _) = Logic_utils.is_result out.it_content in let result = List.filter for_result l in if result = [] then let source = fst (Kernel_function.get_location kf) in Value_parameters.warning ~once:true ~source "@[no 'assigns \\result@ \\from ...'@ clause@ specified \ for@ function %a@]" Kernel_function.pretty kf ); (* Compute the effects of the assigns clause *) List.fold_left treat_assign with_formals l in let retres_vi, state = let return_type = getReturnType vi.vtype in if isVoidType return_type then None, state else let offsetmap = Eval_op.offsetmap_of_v return_type !returned_value in let rvi, state = Library_functions.add_retres_to_state kf offsetmap state in Some rvi, state in retres_vi, state Performs the join of two varinfo option , used for the return value . If both are Some , then they should be the same . If both are Some, then they should be the same. *) let join_rvi rvi1 rvi2 = Extlib.merge_opt (fun () vi1 vi2 -> assert (Cil_datatype.Varinfo.equal vi1 vi2); vi1 ) () rvi1 rvi2 (* Returns the assigns clause to be used during per-behavior processing. The specification states that, if a behavior has no assigns clause, then the assigns clause of the default behavior must be used instead. *) let get_assigns_for_behavior ab b = match b.b_assigns with | WritesAny -> (* no assigns clause, using the default behavior's *) let def_b = AB.behavior_from_name ab Cil.default_behavior_name in def_b.b_assigns | _ -> b.b_assigns let compute_assigns_and_post_conds_for_behavior kf ab ~with_formals bhv_states_after_requires return_used sclob b_name = let b = AB.behavior_from_name ab b_name in let states_after_requires = List.assoc b_name bhv_states_after_requires in let retres_vi = ref None in let states_after_assigns = State_set.fold (fun acc_st (state, trace) -> let rvi, state_after_assigns = let assigns = get_assigns_for_behavior ab b in compute_assigns kf assigns return_used sclob state true in retres_vi := join_rvi !retres_vi rvi; State_set.add (state_after_assigns, trace) acc_st ) State_set.empty states_after_requires in let states_after_post_conds = Eval_annots.check_fct_postconditions_for_behavior kf ab b Normal ~result:!retres_vi ~per_behavior:true ~pre_state:with_formals states_after_assigns in (b_name, states_after_post_conds) When there is at least one behavior whose active status is [ True ] , we can perform the intersection of the states and assigns clauses , and compute the result for every [ True ] state at once . Here , [ b_names ] is a list of True behaviors . perform the intersection of the states and assigns clauses, and compute the result for every [True] state at once. Here, [b_names] is a list of True behaviors. *) let compute_merged_assigns_and_post_conds_for_behaviors kf ab bhv_states_after_requires return_used sclob b_names = if b_names = [] then State_set.empty else let bs = List.map (AB.behavior_from_name ab) b_names in let states_after_requires_list = Extlib.filter_map (fun (b_name, _) -> List.mem b_name b_names) snd bhv_states_after_requires in let state_after_requires, trace = State_set.(join (narrow_list states_after_requires_list)) in let retres_vi = ref None in let state_after_assigns = List.fold_left (fun st0 b -> let rvi, state_after_assigns = let assigns = get_assigns_for_behavior ab b in compute_assigns kf assigns return_used sclob st0 true in retres_vi := join_rvi !retres_vi rvi; state_after_assigns ) state_after_requires bs in let states_after_post_conds = Eval_annots.check_fct_postconditions kf ab bs Normal ~result:!retres_vi ~per_behavior:true ~pre_state:state_after_requires (State_set.singleton (state_after_assigns, trace)) in let l = State_set.to_list states_after_post_conds in let lr = List.map (fun s -> s,trace) l in State_set.of_list lr * Computes and returns three disjoint sets , [ b_t ] , [ b_u ] and [ b_f ] , where [ b_t ] contains all behaviors which are certainly active ( status [ True ] , and not empty after requires ) , [ b_u ] contains behaviors which are possibly active ( status [ Unknown ] , and not empty after requires ) , and [ b_f ] contains behaviors which are empty . The default behavior is never included in the returned sets . Note that [ b_f ] does NOT contain behaviors which were previously known to be inactive ( set to [ False ] by the assumes clause ) . [ bhv_states_post_requires ] is an association list from behaviors to their states after applying requires clauses . where [b_t] contains all behaviors which are certainly active (status [True], and not empty after requires), [b_u] contains behaviors which are possibly active (status [Unknown], and not empty after requires), and [b_f] contains behaviors which are empty. The default behavior is never included in the returned sets. Note that [b_f] does NOT contain behaviors which were previously known to be inactive (set to [False] by the assumes clause). [bhv_states_post_requires] is an association list from behaviors to their states after applying requires clauses. *) let partition_behaviors_after_requires ab bhv_states_after_requires = (* We filter the default behavior here *) let bhv_states_after_requires' = List.filter (fun (b_name, _) -> b_name <> Cil.default_behavior_name) bhv_states_after_requires in List.fold_left (fun (b_t0, b_u0, b_f0) (b_name, stateset) -> if State_set.is_empty stateset then (* falsely active behavior: requires clauses not satisfied *) (b_t0, b_u0, b_name :: b_f0) else (* requires clauses did not change the behavior's status *) match ab.AB.is_active (AB.behavior_from_name ab b_name) with | Eval_terms.True -> (b_name :: b_t0, b_u0, b_f0) | Eval_terms.Unknown -> (b_t0, b_name :: b_u0, b_f0) | Eval_terms.False -> (b_t0, b_u0, b_name :: b_f0) ) ([],[],[]) bhv_states_after_requires' * Promotes [ Unknown ] behaviors from [ b_u ] to [ True ] when they are the only possible choice in a given complete set . Returns the new sets [ b_t ] and [ b_u ] , of [ True ] and [ Unknown ] behaviors . Promotes [Unknown] behaviors from [b_u] to [True] when they are the only possible choice in a given complete set. Returns the new sets [b_t] and [b_u], of [True] and [Unknown] behaviors. *) let promote_complete_unknown_behaviors comp_lists b_t b_u = ListLabels.fold_left ~init:(b_t,b_u) comp_lists ~f:(fun (acc_t,acc_u as acc) comp_set -> let unk_bhvs_in_set = List.filter (ListLabels.mem ~set:b_u) comp_set in match unk_bhvs_in_set with | [] -> (* no Unknown behaviors, nothing to promote *)acc | [b_unk] -> (* a single Unknown behavior, will be promoted to True *) b_unk :: acc_t,List.filter (fun b -> b <> b_unk) acc_u more than one Unknown behavior , can not promote acc_t,acc_u ) (* Applies the given [assumes] clauses of a given behavior [b] to the states passed as argument, in order to reduce them (no status is emitted). *) let reduce_by_assumes_of_behavior kf states b = let build_prop assume = Property.ip_of_assumes kf Kglobal b assume in let build_env pre = Eval_terms.env_pre_f ~pre () in eval_and_reduce_p_kind kf b ~active:true Assumes b.b_assumes build_prop build_env states (* Reduce the state by the assumes and requires clauses for behavior [b], and emit statuses for the requires. *) let compute_assumes_and_requires_for_behavior kf ab b call_kinstr states = let states_after_assumes = reduce_by_assumes_of_behavior kf states b in check_fct_preconditions_for_behavior kf ab ~per_behavior:true call_kinstr states_after_assumes b let compute_using_specification_single_behavior kf spec ~call_kinstr ~with_formals = let ab = AB.create_from_spec with_formals spec in let stateset = Eval_annots.check_fct_preconditions kf ab call_kinstr with_formals in let (with_formals,trace) = State_set.join stateset in let return_used = match call_kinstr with | Kglobal -> true | Kstmt {skind = Instr (Call (lv, _, _, _))} -> lv <> None || Value_util.postconditions_mention_result spec | _ -> assert false in let sclob = Locals_scoping.bottom () in let retres_vi, result_state = let assigns = Ast_info.merge_assigns (AB.active_behaviors ab) in compute_assigns kf assigns return_used sclob ~with_formals ~per_behavior:false in let result_states = Eval_annots.check_fct_postconditions kf ab (Annotations.behaviors kf) Normal ~result:retres_vi ~per_behavior:false ~pre_state:with_formals (State_set.singleton (result_state,trace)) in let aux state = match retres_vi with | None -> None, state | Some vi -> match state with | Cvalue.Model.Bottom -> None, state | Cvalue.Model.Top -> Warn.warn_top () | Cvalue.Model.Map _ -> let retres_base = Base.of_varinfo vi in let without_ret = Cvalue.Model.remove_base retres_base state in match Cvalue.Model.find_base_or_default retres_base state with | `Map m -> Some m, without_ret | `Bottom -> None, state | `Top -> Warn.warn_top () in { Value_types.c_values = List.map aux (State_set.to_list result_states); c_clobbered = sclob.Locals_scoping.clob; c_cacheable = Value_types.Cacheable; c_from = None; } let compute_using_specification_multiple_behaviors kf spec ~call_kinstr ~with_formals = let ab = AB.create_from_spec with_formals spec in let sclob = Locals_scoping.bottom () in let complete_bhvs_lists = ab.AB.funspec.spec_complete_behaviors in let maybe_active_behaviors = ListLabels.filter ab.AB.funspec.spec_behavior ~f:(fun b -> ab.AB.is_active b <> Eval_terms.False && not (Cil.is_default_behavior b)) in let def_bhv = AB.behavior_from_name ab Cil.default_behavior_name in (* TODO: integrate slevel *) let init_trace = Trace.initial kf in let init_state_set = State_set.singleton (with_formals, init_trace) in let states_after_global_requires = Eval_annots.check_fct_preconditions_for_behavior kf ab ~per_behavior:true call_kinstr init_state_set def_bhv in (* joined_state_after_global_requires is an overapproximation of the disjunction of states after the global requires clause. It is used in some places, but the actual disjunction is more precise and should be used when possible. *) let (joined_state_after_global_requires,trace) = State_set.join states_after_global_requires in (* Notify user about inactive behaviors *) Eval_annots.process_inactive_behaviors kf ab (joined_state_after_global_requires,trace); In order to know which behaviors will be considered by the analysis , we need to compute the \requires clause to eliminate empty behaviors , such as " assumes x < 0 ; requires x > 0 ; " . Otherwise , we will later incorrectly consider such cases as if we had Bottom ( empty state sets ) , and the narrow operator will give an incorrect result . we need to compute the \requires clause to eliminate empty behaviors, such as "assumes x < 0; requires x > 0;". Otherwise, we will later incorrectly consider such cases as if we had Bottom (empty state sets), and the narrow operator will give an incorrect result. *) let final_states = bhv_states_after_requires : association list ( name , stateset ) , from ( possibly active ) behavior names to their post - requires sets of disjoint states . from (possibly active) behavior names to their post-requires sets of disjoint states. *) let bhv_states_after_requires = (* requires for default behavior already computed *) (Cil.default_behavior_name, states_after_global_requires) :: ListLabels.map maybe_active_behaviors ~f:(fun b -> b.b_name, compute_assumes_and_requires_for_behavior kf ab b call_kinstr states_after_global_requires) in let return_used = match call_kinstr with | Kglobal -> true | Kstmt {skind = Instr (Call (lv, _, _, _))} -> lv <> None || Value_util.postconditions_mention_result spec | _ -> assert false in let (b_t, b_u, b_f) = partition_behaviors_after_requires ab bhv_states_after_requires in (* If there are behaviors with invalid preconditions, notify the user. *) Eval_annots.process_inactive_postconds kf (Extlib.filter_map (fun (b,_st) -> List.mem b b_f) (fun (b,st) -> AB.behavior_from_name ab b, (State_set.join st)) bhv_states_after_requires); To obtain maximum precision , we consider behaviors according to these rules : 1 ) Inactive behaviors are never considered . 3 ) All behaviors which are [ True ] ( including the default behavior ) have their assigns / ensures clauses computed as in the case of a single specification , to avoid a combinatorial explosion and to obtain the equivalent of a narrowed state S_t . 4 ) [ Unknown ] behaviors are added to S_t . For each set of complete behaviors , we join its [ Unknown ] states . We obtain different states S_c_1 , S_c_2 , etc . , for each set of complete states c_i . We then narrow these states to obtain the final result . these rules: 1) Inactive behaviors are never considered. 3) All behaviors which are [True] (including the default behavior) have their assigns/ensures clauses computed as in the case of a single specification, to avoid a combinatorial explosion and to obtain the equivalent of a narrowed state S_t. 4) [Unknown] behaviors are added to S_t. For each set of complete behaviors, we join its [Unknown] states. We obtain different states S_c_1, S_c_2, etc., for each set of complete states c_i. We then narrow these states to obtain the final result. *) let b_t,b_u = promote_complete_unknown_behaviors ab.AB.funspec.spec_complete_behaviors b_t b_u in If there is at least one " complete behaviors " clause , then we ignore the default behavior when computing a " true state " ( intersection of True behaviors ) . Otherwise , we add the default behavior to the set of True behaviors . the default behavior when computing a "true state" (intersection of True behaviors). Otherwise, we add the default behavior to the set of True behaviors. *) let b_t = if complete_bhvs_lists = [] then Cil.default_behavior_name :: b_t else b_t in let true_states = compute_merged_assigns_and_post_conds_for_behaviors kf ab bhv_states_after_requires return_used sclob b_t in (* If there are no "complete behaviors" clauses, we add a set containing the default behavior. *) let complete_sets = if complete_bhvs_lists = [] then [[Cil.default_behavior_name]] else complete_bhvs_lists in (* From now on, we compute the state corresponding to the behaviors with status Unknown *) (* We only compute states for useful behaviors: those that are present in some of the complete_bhvs_lists and that are [Unknown] (because they are in the true state), plus the default behavior. *) let bhvs_to_compute = Extlib.sort_unique Pervasives.compare (List.filter (ListLabels.mem ~set:b_u) (List.flatten complete_sets)) in let bhv_states_after_post_conds = List.map (compute_assigns_and_post_conds_for_behavior kf ab ~with_formals:joined_state_after_global_requires bhv_states_after_requires return_used sclob) bhvs_to_compute in (* For each set [c_i] of complete behaviors, compute a state set [stateset_per_c_i] with its unknown behaviors, then narrow the resulting state sets to obtain a more precise result. *) let stateset_per_c_i_list = List.map ( Extlib.filter_map (fun b -> List.mem b bhvs_to_compute) (fun b -> List.assoc b bhv_states_after_post_conds) ) complete_sets in let stateset_per_c_i = List.map (fun c_i_stateset_list -> List.fold_left (fun acc_st stateset -> State_set.merge stateset acc_st) State_set.empty c_i_stateset_list ) stateset_per_c_i_list in (* Finally, we narrow the result obtained for each set c_i of complete behaviors. The more sets there are, the more precise the final result will be. *) let unk_state = State_set.narrow_list stateset_per_c_i in (* Finally, we merge the states for the behaviors with status True and Unknown*) State_set.merge true_states unk_state in let rvi = Kernel_function.get_vi kf in let return_type = getReturnType rvi.vtype in let infer_rvi state = if isVoidType return_type || Cil.hasAttribute "noreturn" rvi.vattr || not (Cvalue.Model.is_reachable state) then None else Some (Library_functions.get_retres_vi kf) in let aux state = match infer_rvi state with | None -> None, state | Some vi -> match state with | Cvalue.Model.Bottom -> None, state | Cvalue.Model.Top -> Warn.warn_top () | Cvalue.Model.Map _ -> let retres_base = Base.of_varinfo vi in let without_ret = Cvalue.Model.remove_base retres_base state in match Cvalue.Model.find_base_or_default retres_base state with | `Map m -> Some m, without_ret | `Bottom -> None, state | `Top -> Warn.warn_top () in { Value_types.c_values = List.map aux (State_set.to_list final_states); c_clobbered = sclob.Locals_scoping.clob; c_cacheable = Value_types.Cacheable; c_from = None; }
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/legacy/eval_behaviors.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ Treat one assign ... \from ... clause. Update [state] accordingly, as well as [returned_value] and [sclob] evaluation of the entire from clause Treat the output part of the assigns clause Special case for \result TODO: warn about errors during evaluation Treat all the assigns for the function No need to warn for missing assigns when evaluating a behavior, we can always use those of the default behavior as a fallback. Compute the effects of the assigns clause Returns the assigns clause to be used during per-behavior processing. The specification states that, if a behavior has no assigns clause, then the assigns clause of the default behavior must be used instead. no assigns clause, using the default behavior's We filter the default behavior here falsely active behavior: requires clauses not satisfied requires clauses did not change the behavior's status no Unknown behaviors, nothing to promote a single Unknown behavior, will be promoted to True Applies the given [assumes] clauses of a given behavior [b] to the states passed as argument, in order to reduce them (no status is emitted). Reduce the state by the assumes and requires clauses for behavior [b], and emit statuses for the requires. TODO: integrate slevel joined_state_after_global_requires is an overapproximation of the disjunction of states after the global requires clause. It is used in some places, but the actual disjunction is more precise and should be used when possible. Notify user about inactive behaviors requires for default behavior already computed If there are behaviors with invalid preconditions, notify the user. If there are no "complete behaviors" clauses, we add a set containing the default behavior. From now on, we compute the state corresponding to the behaviors with status Unknown We only compute states for useful behaviors: those that are present in some of the complete_bhvs_lists and that are [Unknown] (because they are in the true state), plus the default behavior. For each set [c_i] of complete behaviors, compute a state set [stateset_per_c_i] with its unknown behaviors, then narrow the resulting state sets to obtain a more precise result. Finally, we narrow the result obtained for each set c_i of complete behaviors. The more sets there are, the more precise the final result will be. Finally, we merge the states for the behaviors with status True and Unknown
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types open Cil open Value_util open Eval_annots module AB = Eval_annots.ActiveBehaviors * Evaluate the assigns [ assigns ] of [ kf ] ( for one or more behaviors ) in the state [ with_formals ] . [ per_behavior ] indicates that the assigns clause is computed separately for each behavior . It is used to control the emission of warnings . in the state [with_formals]. [per_behavior] indicates that the assigns clause is computed separately for each behavior. It is used to control the emission of warnings. *) let compute_assigns kf assigns return_used sclob ~with_formals ~per_behavior = let with_alarms = CilE.warn_none_mode in let vi = Kernel_function.get_vi kf in if (not (Cvalue.Model.is_reachable with_formals)) || Cil.hasAttribute "noreturn" vi.vattr then None, Cvalue.Model.bottom else let returned_value, with_formals = Library_functions.returned_value kf with_formals in let returned_value = ref returned_value in let env = Eval_terms.env_assigns with_formals in let pp_eval_error fmt e = if e <> Eval_terms.CAlarm then Format.fprintf fmt "@ (%a)" Eval_terms.pretty_logic_evaluation_error e in let treat_assign state ({it_content = out}, ins as asgn) = Evaluate the contents of one element of the from clause , topify them , and add them to the current state of the evaluation in acc and add them to the current state of the evaluation in acc *) if Value_parameters.InterpreterMode.get() then begin warning_once_current "Assign in extern function call. Stopping.%t" Value_util.pp_callstack; raise Db.Value.Aborted end; let one_from_contents acc { it_content = t } = let r = Eval_terms.eval_term ~with_alarms env t in Cvalue.V.join acc (Cvalue.V.topify_arith_origin r.Eval_terms.eover) in let froms_contents = match ins with | FromAny -> Cvalue.V.top_int | From l -> try let filter x = not(List.mem "indirect" x.it_content.term_name) in let direct = List.filter filter l in List.fold_left one_from_contents Cvalue.V.top_int direct with Eval_terms.LogicEvalError e -> warning_once_current "cannot interpret@ 'from' clause@ \ '%a'@ of function %a%a" Printer.pp_from asgn Kernel_function.pretty kf pp_eval_error e; Cvalue.V.top in Treat one location coming from the evaluation of [ out ] let treat_output_loc acc loc = let valid = Locations.valid_part ~for_writing:true loc in if Locations.is_bottom_loc valid then (if (not (Locations.is_bottom_loc loc)) then (Value_parameters.warning ~current:true ~once:true "@[Completely invalid destination@ for assigns@ clause %a.@ \ Ignoring.@]" Printer.pp_term out); acc) else ( Locals_scoping.remember_if_locals_in_value sclob loc froms_contents; let state' = snd (Cvalue.Model.add_binding ~exact:false acc loc froms_contents) in if Cvalue.Model.equal Cvalue.Model.top state' then ( Value_parameters.error ~once:true ~current:true "Cannot@ handle@ assigns@ for %a,@ location@ is@ too@ imprecise@ \ (%a).@ Assuming@ it@ is@ not@ assigned,@ but@ be@ aware@ this\ @ is@ incorrect." Printer.pp_term out Locations.pretty loc; acc) else state') in if Logic_utils.is_result out then ( returned_value := Cvalue.V.join froms_contents !returned_value; state ) else try let loc = Eval_terms.eval_tlval_as_location ~with_alarms env out in treat_output_loc state loc with | Eval_terms.LogicEvalError e -> warning_once_current "cannot interpret assigns %a@ in function %a%a; effects will be \ ignored" Printer.pp_term out Kernel_function.pretty kf pp_eval_error e; state in let state = match assigns with | WritesAny -> if not per_behavior then warning_once_current "Cannot handle empty assigns clause. Assuming assigns \\nothing: be aware this is probably incorrect."; with_formals | Writes l -> Warn for clauses without \from let no_from = List.filter (fun (_, from) -> from = FromAny) l in (match no_from with | (out, _) :: _ as l -> let source = fst out.it_content.term_loc in Value_parameters.warning ~source ~once:true "@[no \\from part@ for clause '%a' of@ function %a@]" Printer.pp_assigns (Writes l) Kernel_function.pretty kf | [] -> () ); Warn in case the ' assigns \result ' clause is missing (if return_used then let for_result (out, _) = Logic_utils.is_result out.it_content in let result = List.filter for_result l in if result = [] then let source = fst (Kernel_function.get_location kf) in Value_parameters.warning ~once:true ~source "@[no 'assigns \\result@ \\from ...'@ clause@ specified \ for@ function %a@]" Kernel_function.pretty kf ); List.fold_left treat_assign with_formals l in let retres_vi, state = let return_type = getReturnType vi.vtype in if isVoidType return_type then None, state else let offsetmap = Eval_op.offsetmap_of_v return_type !returned_value in let rvi, state = Library_functions.add_retres_to_state kf offsetmap state in Some rvi, state in retres_vi, state Performs the join of two varinfo option , used for the return value . If both are Some , then they should be the same . If both are Some, then they should be the same. *) let join_rvi rvi1 rvi2 = Extlib.merge_opt (fun () vi1 vi2 -> assert (Cil_datatype.Varinfo.equal vi1 vi2); vi1 ) () rvi1 rvi2 let get_assigns_for_behavior ab b = match b.b_assigns with let def_b = AB.behavior_from_name ab Cil.default_behavior_name in def_b.b_assigns | _ -> b.b_assigns let compute_assigns_and_post_conds_for_behavior kf ab ~with_formals bhv_states_after_requires return_used sclob b_name = let b = AB.behavior_from_name ab b_name in let states_after_requires = List.assoc b_name bhv_states_after_requires in let retres_vi = ref None in let states_after_assigns = State_set.fold (fun acc_st (state, trace) -> let rvi, state_after_assigns = let assigns = get_assigns_for_behavior ab b in compute_assigns kf assigns return_used sclob state true in retres_vi := join_rvi !retres_vi rvi; State_set.add (state_after_assigns, trace) acc_st ) State_set.empty states_after_requires in let states_after_post_conds = Eval_annots.check_fct_postconditions_for_behavior kf ab b Normal ~result:!retres_vi ~per_behavior:true ~pre_state:with_formals states_after_assigns in (b_name, states_after_post_conds) When there is at least one behavior whose active status is [ True ] , we can perform the intersection of the states and assigns clauses , and compute the result for every [ True ] state at once . Here , [ b_names ] is a list of True behaviors . perform the intersection of the states and assigns clauses, and compute the result for every [True] state at once. Here, [b_names] is a list of True behaviors. *) let compute_merged_assigns_and_post_conds_for_behaviors kf ab bhv_states_after_requires return_used sclob b_names = if b_names = [] then State_set.empty else let bs = List.map (AB.behavior_from_name ab) b_names in let states_after_requires_list = Extlib.filter_map (fun (b_name, _) -> List.mem b_name b_names) snd bhv_states_after_requires in let state_after_requires, trace = State_set.(join (narrow_list states_after_requires_list)) in let retres_vi = ref None in let state_after_assigns = List.fold_left (fun st0 b -> let rvi, state_after_assigns = let assigns = get_assigns_for_behavior ab b in compute_assigns kf assigns return_used sclob st0 true in retres_vi := join_rvi !retres_vi rvi; state_after_assigns ) state_after_requires bs in let states_after_post_conds = Eval_annots.check_fct_postconditions kf ab bs Normal ~result:!retres_vi ~per_behavior:true ~pre_state:state_after_requires (State_set.singleton (state_after_assigns, trace)) in let l = State_set.to_list states_after_post_conds in let lr = List.map (fun s -> s,trace) l in State_set.of_list lr * Computes and returns three disjoint sets , [ b_t ] , [ b_u ] and [ b_f ] , where [ b_t ] contains all behaviors which are certainly active ( status [ True ] , and not empty after requires ) , [ b_u ] contains behaviors which are possibly active ( status [ Unknown ] , and not empty after requires ) , and [ b_f ] contains behaviors which are empty . The default behavior is never included in the returned sets . Note that [ b_f ] does NOT contain behaviors which were previously known to be inactive ( set to [ False ] by the assumes clause ) . [ bhv_states_post_requires ] is an association list from behaviors to their states after applying requires clauses . where [b_t] contains all behaviors which are certainly active (status [True], and not empty after requires), [b_u] contains behaviors which are possibly active (status [Unknown], and not empty after requires), and [b_f] contains behaviors which are empty. The default behavior is never included in the returned sets. Note that [b_f] does NOT contain behaviors which were previously known to be inactive (set to [False] by the assumes clause). [bhv_states_post_requires] is an association list from behaviors to their states after applying requires clauses. *) let partition_behaviors_after_requires ab bhv_states_after_requires = let bhv_states_after_requires' = List.filter (fun (b_name, _) -> b_name <> Cil.default_behavior_name) bhv_states_after_requires in List.fold_left (fun (b_t0, b_u0, b_f0) (b_name, stateset) -> if State_set.is_empty stateset then (b_t0, b_u0, b_name :: b_f0) else match ab.AB.is_active (AB.behavior_from_name ab b_name) with | Eval_terms.True -> (b_name :: b_t0, b_u0, b_f0) | Eval_terms.Unknown -> (b_t0, b_name :: b_u0, b_f0) | Eval_terms.False -> (b_t0, b_u0, b_name :: b_f0) ) ([],[],[]) bhv_states_after_requires' * Promotes [ Unknown ] behaviors from [ b_u ] to [ True ] when they are the only possible choice in a given complete set . Returns the new sets [ b_t ] and [ b_u ] , of [ True ] and [ Unknown ] behaviors . Promotes [Unknown] behaviors from [b_u] to [True] when they are the only possible choice in a given complete set. Returns the new sets [b_t] and [b_u], of [True] and [Unknown] behaviors. *) let promote_complete_unknown_behaviors comp_lists b_t b_u = ListLabels.fold_left ~init:(b_t,b_u) comp_lists ~f:(fun (acc_t,acc_u as acc) comp_set -> let unk_bhvs_in_set = List.filter (ListLabels.mem ~set:b_u) comp_set in match unk_bhvs_in_set with b_unk :: acc_t,List.filter (fun b -> b <> b_unk) acc_u more than one Unknown behavior , can not promote acc_t,acc_u ) let reduce_by_assumes_of_behavior kf states b = let build_prop assume = Property.ip_of_assumes kf Kglobal b assume in let build_env pre = Eval_terms.env_pre_f ~pre () in eval_and_reduce_p_kind kf b ~active:true Assumes b.b_assumes build_prop build_env states let compute_assumes_and_requires_for_behavior kf ab b call_kinstr states = let states_after_assumes = reduce_by_assumes_of_behavior kf states b in check_fct_preconditions_for_behavior kf ab ~per_behavior:true call_kinstr states_after_assumes b let compute_using_specification_single_behavior kf spec ~call_kinstr ~with_formals = let ab = AB.create_from_spec with_formals spec in let stateset = Eval_annots.check_fct_preconditions kf ab call_kinstr with_formals in let (with_formals,trace) = State_set.join stateset in let return_used = match call_kinstr with | Kglobal -> true | Kstmt {skind = Instr (Call (lv, _, _, _))} -> lv <> None || Value_util.postconditions_mention_result spec | _ -> assert false in let sclob = Locals_scoping.bottom () in let retres_vi, result_state = let assigns = Ast_info.merge_assigns (AB.active_behaviors ab) in compute_assigns kf assigns return_used sclob ~with_formals ~per_behavior:false in let result_states = Eval_annots.check_fct_postconditions kf ab (Annotations.behaviors kf) Normal ~result:retres_vi ~per_behavior:false ~pre_state:with_formals (State_set.singleton (result_state,trace)) in let aux state = match retres_vi with | None -> None, state | Some vi -> match state with | Cvalue.Model.Bottom -> None, state | Cvalue.Model.Top -> Warn.warn_top () | Cvalue.Model.Map _ -> let retres_base = Base.of_varinfo vi in let without_ret = Cvalue.Model.remove_base retres_base state in match Cvalue.Model.find_base_or_default retres_base state with | `Map m -> Some m, without_ret | `Bottom -> None, state | `Top -> Warn.warn_top () in { Value_types.c_values = List.map aux (State_set.to_list result_states); c_clobbered = sclob.Locals_scoping.clob; c_cacheable = Value_types.Cacheable; c_from = None; } let compute_using_specification_multiple_behaviors kf spec ~call_kinstr ~with_formals = let ab = AB.create_from_spec with_formals spec in let sclob = Locals_scoping.bottom () in let complete_bhvs_lists = ab.AB.funspec.spec_complete_behaviors in let maybe_active_behaviors = ListLabels.filter ab.AB.funspec.spec_behavior ~f:(fun b -> ab.AB.is_active b <> Eval_terms.False && not (Cil.is_default_behavior b)) in let def_bhv = AB.behavior_from_name ab Cil.default_behavior_name in let init_trace = Trace.initial kf in let init_state_set = State_set.singleton (with_formals, init_trace) in let states_after_global_requires = Eval_annots.check_fct_preconditions_for_behavior kf ab ~per_behavior:true call_kinstr init_state_set def_bhv in let (joined_state_after_global_requires,trace) = State_set.join states_after_global_requires in Eval_annots.process_inactive_behaviors kf ab (joined_state_after_global_requires,trace); In order to know which behaviors will be considered by the analysis , we need to compute the \requires clause to eliminate empty behaviors , such as " assumes x < 0 ; requires x > 0 ; " . Otherwise , we will later incorrectly consider such cases as if we had Bottom ( empty state sets ) , and the narrow operator will give an incorrect result . we need to compute the \requires clause to eliminate empty behaviors, such as "assumes x < 0; requires x > 0;". Otherwise, we will later incorrectly consider such cases as if we had Bottom (empty state sets), and the narrow operator will give an incorrect result. *) let final_states = bhv_states_after_requires : association list ( name , stateset ) , from ( possibly active ) behavior names to their post - requires sets of disjoint states . from (possibly active) behavior names to their post-requires sets of disjoint states. *) let bhv_states_after_requires = (Cil.default_behavior_name, states_after_global_requires) :: ListLabels.map maybe_active_behaviors ~f:(fun b -> b.b_name, compute_assumes_and_requires_for_behavior kf ab b call_kinstr states_after_global_requires) in let return_used = match call_kinstr with | Kglobal -> true | Kstmt {skind = Instr (Call (lv, _, _, _))} -> lv <> None || Value_util.postconditions_mention_result spec | _ -> assert false in let (b_t, b_u, b_f) = partition_behaviors_after_requires ab bhv_states_after_requires in Eval_annots.process_inactive_postconds kf (Extlib.filter_map (fun (b,_st) -> List.mem b b_f) (fun (b,st) -> AB.behavior_from_name ab b, (State_set.join st)) bhv_states_after_requires); To obtain maximum precision , we consider behaviors according to these rules : 1 ) Inactive behaviors are never considered . 3 ) All behaviors which are [ True ] ( including the default behavior ) have their assigns / ensures clauses computed as in the case of a single specification , to avoid a combinatorial explosion and to obtain the equivalent of a narrowed state S_t . 4 ) [ Unknown ] behaviors are added to S_t . For each set of complete behaviors , we join its [ Unknown ] states . We obtain different states S_c_1 , S_c_2 , etc . , for each set of complete states c_i . We then narrow these states to obtain the final result . these rules: 1) Inactive behaviors are never considered. 3) All behaviors which are [True] (including the default behavior) have their assigns/ensures clauses computed as in the case of a single specification, to avoid a combinatorial explosion and to obtain the equivalent of a narrowed state S_t. 4) [Unknown] behaviors are added to S_t. For each set of complete behaviors, we join its [Unknown] states. We obtain different states S_c_1, S_c_2, etc., for each set of complete states c_i. We then narrow these states to obtain the final result. *) let b_t,b_u = promote_complete_unknown_behaviors ab.AB.funspec.spec_complete_behaviors b_t b_u in If there is at least one " complete behaviors " clause , then we ignore the default behavior when computing a " true state " ( intersection of True behaviors ) . Otherwise , we add the default behavior to the set of True behaviors . the default behavior when computing a "true state" (intersection of True behaviors). Otherwise, we add the default behavior to the set of True behaviors. *) let b_t = if complete_bhvs_lists = [] then Cil.default_behavior_name :: b_t else b_t in let true_states = compute_merged_assigns_and_post_conds_for_behaviors kf ab bhv_states_after_requires return_used sclob b_t in let complete_sets = if complete_bhvs_lists = [] then [[Cil.default_behavior_name]] else complete_bhvs_lists in let bhvs_to_compute = Extlib.sort_unique Pervasives.compare (List.filter (ListLabels.mem ~set:b_u) (List.flatten complete_sets)) in let bhv_states_after_post_conds = List.map (compute_assigns_and_post_conds_for_behavior kf ab ~with_formals:joined_state_after_global_requires bhv_states_after_requires return_used sclob) bhvs_to_compute in let stateset_per_c_i_list = List.map ( Extlib.filter_map (fun b -> List.mem b bhvs_to_compute) (fun b -> List.assoc b bhv_states_after_post_conds) ) complete_sets in let stateset_per_c_i = List.map (fun c_i_stateset_list -> List.fold_left (fun acc_st stateset -> State_set.merge stateset acc_st) State_set.empty c_i_stateset_list ) stateset_per_c_i_list in let unk_state = State_set.narrow_list stateset_per_c_i in State_set.merge true_states unk_state in let rvi = Kernel_function.get_vi kf in let return_type = getReturnType rvi.vtype in let infer_rvi state = if isVoidType return_type || Cil.hasAttribute "noreturn" rvi.vattr || not (Cvalue.Model.is_reachable state) then None else Some (Library_functions.get_retres_vi kf) in let aux state = match infer_rvi state with | None -> None, state | Some vi -> match state with | Cvalue.Model.Bottom -> None, state | Cvalue.Model.Top -> Warn.warn_top () | Cvalue.Model.Map _ -> let retres_base = Base.of_varinfo vi in let without_ret = Cvalue.Model.remove_base retres_base state in match Cvalue.Model.find_base_or_default retres_base state with | `Map m -> Some m, without_ret | `Bottom -> None, state | `Top -> Warn.warn_top () in { Value_types.c_values = List.map aux (State_set.to_list final_states); c_clobbered = sclob.Locals_scoping.clob; c_cacheable = Value_types.Cacheable; c_from = None; }
805069618c2ca4952aee66e951ea4d00c18556bfd61ecc052e410cdd3c161a20
YoshikuniJujo/test_haskell
TryHuman.hs
# LANGUAGE BlockArguments # {-# LANGUAGE ScopedTypeVariables, AllowAmbiguousTypes #-} # OPTIONS_GHC -Wall -fno - warn - tabs # module TryHuman where import Control.Monad.ST import Control.Exception import Human catchAndShow :: forall e . Exception e => IO () -> IO () catchAndShow act = act `catch` \(e :: e) -> putStrLn "CATCHED" >> print e image1 :: Image image1 = runST do f <- fieldNewSt fieldPutHumanSt f 30 10 fieldGetImage f
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/7cbaf8985a94fdc090119287baa530f237af44b9/tribial/try-use-c-lib/src/TryHuman.hs
haskell
# LANGUAGE ScopedTypeVariables, AllowAmbiguousTypes #
# LANGUAGE BlockArguments # # OPTIONS_GHC -Wall -fno - warn - tabs # module TryHuman where import Control.Monad.ST import Control.Exception import Human catchAndShow :: forall e . Exception e => IO () -> IO () catchAndShow act = act `catch` \(e :: e) -> putStrLn "CATCHED" >> print e image1 :: Image image1 = runST do f <- fieldNewSt fieldPutHumanSt f 30 10 fieldGetImage f
39669b47076f49c9825b01dc3e9ef621da3710bda183455e9aeedacf47732f58
status-im/status-electron
contacts.cljs
(ns status-desktop-front.override.contacts (:require [re-frame.core :as re-frame] [status-im.utils.js-resources :as js-res] [status-im.ui.screens.contacts.events :as contacts.events] [status-desktop-front.storage :as storage] [status-im.utils.handlers :as handlers])) ;;;; COFX (re-frame/reg-cofx ::contacts.events/get-all-contacts (fn [coeffects _] (assoc coeffects :all-contacts (storage/get-all-contacts)))) (re-frame/reg-cofx ::contacts.events/get-default-contacts-and-groups (fn [coeffects _] (assoc coeffects :default-contacts js-res/default-contacts :default-groups js-res/default-contact-groups))) FX (re-frame/reg-fx ::contacts.events/save-contact (fn [contact] (storage/save-contact contact))) (re-frame/reg-fx ::contacts.events/save-contacts! (fn [new-contacts] (storage/save-contacts new-contacts))) (re-frame/reg-fx ::contacts.events/delete-contact (fn [contact])) ;(contacts/delete contact))) (re-frame/reg-fx ::contacts.events/fetch-contacts-from-phone! (fn [on-contacts-event-creator])) (re-frame/reg-fx ::contacts.events/request-stored-contacts (fn [{:keys [contacts on-contacts-event-creator]}])) (re-frame/reg-fx ::contacts.events/request-contact-by-address (fn [id])) ;;;; Handlers (handlers/register-handler-fx :load-default-contacts! (fn [cofx _] cofx))
null
https://raw.githubusercontent.com/status-im/status-electron/aad18c34c0ee0304071e984f21d5622735ec5bef/src_front/status_desktop_front/override/contacts.cljs
clojure
COFX (contacts/delete contact))) Handlers
(ns status-desktop-front.override.contacts (:require [re-frame.core :as re-frame] [status-im.utils.js-resources :as js-res] [status-im.ui.screens.contacts.events :as contacts.events] [status-desktop-front.storage :as storage] [status-im.utils.handlers :as handlers])) (re-frame/reg-cofx ::contacts.events/get-all-contacts (fn [coeffects _] (assoc coeffects :all-contacts (storage/get-all-contacts)))) (re-frame/reg-cofx ::contacts.events/get-default-contacts-and-groups (fn [coeffects _] (assoc coeffects :default-contacts js-res/default-contacts :default-groups js-res/default-contact-groups))) FX (re-frame/reg-fx ::contacts.events/save-contact (fn [contact] (storage/save-contact contact))) (re-frame/reg-fx ::contacts.events/save-contacts! (fn [new-contacts] (storage/save-contacts new-contacts))) (re-frame/reg-fx ::contacts.events/delete-contact (fn [contact])) (re-frame/reg-fx ::contacts.events/fetch-contacts-from-phone! (fn [on-contacts-event-creator])) (re-frame/reg-fx ::contacts.events/request-stored-contacts (fn [{:keys [contacts on-contacts-event-creator]}])) (re-frame/reg-fx ::contacts.events/request-contact-by-address (fn [id])) (handlers/register-handler-fx :load-default-contacts! (fn [cofx _] cofx))
72195d0ee184e6da07ad9b304389ebc804a08fd9878c8e8318331f145c4081ac
brendanhay/text-manipulate
Types.hs
# LANGUAGE MagicHash # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # -- Module : Data.Text.Manipulate.Internal.Types Copyright : ( c ) 2014 - 2022 < > License : This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . A copy of the MPL can be found in the LICENSE file or -- you can obtain it at /. Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC extensions ) module Data.Text.Manipulate.Internal.Types where import Control.Monad import qualified Data.Char as Char import Data.Text.Lazy.Builder (Builder, singleton) import GHC.Base -- | Returns 'True' for any boundary or uppercase character. isWordBoundary :: Char -> Bool isWordBoundary c = Char.isUpper c || isBoundary c -- | Returns 'True' for any boundary character. isBoundary :: Char -> Bool isBoundary = not . Char.isAlphaNum ordinal :: Integral a => a -> Builder ordinal (toInteger -> n) = decimal n <> suf where suf | x `elem` [11 .. 13] = "th" | y == 1 = "st" | y == 2 = "nd" | y == 3 = "rd" | otherwise = "th" (flip mod 100 -> x, flip mod 10 -> y) = join (,) (abs n) {-# NOINLINE [0] ordinal #-} decimal :: Integral a => a -> Builder {-# SPECIALIZE decimal :: Int -> Builder #-} decimal i | i < 0 = singleton '-' <> go (- i) | otherwise = go i where go n | n < 10 = digit n | otherwise = go (n `quot` 10) <> digit (n `rem` 10) {-# NOINLINE [0] decimal #-} digit :: Integral a => a -> Builder digit n = singleton $! i2d (fromIntegral n) # INLINE digit # i2d :: Int -> Char i2d (I# i#) = C# (chr# (ord# '0'# +# i#)) # INLINE i2d #
null
https://raw.githubusercontent.com/brendanhay/text-manipulate/5b21510103a069537ad7b0f3a5b377f7cdb49d2b/lib/Data/Text/Manipulate/Internal/Types.hs
haskell
# LANGUAGE OverloadedStrings # Module : Data.Text.Manipulate.Internal.Types you can obtain it at /. Stability : experimental | Returns 'True' for any boundary or uppercase character. | Returns 'True' for any boundary character. # NOINLINE [0] ordinal # # SPECIALIZE decimal :: Int -> Builder # # NOINLINE [0] decimal #
# LANGUAGE MagicHash # # LANGUAGE ViewPatterns # Copyright : ( c ) 2014 - 2022 < > License : This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . A copy of the MPL can be found in the LICENSE file or Maintainer : < > Portability : non - portable ( GHC extensions ) module Data.Text.Manipulate.Internal.Types where import Control.Monad import qualified Data.Char as Char import Data.Text.Lazy.Builder (Builder, singleton) import GHC.Base isWordBoundary :: Char -> Bool isWordBoundary c = Char.isUpper c || isBoundary c isBoundary :: Char -> Bool isBoundary = not . Char.isAlphaNum ordinal :: Integral a => a -> Builder ordinal (toInteger -> n) = decimal n <> suf where suf | x `elem` [11 .. 13] = "th" | y == 1 = "st" | y == 2 = "nd" | y == 3 = "rd" | otherwise = "th" (flip mod 100 -> x, flip mod 10 -> y) = join (,) (abs n) decimal :: Integral a => a -> Builder decimal i | i < 0 = singleton '-' <> go (- i) | otherwise = go i where go n | n < 10 = digit n | otherwise = go (n `quot` 10) <> digit (n `rem` 10) digit :: Integral a => a -> Builder digit n = singleton $! i2d (fromIntegral n) # INLINE digit # i2d :: Int -> Char i2d (I# i#) = C# (chr# (ord# '0'# +# i#)) # INLINE i2d #
b186ac08af0404d82b3456fe5e87e27e0e8cea10c2a8eb595ff188f24ecde0cb
blindglobe/clocc
mchoices.lisp
-*- Mode : Lisp ; Package : CLIO - OPEN ; ; Lowercase : T ; Fonts:(CPTFONT ) ; Syntax : Common - Lisp -*- ;;;----------------------------------------------------------------------------------+ ;;; | ;;; TEXAS INSTRUMENTS INCORPORATED | ;;; P.O. BOX 149149 | , TEXAS 78714 | ;;; | Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . | ;;; | ;;; Permission is granted to any individual or institution to use, copy, modify, and | ;;; distribute this software, provided that this complete copyright and permission | ;;; notice is maintained, intact, in all copies and supporting documentation. | ;;; | Texas Instruments Incorporated provides this software " as is " without express or | ;;; implied warranty. | ;;; | ;;;----------------------------------------------------------------------------------+ (in-package "CLIO-OPEN") (EXPORT '( choice-default choice-font choice-selection make-multiple-choices multiple-choices )) ;;; ============================================================================ ;;; T h e M U L T I P L E - C H O I C E S C o n t a c t ;;; ============================================================================ (DEFCONTACT multiple-choices (table) ((font :type fontable :reader choice-font :initarg :font :initform nil) (selection :type list :accessor choice-selection :initform nil) (default :type list :accessor choice-default :initarg :default-selection :initform nil) ) (:resources font default (horizontal-space :initform 3) (vertical-space :initform 3)) (:documentation "Provides a mechanism for displaying N choices to a user of which the user may select M, where N >= M >= 0.")) (DEFUN make-multiple-choices (&rest initargs &key &allow-other-keys) (APPLY #'make-contact 'multiple-choices initargs)) (DEFMETHOD add-child :after ((choices multiple-choices) this-child &key) (flet ( ;;; =============================================================================== ;;; ;;; Our :changing and :canceling-change callback functions... ;;; (choices-changing (to-selected-p choices self) (DECLARE (IGNORE self)) (LET((selection (choice-selection choices)) (default (choice-default choices))) (WHEN default ;; If there is a current choice default then we *may* have ;; to temporarily inhibit display of the default ring. (UNLESS (and selection to-selected-p) ;; If there is a current selection already and we are ;; transitioning *to* selected state then the default ring(s) are already inhibited . Otherwise , there are two possibilites : ( 1 ) No selection , transitioning * to * selected . ;; We must inhibit ring display on all defaults. ( 2 ) Have selection , transitioning * from * selected . If there is only one selection and it is transitioning to ;; unselected, then we must restore default ring(s) display. (let ((highlighted-p (not to-selected-p))) (when (or to-selected-p (null (cdr selection))) (DOLIST (item default) (SETF (choice-item-highlight-default-p item) highlighted-p)))))))) (choices-canceling-change (to-selected-p choices self) (DECLARE (IGNORE self)) (LET((selection (choice-selection choices)) (default (choice-default choices))) (WHEN default ;; If we are canceling a transition to "selected" then we ;; must restore the inhibited default ring display. ;; If, on the other hand, we are canceling a transition ;; back to "unselected" then we must once again inhibit ;; default ring display. (UNLESS (and selection to-selected-p) ;; As in choices-changing, if there is a current selection ;; already inhibiting default ring display then we need not ;; restore display here. (when (or to-selected-p (null (cdr selection))) (DOLIST (item default) (SETF (choice-item-highlight-default-p item) to-selected-p))))))) ;;; ================================================================================ ;;; This :off callback (destructively) removes the item from the current ;;; selection set for this multiple-choices contact. ;;; (choices-off (choices self) (WITH-SLOTS (selection) choices (WHEN selection (SETF selection (DELETE self selection))))) ;;; ================================================================================ ;;; This :on callback adds the item to the current selection set ;;; for this multiple-choices contact. ;;; (choices-on (choices self) (WITH-SLOTS (selection) choices It is important to * not * use the SETF method here since doing so would potentially cause a loop . [ SETF method invokes this callback ! ] (SETF selection (cons self selection)))) ) ; ... end of flet ... (let((font (choice-font choices))) (WHEN font (SETF (choice-item-font this-child) font))) ;; ===================================================================================== ;; If this child's name is on the default-selection list, replace it with this child. ;; (with-slots (default) choices (DO ((defaults default (REST defaults))) ((NULL defaults)) (WHEN (EQ (FIRST defaults) (contact-name this-child)) (RPLACA defaults this-child) (SETF (choice-item-highlight-default-p this-child) T) (RETURN)))) (add-callback this-child :changing #'choices-changing choices this-child) (add-callback this-child :canceling-change #'choices-canceling-change choices this-child) (add-callback this-child :on #'choices-on choices this-child) (add-callback this-child :off #'choices-off choices this-child))) ;;; =============================================================================== ;;; ;;; Method to set the default choice item set ;;; (DEFMETHOD (SETF choice-default) (new-default-choice-items (choices multiple-choices)) (with-slots (default children) choices (let ((new-defaults (set-difference new-default-choice-items default)) (no-longer-defaults (set-difference default new-default-choice-items))) (WHEN new-defaults (ASSERT (subsetp new-defaults children) NIL "New default choice-items ~a are not children of ~a." (set-difference new-defaults children) choices) (DOLIST (item new-defaults) (SETF (choice-item-highlight-default-p item) T)) (DOLIST (item no-longer-defaults) (SETF (choice-item-highlight-default-p item) NIL)) (SETF default new-default-choice-items)))) new-default-choice-items) ;;; =============================================================================== ;;; ;;; Methods to set the selected choice-items set ;;; (DEFMETHOD (SETF choice-selection) (children-to-be-selected (choices multiple-choices)) (DECLARE (TYPE list children-to-be-selected)) (with-slots (children selection) choices (let ((new-selections (set-difference children-to-be-selected selection)) (no-longer-selected (set-difference selection children-to-be-selected))) ;; Make sure the caller's selection are indeed a children of ours... (ASSERT (subsetp new-selections children) NIL "Selections ~a are not children of ~a." (set-difference new-selections selection) choices) Clear selected status of items no longer selected (DOLIST (item no-longer-selected) (SETF (choice-item-selected-p item) NIL)) ;; Set selected status of items newly selected (DOLIST (item new-selections) (SETF (choice-item-selected-p item) T)))) children-to-be-selected) ;;; =============================================================================== ;;; ;;; Method to force the font of all children... ;;; (DEFMETHOD (SETF choice-font) (new-value (multiple-choices multiple-choices)) (with-slots (children font) multiple-choices (if new-value (progn (SETF font (find-font multiple-choices new-value)) (DOLIST (child children) (SETF (choice-item-font child) new-value))) (SETF font NIL)) new-value))
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/clio/mchoices.lisp
lisp
Package : CLIO - OPEN ; ; Lowercase : T ; Fonts:(CPTFONT ) ; Syntax : Common - Lisp -*- ----------------------------------------------------------------------------------+ | TEXAS INSTRUMENTS INCORPORATED | P.O. BOX 149149 | | | Permission is granted to any individual or institution to use, copy, modify, and | distribute this software, provided that this complete copyright and permission | notice is maintained, intact, in all copies and supporting documentation. | | implied warranty. | | ----------------------------------------------------------------------------------+ ============================================================================ T h e M U L T I P L E - C H O I C E S C o n t a c t ============================================================================ =============================================================================== Our :changing and :canceling-change callback functions... If there is a current choice default then we *may* have to temporarily inhibit display of the default ring. If there is a current selection already and we are transitioning *to* selected state then the default ring(s) We must inhibit ring display on all defaults. unselected, then we must restore default ring(s) display. If we are canceling a transition to "selected" then we must restore the inhibited default ring display. If, on the other hand, we are canceling a transition back to "unselected" then we must once again inhibit default ring display. As in choices-changing, if there is a current selection already inhibiting default ring display then we need not restore display here. ================================================================================ This :off callback (destructively) removes the item from the current selection set for this multiple-choices contact. ================================================================================ This :on callback adds the item to the current selection set for this multiple-choices contact. ... end of flet ... ===================================================================================== If this child's name is on the default-selection list, replace it with this child. =============================================================================== Method to set the default choice item set =============================================================================== Methods to set the selected choice-items set Make sure the caller's selection are indeed a children of ours... Set selected status of items newly selected =============================================================================== Method to force the font of all children...
, TEXAS 78714 | Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . | Texas Instruments Incorporated provides this software " as is " without express or | (in-package "CLIO-OPEN") (EXPORT '( choice-default choice-font choice-selection make-multiple-choices multiple-choices )) (DEFCONTACT multiple-choices (table) ((font :type fontable :reader choice-font :initarg :font :initform nil) (selection :type list :accessor choice-selection :initform nil) (default :type list :accessor choice-default :initarg :default-selection :initform nil) ) (:resources font default (horizontal-space :initform 3) (vertical-space :initform 3)) (:documentation "Provides a mechanism for displaying N choices to a user of which the user may select M, where N >= M >= 0.")) (DEFUN make-multiple-choices (&rest initargs &key &allow-other-keys) (APPLY #'make-contact 'multiple-choices initargs)) (DEFMETHOD add-child :after ((choices multiple-choices) this-child &key) (flet ( (choices-changing (to-selected-p choices self) (DECLARE (IGNORE self)) (LET((selection (choice-selection choices)) (default (choice-default choices))) (WHEN default (UNLESS (and selection to-selected-p) are already inhibited . Otherwise , there are two possibilites : ( 1 ) No selection , transitioning * to * selected . ( 2 ) Have selection , transitioning * from * selected . If there is only one selection and it is transitioning to (let ((highlighted-p (not to-selected-p))) (when (or to-selected-p (null (cdr selection))) (DOLIST (item default) (SETF (choice-item-highlight-default-p item) highlighted-p)))))))) (choices-canceling-change (to-selected-p choices self) (DECLARE (IGNORE self)) (LET((selection (choice-selection choices)) (default (choice-default choices))) (WHEN default (UNLESS (and selection to-selected-p) (when (or to-selected-p (null (cdr selection))) (DOLIST (item default) (SETF (choice-item-highlight-default-p item) to-selected-p))))))) (choices-off (choices self) (WITH-SLOTS (selection) choices (WHEN selection (SETF selection (DELETE self selection))))) (choices-on (choices self) (WITH-SLOTS (selection) choices It is important to * not * use the SETF method here since doing so would potentially cause a loop . [ SETF method invokes this callback ! ] (SETF selection (cons self selection)))) (let((font (choice-font choices))) (WHEN font (SETF (choice-item-font this-child) font))) (with-slots (default) choices (DO ((defaults default (REST defaults))) ((NULL defaults)) (WHEN (EQ (FIRST defaults) (contact-name this-child)) (RPLACA defaults this-child) (SETF (choice-item-highlight-default-p this-child) T) (RETURN)))) (add-callback this-child :changing #'choices-changing choices this-child) (add-callback this-child :canceling-change #'choices-canceling-change choices this-child) (add-callback this-child :on #'choices-on choices this-child) (add-callback this-child :off #'choices-off choices this-child))) (DEFMETHOD (SETF choice-default) (new-default-choice-items (choices multiple-choices)) (with-slots (default children) choices (let ((new-defaults (set-difference new-default-choice-items default)) (no-longer-defaults (set-difference default new-default-choice-items))) (WHEN new-defaults (ASSERT (subsetp new-defaults children) NIL "New default choice-items ~a are not children of ~a." (set-difference new-defaults children) choices) (DOLIST (item new-defaults) (SETF (choice-item-highlight-default-p item) T)) (DOLIST (item no-longer-defaults) (SETF (choice-item-highlight-default-p item) NIL)) (SETF default new-default-choice-items)))) new-default-choice-items) (DEFMETHOD (SETF choice-selection) (children-to-be-selected (choices multiple-choices)) (DECLARE (TYPE list children-to-be-selected)) (with-slots (children selection) choices (let ((new-selections (set-difference children-to-be-selected selection)) (no-longer-selected (set-difference selection children-to-be-selected))) (ASSERT (subsetp new-selections children) NIL "Selections ~a are not children of ~a." (set-difference new-selections selection) choices) Clear selected status of items no longer selected (DOLIST (item no-longer-selected) (SETF (choice-item-selected-p item) NIL)) (DOLIST (item new-selections) (SETF (choice-item-selected-p item) T)))) children-to-be-selected) (DEFMETHOD (SETF choice-font) (new-value (multiple-choices multiple-choices)) (with-slots (children font) multiple-choices (if new-value (progn (SETF font (find-font multiple-choices new-value)) (DOLIST (child children) (SETF (choice-item-font child) new-value))) (SETF font NIL)) new-value))
48bec6d707f0c1166808d007d5706295b2f79db93958d0d4a6b8bfcaca43227d
8c6794b6/haskell-sc-scratch
Take06.hs
# LANGUAGE NoMonomorphismRestriction # {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} # LANGUAGE TypeFamilies # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : non - portable To deserialize lambda expression , take 6 . Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : non-portable To deserialize lambda expression, take 6. -} module Take06 where import Type01 class Sym r where v :: Var -> r a lam :: (Var -> r b) -> r (a->b) app :: r (a->b) -> r a -> r b int :: Int -> r Int add :: r Int -> r Int -> r Int Although Var type is used inside v and lam in Sym class , Sym expressions does not need to refer to VZ nor VS explicitly . -- e01 = add (int 3) (int 4) e02 = lam (\x -> v x) e03 = lam (\x -> lam (\y -> add (v x) (v y))) e04 = e03 `app` int 27 `app` int 72 e05 = lam (\x -> app (v x) (int 3)) e06 = lam (\x -> add (v x) (int 4)) e07 = app e05 e06 | indice . data Var = VZ | VS Var deriving (Eq,Show) newtype Dbj a = Dbj Var data Variable where Variable :: Show t => t -> Variable instance Show Variable where show (Variable t) = show t data Vars where Nil :: Vars Cons :: Variable -> Vars -> Vars lkp :: Var -> Vars -> Variable lkp i vs = case (i,vs) of (VZ, Cons v _) -> v (VS i', Cons _ vs) -> lkp i' vs _ -> error "Variable unbound" -- instance Variables () where -- type Value () = () _ _ = Left " Unbound variable " instance = > Variables ( t , g ) where -- type Value (t,g) = t ( a , g ) = case dbj of -- VZ -> return $ v VZ VS dbj ' - > VS $ g In Sym class , ther exists fixed use of Var type class in v and lam methods . How to get result in arbitrary types with this fixed Var type ? In Sym class, ther exists fixed use of Var type class in v and lam methods. How to get result in arbitrary types with this fixed Var type? -} newtype R a = R {unR :: Vars -> a} data RTerm = forall a. RTerm (R a) rv x = R $ \h -> lookupR x h class VarEnv g where type Value g :: * lookupVE :: Var -> g -> Value g instance VarEnv () where type Value () = () lookupVE _ _ = error "Unbound variable" instance VarEnv g => VarEnv (t,g) where type Value (t,g) = (t,Value g) lookupVE v (t,g) = case v of VZ -> (t,undefined) VS v' -> undefined -- lookupVE v' g lookupR v h = undefined -- (VZ,t) -> return t -- (VS v,ts) -> lookupR v ts instance Sym R where int x = R $ \_ -> x add e1 e2 = R $ \h -> unR e1 h + unR e2 h v x = R $ \h -> undefined v x = case h of -- Variable a -> a -- _ -> error $ "Unbound variable: " ++ show x lam f = R $ \h -> undefined app e1 e2 = R $ \h -> undefined lkup :: Var -> Vars -> Variable lkup = lkp ------------------------------------------------------------------------------ -- Show interpreter, working. newtype S a = S {unS :: Var -> String} toS :: S a -> S a toS = id instance Sym S where int x = S $ \_ -> show x add e1 e2 = S $ \h -> "add (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")" v x = S $ \h -> go x 0 lam f = S $ \h -> let x = go h 0 in "lam (\\" ++ x ++ " -> " ++ unS (f h) (VS h) ++ ")" app e1 e2 = S $ \h -> "app (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")" go :: Var -> Int -> String go y i = case y of VZ -> "x" ++ show i; VS z -> go z (succ i) view :: S a -> String view e = unS e VZ instance Show (S a) where show = view
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Oleg/TTF/Extra/Take06.hs
haskell
# LANGUAGE GADTs # # LANGUAGE Rank2Types # instance Variables () where type Value () = () type Value (t,g) = t VZ -> return $ v VZ lookupVE v' g (VZ,t) -> return t (VS v,ts) -> lookupR v ts Variable a -> a _ -> error $ "Unbound variable: " ++ show x ---------------------------------------------------------------------------- Show interpreter, working.
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE TypeFamilies # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : non - portable To deserialize lambda expression , take 6 . Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : non-portable To deserialize lambda expression, take 6. -} module Take06 where import Type01 class Sym r where v :: Var -> r a lam :: (Var -> r b) -> r (a->b) app :: r (a->b) -> r a -> r b int :: Int -> r Int add :: r Int -> r Int -> r Int Although Var type is used inside v and lam in Sym class , Sym expressions does not need to refer to VZ nor VS explicitly . e01 = add (int 3) (int 4) e02 = lam (\x -> v x) e03 = lam (\x -> lam (\y -> add (v x) (v y))) e04 = e03 `app` int 27 `app` int 72 e05 = lam (\x -> app (v x) (int 3)) e06 = lam (\x -> add (v x) (int 4)) e07 = app e05 e06 | indice . data Var = VZ | VS Var deriving (Eq,Show) newtype Dbj a = Dbj Var data Variable where Variable :: Show t => t -> Variable instance Show Variable where show (Variable t) = show t data Vars where Nil :: Vars Cons :: Variable -> Vars -> Vars lkp :: Var -> Vars -> Variable lkp i vs = case (i,vs) of (VZ, Cons v _) -> v (VS i', Cons _ vs) -> lkp i' vs _ -> error "Variable unbound" _ _ = Left " Unbound variable " instance = > Variables ( t , g ) where ( a , g ) = case dbj of VS dbj ' - > VS $ g In Sym class , ther exists fixed use of Var type class in v and lam methods . How to get result in arbitrary types with this fixed Var type ? In Sym class, ther exists fixed use of Var type class in v and lam methods. How to get result in arbitrary types with this fixed Var type? -} newtype R a = R {unR :: Vars -> a} data RTerm = forall a. RTerm (R a) rv x = R $ \h -> lookupR x h class VarEnv g where type Value g :: * lookupVE :: Var -> g -> Value g instance VarEnv () where type Value () = () lookupVE _ _ = error "Unbound variable" instance VarEnv g => VarEnv (t,g) where type Value (t,g) = (t,Value g) lookupVE v (t,g) = case v of VZ -> (t,undefined) lookupR v h = undefined instance Sym R where int x = R $ \_ -> x add e1 e2 = R $ \h -> unR e1 h + unR e2 h v x = R $ \h -> undefined v x = case h of lam f = R $ \h -> undefined app e1 e2 = R $ \h -> undefined lkup :: Var -> Vars -> Variable lkup = lkp newtype S a = S {unS :: Var -> String} toS :: S a -> S a toS = id instance Sym S where int x = S $ \_ -> show x add e1 e2 = S $ \h -> "add (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")" v x = S $ \h -> go x 0 lam f = S $ \h -> let x = go h 0 in "lam (\\" ++ x ++ " -> " ++ unS (f h) (VS h) ++ ")" app e1 e2 = S $ \h -> "app (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")" go :: Var -> Int -> String go y i = case y of VZ -> "x" ++ show i; VS z -> go z (succ i) view :: S a -> String view e = unS e VZ instance Show (S a) where show = view
579718580405f1c1857d994803d2c2e9cbcf827ce6b209127b27345d9969c7b9
TrustInSoft/tis-interpreter
slicingProject.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** Handle the project global object. *) (**/**) module T = SlicingInternals module M = SlicingMacros (**/**) (*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*) * { 2 Building project } * API function : see { ! : Db . Slicing . Project.mk_project } . let mk_project name = SlicingParameters.feedback ~level:1 "making slicing project '%s'..." name; let r = { T.name = name ; T.application = Project.current () ; T.functions = Cil_datatype.Varinfo.Hashtbl.create 17; T.actions = []; } in SlicingParameters.feedback ~level:2 "done (making slicing project '%s')." name; r let get_name proj = proj.T.name (*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*) * { 2 Managing the slices } let add_proj_actions proj actions = proj.T.actions <- actions @ proj.T.actions * Add a new slice for the function . It can be the case that it create actions * if the function has some persistent selection , that make function calls to * choose . * @raise SlicingTypes . NoPdg when the function has no . * * if the function has some persistent selection, that make function calls to * choose. * @raise SlicingTypes.NoPdg when the function has no PDG. * *) let create_slice proj kf = let ff, actions = Fct_slice.make_new_ff (M.get_kf_fi proj kf) true in add_proj_actions proj actions; ff * Delete [ ff_to_remove ] if it is not called . * @raise T.CantRemoveCalledFf if it is . * @raise T.CantRemoveCalledFf if it is. *) let remove_ff proj ff_to_remove = let rec remove ff_list ff_num = match ff_list with | [] -> raise Not_found | ff :: tail -> if ff.T.ff_id = ff_num then (Fct_slice.clear_ff proj ff; tail) else ff :: (remove tail ff_num) in let fi = ff_to_remove.T.ff_fct in let ff_num = ff_to_remove.T.ff_id in let new_ff_list = remove fi.T.fi_slices ff_num in fi.T.fi_slices <- new_ff_list let call_src_and_remove_all_ff proj fi = let do_call actions (ff_caller, call_id) = let new_actions = Fct_slice.apply_change_call proj ff_caller call_id (T.CallSrc (Some fi)) in new_actions @ actions in let do_ff actions ff = let calls = ff.SlicingInternals.ff_called_by in let actions = List.fold_left do_call actions calls in remove_ff proj ff; actions in List.fold_left do_ff [] fi.T.fi_slices let rec remove_uncalled_slices proj = let kf_entry, _ = Globals.entry_point () in let entry_name = Kernel_function.get_name kf_entry in let check_ff changes ff = match ff.T.ff_called_by with [] -> remove_ff proj ff; true | _ -> changes in let check_fi changes fi = if (M.fi_name fi) <> entry_name then List.fold_left check_ff changes (M.fi_slices fi) else changes in let changes = M.fold_fi check_fi false proj in if changes then remove_uncalled_slices proj else () * Build a new slice [ ff ] which contains the marks of [ ff1 ] and [ ff2 ] * and generate everything that is needed to choose the calls in [ ff ] . * If [ replace ] also generate requests call [ ff ] instead of [ ff1 ] and [ ff2 ] . * and generate everything that is needed to choose the calls in [ff]. * If [replace] also generate requests call [ff] instead of [ff1] and [ff2]. *) let merge_slices proj ff1 ff2 replace = let ff, ff_actions = Fct_slice.merge_slices ff1 ff2 in if replace then begin let add actions (caller, call) = let rq = SlicingActions.mk_crit_change_call caller call (T.CallSlice ff) in rq :: actions in let actions = List.fold_left add [] ff2.T.ff_called_by in let actions = List.fold_left add actions ff1.T.ff_called_by in add_proj_actions proj actions end; add_proj_actions proj ff_actions; ff let split_slice proj ff = let add (actions, slices) (caller, call) = let new_ff = Fct_slice.copy_slice ff in let rq = SlicingActions.mk_crit_change_call caller call (T.CallSlice new_ff) in rq::actions, new_ff::slices in keep ff for the first call let actions, slices = List.fold_left add ([], [ff]) calls in add_proj_actions proj actions; slices (*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*) * { 2 Getting information } let get_slices proj kf = M.fi_slices (M.get_kf_fi proj kf) let get_slice_callers ff = List.map (fun (ff, _) -> ff) ff.T.ff_called_by (*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*) * { 2 Adding requests } let add_filter proj filter = proj.T.actions <- filter :: proj.T.actions (* let add_fct_filter proj f_id criterion = let ff_res = match f_id with | T.FctSrc fi -> Fct_slice.make_new_ff fi | T.FctSliced ff -> ff in let filter = SlicingActions.mk_ff_user_crit ff_res criterion in let _ = add_filter proj filter in ff_res *) (** Add an action to the action list to filter the function [fct_id] with the given criterion. The filter gives a name to the result of the filter which is a new slice if the function to filter is the source one, or the given slice otherwise. *) let add_fct_src_filter proj fi to_select = match to_select with (* T.CuSelect [] : don't ignore empty selection because the input control node has to be selected anyway... *) | T.CuSelect select -> let filter = SlicingActions.mk_crit_fct_user_select fi select in add_filter proj filter | T.CuTop m -> let filter = SlicingActions.mk_crit_fct_top fi m in add_filter proj filter (* let add_fct_src_filters proj fi actions = List.iter (fun a -> ignore (add_fct_src_filter proj fi a)) actions *) let add_fct_ff_filter proj ff to_select = match to_select with | T.CuSelect [] -> SlicingParameters.debug ~level:1 "[SlicingProject.add_fct_ff_filter] (ignored empty selection)" | T.CuSelect select -> let filter = SlicingActions.mk_ff_user_select ff select in add_filter proj filter | T.CuTop _ -> assert false (*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*) * { 2 Print } let print_project fmt proj = let get_slices var_fct = let kf = Globals.Functions.get var_fct in let fct_info = M.get_kf_fi proj kf in M.fi_slices fct_info in let print glob = match glob with | Cil_types.GFun (func, _) -> (* function definition *) let slices = get_slices func.Cil_types.svar in List.iter (PrintSlice.print_marked_ff fmt) slices (* TODO see if we have to print the original function *) | _ -> PrintSlice.print_original_glob fmt glob in let source = Ast.get () in let global_decls = source.Cil_types.globals in List.iter print global_decls let print_proj_worklist fmt proj = Format.fprintf fmt "Slicing project worklist [%s/%s] =@\n%a@.@." (Project.get_name proj.T.application) proj.T.name SlicingActions.print_list_crit proj.T.actions let print_project_and_worklist fmt proj = print_project fmt proj; print_proj_worklist fmt proj let pretty_slice fmt ff = PrintSlice.print_marked_ff fmt ff; Format.pp_print_newline fmt () (*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*) * { 2 Managing ( and applying ) requests } (** apply the given criterion and returns the list of new criterions to add to the project worklist. *) let apply_fct_crit ff to_select = let actions = Fct_slice.apply_add_marks ff to_select in actions let apply_appli_crit proj appli_crit = match appli_crit with | T.CaCall fi_to_call -> let kf_to_call = M.get_fi_kf fi_to_call in let add_actions actions (kf_caller,_) = let fi_caller = M.get_kf_fi proj kf_caller in let mark = SlicingMarks.mk_user_spare in let action = SlicingActions.mk_crit_mark_calls fi_caller kf_to_call mark in action :: actions in List.fold_left add_actions [] (!Db.Value.callers kf_to_call) | _ -> SlicingParameters.not_yet_implemented "This slicing criterion on application" * Add persistent the marks [ ] in [ fi ] and also add the marks * to existing slices if any . * If the propagation is ON , some actions are generated to propagate the * persistent marks to the callers , and other actions are generated to * make all the calls to [ fi ] visible . * If there is no slice for [ fi ] we create a new one * if it is the original request . * It will be automatically created with the persistent marks . * If it is a propagation , no need to create a new slice * because it will be created when the call will be selected anyway . * * to existing slices if any. * If the propagation is ON, some actions are generated to propagate the * persistent marks to the callers, and other actions are generated to * make all the calls to [fi] visible. * If there is no slice for [fi] we create a new one * if it is the original request. * It will be automatically created with the persistent marks. * If it is a propagation, no need to create a new slice * because it will be created when the call will be selected anyway. * *) let add_persistant_marks proj fi node_marks orig propagate actions = let new_fi_marks, actions = Fct_slice.add_marks_to_fi proj fi node_marks propagate actions in let actions = match M.fi_slices fi with | [] -> (* no slice *) let actions = if orig then let _ff, new_actions = Fct_slice.make_new_ff fi true in TODO catch NoPdg and mark fi as Top new_actions @ actions else actions in actions | slices -> let add_filter acc ff = let a = SlicingActions.mk_ff_user_select ff node_marks in a::acc in List.fold_left add_filter actions slices in let actions = if propagate && new_fi_marks then let a = SlicingActions.mk_appli_select_calls fi in actions @ [a] else actions in actions let apply_fct_action proj fct_crit = match fct_crit.T.cf_fct with | T.FctSliced ff -> let _ = M.get_ff_pdg ff in let new_filters = match fct_crit.T.cf_info with | T.CcUserMark (T.CuSelect []) -> SlicingParameters.debug ~level:1 "[apply_fct_action] ignore empty selection on existing slice"; [] | T.CcUserMark (T.CuSelect crit) -> apply_fct_crit ff crit | T.CcUserMark (T.CuTop _) -> assert false (* impossible on ff ! *) | T.CcChangeCall (call, f) -> Fct_slice.apply_change_call proj ff call f | T.CcChooseCall call -> Fct_slice.apply_choose_call proj ff call | T.CcMissingInputs (call, input_marks, more_inputs) -> Fct_slice.apply_missing_inputs proj ff call (input_marks, more_inputs) | T.CcMissingOutputs (call, output_marks, more_outputs) -> Fct_slice.apply_missing_outputs proj ff call output_marks more_outputs | T.CcPropagate _ -> assert false (* not for ff at the moment *) | T.CcExamineCalls marks -> Fct_slice.apply_examine_calls ff marks in SlicingParameters.debug ~level:4 "[slicingProject.apply_fct_action] result =@\n%a" PrintSlice.print_marked_ff ff; new_filters | T.FctSrc fi -> (* the marks have to be added to all slices *) let propagate = SlicingParameters.Mode.Callers.get () in match fct_crit.T.cf_info with | T.CcUserMark (T.CuSelect to_select) -> add_persistant_marks proj fi to_select true propagate [] | T.CcUserMark (T.CuTop m) -> SlicingParameters.result ~level:1 "unable to slice %s (-> TOP)" (M.fi_name fi); let filters = call_src_and_remove_all_ff proj fi in Fct_slice.add_top_mark_to_fi fi m propagate filters | T.CcPropagate [] -> SlicingParameters.debug ~level:1 "[apply_fct_action] nothing to propagate"; [] | T.CcPropagate node_marks -> add_persistant_marks proj fi node_marks false propagate [] | T.CcExamineCalls _ | _ -> SlicingParameters.not_yet_implemented "This slicing criterion on source function" (** apply [filter] and return a list of generated filters *) let apply_action proj filter = SlicingParameters.debug ~level:1 "[SlicingProject.apply_action] : %a" SlicingActions.print_crit filter; let new_filters = try match filter with | T.CrFct fct_crit -> begin try (apply_fct_action proj fct_crit) with PdgTypes.Pdg.Bottom -> SlicingParameters.debug ~level:1 " -> action ABORTED (PDG is bottom)" ; [] end | T.CrAppli appli_crit -> apply_appli_crit proj appli_crit with Not_found -> (* catch unprocessed Not_found here *) assert false in SlicingParameters.debug ~level:1 " -> %d generated filters : %a@." (List.length new_filters) SlicingActions.print_list_crit new_filters; new_filters let get_next_filter proj = match proj.T.actions with | [] -> SlicingParameters.debug ~level:2 "[SlicingProject.get_next_filter] No more filter"; raise Not_found | f :: tail -> proj.T.actions <- tail; f let apply_next_action proj = SlicingParameters.debug ~level:2 "[SlicingProject.apply_next_action]"; let filter = get_next_filter proj in let new_filters = apply_action proj filter in proj.T.actions <- new_filters @ proj.T.actions let is_request_empty proj = proj.T.actions = [] let apply_all_actions proj = let nb_actions = List.length proj.T.actions in let rec apply actions = match actions with [] -> () | a::actions -> SlicingParameters.feedback ~level:2 "applying sub action..."; let new_filters = apply_action proj a in apply new_filters; apply actions in SlicingParameters.feedback ~level:1 "applying %d actions..." nb_actions; let rec apply_user n = try let a = get_next_filter proj in SlicingParameters.feedback ~level:1 "applying actions: %d/%d..." n nb_actions; let new_filters = apply_action proj a in apply new_filters; apply_user (n+1) with Not_found -> if nb_actions > 0 then SlicingParameters.feedback ~level:2 "done (applying %d actions." nb_actions in apply_user 1 (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/slicing/slicingProject.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * Handle the project global object. */* */* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ let add_fct_filter proj f_id criterion = let ff_res = match f_id with | T.FctSrc fi -> Fct_slice.make_new_ff fi | T.FctSliced ff -> ff in let filter = SlicingActions.mk_ff_user_crit ff_res criterion in let _ = add_filter proj filter in ff_res * Add an action to the action list to filter the function [fct_id] with the given criterion. The filter gives a name to the result of the filter which is a new slice if the function to filter is the source one, or the given slice otherwise. T.CuSelect [] : don't ignore empty selection because the input control node has to be selected anyway... let add_fct_src_filters proj fi actions = List.iter (fun a -> ignore (add_fct_src_filter proj fi a)) actions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function definition TODO see if we have to print the original function ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * apply the given criterion and returns the list of new criterions to add to the project worklist. no slice impossible on ff ! not for ff at the moment the marks have to be added to all slices * apply [filter] and return a list of generated filters catch unprocessed Not_found here Local Variables: compile-command: "make -C ../../.." End:
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . module T = SlicingInternals module M = SlicingMacros * { 2 Building project } * API function : see { ! : Db . Slicing . Project.mk_project } . let mk_project name = SlicingParameters.feedback ~level:1 "making slicing project '%s'..." name; let r = { T.name = name ; T.application = Project.current () ; T.functions = Cil_datatype.Varinfo.Hashtbl.create 17; T.actions = []; } in SlicingParameters.feedback ~level:2 "done (making slicing project '%s')." name; r let get_name proj = proj.T.name * { 2 Managing the slices } let add_proj_actions proj actions = proj.T.actions <- actions @ proj.T.actions * Add a new slice for the function . It can be the case that it create actions * if the function has some persistent selection , that make function calls to * choose . * @raise SlicingTypes . NoPdg when the function has no . * * if the function has some persistent selection, that make function calls to * choose. * @raise SlicingTypes.NoPdg when the function has no PDG. * *) let create_slice proj kf = let ff, actions = Fct_slice.make_new_ff (M.get_kf_fi proj kf) true in add_proj_actions proj actions; ff * Delete [ ff_to_remove ] if it is not called . * @raise T.CantRemoveCalledFf if it is . * @raise T.CantRemoveCalledFf if it is. *) let remove_ff proj ff_to_remove = let rec remove ff_list ff_num = match ff_list with | [] -> raise Not_found | ff :: tail -> if ff.T.ff_id = ff_num then (Fct_slice.clear_ff proj ff; tail) else ff :: (remove tail ff_num) in let fi = ff_to_remove.T.ff_fct in let ff_num = ff_to_remove.T.ff_id in let new_ff_list = remove fi.T.fi_slices ff_num in fi.T.fi_slices <- new_ff_list let call_src_and_remove_all_ff proj fi = let do_call actions (ff_caller, call_id) = let new_actions = Fct_slice.apply_change_call proj ff_caller call_id (T.CallSrc (Some fi)) in new_actions @ actions in let do_ff actions ff = let calls = ff.SlicingInternals.ff_called_by in let actions = List.fold_left do_call actions calls in remove_ff proj ff; actions in List.fold_left do_ff [] fi.T.fi_slices let rec remove_uncalled_slices proj = let kf_entry, _ = Globals.entry_point () in let entry_name = Kernel_function.get_name kf_entry in let check_ff changes ff = match ff.T.ff_called_by with [] -> remove_ff proj ff; true | _ -> changes in let check_fi changes fi = if (M.fi_name fi) <> entry_name then List.fold_left check_ff changes (M.fi_slices fi) else changes in let changes = M.fold_fi check_fi false proj in if changes then remove_uncalled_slices proj else () * Build a new slice [ ff ] which contains the marks of [ ff1 ] and [ ff2 ] * and generate everything that is needed to choose the calls in [ ff ] . * If [ replace ] also generate requests call [ ff ] instead of [ ff1 ] and [ ff2 ] . * and generate everything that is needed to choose the calls in [ff]. * If [replace] also generate requests call [ff] instead of [ff1] and [ff2]. *) let merge_slices proj ff1 ff2 replace = let ff, ff_actions = Fct_slice.merge_slices ff1 ff2 in if replace then begin let add actions (caller, call) = let rq = SlicingActions.mk_crit_change_call caller call (T.CallSlice ff) in rq :: actions in let actions = List.fold_left add [] ff2.T.ff_called_by in let actions = List.fold_left add actions ff1.T.ff_called_by in add_proj_actions proj actions end; add_proj_actions proj ff_actions; ff let split_slice proj ff = let add (actions, slices) (caller, call) = let new_ff = Fct_slice.copy_slice ff in let rq = SlicingActions.mk_crit_change_call caller call (T.CallSlice new_ff) in rq::actions, new_ff::slices in keep ff for the first call let actions, slices = List.fold_left add ([], [ff]) calls in add_proj_actions proj actions; slices * { 2 Getting information } let get_slices proj kf = M.fi_slices (M.get_kf_fi proj kf) let get_slice_callers ff = List.map (fun (ff, _) -> ff) ff.T.ff_called_by * { 2 Adding requests } let add_filter proj filter = proj.T.actions <- filter :: proj.T.actions let add_fct_src_filter proj fi to_select = match to_select with | T.CuSelect select -> let filter = SlicingActions.mk_crit_fct_user_select fi select in add_filter proj filter | T.CuTop m -> let filter = SlicingActions.mk_crit_fct_top fi m in add_filter proj filter let add_fct_ff_filter proj ff to_select = match to_select with | T.CuSelect [] -> SlicingParameters.debug ~level:1 "[SlicingProject.add_fct_ff_filter] (ignored empty selection)" | T.CuSelect select -> let filter = SlicingActions.mk_ff_user_select ff select in add_filter proj filter | T.CuTop _ -> assert false * { 2 Print } let print_project fmt proj = let get_slices var_fct = let kf = Globals.Functions.get var_fct in let fct_info = M.get_kf_fi proj kf in M.fi_slices fct_info in let print glob = match glob with let slices = get_slices func.Cil_types.svar in List.iter (PrintSlice.print_marked_ff fmt) slices | _ -> PrintSlice.print_original_glob fmt glob in let source = Ast.get () in let global_decls = source.Cil_types.globals in List.iter print global_decls let print_proj_worklist fmt proj = Format.fprintf fmt "Slicing project worklist [%s/%s] =@\n%a@.@." (Project.get_name proj.T.application) proj.T.name SlicingActions.print_list_crit proj.T.actions let print_project_and_worklist fmt proj = print_project fmt proj; print_proj_worklist fmt proj let pretty_slice fmt ff = PrintSlice.print_marked_ff fmt ff; Format.pp_print_newline fmt () * { 2 Managing ( and applying ) requests } let apply_fct_crit ff to_select = let actions = Fct_slice.apply_add_marks ff to_select in actions let apply_appli_crit proj appli_crit = match appli_crit with | T.CaCall fi_to_call -> let kf_to_call = M.get_fi_kf fi_to_call in let add_actions actions (kf_caller,_) = let fi_caller = M.get_kf_fi proj kf_caller in let mark = SlicingMarks.mk_user_spare in let action = SlicingActions.mk_crit_mark_calls fi_caller kf_to_call mark in action :: actions in List.fold_left add_actions [] (!Db.Value.callers kf_to_call) | _ -> SlicingParameters.not_yet_implemented "This slicing criterion on application" * Add persistent the marks [ ] in [ fi ] and also add the marks * to existing slices if any . * If the propagation is ON , some actions are generated to propagate the * persistent marks to the callers , and other actions are generated to * make all the calls to [ fi ] visible . * If there is no slice for [ fi ] we create a new one * if it is the original request . * It will be automatically created with the persistent marks . * If it is a propagation , no need to create a new slice * because it will be created when the call will be selected anyway . * * to existing slices if any. * If the propagation is ON, some actions are generated to propagate the * persistent marks to the callers, and other actions are generated to * make all the calls to [fi] visible. * If there is no slice for [fi] we create a new one * if it is the original request. * It will be automatically created with the persistent marks. * If it is a propagation, no need to create a new slice * because it will be created when the call will be selected anyway. * *) let add_persistant_marks proj fi node_marks orig propagate actions = let new_fi_marks, actions = Fct_slice.add_marks_to_fi proj fi node_marks propagate actions in let actions = match M.fi_slices fi with let actions = if orig then let _ff, new_actions = Fct_slice.make_new_ff fi true in TODO catch NoPdg and mark fi as Top new_actions @ actions else actions in actions | slices -> let add_filter acc ff = let a = SlicingActions.mk_ff_user_select ff node_marks in a::acc in List.fold_left add_filter actions slices in let actions = if propagate && new_fi_marks then let a = SlicingActions.mk_appli_select_calls fi in actions @ [a] else actions in actions let apply_fct_action proj fct_crit = match fct_crit.T.cf_fct with | T.FctSliced ff -> let _ = M.get_ff_pdg ff in let new_filters = match fct_crit.T.cf_info with | T.CcUserMark (T.CuSelect []) -> SlicingParameters.debug ~level:1 "[apply_fct_action] ignore empty selection on existing slice"; [] | T.CcUserMark (T.CuSelect crit) -> apply_fct_crit ff crit | T.CcChangeCall (call, f) -> Fct_slice.apply_change_call proj ff call f | T.CcChooseCall call -> Fct_slice.apply_choose_call proj ff call | T.CcMissingInputs (call, input_marks, more_inputs) -> Fct_slice.apply_missing_inputs proj ff call (input_marks, more_inputs) | T.CcMissingOutputs (call, output_marks, more_outputs) -> Fct_slice.apply_missing_outputs proj ff call output_marks more_outputs | T.CcExamineCalls marks -> Fct_slice.apply_examine_calls ff marks in SlicingParameters.debug ~level:4 "[slicingProject.apply_fct_action] result =@\n%a" PrintSlice.print_marked_ff ff; new_filters let propagate = SlicingParameters.Mode.Callers.get () in match fct_crit.T.cf_info with | T.CcUserMark (T.CuSelect to_select) -> add_persistant_marks proj fi to_select true propagate [] | T.CcUserMark (T.CuTop m) -> SlicingParameters.result ~level:1 "unable to slice %s (-> TOP)" (M.fi_name fi); let filters = call_src_and_remove_all_ff proj fi in Fct_slice.add_top_mark_to_fi fi m propagate filters | T.CcPropagate [] -> SlicingParameters.debug ~level:1 "[apply_fct_action] nothing to propagate"; [] | T.CcPropagate node_marks -> add_persistant_marks proj fi node_marks false propagate [] | T.CcExamineCalls _ | _ -> SlicingParameters.not_yet_implemented "This slicing criterion on source function" let apply_action proj filter = SlicingParameters.debug ~level:1 "[SlicingProject.apply_action] : %a" SlicingActions.print_crit filter; let new_filters = try match filter with | T.CrFct fct_crit -> begin try (apply_fct_action proj fct_crit) with PdgTypes.Pdg.Bottom -> SlicingParameters.debug ~level:1 " -> action ABORTED (PDG is bottom)" ; [] end | T.CrAppli appli_crit -> apply_appli_crit proj appli_crit in SlicingParameters.debug ~level:1 " -> %d generated filters : %a@." (List.length new_filters) SlicingActions.print_list_crit new_filters; new_filters let get_next_filter proj = match proj.T.actions with | [] -> SlicingParameters.debug ~level:2 "[SlicingProject.get_next_filter] No more filter"; raise Not_found | f :: tail -> proj.T.actions <- tail; f let apply_next_action proj = SlicingParameters.debug ~level:2 "[SlicingProject.apply_next_action]"; let filter = get_next_filter proj in let new_filters = apply_action proj filter in proj.T.actions <- new_filters @ proj.T.actions let is_request_empty proj = proj.T.actions = [] let apply_all_actions proj = let nb_actions = List.length proj.T.actions in let rec apply actions = match actions with [] -> () | a::actions -> SlicingParameters.feedback ~level:2 "applying sub action..."; let new_filters = apply_action proj a in apply new_filters; apply actions in SlicingParameters.feedback ~level:1 "applying %d actions..." nb_actions; let rec apply_user n = try let a = get_next_filter proj in SlicingParameters.feedback ~level:1 "applying actions: %d/%d..." n nb_actions; let new_filters = apply_action proj a in apply new_filters; apply_user (n+1) with Not_found -> if nb_actions > 0 then SlicingParameters.feedback ~level:2 "done (applying %d actions." nb_actions in apply_user 1
65632bb764ae4d495acde3884214f9f6513268418392ce432c0c6716b4b44bc5
ucsd-progsys/nate
ocamlbuild_executor.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 Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : ocamlbuild_executor.ml , v 1.1.2.3 2007/11/28 17:21:00 ertai Exp $ Original author : Ocamlbuild_executor open Unix;; type error = | Subcommand_failed | Subcommand_got_signal | Io_error | Exceptionl_condition type task = unit -> string;; type job = { job_id : int * int; job_command : string; job_next : task list; job_result : bool ref; (* Result of this sequence group *) job_stdout : in_channel; job_stdin : out_channel; job_stderr : in_channel; job_buffer : Buffer.t; mutable job_dying : bool; };; module JS = Set.Make(struct type t = job let compare = compare end);; module FDM = Map.Make(struct type t = file_descr let compare = compare end);; let sf = Printf.sprintf;; let fp = Printf.fprintf;; (*** print_unix_status *) (* FIXME never called *) let print_unix_status oc = function | WEXITED x -> fp oc "exit %d" x | WSIGNALED i -> fp oc "signal %d" i | WSTOPPED i -> fp oc "stop %d" i ;; (* ***) (*** print_job_id *) let print_job_id oc (x,y) = fp oc "%d.%d" x y;; (* ***) (*** output_lines *) let output_lines prefix oc buffer = let u = Buffer.contents buffer in let m = String.length u in let output_line i j = output_string oc prefix; output oc u i (j - i); output_char oc '\n' in let rec loop i = if i = m then () else begin try let j = String.index_from u i '\n' in output_line i j; loop (j + 1) with | Not_found -> output_line i m end in loop 0 ;; (* ***) (*** execute *) (* XXX: Add test for non reentrancy *) let execute ?(max_jobs=max_int) ?(ticker=ignore) ?(period=0.1) ?(display=(fun f -> f Pervasives.stdout)) ~exit (commands : task list list) = let batch_id = ref 0 in let env = environment () in let jobs = ref JS.empty in let jobs_active = ref 0 in let jobs_to_terminate = Queue.create () in let commands_to_execute = Queue.create () in let all_ok = ref true in let results = List.map (fun tasks -> let result = ref false in Queue.add (tasks, result) commands_to_execute; result) commands in let outputs = ref FDM.empty in let doi = descr_of_in_channel in let doo = descr_of_out_channel in (*** compute_fds *) let compute_fds = let fds = ref ([], [], []) in let prev_jobs = ref JS.empty in fun () -> if not (!prev_jobs == !jobs) then begin prev_jobs := !jobs; fds := JS.fold begin fun job (rfds, wfds, xfds) -> let ofd = doi job.job_stdout and ifd = doo job.job_stdin and efd = doi job.job_stderr in (ofd :: efd :: rfds, wfds, ofd :: ifd :: efd :: xfds) end !jobs ([], [], []) end; !fds in (* ***) (*** add_job *) let add_job cmd rest result id = (*display begin fun oc -> fp oc "Job %a is %s\n%!" print_job_id id cmd; end;*) let (stdout', stdin', stderr') = open_process_full cmd env in incr jobs_active; set_nonblock (doi stdout'); set_nonblock (doi stderr'); let job = { job_id = id; job_command = cmd; job_next = rest; job_result = result; job_stdout = stdout'; job_stdin = stdin'; job_stderr = stderr'; job_buffer = Buffer.create 1024; job_dying = false } in outputs := FDM.add (doi stdout') job (FDM.add (doi stderr') job !outputs); jobs := JS.add job !jobs; in (* ***) (*** skip_empty_tasks *) let rec skip_empty_tasks = function | [] -> None | task :: tasks -> let cmd = task () in if cmd = "" then skip_empty_tasks tasks else Some(cmd, tasks) in (* ***) (*** add_some_jobs *) let add_some_jobs () = let (tasks, result) = Queue.take commands_to_execute in match skip_empty_tasks tasks with | None -> result := false | Some(cmd, rest) -> let b_id = !batch_id in incr batch_id; add_job cmd rest result (b_id, 0) in (* ***) (*** terminate *) let terminate ?(continue=true) job = if not job.job_dying then begin job.job_dying <- true; Queue.add (job, continue) jobs_to_terminate end else () in (* ***) (*** add_more_jobs_if_possible *) let add_more_jobs_if_possible () = while !jobs_active < max_jobs && not (Queue.is_empty commands_to_execute) do add_some_jobs () done in (* ***) (*** do_read *) let do_read = let u = String.create 4096 in fun ?(loop=false) fd job -> (*if job.job_dying then () else*) try let rec iteration () = let m = try read fd u 0 (String.length u) with | Unix.Unix_error(_,_,_) -> 0 in if m = 0 then if job.job_dying then () else terminate job else begin Buffer.add_substring job.job_buffer u 0 m; if loop then iteration () else () end in iteration () with | x -> display begin fun oc -> fp oc "Exception %s while reading output of command %S\n%!" job.job_command (Printexc.to_string x); end; exit Io_error in (* ***) (*** process_jobs_to_terminate *) let process_jobs_to_terminate () = while not (Queue.is_empty jobs_to_terminate) do ticker (); let (job, continue) = Queue.take jobs_to_terminate in (*display begin fun oc -> fp oc "Terminating job %a\n%!" print_job_id job.job_id; end;*) decr jobs_active; do_read ~loop:true (doi job.job_stdout) job; do_read ~loop:true (doi job.job_stderr) job; outputs := FDM.remove (doi job.job_stdout) (FDM.remove (doi job.job_stderr) !outputs); jobs := JS.remove job !jobs; let status = close_process_full (job.job_stdout, job.job_stdin, job.job_stderr) in let shown = ref false in let show_command () = if !shown then () else display begin fun oc -> shown := true; fp oc "+ %s\n" job.job_command; output_lines "" oc job.job_buffer end in if Buffer.length job.job_buffer > 0 then show_command (); begin match status with | Unix.WEXITED 0 -> begin if continue then begin match skip_empty_tasks job.job_next with | None -> job.job_result := true | Some(cmd, rest) -> let (b_id, s_id) = job.job_id in add_job cmd rest job.job_result (b_id, s_id + 1) end else all_ok := false; end | Unix.WEXITED rc -> show_command (); display (fun oc -> fp oc "Command exited with code %d.\n" rc); all_ok := false; exit Subcommand_failed | Unix.WSTOPPED s | Unix.WSIGNALED s -> show_command (); all_ok := false; display (fun oc -> fp oc "Command got signal %d.\n" s); exit Subcommand_got_signal end done in (* ***) (*** terminate_all_jobs *) let terminate_all_jobs () = JS.iter (terminate ~continue:false) !jobs in (* ***) (*** loop *) let rec loop () = (*display (fun oc -> fp oc "Total %d jobs\n" !jobs_active);*) process_jobs_to_terminate (); add_more_jobs_if_possible (); if JS.is_empty !jobs then () else begin let (rfds, wfds, xfds) = compute_fds () in ticker (); let (chrfds, chwfds, chxfds) = select rfds wfds xfds period in List.iter begin fun (fdlist, hook) -> List.iter begin fun fd -> try let job = FDM.find fd !outputs in ticker (); hook fd job with | Not_found -> () (* XXX *) end fdlist end [chrfds, do_read ~loop:false; chwfds, (fun _ _ -> ()); chxfds, begin fun _ _job -> (*display (fun oc -> fp oc "Exceptional condition on command %S\n%!" job.job_command); exit Exceptional_condition*) FIXME end]; loop () end in try loop (); None with | x -> begin try terminate_all_jobs () with | x' -> display (fun oc -> fp oc "Extra exception %s\n%!" (Printexc.to_string x')) end; Some(List.map (!) results, x) ;; (* ***)
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/ocamlbuild/ocamlbuild_executor.ml
ocaml
********************************************************************* ocamlbuild ********************************************************************* Result of this sequence group ** print_unix_status FIXME never called ** ** print_job_id ** ** output_lines ** ** execute XXX: Add test for non reentrancy ** compute_fds ** ** add_job display begin fun oc -> fp oc "Job %a is %s\n%!" print_job_id id cmd; end; ** ** skip_empty_tasks ** ** add_some_jobs ** ** terminate ** ** add_more_jobs_if_possible ** ** do_read if job.job_dying then () else ** ** process_jobs_to_terminate display begin fun oc -> fp oc "Terminating job %a\n%!" print_job_id job.job_id; end; ** ** terminate_all_jobs ** ** loop display (fun oc -> fp oc "Total %d jobs\n" !jobs_active); XXX display (fun oc -> fp oc "Exceptional condition on command %S\n%!" job.job_command); exit Exceptional_condition **
, , 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 Q Public License version 1.0 . $ I d : ocamlbuild_executor.ml , v 1.1.2.3 2007/11/28 17:21:00 ertai Exp $ Original author : Ocamlbuild_executor open Unix;; type error = | Subcommand_failed | Subcommand_got_signal | Io_error | Exceptionl_condition type task = unit -> string;; type job = { job_id : int * int; job_command : string; job_next : task list; job_stdout : in_channel; job_stdin : out_channel; job_stderr : in_channel; job_buffer : Buffer.t; mutable job_dying : bool; };; module JS = Set.Make(struct type t = job let compare = compare end);; module FDM = Map.Make(struct type t = file_descr let compare = compare end);; let sf = Printf.sprintf;; let fp = Printf.fprintf;; let print_unix_status oc = function | WEXITED x -> fp oc "exit %d" x | WSIGNALED i -> fp oc "signal %d" i | WSTOPPED i -> fp oc "stop %d" i ;; let print_job_id oc (x,y) = fp oc "%d.%d" x y;; let output_lines prefix oc buffer = let u = Buffer.contents buffer in let m = String.length u in let output_line i j = output_string oc prefix; output oc u i (j - i); output_char oc '\n' in let rec loop i = if i = m then () else begin try let j = String.index_from u i '\n' in output_line i j; loop (j + 1) with | Not_found -> output_line i m end in loop 0 ;; let execute ?(max_jobs=max_int) ?(ticker=ignore) ?(period=0.1) ?(display=(fun f -> f Pervasives.stdout)) ~exit (commands : task list list) = let batch_id = ref 0 in let env = environment () in let jobs = ref JS.empty in let jobs_active = ref 0 in let jobs_to_terminate = Queue.create () in let commands_to_execute = Queue.create () in let all_ok = ref true in let results = List.map (fun tasks -> let result = ref false in Queue.add (tasks, result) commands_to_execute; result) commands in let outputs = ref FDM.empty in let doi = descr_of_in_channel in let doo = descr_of_out_channel in let compute_fds = let fds = ref ([], [], []) in let prev_jobs = ref JS.empty in fun () -> if not (!prev_jobs == !jobs) then begin prev_jobs := !jobs; fds := JS.fold begin fun job (rfds, wfds, xfds) -> let ofd = doi job.job_stdout and ifd = doo job.job_stdin and efd = doi job.job_stderr in (ofd :: efd :: rfds, wfds, ofd :: ifd :: efd :: xfds) end !jobs ([], [], []) end; !fds in let add_job cmd rest result id = let (stdout', stdin', stderr') = open_process_full cmd env in incr jobs_active; set_nonblock (doi stdout'); set_nonblock (doi stderr'); let job = { job_id = id; job_command = cmd; job_next = rest; job_result = result; job_stdout = stdout'; job_stdin = stdin'; job_stderr = stderr'; job_buffer = Buffer.create 1024; job_dying = false } in outputs := FDM.add (doi stdout') job (FDM.add (doi stderr') job !outputs); jobs := JS.add job !jobs; in let rec skip_empty_tasks = function | [] -> None | task :: tasks -> let cmd = task () in if cmd = "" then skip_empty_tasks tasks else Some(cmd, tasks) in let add_some_jobs () = let (tasks, result) = Queue.take commands_to_execute in match skip_empty_tasks tasks with | None -> result := false | Some(cmd, rest) -> let b_id = !batch_id in incr batch_id; add_job cmd rest result (b_id, 0) in let terminate ?(continue=true) job = if not job.job_dying then begin job.job_dying <- true; Queue.add (job, continue) jobs_to_terminate end else () in let add_more_jobs_if_possible () = while !jobs_active < max_jobs && not (Queue.is_empty commands_to_execute) do add_some_jobs () done in let do_read = let u = String.create 4096 in fun ?(loop=false) fd job -> try let rec iteration () = let m = try read fd u 0 (String.length u) with | Unix.Unix_error(_,_,_) -> 0 in if m = 0 then if job.job_dying then () else terminate job else begin Buffer.add_substring job.job_buffer u 0 m; if loop then iteration () else () end in iteration () with | x -> display begin fun oc -> fp oc "Exception %s while reading output of command %S\n%!" job.job_command (Printexc.to_string x); end; exit Io_error in let process_jobs_to_terminate () = while not (Queue.is_empty jobs_to_terminate) do ticker (); let (job, continue) = Queue.take jobs_to_terminate in decr jobs_active; do_read ~loop:true (doi job.job_stdout) job; do_read ~loop:true (doi job.job_stderr) job; outputs := FDM.remove (doi job.job_stdout) (FDM.remove (doi job.job_stderr) !outputs); jobs := JS.remove job !jobs; let status = close_process_full (job.job_stdout, job.job_stdin, job.job_stderr) in let shown = ref false in let show_command () = if !shown then () else display begin fun oc -> shown := true; fp oc "+ %s\n" job.job_command; output_lines "" oc job.job_buffer end in if Buffer.length job.job_buffer > 0 then show_command (); begin match status with | Unix.WEXITED 0 -> begin if continue then begin match skip_empty_tasks job.job_next with | None -> job.job_result := true | Some(cmd, rest) -> let (b_id, s_id) = job.job_id in add_job cmd rest job.job_result (b_id, s_id + 1) end else all_ok := false; end | Unix.WEXITED rc -> show_command (); display (fun oc -> fp oc "Command exited with code %d.\n" rc); all_ok := false; exit Subcommand_failed | Unix.WSTOPPED s | Unix.WSIGNALED s -> show_command (); all_ok := false; display (fun oc -> fp oc "Command got signal %d.\n" s); exit Subcommand_got_signal end done in let terminate_all_jobs () = JS.iter (terminate ~continue:false) !jobs in let rec loop () = process_jobs_to_terminate (); add_more_jobs_if_possible (); if JS.is_empty !jobs then () else begin let (rfds, wfds, xfds) = compute_fds () in ticker (); let (chrfds, chwfds, chxfds) = select rfds wfds xfds period in List.iter begin fun (fdlist, hook) -> List.iter begin fun fd -> try let job = FDM.find fd !outputs in ticker (); hook fd job with end fdlist end [chrfds, do_read ~loop:false; chwfds, (fun _ _ -> ()); chxfds, begin fun _ _job -> FIXME end]; loop () end in try loop (); None with | x -> begin try terminate_all_jobs () with | x' -> display (fun oc -> fp oc "Extra exception %s\n%!" (Printexc.to_string x')) end; Some(List.map (!) results, x) ;;
f41f30b5c49bb1ec45987e7be661a284745f9fdef5ba4a9f8600ded3800c3432
danielmiladinov/joy-of-clojure
macros_changing_forms.clj
;; Using macros to change forms ;; --------------------------------------------------------------------------------------------------------------------- One way to design macros is to start by writing out example code that you wish worked -- code that has the minimal ;; distance between what you must specify and the specific application domain in which you're working. Then, with the ;; goal of making this code work, you begin writing macros and functions to fill in the missing pieces. ;; For example, when designing software systems, it's often useful to identify the 'things" that make up your given ;; application domain, including their logical groupings. The level of abstraction at this point in the design is best ;; kept high and shouldn't include details about implementation. Imagine that you want to describe a simple domain of ;; the ongoing struggle between humans and monsters: ;; * Man versus monster ;; * People ;; * Men (humans) ;; - Name ;; - Have beards? ;; * Monsters * ;; - Eats goats? ;; Although this is a simple format, it needs work to be programmatically useful. Therefore, the goal of this section is to write macros that perform the steps to get from this simple representation to the one more conducive to processing . The outline form can be rendered in a Clojure form , assuming the existence of some macros and functions ;; you've yet to define, like this: (domain man-vs-monster (grouping people (Human "A stock human") (Man (isa Human) "A man, baby!" [name] [has-beard?])) (grouping monsters (Chupacabra "A fierce, yet elusive creature" [eats-goats?]))) One possible structure underlying this sample format is a tree composed of individual generic nodes , each taking a ;; form similar to the following: {:tag <node form>, ; Domain grouping, and so on :attrs {}, ; For example, :name people :content [<nodes>]} ; For example, properties ;; You'd never say this is a beautiful format, but it does present practical advantages over the original format -- it's ;; a tree, it's composed of simple types, it's regular, and it's recognizable to some existing libraries. Clojure aphorism ;; ---------------- Clojure is a design language where the conceptual model is also Clojure . ;; Start with the outer-level element, domain: (defmacro domain [name & body] `{:tag :domain, :attrs {:name (str '~name)}, :content [~@body]}) ;; The body of domain is fairly straightforward in that it sets the domain-level tree node and splices the body of the ;; macro into the :content slot. After domain expands, you'd expect its body to be composed of a number of grouping ;; forms, which are then handled by an aptly named macro: (declare handle-things) (defmacro grouping [name & body] `{:tag :grouping, :attrs {:name (str '~name)}, :content [~@(handle-things body)]}) ;; Similar to domain, grouping expands into a node with its body spliced into the :content slot. In its body, the ;; grouping macro uses a form named handle-things that hasn't been written yet, so you have to use declare to avoid a ;; compilation error. But grouping differs from domain in that it splices in the result of the call to a function, ;; handle-things: (declare grok-attrs grok-props) (defn handle-things [things] (for [t things] {:tag :thing, :attrs (grok-attrs (take-while (comp not vector?) t)) :content (if-let [c (grok-props (drop-while (comp not vector?) t))] [c] [])})) ;; Because the body of a thing is fairly simple and regular, you can simplify the implementation of handle-things by again splitting it into two functions . The first function , grok - attrs , handles everything in the body of a thing ;; that's not a vector, and grok-props handles properties that are. In both cases, these leaf-level functions return ;; specifically formed maps: (defn grok-attrs [attrs] (into {:name (str (first attrs))} (for [a (rest attrs)] (cond (list? a) [:isa (str (second a))] (string? a) [:comment a])))) ;; The implementation of grok-attrs may seem overly complex, especially given that the sample domain model DSL only ;; allows for a comment attribute and an optional isa specification (as shown in the sample layout in the beginning of ;; this section). But by laying it out this way, you can easily expand the function to handle a richer set of attributes later . Likewise with grok - props , this more complicated function pulls apart the vector representing a ;; property so it's more conducive to expansion: (defn grok-props [props] (when props {:tag :properties, :attrs nil, :content (apply vector (for [p props] {:tag :property, :attrs {:name (str first p)}, :content nil}))})) ;; Now that you've created the pieces, take a look at the new DSL in action: (def d (domain man-vs-monster (grouping people ; Group of people One kind of person (Man (isa Human) ; Another kind of person "A man, baby" [name] [has-beard?])) (grouping monsters ; Group of monsters One kind of monsters "A fierce, yet elusive creature" [eats-goats?])))) ;; You can navigate this structure as follows: (:tag d) ;;=> :domain (:tag (first (:content d))) ;;=> :grouping ;; Maybe that's enough to prove to you that you've constructed the promised tree, but probably not. Therefore, you can pass a tree into a function that expects one of that form8 and see what comes out on the other end : (use '[clojure.xml :as xml]) (xml/emit d) Performing this function call prints out the corresponding XML representation , minus the pretty printing : ;; <?xml version='1.0' encoding='UTF-8'?> < domain - monster ' > ;; <grouping name='people'> ;; <thing name='Human' comment='A stock human'> ;; <properties> ;; </properties> ;; </thing> ;; <thing isa='Human' name='Man' comment='A man, baby'> ;; <properties> ;; <property name='clojure.core$first@4cd7ec6a[name]'/> ;; <property name='clojure.core$first@4cd7ec6a[has-beard?]'/> ;; </properties> ;; </thing> ;; </grouping> ;; <grouping name='monsters'> ;; <thing name='Chupacabra' comment='A fierce, yet elusive creature'> ;; <properties> < property name='clojure.core$first@4cd7ec6a[eats - goats?]'/ > ;; </properties> ;; </thing> ;; </grouping> ;; </domain> ;; Our approach was to define a single macro entry point domain, intended to build the top-level layers of the output ;; data structure and instead pass the remainder on to auxiliary functions for further processing. In this way, the body ;; of the macro expands into a series of function calls, each taking some subset of the remaining structure and ;; returning some result that's spliced into the final result. This functional composition approach is fairly common when defining macros . The entirety of the domain description could have been written in one monolithic macro , but by ;; splitting the responsibilities, you can more easily extend the representations for the constituent parts. Macros take data and return data , always . It so happens that in Clojure , code is data and data is code .
null
https://raw.githubusercontent.com/danielmiladinov/joy-of-clojure/cad7d1851e153beb12a2cd536eb467be12cb7a73/src/joy-of-clojure/chapter8/macros_changing_forms.clj
clojure
Using macros to change forms --------------------------------------------------------------------------------------------------------------------- distance between what you must specify and the specific application domain in which you're working. Then, with the goal of making this code work, you begin writing macros and functions to fill in the missing pieces. For example, when designing software systems, it's often useful to identify the 'things" that make up your given application domain, including their logical groupings. The level of abstraction at this point in the design is best kept high and shouldn't include details about implementation. Imagine that you want to describe a simple domain of the ongoing struggle between humans and monsters: * Man versus monster * People * Men (humans) - Name - Have beards? * Monsters - Eats goats? Although this is a simple format, it needs work to be programmatically useful. Therefore, the goal of this section is you've yet to define, like this: form similar to the following: Domain grouping, and so on For example, :name people For example, properties You'd never say this is a beautiful format, but it does present practical advantages over the original format -- it's a tree, it's composed of simple types, it's regular, and it's recognizable to some existing libraries. ---------------- Start with the outer-level element, domain: The body of domain is fairly straightforward in that it sets the domain-level tree node and splices the body of the macro into the :content slot. After domain expands, you'd expect its body to be composed of a number of grouping forms, which are then handled by an aptly named macro: Similar to domain, grouping expands into a node with its body spliced into the :content slot. In its body, the grouping macro uses a form named handle-things that hasn't been written yet, so you have to use declare to avoid a compilation error. But grouping differs from domain in that it splices in the result of the call to a function, handle-things: Because the body of a thing is fairly simple and regular, you can simplify the implementation of handle-things by that's not a vector, and grok-props handles properties that are. In both cases, these leaf-level functions return specifically formed maps: The implementation of grok-attrs may seem overly complex, especially given that the sample domain model DSL only allows for a comment attribute and an optional isa specification (as shown in the sample layout in the beginning of this section). But by laying it out this way, you can easily expand the function to handle a richer set of property so it's more conducive to expansion: Now that you've created the pieces, take a look at the new DSL in action: Group of people Another kind of person Group of monsters You can navigate this structure as follows: => :domain => :grouping Maybe that's enough to prove to you that you've constructed the promised tree, but probably not. Therefore, you can <?xml version='1.0' encoding='UTF-8'?> <grouping name='people'> <thing name='Human' comment='A stock human'> <properties> </properties> </thing> <thing isa='Human' name='Man' comment='A man, baby'> <properties> <property name='clojure.core$first@4cd7ec6a[name]'/> <property name='clojure.core$first@4cd7ec6a[has-beard?]'/> </properties> </thing> </grouping> <grouping name='monsters'> <thing name='Chupacabra' comment='A fierce, yet elusive creature'> <properties> </properties> </thing> </grouping> </domain> Our approach was to define a single macro entry point domain, intended to build the top-level layers of the output data structure and instead pass the remainder on to auxiliary functions for further processing. In this way, the body of the macro expands into a series of function calls, each taking some subset of the remaining structure and returning some result that's spliced into the final result. This functional composition approach is fairly common splitting the responsibilities, you can more easily extend the representations for the constituent parts.
One way to design macros is to start by writing out example code that you wish worked -- code that has the minimal * to write macros that perform the steps to get from this simple representation to the one more conducive to processing . The outline form can be rendered in a Clojure form , assuming the existence of some macros and functions (domain man-vs-monster (grouping people (Human "A stock human") (Man (isa Human) "A man, baby!" [name] [has-beard?])) (grouping monsters (Chupacabra "A fierce, yet elusive creature" [eats-goats?]))) One possible structure underlying this sample format is a tree composed of individual generic nodes , each taking a Clojure aphorism Clojure is a design language where the conceptual model is also Clojure . (defmacro domain [name & body] `{:tag :domain, :attrs {:name (str '~name)}, :content [~@body]}) (declare handle-things) (defmacro grouping [name & body] `{:tag :grouping, :attrs {:name (str '~name)}, :content [~@(handle-things body)]}) (declare grok-attrs grok-props) (defn handle-things [things] (for [t things] {:tag :thing, :attrs (grok-attrs (take-while (comp not vector?) t)) :content (if-let [c (grok-props (drop-while (comp not vector?) t))] [c] [])})) again splitting it into two functions . The first function , grok - attrs , handles everything in the body of a thing (defn grok-attrs [attrs] (into {:name (str (first attrs))} (for [a (rest attrs)] (cond (list? a) [:isa (str (second a))] (string? a) [:comment a])))) attributes later . Likewise with grok - props , this more complicated function pulls apart the vector representing a (defn grok-props [props] (when props {:tag :properties, :attrs nil, :content (apply vector (for [p props] {:tag :property, :attrs {:name (str first p)}, :content nil}))})) (def d (domain man-vs-monster One kind of person "A man, baby" [name] [has-beard?])) One kind of monsters "A fierce, yet elusive creature" [eats-goats?])))) (:tag d) (:tag (first (:content d))) pass a tree into a function that expects one of that form8 and see what comes out on the other end : (use '[clojure.xml :as xml]) (xml/emit d) Performing this function call prints out the corresponding XML representation , minus the pretty printing : < domain - monster ' > < property name='clojure.core$first@4cd7ec6a[eats - goats?]'/ > when defining macros . The entirety of the domain description could have been written in one monolithic macro , but by Macros take data and return data , always . It so happens that in Clojure , code is data and data is code .
74d630e1eb62e83127ad2ac4354185b581b4c670e68bceeea74ae8052d58c169
dparis/gen-phzr
load_texture.cljs
(ns phzr.impl.accessors.component.load-texture) (def load-texture-get-properties {:frame "frame" :frame-name "frameName"}) (def load-texture-set-properties {:frame "frame" :frame-name "frameName"})
null
https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/impl/accessors/component/load_texture.cljs
clojure
(ns phzr.impl.accessors.component.load-texture) (def load-texture-get-properties {:frame "frame" :frame-name "frameName"}) (def load-texture-set-properties {:frame "frame" :frame-name "frameName"})
6681b6e6be1b571bbda934c8f5fde980c168160f2800e61fccdcb213073222ca
zwizwa/staapl
asm.rkt
#lang racket/base (require "tools.rkt") (require/provide "op.rkt" "asm/operand.rkt" "asm/assembler.rkt" "asm/dasm.rkt" "asm/directives.rkt" "asm/pointers.rkt" "asm/instruction-set.rkt") ;; highlevel language for instruction set definition ;; (loading "asm")
null
https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/asm.rkt
racket
highlevel language for instruction set definition (loading "asm")
#lang racket/base (require "tools.rkt") (require/provide "op.rkt" "asm/operand.rkt" "asm/assembler.rkt" "asm/dasm.rkt" "asm/directives.rkt" "asm/pointers.rkt"
64f469719090861e094d093aa31fa4b75605ddb1df8c495ed4fe06cee5c37994
mgree/smoosh
runtest.ml
let main () = let results = [Test_arith.run_tests (); Test_path.run_tests (); Test_expansion.run_tests (); Test_evaluation.run_tests ()] in let exit_code = List.length (List.filter not results) in exit exit_code;; main ()
null
https://raw.githubusercontent.com/mgree/smoosh/84b1ff86f59573a2e4fd7e23edfa0cf9fdb45db9/src/runtest.ml
ocaml
let main () = let results = [Test_arith.run_tests (); Test_path.run_tests (); Test_expansion.run_tests (); Test_evaluation.run_tests ()] in let exit_code = List.length (List.filter not results) in exit exit_code;; main ()
ba091228fcb40fe81e6fcd90ab1964edb349839b11263f270189e983af53a59f
VERIMAG-Polyhedra/VPL
demo_vplcoq.ml
ML source file of an exectuable running the examples of DemoPLTests.v ( in directory coq/ ) the examples of DemoPLTests.v (in directory coq/) *) open Vpl;; open CertcheckerConfig;; open Debugging;; Printf.printf "*** run tests generated from Coq...\n";; OraclePattern.Debug.enable ; MInput ; MOutput ; Normal ; Detail ] ) ; ; OraclePattern . Debug.print_enable ( ) ; ; IOtypes.Debug.enable DebugTypes.([Title ; MInput ; MOutput ; Normal ; Detail ] ) ; ; IOtypes . Debug.print_enable ( ) ; ; OraclePattern.Debug.enable DebugTypes.([Title ; MInput ; MOutput ; Normal ; Detail]);; OraclePattern.Debug.print_enable();; IOtypes.Debug.enable DebugTypes.([Title ; MInput ; MOutput ; Normal ; Detail]);; IOtypes.Debug.print_enable();; *) (* Debug.enable();; Debug.print_enable();; Debug.set_colors();; *) (** options (fixées en dur !) *) let firstfail_mode = false;; (** Déclaration de variables *) let nextVar = ref Var.XH;; let newvar _ = let x = !nextVar in nextVar := Var.next !nextVar; (PedraQOracles.varToProgVar x);; module VB = struct let x = newvar "x";; let y = newvar "y";; let q = newvar "q";; let r = newvar "r";; let a = newvar "a";; let x1 = newvar "x1";; let x2 = newvar "x2";; let y1 = newvar "y1";; let y2 = newvar "y2";; let aux = newvar "aux";; let lb = newvar "lb" ;; let ub = newvar "ub" ;; let c = newvar "c";; end;; open VB;; (** Execution des tests **) open DemoPLVerifier;; let tests = ref 0 ;; let failed = ref 0;; let incr r = r:=!r+1;; let afficheok attendu = if attendu then print_string " passed as expected\n" else print_string " failed as expected\n";; let afficheko attendu = incr failed; if attendu then print_string "ko (failed vs passed expected)\n" else print_string "ko (passed vs failed expected)\n";; let firstfail_launch nom test attendu = Printf.printf "*** %s: " nom; if (verifier test)=attendu then ( afficheok attendu ) else ( afficheko attendu ) let launch nom test attendu = try firstfail_launch nom test attendu with CertCheckerFailure(st, mesg) -> if st = DEMO then ( Printf.printf " failure %s !\n" mesg ; if attendu then afficheko true else afficheok false ) else ( Printf.printf " %s: %s !\n" (if st=CERT then "certificate error" else "internal error from cert checker") mesg; incr failed; ) let rec launch_list l attendu = match l with | [] -> print_newline(); | (nom,test)::ll -> incr tests; if firstfail_mode then firstfail_launch (CoqPr.charListTr nom) test attendu else launch (CoqPr.charListTr nom) test attendu; launch_list ll attendu;; module Ex = DemoPLTests.Examples(VB);; launch_list Ex.tests_ok true;; launch_list Ex.tests_ko false;; let nbfails = !failed in if nbfails=0 then Printf.printf "*** Passed %d tests\n" !tests else ( Printf.printf "*** %d failure(s) in %d tests:\n" nbfails !tests; exit 1);;
null
https://raw.githubusercontent.com/VERIMAG-Polyhedra/VPL/cd78d6e7d120508fd5a694bdb01300477e5646f8/test/demo_vplcoq.ml
ocaml
Debug.enable();; Debug.print_enable();; Debug.set_colors();; * options (fixées en dur !) * Déclaration de variables * Execution des tests *
ML source file of an exectuable running the examples of DemoPLTests.v ( in directory coq/ ) the examples of DemoPLTests.v (in directory coq/) *) open Vpl;; open CertcheckerConfig;; open Debugging;; Printf.printf "*** run tests generated from Coq...\n";; OraclePattern.Debug.enable ; MInput ; MOutput ; Normal ; Detail ] ) ; ; OraclePattern . Debug.print_enable ( ) ; ; IOtypes.Debug.enable DebugTypes.([Title ; MInput ; MOutput ; Normal ; Detail ] ) ; ; IOtypes . Debug.print_enable ( ) ; ; OraclePattern.Debug.enable DebugTypes.([Title ; MInput ; MOutput ; Normal ; Detail]);; OraclePattern.Debug.print_enable();; IOtypes.Debug.enable DebugTypes.([Title ; MInput ; MOutput ; Normal ; Detail]);; IOtypes.Debug.print_enable();; *) let firstfail_mode = false;; let nextVar = ref Var.XH;; let newvar _ = let x = !nextVar in nextVar := Var.next !nextVar; (PedraQOracles.varToProgVar x);; module VB = struct let x = newvar "x";; let y = newvar "y";; let q = newvar "q";; let r = newvar "r";; let a = newvar "a";; let x1 = newvar "x1";; let x2 = newvar "x2";; let y1 = newvar "y1";; let y2 = newvar "y2";; let aux = newvar "aux";; let lb = newvar "lb" ;; let ub = newvar "ub" ;; let c = newvar "c";; end;; open VB;; open DemoPLVerifier;; let tests = ref 0 ;; let failed = ref 0;; let incr r = r:=!r+1;; let afficheok attendu = if attendu then print_string " passed as expected\n" else print_string " failed as expected\n";; let afficheko attendu = incr failed; if attendu then print_string "ko (failed vs passed expected)\n" else print_string "ko (passed vs failed expected)\n";; let firstfail_launch nom test attendu = Printf.printf "*** %s: " nom; if (verifier test)=attendu then ( afficheok attendu ) else ( afficheko attendu ) let launch nom test attendu = try firstfail_launch nom test attendu with CertCheckerFailure(st, mesg) -> if st = DEMO then ( Printf.printf " failure %s !\n" mesg ; if attendu then afficheko true else afficheok false ) else ( Printf.printf " %s: %s !\n" (if st=CERT then "certificate error" else "internal error from cert checker") mesg; incr failed; ) let rec launch_list l attendu = match l with | [] -> print_newline(); | (nom,test)::ll -> incr tests; if firstfail_mode then firstfail_launch (CoqPr.charListTr nom) test attendu else launch (CoqPr.charListTr nom) test attendu; launch_list ll attendu;; module Ex = DemoPLTests.Examples(VB);; launch_list Ex.tests_ok true;; launch_list Ex.tests_ko false;; let nbfails = !failed in if nbfails=0 then Printf.printf "*** Passed %d tests\n" !tests else ( Printf.printf "*** %d failure(s) in %d tests:\n" nbfails !tests; exit 1);;
0bf23d2ebea9cb8bad91672bc3a2c880e48caf779b3e303a12aec47cef7adcdf
hdima/erlport
ruby19_tests.erl
Copyright ( c ) 2009 - 2015 , < > %%% 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. %%% * Neither the name of the copyright holders nor the names of its %%% contributors may be used to endorse or promote products derived from %%% this software without specific prior written permission. %%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " %%% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR %%% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF %%% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN %%% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) %%% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE %%% POSSIBILITY OF SUCH DAMAGE. -module(ruby19_tests). -export([test_callback/1, recurse/2]). -include_lib("eunit/include/eunit.hrl"). -define(SETUP(Setup, Tests), {setup, Setup, fun cleanup/1, fun (P) -> Tests end}). -define(SETUP(Tests), ?SETUP(fun setup/0, Tests)). -define(TIMEOUT, 5000). test_callback(Result) -> log_event({test_callback, Result}), Result. recurse(P, N) -> python:call(P, test_utils, recurse, [P, N]). start_stop_test_() -> [ fun () -> {ok, P} = ruby:start(), ?assertEqual(ok, ruby:stop(P)) end, fun () -> {ok, P} = ruby:start_link(), ?assertEqual(ok, ruby:stop(P)) end, fun () -> ?assertMatch({ok, _}, ruby:start({local, ruby_test})), ?assertEqual(ok, ruby:stop(ruby_test)) end, fun () -> ?assertMatch({ok, _}, ruby:start_link({local, ruby_test})), ?assertEqual(ok, ruby:stop(ruby_test)) end, fun () -> ?assertMatch({ok, _}, ruby:start({local, ruby_test}, [])), ?assertEqual(ok, ruby:stop(ruby_test)) end, fun () -> ?assertMatch({ok, _}, ruby:start_link({local, ruby_test}, [])), ?assertEqual(ok, ruby:stop(ruby_test)) end ]. call_test_() -> ?SETUP( ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). ruby_cast_test_() -> ?SETUP( fun () -> Pid = self(), Message = test_message, ?assertEqual(undefined, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::cast', [Pid, Message])), ?assertEqual(ok, receive Message -> ok after ?TIMEOUT -> timeout end) end ). erlang_cast_test_() -> {setup, fun () -> setup_event_logger(), setup() end, fun (P) -> cleanup(P), cleanup_event_logger() end, fun (P) -> fun () -> ?assertEqual(ok, ruby:call(P, test_utils, setup_message_handler, [])), ?assertEqual(ok, ruby:cast(P, test_message)), P ! test_message2, timer:sleep(500), ?assertEqual([{test_callback, {message, test_message}}, {test_callback, {message, test_message2}}], get_events()) end end}. message_handler_error_test_() -> {setup, fun () -> ok = error_logger:tty(false) end, fun (_) -> ok = error_logger:tty(true) end, fun () -> P = setup(), process_flag(trap_exit, true), try link(P), ?assertEqual(ok, ruby:call(P, test_utils, setup_faulty_message_handler, [])), P ! test_message, ?assertEqual(ok, receive {'EXIT', P, {message_handler_error, {ruby, 'ValueError', <<"test_message">>, [_|_]}}} -> ok; % Ruby 1.9.[12] {'EXIT', P, {message_handler_error, {ruby, 'ValueError', test_message, [_|_]}}} -> ok after 3000 -> timeout end) after process_flag(trap_exit, false) end end}. async_call_error_test_() -> {setup, fun () -> ok = error_logger:tty(false) end, fun (_) -> ok = error_logger:tty(true) end, fun () -> P = setup(), process_flag(trap_exit, true), try link(P), ruby:call(P, unknown, unknown, [], [async]), ?assertEqual(ok, receive {'EXIT', P, {async_call_error, {ruby, 'LoadError', <<"cannot load such file -- unknown">>, [_|_]}}} -> ok; % Ruby 1.9.[12] {'EXIT', P, {async_call_error, {ruby, 'LoadError', <<"no such file to load -- unknown">>, [_|_]}}} -> ok after 3000 -> timeout end) after process_flag(trap_exit, false) end end}. recursion_test_() -> ?SETUP( ?_assertEqual(done, ruby:call(P, test_utils, recurse, [P, 50])) ). objects_hierarchy_test_() -> ?SETUP( ?_assertEqual(ok, ruby:call(P, test_utils, 'TestModule::TestClass::test_method', [])) ). erlang_util_functions_test_() -> ?SETUP([ fun () -> ?assertEqual(P, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::self', [])), % Check cached value ?assertEqual(P, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::self', [])) end, fun () -> Ref = ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::make_ref', []), ?assert(is_reference(Ref)), Ref2 = ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::make_ref', []), ?assert(is_reference(Ref2)), ?assertNot(Ref =:= Ref2) end ]). error_test_() -> ?SETUP([ ?_assertEqual({error, ruby}, try ruby:call(P, unknown, unknown, []) catch error:{ruby, 'LoadError', <<"cannot load such file -- unknown">>, [_|_]} -> {error, ruby}; % Ruby 1.9.[12] error:{ruby, 'LoadError', <<"no such file to load -- unknown">>, [_|_]} -> {error, ruby} end), ?_assertError({ruby, 'ErlPort::Erlang::CallError', <<"Tuple([:erlang, :error, :undef, " "[Tuple([:unknown, :unknown, []", _/binary>>, [_|_]}, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::call', [unknown, unknown, []])), fun () -> R2 = setup(), try ?assertEqual({error, ruby}, try ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::call', [ruby, call, [R2, unknown, unknown, []]]) catch error:{ruby, 'ErlPort::Erlang::CallError', <<"Tuple([:ruby, :LoadError, " "\"cannot load such file -- unknown\", ", _/binary>>, [_|_]} -> {error, ruby}; % Ruby 1.9.[12] error:{ruby, 'ErlPort::Erlang::CallError', <<"Tuple([:ruby, :LoadError, " "\"no such file to load -- unknown\", ", _/binary>>, [_|_]} -> {error, ruby} end) after cleanup(R2) end end ]). stdin_stdout_test_() -> ?SETUP([ ?_test(erlport_test_utils:assert_output(<<"HELLO!\n">>, fun () -> undefined = ruby:call(P, test_utils, 'print_string', ["HELLO!"]) end, P)), ?_test(erlport_test_utils:assert_output( <<16#d0, 16#9f, 16#d1, 16#80, 16#d0, 16#b8, 16#d0, 16#b2, 16#d0, 16#b5, 16#d1, 16#82, "!\n">>, fun () -> undefined = ruby:call(P, test_utils, 'print_string', [[16#41f, 16#440, 16#438, 16#432, 16#435, 16#442, $!]]) end, P)), ?_assertError({ruby, 'IOError', <<"STDIN is closed for ErlPort connected process">>, [_|_]}, ruby:call(P, '', 'ARGF::read', [])) ]). nouse_stdio_test_() -> case os:type() of {win32, _} -> []; _ -> ?SETUP( setup_factory([nouse_stdio]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ) end. packet4_test_() -> ?SETUP( setup_factory([{packet, 4}]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). packet2_test_() -> ?SETUP( setup_factory([{packet, 2}]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). packet1_test_() -> ?SETUP( setup_factory([{packet, 1}]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). compressed_test_() -> ?SETUP( setup_factory([{compressed, 9}]), fun () -> S1 = list_to_binary(lists:duplicate(200, $0)), S2 = list_to_binary(lists:duplicate(200, $1)), ?assertEqual(<<S1/binary, S2/binary>>, ruby:call(P, test_utils, 'add', [S1, S2])) end ). call_pipeline_test_() -> ?SETUP( {inparallel, [ ?_assertEqual(N + 1, ruby:call(P, test_utils, 'add', [N , 1])) || N <- lists:seq(1, 50)]} ). queue_test_() -> ?SETUP( {inparallel, [ ?_assertEqual(262144, ruby:call(P, test_utils, 'len', [<<0:262144/unit:8>>])) || _ <- lists:seq(1, 50)]} ). call_back_test_() -> {setup, fun () -> setup_event_logger(), setup() end, fun (P) -> cleanup(P), cleanup_event_logger() end, fun (P) -> [ ?_assertEqual(3, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::call', [erlang, length, [[1, 2, 3]]])), fun () -> ?assertEqual(ok, ruby:call(P, test_utils, switch, [5], [async])), timer:sleep(500), ?assertEqual([ {test_callback, {0, 0}}, {test_callback, {0, 1}}, {test_callback, {1, 2}}, {test_callback, {2, 3}}, {test_callback, {3, 4}} ], get_events()) end, fun () -> ?assertEqual(5, ruby:call(P, test_utils, switch, [5])), ?assertEqual([ {test_callback, {0, 0}}, {test_callback, {0, 1}}, {test_callback, {1, 2}}, {test_callback, {2, 3}}, {test_callback, {3, 4}} ], get_events()) end ] end}. datatype_test_() -> ?SETUP( [?_assertEqual(V, ruby:call(P, test_utils, identity, [V])) || V <- datatype_test_data:get_test_data()] ). unicode_symbols_test_() -> ?SETUP( ?_assertEqual(list_to_atom([16#d0, 16#90, 16#d0, 16#91]), ruby:call(P, test_utils, string_to_sym, [[16#410, 16#411]])) ). custom_datatype_test_() -> ?SETUP( fun () -> ?assertEqual(ok, ruby:call(P, test_utils, setup_date_types, [])), ?assertEqual({date, {2013, 2, 1}}, ruby:call(P, test_utils, add, [{date, {2013, 1, 31}}, 60 * 60 * 24])) end ). %%% %%% Utility functions %%% setup() -> (setup_factory([]))(). setup_factory(Options) -> fun () -> {ok, P} = ruby:start_link([{ruby_lib, "test/ruby1.9"} | Options]), P end. cleanup(P) -> ok = ruby:stop(P). log_event(Event) -> true = ets:insert(events, {events, Event}). get_events() -> Events = [E || {_, E} <- ets:lookup(events, events)], true = ets:delete(events, events), Events. setup_event_logger() -> ets:new(events, [public, named_table, duplicate_bag]). cleanup_event_logger() -> true = ets:delete(events).
null
https://raw.githubusercontent.com/hdima/erlport/246b7722d62b87b48be66d9a871509a537728962/test/ruby1.9/ruby19_tests.erl
erlang
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. * Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 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. Ruby 1.9.[12] Ruby 1.9.[12] Check cached value Ruby 1.9.[12] Ruby 1.9.[12] Utility functions
Copyright ( c ) 2009 - 2015 , < > THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN -module(ruby19_tests). -export([test_callback/1, recurse/2]). -include_lib("eunit/include/eunit.hrl"). -define(SETUP(Setup, Tests), {setup, Setup, fun cleanup/1, fun (P) -> Tests end}). -define(SETUP(Tests), ?SETUP(fun setup/0, Tests)). -define(TIMEOUT, 5000). test_callback(Result) -> log_event({test_callback, Result}), Result. recurse(P, N) -> python:call(P, test_utils, recurse, [P, N]). start_stop_test_() -> [ fun () -> {ok, P} = ruby:start(), ?assertEqual(ok, ruby:stop(P)) end, fun () -> {ok, P} = ruby:start_link(), ?assertEqual(ok, ruby:stop(P)) end, fun () -> ?assertMatch({ok, _}, ruby:start({local, ruby_test})), ?assertEqual(ok, ruby:stop(ruby_test)) end, fun () -> ?assertMatch({ok, _}, ruby:start_link({local, ruby_test})), ?assertEqual(ok, ruby:stop(ruby_test)) end, fun () -> ?assertMatch({ok, _}, ruby:start({local, ruby_test}, [])), ?assertEqual(ok, ruby:stop(ruby_test)) end, fun () -> ?assertMatch({ok, _}, ruby:start_link({local, ruby_test}, [])), ?assertEqual(ok, ruby:stop(ruby_test)) end ]. call_test_() -> ?SETUP( ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). ruby_cast_test_() -> ?SETUP( fun () -> Pid = self(), Message = test_message, ?assertEqual(undefined, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::cast', [Pid, Message])), ?assertEqual(ok, receive Message -> ok after ?TIMEOUT -> timeout end) end ). erlang_cast_test_() -> {setup, fun () -> setup_event_logger(), setup() end, fun (P) -> cleanup(P), cleanup_event_logger() end, fun (P) -> fun () -> ?assertEqual(ok, ruby:call(P, test_utils, setup_message_handler, [])), ?assertEqual(ok, ruby:cast(P, test_message)), P ! test_message2, timer:sleep(500), ?assertEqual([{test_callback, {message, test_message}}, {test_callback, {message, test_message2}}], get_events()) end end}. message_handler_error_test_() -> {setup, fun () -> ok = error_logger:tty(false) end, fun (_) -> ok = error_logger:tty(true) end, fun () -> P = setup(), process_flag(trap_exit, true), try link(P), ?assertEqual(ok, ruby:call(P, test_utils, setup_faulty_message_handler, [])), P ! test_message, ?assertEqual(ok, receive {'EXIT', P, {message_handler_error, {ruby, 'ValueError', <<"test_message">>, [_|_]}}} -> ok; {'EXIT', P, {message_handler_error, {ruby, 'ValueError', test_message, [_|_]}}} -> ok after 3000 -> timeout end) after process_flag(trap_exit, false) end end}. async_call_error_test_() -> {setup, fun () -> ok = error_logger:tty(false) end, fun (_) -> ok = error_logger:tty(true) end, fun () -> P = setup(), process_flag(trap_exit, true), try link(P), ruby:call(P, unknown, unknown, [], [async]), ?assertEqual(ok, receive {'EXIT', P, {async_call_error, {ruby, 'LoadError', <<"cannot load such file -- unknown">>, [_|_]}}} -> ok; {'EXIT', P, {async_call_error, {ruby, 'LoadError', <<"no such file to load -- unknown">>, [_|_]}}} -> ok after 3000 -> timeout end) after process_flag(trap_exit, false) end end}. recursion_test_() -> ?SETUP( ?_assertEqual(done, ruby:call(P, test_utils, recurse, [P, 50])) ). objects_hierarchy_test_() -> ?SETUP( ?_assertEqual(ok, ruby:call(P, test_utils, 'TestModule::TestClass::test_method', [])) ). erlang_util_functions_test_() -> ?SETUP([ fun () -> ?assertEqual(P, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::self', [])), ?assertEqual(P, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::self', [])) end, fun () -> Ref = ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::make_ref', []), ?assert(is_reference(Ref)), Ref2 = ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::make_ref', []), ?assert(is_reference(Ref2)), ?assertNot(Ref =:= Ref2) end ]). error_test_() -> ?SETUP([ ?_assertEqual({error, ruby}, try ruby:call(P, unknown, unknown, []) catch error:{ruby, 'LoadError', <<"cannot load such file -- unknown">>, [_|_]} -> {error, ruby}; error:{ruby, 'LoadError', <<"no such file to load -- unknown">>, [_|_]} -> {error, ruby} end), ?_assertError({ruby, 'ErlPort::Erlang::CallError', <<"Tuple([:erlang, :error, :undef, " "[Tuple([:unknown, :unknown, []", _/binary>>, [_|_]}, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::call', [unknown, unknown, []])), fun () -> R2 = setup(), try ?assertEqual({error, ruby}, try ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::call', [ruby, call, [R2, unknown, unknown, []]]) catch error:{ruby, 'ErlPort::Erlang::CallError', <<"Tuple([:ruby, :LoadError, " "\"cannot load such file -- unknown\", ", _/binary>>, [_|_]} -> {error, ruby}; error:{ruby, 'ErlPort::Erlang::CallError', <<"Tuple([:ruby, :LoadError, " "\"no such file to load -- unknown\", ", _/binary>>, [_|_]} -> {error, ruby} end) after cleanup(R2) end end ]). stdin_stdout_test_() -> ?SETUP([ ?_test(erlport_test_utils:assert_output(<<"HELLO!\n">>, fun () -> undefined = ruby:call(P, test_utils, 'print_string', ["HELLO!"]) end, P)), ?_test(erlport_test_utils:assert_output( <<16#d0, 16#9f, 16#d1, 16#80, 16#d0, 16#b8, 16#d0, 16#b2, 16#d0, 16#b5, 16#d1, 16#82, "!\n">>, fun () -> undefined = ruby:call(P, test_utils, 'print_string', [[16#41f, 16#440, 16#438, 16#432, 16#435, 16#442, $!]]) end, P)), ?_assertError({ruby, 'IOError', <<"STDIN is closed for ErlPort connected process">>, [_|_]}, ruby:call(P, '', 'ARGF::read', [])) ]). nouse_stdio_test_() -> case os:type() of {win32, _} -> []; _ -> ?SETUP( setup_factory([nouse_stdio]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ) end. packet4_test_() -> ?SETUP( setup_factory([{packet, 4}]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). packet2_test_() -> ?SETUP( setup_factory([{packet, 2}]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). packet1_test_() -> ?SETUP( setup_factory([{packet, 1}]), ?_assertEqual(4, ruby:call(P, test_utils, add, [2, 2])) ). compressed_test_() -> ?SETUP( setup_factory([{compressed, 9}]), fun () -> S1 = list_to_binary(lists:duplicate(200, $0)), S2 = list_to_binary(lists:duplicate(200, $1)), ?assertEqual(<<S1/binary, S2/binary>>, ruby:call(P, test_utils, 'add', [S1, S2])) end ). call_pipeline_test_() -> ?SETUP( {inparallel, [ ?_assertEqual(N + 1, ruby:call(P, test_utils, 'add', [N , 1])) || N <- lists:seq(1, 50)]} ). queue_test_() -> ?SETUP( {inparallel, [ ?_assertEqual(262144, ruby:call(P, test_utils, 'len', [<<0:262144/unit:8>>])) || _ <- lists:seq(1, 50)]} ). call_back_test_() -> {setup, fun () -> setup_event_logger(), setup() end, fun (P) -> cleanup(P), cleanup_event_logger() end, fun (P) -> [ ?_assertEqual(3, ruby:call(P, 'erlport/erlang', 'ErlPort::Erlang::call', [erlang, length, [[1, 2, 3]]])), fun () -> ?assertEqual(ok, ruby:call(P, test_utils, switch, [5], [async])), timer:sleep(500), ?assertEqual([ {test_callback, {0, 0}}, {test_callback, {0, 1}}, {test_callback, {1, 2}}, {test_callback, {2, 3}}, {test_callback, {3, 4}} ], get_events()) end, fun () -> ?assertEqual(5, ruby:call(P, test_utils, switch, [5])), ?assertEqual([ {test_callback, {0, 0}}, {test_callback, {0, 1}}, {test_callback, {1, 2}}, {test_callback, {2, 3}}, {test_callback, {3, 4}} ], get_events()) end ] end}. datatype_test_() -> ?SETUP( [?_assertEqual(V, ruby:call(P, test_utils, identity, [V])) || V <- datatype_test_data:get_test_data()] ). unicode_symbols_test_() -> ?SETUP( ?_assertEqual(list_to_atom([16#d0, 16#90, 16#d0, 16#91]), ruby:call(P, test_utils, string_to_sym, [[16#410, 16#411]])) ). custom_datatype_test_() -> ?SETUP( fun () -> ?assertEqual(ok, ruby:call(P, test_utils, setup_date_types, [])), ?assertEqual({date, {2013, 2, 1}}, ruby:call(P, test_utils, add, [{date, {2013, 1, 31}}, 60 * 60 * 24])) end ). setup() -> (setup_factory([]))(). setup_factory(Options) -> fun () -> {ok, P} = ruby:start_link([{ruby_lib, "test/ruby1.9"} | Options]), P end. cleanup(P) -> ok = ruby:stop(P). log_event(Event) -> true = ets:insert(events, {events, Event}). get_events() -> Events = [E || {_, E} <- ets:lookup(events, events)], true = ets:delete(events, events), Events. setup_event_logger() -> ets:new(events, [public, named_table, duplicate_bag]). cleanup_event_logger() -> true = ets:delete(events).
b38a44656402b47c873b1a55062b71fbaea7531bd83788a8e14de51b30c1f0f3
hyperfiddle/electric
match.clj
(ns dustin.y2020.match (:require [hyperfiddle.rcf :refer [tests]])) (defn form? [x] (and (seq? x) ; yep, i bet you're surprised (not (empty? x)))) (tests (form? '(list)) := true (form? '#()) := true (form? '()) := false (form? 1) := false (form? {}) := false (form? []) := false) (defmacro match [& xs] (letfn [(matcher? [x] (and (form? x) (= 'let (first x)))) (denote [xs] (cond (empty? xs) `(throw (ex-info "no match" {})) (matcher? (first xs)) (let [[_ bs & r] (first xs) bs (destructure bs) ; todo vars (take-nth 2 bs)] `(let [~@bs] (if (every? (comp not nil?) [~@vars]) (do ~@r) ~(denote (rest xs))))) () (throw (ex-info "unexpected" {:x (first xs)}))))] (if (not (matcher? (first xs))) (let [[v & xs] xs] `(let [~'&_ ~v] ~(denote xs))) (denote xs)))) (tests "the first value passed is also bound as &_ so you can branch on that directly" (match {:x 123} (let [{y :y} &_] y) (let [{x :x} &_] [:x 123])) := [:x 123] (match nil (let [{y :y} &_] y)) :throws Exception "works with deep destructures" (match [{:a {:b {:c 3}} :d [4 44] :e 5 :f 6}] (let [[{:keys [:e :f] [d1 d2] :d {{c :c} :b} :a}] &_] [c [d1 d2] e f])) := [3 [4 44] 5 6]) (tests "first parameter is optional" (match (let [x nil] 1) (let [x 1 y nil] 2) (let [x 1 y 2] 3)) := 3) ; if you add a helper for inspecting the type/tag for a value you get something like pattern matching ; (this matches the lambda calculus structure we went into before) ; (the let part is like a continuation that reads things out of the topic value)
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2020/match.clj
clojure
yep, i bet you're surprised todo if you add a helper for inspecting the type/tag for a value you get something like pattern matching (this matches the lambda calculus structure we went into before) (the let part is like a continuation that reads things out of the topic value)
(ns dustin.y2020.match (:require [hyperfiddle.rcf :refer [tests]])) (defn form? [x] (not (empty? x)))) (tests (form? '(list)) := true (form? '#()) := true (form? '()) := false (form? 1) := false (form? {}) := false (form? []) := false) (defmacro match [& xs] (letfn [(matcher? [x] (and (form? x) (= 'let (first x)))) (denote [xs] (cond (empty? xs) `(throw (ex-info "no match" {})) (matcher? (first xs)) (let [[_ bs & r] (first xs) vars (take-nth 2 bs)] `(let [~@bs] (if (every? (comp not nil?) [~@vars]) (do ~@r) ~(denote (rest xs))))) () (throw (ex-info "unexpected" {:x (first xs)}))))] (if (not (matcher? (first xs))) (let [[v & xs] xs] `(let [~'&_ ~v] ~(denote xs))) (denote xs)))) (tests "the first value passed is also bound as &_ so you can branch on that directly" (match {:x 123} (let [{y :y} &_] y) (let [{x :x} &_] [:x 123])) := [:x 123] (match nil (let [{y :y} &_] y)) :throws Exception "works with deep destructures" (match [{:a {:b {:c 3}} :d [4 44] :e 5 :f 6}] (let [[{:keys [:e :f] [d1 d2] :d {{c :c} :b} :a}] &_] [c [d1 d2] e f])) := [3 [4 44] 5 6]) (tests "first parameter is optional" (match (let [x nil] 1) (let [x 1 y nil] 2) (let [x 1 y 2] 3)) := 3)
1905457dedc3fe70d43eaea78db90ddfbf590874eaac06ec2675bcf2210315f8
pixlsus/registry.gimp.org_static
JMS-Grid_TwoTonedShapes.scm
;; *************************************************************************** * Copyright ( C ) 2011 by * ;; * * ;; * * ;; * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation ; either version 2 of the License , or * ;; * (at your option) any later version. * ;; * * ;; * This program is distributed in the hope that it will be useful, * ;; * but WITHOUT ANY WARRANTY; without even the implied warranty of * ;; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * ;; * GNU General Public License for more details. * ;; * * * You should have received a copy of the GNU General Public License * ;; * along with this program; if not, write to the * * Free Software Foundation , Inc. , * * 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * ;; *************************************************************************** (define (drawing-hex-shapes image x1 y1 x2 y2 x3 y3 x4 aliasYN) (let* ( (hexArray (make-vector 14 0.0)) ) (gimp-selection-none image) (vector-set! hexArray 0 x1) (vector-set! hexArray 1 y1) (vector-set! hexArray 2 x2) (vector-set! hexArray 3 y2) (vector-set! hexArray 4 x3) (vector-set! hexArray 5 y2) (vector-set! hexArray 6 x4) (vector-set! hexArray 7 y1) (vector-set! hexArray 8 x3) (vector-set! hexArray 9 y3) (vector-set! hexArray 10 x2) (vector-set! hexArray 11 y3) (vector-set! hexArray 12 x1) (vector-set! hexArray 13 y1) (gimp-free-select image 14 hexArray 0 aliasYN FALSE 0) ) ) ; ------------------------------------------------------------------------------ (define (drawing-oct-shapes image x1 y1 x2 y2 x3 y3 x4 y4 aliasYN) (let* ( (octArray (make-vector 18 0.0)) ) (gimp-selection-none image) (vector-set! octArray 0 x1) (vector-set! octArray 1 y2) (vector-set! octArray 2 x2) (vector-set! octArray 3 y1) (vector-set! octArray 4 x3) (vector-set! octArray 5 y1) (vector-set! octArray 6 x4) (vector-set! octArray 7 y2) (vector-set! octArray 8 x4) (vector-set! octArray 9 y3) (vector-set! octArray 10 x3) (vector-set! octArray 11 y4) (vector-set! octArray 12 x2) (vector-set! octArray 13 y4) (vector-set! octArray 14 x1) (vector-set! octArray 15 y3) (vector-set! octArray 16 x1) (vector-set! octArray 17 y2) (gimp-free-select image 18 octArray 0 aliasYN FALSE 0) ) ) ; ------------------------------------------------------------------------------ (define (script-fu-CircleGrid2 Circle ( shape=0 ) ; Square (shape=1) Hexagon ( shape=2 ) Octagon ( shape=3 ) Grid type ( 0 = Rectangular , 1 = Hexagonal ) bigDiam ; Outer diameter for circles smallDiam ; Inner diameter for circles xCirc ; Number of circles in the X direction yCirc ; Number of circles in the Y direction oBorder ; Outer border around image Space between the circles Outer color for the circles in the first row / column Inner color for the circles in the first row / column Outer color for the circles in the second row / column Inner color for the circles in the second row / column constColor ; Constant colors along the rows or columns (0=Rows, 1=Columns) randColor ; Completely random colors for the circles? bgColor ; Background color for entire image aliasing ; Anti-aliasing for the circles? layered ; Separate layers for the inner and outer circles ) (let* ( ; Square roots (s3 (sqrt 3)) (s2 (sqrt 2)) Circle Diameters (bigcircDiam (max bigDiam smallDiam)) (smallcircDiam (min bigDiam smallDiam)) (shrinkDiff (/ (- bigcircDiam smallcircDiam) 2)) ; make calculations a bit easier by defining the radius and total border space (circRad (/ bigcircDiam 2.0)) (smallcircRad (/ smallcircDiam 2.0)) (tBorder (* 2 oBorder)) (inWidth 0) (inHeight 0) (temp 0) (xGap 0) (yGap 0) ; Add in the image, and the layer (or layers, if the shapes are on different layers) (theImage 0) (baseLayer 0) (innerLayer 0) (outerLayer 0) ; Variables for calculating the position of each shape (xFlag 0) (yFlag 0) (xStart 0.0) (yStart 0.0) (rowCheck 0.0) (xCenter 0.0) (yCenter 0.0) (x1 0.0) (x2 0.0) (x3 0.0) (x4 0.0) (y1 0.0) (y2 0.0) (y3 0.0) (y4 0.0) ; Hexagonal coordinates (bigHexX (* s3 0.25 circRad)) (bigHexY (* s3 0.5 circRad)) (smallHexX (* s3 0.25 smallcircRad)) (smallHexY (* s3 0.5 smallcircRad)) Octagonal coordinates (bigoctSide (/ bigcircDiam (+ 1.0 s2))) (smalloctSide (/ smallcircDiam (+ 1.0 s2))) ) ; If the colors are constant along rows, then switch the X and Y flags (if (= constColor 0) (begin (set! temp xCirc) (set! xCirc yCirc) (set! yCirc temp) ) ) ; Determine the dimensions of the image based on the grid type and number of circles (cond ((= gType 0) ; Rectangular Grid (set! inWidth (+ tBorder (* bigcircDiam xCirc) (* gapSpace (- xCirc 1)))) (set! inHeight (+ tBorder (* bigcircDiam yCirc) (* gapSpace (- yCirc 1)))) ) Hexagonal Grid (cond ((= shape 0) ; Circles (set! xGap (* s3 (+ circRad (* 0.5 gapSpace)))) (set! inWidth (+ tBorder bigcircDiam (* (- xCirc 1) xGap))) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) ((= shape 1) ; Rectangles (set! xGap (* gapSpace (- xCirc 1))) (set! inWidth (+ tBorder (* bigcircDiam xCirc) xGap)) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) Hexagons (set! xGap (* s3 (+ circRad (* 0.5 gapSpace)))) (set! inWidth (+ tBorder bigcircDiam (* (- xCirc 1) xGap))) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) Octagons (set! xGap (* s3 (+ circRad (* 0.5 gapSpace)))) (set! inWidth (+ tBorder bigcircDiam (* (- xCirc 1) xGap))) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) ) ) ) ; Define the image and layer properties based on what was calculated above (cond ((= constColor 0) ; Constant Color in Rows (set! theImage (car (gimp-image-new inHeight inWidth RGB))) (set! baseLayer (car (gimp-layer-new theImage inHeight inWidth RGBA-IMAGE "Constant Rows" 100 NORMAL-MODE))) (set! innerLayer (car (gimp-layer-new theImage inHeight inWidth RGBA-IMAGE "Inner Shapes" 100 NORMAL-MODE))) (set! outerLayer (car (gimp-layer-new theImage inHeight inWidth RGBA-IMAGE "Outer Shapes" 100 NORMAL-MODE))) ) ((= constColor 1) ; Constant Color in Rows (set! theImage (car (gimp-image-new inWidth inHeight RGB))) (set! baseLayer (car (gimp-layer-new theImage inWidth inHeight RGBA-IMAGE "Constant Columns" 100 NORMAL-MODE))) (set! innerLayer (car (gimp-layer-new theImage inWidth inHeight RGBA-IMAGE "Inner Shapes" 100 NORMAL-MODE))) (set! outerLayer (car (gimp-layer-new theImage inWidth inHeight RGBA-IMAGE "Outer Shapes" 100 NORMAL-MODE))) ) ) ; Add the base layer, and fill it up with the background color (gimp-image-add-layer theImage baseLayer 0) (gimp-context-set-background bgColor) (gimp-drawable-fill baseLayer BACKGROUND-FILL) ; Add any extra layers, if needed (if (= layered TRUE) (begin (gimp-image-add-layer theImage outerLayer 0) (if (> shrinkDiff 0) (gimp-image-add-layer theImage innerLayer 0) ) ) ) ; Start drawing circles, and figure out what the X-coordinate is for this row (while (< xFlag xCirc) (cond ((= gType 0) (set! xStart (+ oBorder (* xFlag (+ bigcircDiam gapSpace)))) ) ((= gType 1) (if (= (fmod xFlag 2) 1) (set! rowCheck (+ (* gapSpace 0.5) circRad)) ) (cond ((= shape 0) (set! xStart (+ oBorder (* s3 (+ circRad (* 0.5 gapSpace)) xFlag))) ) ((= shape 1) (set! xStart (+ oBorder (* bigcircDiam xFlag) (* xFlag gapSpace))) ) ((= shape 2) (set! xStart (+ oBorder (* s3 (+ circRad (* 0.5 gapSpace)) xFlag))) ) ((= shape 3) (set! xStart (+ oBorder (* s3 (+ circRad (* 0.5 gapSpace)) xFlag))) ) ) ) ) ; Determine which set of colors is asked for in this row/column of circles. (if (= (fmod xFlag 2) 1) (begin (gimp-context-set-foreground outerColor1) (gimp-context-set-background innerColor1) ) (begin (gimp-context-set-foreground outerColor2) (gimp-context-set-background innerColor2) ) ) ; Now start doing the columns (while (< yFlag yCirc) (set! yStart (+ rowCheck oBorder (* gapSpace yFlag) (* bigcircDiam yFlag))) ; For completely random colors, set the foreground and background colors to random values (if (= randColor TRUE) (begin (gimp-context-set-foreground (list (rand 256) (rand 256) (rand 256))) (gimp-context-set-background (list (rand 256) (rand 256) (rand 256))) ) ) ; If constant color is in rows, then flip the X and Y coordinates to draw the circle (cond ((= shape 0) (if (= constColor 0) (gimp-ellipse-select theImage yStart xStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE aliasing FALSE 0) (gimp-ellipse-select theImage xStart yStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE aliasing FALSE 0) ) ) ((= shape 1) (if (= constColor 0) (gimp-rect-select theImage yStart xStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE FALSE 0) (gimp-rect-select theImage xStart yStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE FALSE 0) ) ) ((= shape 2) (if (= constColor 0) (begin (set! xCenter (+ yStart circRad)) (set! yCenter (+ xStart circRad)) ) (begin (set! xCenter (+ xStart circRad)) (set! yCenter (+ yStart circRad)) ) ) (set! x1 (- xCenter circRad)) (set! x2 (- xCenter bigHexX)) (set! x3 (+ xCenter bigHexX)) (set! x4 (+ xCenter circRad)) (set! y1 yCenter) (set! y2 (- yCenter bigHexY)) (set! y3 (+ yCenter bigHexY)) (drawing-hex-shapes theImage x1 y1 x2 y2 x3 y3 x4 aliasing) ) ((= shape 3) (if (= constColor 0) (begin (set! xCenter (+ yStart circRad)) (set! yCenter (+ xStart circRad)) ) (begin (set! xCenter (+ xStart circRad)) (set! yCenter (+ yStart circRad)) ) ) (set! x1 (- xCenter circRad)) (set! x2 (- xCenter (/ bigoctSide 2.0))) (set! x3 (+ xCenter (/ bigoctSide 2.0))) (set! x4 (+ xCenter circRad)) (set! y1 (- yCenter circRad)) (set! y2 (- yCenter (/ bigoctSide 2.0))) (set! y3 (+ yCenter (/ bigoctSide 2.0))) (set! y4 (+ yCenter circRad)) (drawing-oct-shapes theImage x1 y1 x2 y2 x3 y3 x4 y4 aliasing) ) ) ; Fill the selection, and then fill the inner circle with the proper color (if (= layered TRUE) (gimp-edit-bucket-fill outerLayer FG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) (gimp-edit-bucket-fill baseLayer FG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) ) (if (> shrinkDiff 0) (begin (cond ((= shape 0) (gimp-selection-shrink theImage shrinkDiff) ) ((= shape 1) (gimp-selection-shrink theImage shrinkDiff) ) ((= shape 2) (begin (set! x1 (- xCenter smallcircRad)) (set! x2 (- xCenter smallHexX)) (set! x3 (+ xCenter smallHexX)) (set! x4 (+ xCenter smallcircRad)) (set! y1 yCenter) (set! y2 (- yCenter smallHexY)) (set! y3 (+ yCenter smallHexY)) (drawing-hex-shapes theImage x1 y1 x2 y2 x3 y3 x4 aliasing) ) ) ((= shape 3) (if (= constColor 0) (begin (set! xCenter (+ yStart circRad)) (set! yCenter (+ xStart circRad)) ) (begin (set! xCenter (+ xStart circRad)) (set! yCenter (+ yStart circRad)) ) ) (set! x1 (- xCenter smallcircRad)) (set! x2 (- xCenter (/ smalloctSide 2.0))) (set! x3 (+ xCenter (/ smalloctSide 2.0))) (set! x4 (+ xCenter smallcircRad)) (set! y1 (- yCenter smallcircRad)) (set! y2 (- yCenter (/ smalloctSide 2.0))) (set! y3 (+ yCenter (/ smalloctSide 2.0))) (set! y4 (+ yCenter smallcircRad)) (drawing-oct-shapes theImage x1 y1 x2 y2 x3 y3 x4 y4 aliasing) ) ) (if (= layered TRUE) (gimp-edit-bucket-fill innerLayer BG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) (gimp-edit-bucket-fill baseLayer BG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) ) ) ) ; Move on to the next circle (set! yFlag (+ 1 yFlag)) ) Move on to the next row , and reset the other counting flags (set! xFlag (+ xFlag 1)) (set! yFlag 0) (set! rowCheck 0.0) ) ; Get rid of the selection, and then show the final image. (gimp-selection-none theImage) (gimp-display-new theImage) ) ) (script-fu-register "script-fu-CircleGrid2" _"_Grid - Two-toned shapes..." _"Creates a grid of X by Y two-toned shapes, either in rectangular or hexagonal packing." "James Sambrook" "22 April 2011" "James Sambrook. King George, VA, USA" "" SF-OPTION _"Shape" '(_"Circle" _"Square" _"Hexagon" _"Octagon") SF-OPTION _"Grid Type" '(_"Rectangular" _"Hexagonal") SF-ADJUSTMENT _"Outer Shape Diameter" '(40 10 200 1 5 0 0) SF-ADJUSTMENT _"Inner Shape Diameter" '(30 10 200 1 5 0 0) SF-ADJUSTMENT _"Shapes in X Direction" '(10 1 100 1 5 0 0) SF-ADJUSTMENT _"Shapes in Y Direction" '(11 1 100 1 5 0 0) SF-ADJUSTMENT _"Outer Border Around Shapes" '(12 1 100 1 5 0 0) SF-ADJUSTMENT _"Gap Between the Shapes" '(13 1 100 1 5 0 0) SF-COLOR _"Outer shape color #1" '(0 0 0) SF-COLOR _"Inner shape color #1" '(127 127 127) SF-COLOR _"Outer shape color #2" '(127 127 127) SF-COLOR _"Inner shape color #2" '(0 0 0) SF-OPTION _"Constant colors along rows or columns?" '(_"Rows" _"Columns") SF-TOGGLE _"Completely random colors?" FALSE SF-COLOR _"Background Color" '(255 255 255) SF-TOGGLE _"Anti-aliasing?" FALSE SF-TOGGLE _"Inner and outer shapes on different layers?" TRUE ) (script-fu-menu-register "script-fu-CircleGrid2" "<Image>/Filters/SambrookJM/Grid/")
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/JMS-Grid_TwoTonedShapes.scm
scheme
*************************************************************************** * * * * * This program is free software; you can redistribute it and/or modify * either version 2 of the License , or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * along with this program; if not, write to the * *************************************************************************** ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Square (shape=1) Outer diameter for circles Inner diameter for circles Number of circles in the X direction Number of circles in the Y direction Outer border around image Constant colors along the rows or columns (0=Rows, 1=Columns) Completely random colors for the circles? Background color for entire image Anti-aliasing for the circles? Separate layers for the inner and outer circles Square roots make calculations a bit easier by defining the radius and total border space Add in the image, and the layer (or layers, if the shapes are on different layers) Variables for calculating the position of each shape Hexagonal coordinates If the colors are constant along rows, then switch the X and Y flags Determine the dimensions of the image based on the grid type and number of circles Rectangular Grid Circles Rectangles Define the image and layer properties based on what was calculated above Constant Color in Rows Constant Color in Rows Add the base layer, and fill it up with the background color Add any extra layers, if needed Start drawing circles, and figure out what the X-coordinate is for this row Determine which set of colors is asked for in this row/column of circles. Now start doing the columns For completely random colors, set the foreground and background colors to random values If constant color is in rows, then flip the X and Y coordinates to draw the circle Fill the selection, and then fill the inner circle with the proper color Move on to the next circle Get rid of the selection, and then show the final image.
* Copyright ( C ) 2011 by * * it under the terms of the GNU General Public License as published by * * You should have received a copy of the GNU General Public License * * Free Software Foundation , Inc. , * * 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * (define (drawing-hex-shapes image x1 y1 x2 y2 x3 y3 x4 aliasYN) (let* ( (hexArray (make-vector 14 0.0)) ) (gimp-selection-none image) (vector-set! hexArray 0 x1) (vector-set! hexArray 1 y1) (vector-set! hexArray 2 x2) (vector-set! hexArray 3 y2) (vector-set! hexArray 4 x3) (vector-set! hexArray 5 y2) (vector-set! hexArray 6 x4) (vector-set! hexArray 7 y1) (vector-set! hexArray 8 x3) (vector-set! hexArray 9 y3) (vector-set! hexArray 10 x2) (vector-set! hexArray 11 y3) (vector-set! hexArray 12 x1) (vector-set! hexArray 13 y1) (gimp-free-select image 14 hexArray 0 aliasYN FALSE 0) ) ) (define (drawing-oct-shapes image x1 y1 x2 y2 x3 y3 x4 y4 aliasYN) (let* ( (octArray (make-vector 18 0.0)) ) (gimp-selection-none image) (vector-set! octArray 0 x1) (vector-set! octArray 1 y2) (vector-set! octArray 2 x2) (vector-set! octArray 3 y1) (vector-set! octArray 4 x3) (vector-set! octArray 5 y1) (vector-set! octArray 6 x4) (vector-set! octArray 7 y2) (vector-set! octArray 8 x4) (vector-set! octArray 9 y3) (vector-set! octArray 10 x3) (vector-set! octArray 11 y4) (vector-set! octArray 12 x2) (vector-set! octArray 13 y4) (vector-set! octArray 14 x1) (vector-set! octArray 15 y3) (vector-set! octArray 16 x1) (vector-set! octArray 17 y2) (gimp-free-select image 18 octArray 0 aliasYN FALSE 0) ) ) (define (script-fu-CircleGrid2 Circle ( shape=0 ) Hexagon ( shape=2 ) Octagon ( shape=3 ) Grid type ( 0 = Rectangular , 1 = Hexagonal ) Space between the circles Outer color for the circles in the first row / column Inner color for the circles in the first row / column Outer color for the circles in the second row / column Inner color for the circles in the second row / column ) (let* ( (s3 (sqrt 3)) (s2 (sqrt 2)) Circle Diameters (bigcircDiam (max bigDiam smallDiam)) (smallcircDiam (min bigDiam smallDiam)) (shrinkDiff (/ (- bigcircDiam smallcircDiam) 2)) (circRad (/ bigcircDiam 2.0)) (smallcircRad (/ smallcircDiam 2.0)) (tBorder (* 2 oBorder)) (inWidth 0) (inHeight 0) (temp 0) (xGap 0) (yGap 0) (theImage 0) (baseLayer 0) (innerLayer 0) (outerLayer 0) (xFlag 0) (yFlag 0) (xStart 0.0) (yStart 0.0) (rowCheck 0.0) (xCenter 0.0) (yCenter 0.0) (x1 0.0) (x2 0.0) (x3 0.0) (x4 0.0) (y1 0.0) (y2 0.0) (y3 0.0) (y4 0.0) (bigHexX (* s3 0.25 circRad)) (bigHexY (* s3 0.5 circRad)) (smallHexX (* s3 0.25 smallcircRad)) (smallHexY (* s3 0.5 smallcircRad)) Octagonal coordinates (bigoctSide (/ bigcircDiam (+ 1.0 s2))) (smalloctSide (/ smallcircDiam (+ 1.0 s2))) ) (if (= constColor 0) (begin (set! temp xCirc) (set! xCirc yCirc) (set! yCirc temp) ) ) (cond (set! inWidth (+ tBorder (* bigcircDiam xCirc) (* gapSpace (- xCirc 1)))) (set! inHeight (+ tBorder (* bigcircDiam yCirc) (* gapSpace (- yCirc 1)))) ) Hexagonal Grid (cond (set! xGap (* s3 (+ circRad (* 0.5 gapSpace)))) (set! inWidth (+ tBorder bigcircDiam (* (- xCirc 1) xGap))) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) (set! xGap (* gapSpace (- xCirc 1))) (set! inWidth (+ tBorder (* bigcircDiam xCirc) xGap)) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) Hexagons (set! xGap (* s3 (+ circRad (* 0.5 gapSpace)))) (set! inWidth (+ tBorder bigcircDiam (* (- xCirc 1) xGap))) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) Octagons (set! xGap (* s3 (+ circRad (* 0.5 gapSpace)))) (set! inWidth (+ tBorder bigcircDiam (* (- xCirc 1) xGap))) (set! yGap (* gapSpace (- yCirc 1))) (set! inHeight (+ tBorder circRad yGap (* gapSpace 0.5) (* bigcircDiam yCirc))) ) ) ) ) (cond (set! theImage (car (gimp-image-new inHeight inWidth RGB))) (set! baseLayer (car (gimp-layer-new theImage inHeight inWidth RGBA-IMAGE "Constant Rows" 100 NORMAL-MODE))) (set! innerLayer (car (gimp-layer-new theImage inHeight inWidth RGBA-IMAGE "Inner Shapes" 100 NORMAL-MODE))) (set! outerLayer (car (gimp-layer-new theImage inHeight inWidth RGBA-IMAGE "Outer Shapes" 100 NORMAL-MODE))) ) (set! theImage (car (gimp-image-new inWidth inHeight RGB))) (set! baseLayer (car (gimp-layer-new theImage inWidth inHeight RGBA-IMAGE "Constant Columns" 100 NORMAL-MODE))) (set! innerLayer (car (gimp-layer-new theImage inWidth inHeight RGBA-IMAGE "Inner Shapes" 100 NORMAL-MODE))) (set! outerLayer (car (gimp-layer-new theImage inWidth inHeight RGBA-IMAGE "Outer Shapes" 100 NORMAL-MODE))) ) ) (gimp-image-add-layer theImage baseLayer 0) (gimp-context-set-background bgColor) (gimp-drawable-fill baseLayer BACKGROUND-FILL) (if (= layered TRUE) (begin (gimp-image-add-layer theImage outerLayer 0) (if (> shrinkDiff 0) (gimp-image-add-layer theImage innerLayer 0) ) ) ) (while (< xFlag xCirc) (cond ((= gType 0) (set! xStart (+ oBorder (* xFlag (+ bigcircDiam gapSpace)))) ) ((= gType 1) (if (= (fmod xFlag 2) 1) (set! rowCheck (+ (* gapSpace 0.5) circRad)) ) (cond ((= shape 0) (set! xStart (+ oBorder (* s3 (+ circRad (* 0.5 gapSpace)) xFlag))) ) ((= shape 1) (set! xStart (+ oBorder (* bigcircDiam xFlag) (* xFlag gapSpace))) ) ((= shape 2) (set! xStart (+ oBorder (* s3 (+ circRad (* 0.5 gapSpace)) xFlag))) ) ((= shape 3) (set! xStart (+ oBorder (* s3 (+ circRad (* 0.5 gapSpace)) xFlag))) ) ) ) ) (if (= (fmod xFlag 2) 1) (begin (gimp-context-set-foreground outerColor1) (gimp-context-set-background innerColor1) ) (begin (gimp-context-set-foreground outerColor2) (gimp-context-set-background innerColor2) ) ) (while (< yFlag yCirc) (set! yStart (+ rowCheck oBorder (* gapSpace yFlag) (* bigcircDiam yFlag))) (if (= randColor TRUE) (begin (gimp-context-set-foreground (list (rand 256) (rand 256) (rand 256))) (gimp-context-set-background (list (rand 256) (rand 256) (rand 256))) ) ) (cond ((= shape 0) (if (= constColor 0) (gimp-ellipse-select theImage yStart xStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE aliasing FALSE 0) (gimp-ellipse-select theImage xStart yStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE aliasing FALSE 0) ) ) ((= shape 1) (if (= constColor 0) (gimp-rect-select theImage yStart xStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE FALSE 0) (gimp-rect-select theImage xStart yStart bigcircDiam bigcircDiam CHANNEL-OP-REPLACE FALSE 0) ) ) ((= shape 2) (if (= constColor 0) (begin (set! xCenter (+ yStart circRad)) (set! yCenter (+ xStart circRad)) ) (begin (set! xCenter (+ xStart circRad)) (set! yCenter (+ yStart circRad)) ) ) (set! x1 (- xCenter circRad)) (set! x2 (- xCenter bigHexX)) (set! x3 (+ xCenter bigHexX)) (set! x4 (+ xCenter circRad)) (set! y1 yCenter) (set! y2 (- yCenter bigHexY)) (set! y3 (+ yCenter bigHexY)) (drawing-hex-shapes theImage x1 y1 x2 y2 x3 y3 x4 aliasing) ) ((= shape 3) (if (= constColor 0) (begin (set! xCenter (+ yStart circRad)) (set! yCenter (+ xStart circRad)) ) (begin (set! xCenter (+ xStart circRad)) (set! yCenter (+ yStart circRad)) ) ) (set! x1 (- xCenter circRad)) (set! x2 (- xCenter (/ bigoctSide 2.0))) (set! x3 (+ xCenter (/ bigoctSide 2.0))) (set! x4 (+ xCenter circRad)) (set! y1 (- yCenter circRad)) (set! y2 (- yCenter (/ bigoctSide 2.0))) (set! y3 (+ yCenter (/ bigoctSide 2.0))) (set! y4 (+ yCenter circRad)) (drawing-oct-shapes theImage x1 y1 x2 y2 x3 y3 x4 y4 aliasing) ) ) (if (= layered TRUE) (gimp-edit-bucket-fill outerLayer FG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) (gimp-edit-bucket-fill baseLayer FG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) ) (if (> shrinkDiff 0) (begin (cond ((= shape 0) (gimp-selection-shrink theImage shrinkDiff) ) ((= shape 1) (gimp-selection-shrink theImage shrinkDiff) ) ((= shape 2) (begin (set! x1 (- xCenter smallcircRad)) (set! x2 (- xCenter smallHexX)) (set! x3 (+ xCenter smallHexX)) (set! x4 (+ xCenter smallcircRad)) (set! y1 yCenter) (set! y2 (- yCenter smallHexY)) (set! y3 (+ yCenter smallHexY)) (drawing-hex-shapes theImage x1 y1 x2 y2 x3 y3 x4 aliasing) ) ) ((= shape 3) (if (= constColor 0) (begin (set! xCenter (+ yStart circRad)) (set! yCenter (+ xStart circRad)) ) (begin (set! xCenter (+ xStart circRad)) (set! yCenter (+ yStart circRad)) ) ) (set! x1 (- xCenter smallcircRad)) (set! x2 (- xCenter (/ smalloctSide 2.0))) (set! x3 (+ xCenter (/ smalloctSide 2.0))) (set! x4 (+ xCenter smallcircRad)) (set! y1 (- yCenter smallcircRad)) (set! y2 (- yCenter (/ smalloctSide 2.0))) (set! y3 (+ yCenter (/ smalloctSide 2.0))) (set! y4 (+ yCenter smallcircRad)) (drawing-oct-shapes theImage x1 y1 x2 y2 x3 y3 x4 y4 aliasing) ) ) (if (= layered TRUE) (gimp-edit-bucket-fill innerLayer BG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) (gimp-edit-bucket-fill baseLayer BG-BUCKET-FILL NORMAL-MODE 100 255 0 0 0) ) ) ) (set! yFlag (+ 1 yFlag)) ) Move on to the next row , and reset the other counting flags (set! xFlag (+ xFlag 1)) (set! yFlag 0) (set! rowCheck 0.0) ) (gimp-selection-none theImage) (gimp-display-new theImage) ) ) (script-fu-register "script-fu-CircleGrid2" _"_Grid - Two-toned shapes..." _"Creates a grid of X by Y two-toned shapes, either in rectangular or hexagonal packing." "James Sambrook" "22 April 2011" "James Sambrook. King George, VA, USA" "" SF-OPTION _"Shape" '(_"Circle" _"Square" _"Hexagon" _"Octagon") SF-OPTION _"Grid Type" '(_"Rectangular" _"Hexagonal") SF-ADJUSTMENT _"Outer Shape Diameter" '(40 10 200 1 5 0 0) SF-ADJUSTMENT _"Inner Shape Diameter" '(30 10 200 1 5 0 0) SF-ADJUSTMENT _"Shapes in X Direction" '(10 1 100 1 5 0 0) SF-ADJUSTMENT _"Shapes in Y Direction" '(11 1 100 1 5 0 0) SF-ADJUSTMENT _"Outer Border Around Shapes" '(12 1 100 1 5 0 0) SF-ADJUSTMENT _"Gap Between the Shapes" '(13 1 100 1 5 0 0) SF-COLOR _"Outer shape color #1" '(0 0 0) SF-COLOR _"Inner shape color #1" '(127 127 127) SF-COLOR _"Outer shape color #2" '(127 127 127) SF-COLOR _"Inner shape color #2" '(0 0 0) SF-OPTION _"Constant colors along rows or columns?" '(_"Rows" _"Columns") SF-TOGGLE _"Completely random colors?" FALSE SF-COLOR _"Background Color" '(255 255 255) SF-TOGGLE _"Anti-aliasing?" FALSE SF-TOGGLE _"Inner and outer shapes on different layers?" TRUE ) (script-fu-menu-register "script-fu-CircleGrid2" "<Image>/Filters/SambrookJM/Grid/")
60c6255632ec63e597fe6d917787d70f5905fd563faccd2b9d3e8571d1678943
ocaml-flambda/flambda-backend
downwards_acc.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro and , (* *) (* Copyright 2013--2019 OCamlPro SAS *) Copyright 2014 - -2019 Jane Street Group LLC (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) module CUE = Continuation_uses_env module DE = Downwards_env module LCS = Lifted_constant_state module TE = Flambda2_types.Typing_env type t = { denv : DE.t; continuation_uses_env : CUE.t; shareable_constants : Symbol.t Static_const.Map.t; used_value_slots : Name_occurrences.t; lifted_constants : LCS.t; flow_acc : Flow.Acc.t; demoted_exn_handlers : Continuation.Set.t; code_ids_to_remember : Code_id.Set.t; slot_offsets : Slot_offsets.t Code_id.Map.t } let [@ocamlformat "disable"] print ppf { denv; continuation_uses_env; shareable_constants; used_value_slots; lifted_constants; flow_acc; demoted_exn_handlers; code_ids_to_remember; slot_offsets } = Format.fprintf ppf "@[<hov 1>(\ @[<hov 1>(denv@ %a)@]@ \ @[<hov 1>(continuation_uses_env@ %a)@]@ \ @[<hov 1>(shareable_constants@ %a)@]@ \ @[<hov 1>(used_value_slots@ %a)@]@ \ @[<hov 1>(lifted_constant_state@ %a)@]@ \ @[<hov 1>(flow_acc@ %a)@]@ \ @[<hov 1>(demoted_exn_handlers@ %a)@]@ \ @[<hov 1>(code_ids_to_remember@ %a)@]@ \ @[<hov 1>(slot_offsets@ %a)@]\ )@]" DE.print denv CUE.print continuation_uses_env (Static_const.Map.print Symbol.print) shareable_constants Name_occurrences.print used_value_slots LCS.print lifted_constants Flow.Acc.print flow_acc Continuation.Set.print demoted_exn_handlers Code_id.Set.print code_ids_to_remember (Code_id.Map.print Slot_offsets.print) slot_offsets let create denv continuation_uses_env = { denv; continuation_uses_env; slot_offsets = Code_id.Map.empty; shareable_constants = Static_const.Map.empty; used_value_slots = Name_occurrences.empty; lifted_constants = LCS.empty; flow_acc = Flow.Acc.empty (); demoted_exn_handlers = Continuation.Set.empty; code_ids_to_remember = Code_id.Set.empty } let denv t = t.denv let flow_acc t = t.flow_acc let[@inline always] map_flow_acc t ~f = { t with flow_acc = f t.flow_acc } let[@inline always] map_denv t ~f = { t with denv = f t.denv } let[@inline always] with_denv t denv = { t with denv } let with_continuation_uses_env t ~cont_uses_env = { t with continuation_uses_env = cont_uses_env } let record_continuation_use t cont use_kind ~env_at_use ~arg_types = let cont_uses_env, id = CUE.record_continuation_use t.continuation_uses_env cont use_kind ~env_at_use ~arg_types in with_continuation_uses_env t ~cont_uses_env, id let delete_continuation_uses t cont = let cont_uses_env = CUE.delete_continuation_uses t.continuation_uses_env cont in with_continuation_uses_env t ~cont_uses_env let num_continuation_uses t cont = CUE.num_continuation_uses t.continuation_uses_env cont let continuation_uses_env t = t.continuation_uses_env let code_age_relation t = TE.code_age_relation (DE.typing_env (denv t)) let with_code_age_relation t ~code_age_relation = let typing_env = TE.with_code_age_relation (DE.typing_env (denv t)) code_age_relation in with_denv t (DE.with_typing_env (denv t) typing_env) let typing_env t = DE.typing_env (denv t) let add_variable t var ty = with_denv t (DE.add_variable (denv t) var ty) let get_typing_env_no_more_than_one_use t k = CUE.get_typing_env_no_more_than_one_use t.continuation_uses_env k let add_to_lifted_constant_accumulator ?also_add_to_env t constants = let also_add_to_env = match also_add_to_env with None -> false | Some () -> true in let lifted_constants = LCS.union t.lifted_constants constants in let denv = if also_add_to_env then LCS.add_to_denv t.denv constants else t.denv in { t with lifted_constants; denv } let get_lifted_constants t = t.lifted_constants let clear_lifted_constants t = { t with lifted_constants = LCS.empty } let no_lifted_constants t = LCS.is_empty t.lifted_constants let get_and_clear_lifted_constants t = let constants = t.lifted_constants in let t = clear_lifted_constants t in t, constants let set_lifted_constants t consts = { t with lifted_constants = consts } let find_shareable_constant t static_const = Static_const.Map.find_opt static_const t.shareable_constants let consider_constant_for_sharing t symbol static_const = if not (Static_const.can_share static_const) then t else { t with shareable_constants = Static_const.Map.add static_const symbol t.shareable_constants } let with_shareable_constants t ~shareable_constants = { t with shareable_constants } let shareable_constants t = t.shareable_constants let add_use_of_value_slot t value_slot = { t with used_value_slots = Name_occurrences.add_value_slot_in_projection t.used_value_slots value_slot Name_mode.normal } let used_value_slots t = t.used_value_slots let all_continuations_used t = CUE.all_continuations_used t.continuation_uses_env let with_used_value_slots t ~used_value_slots = { t with used_value_slots } let add_code_ids_to_remember t code_ids = if DE.at_unit_toplevel t.denv then t else { t with code_ids_to_remember = Code_id.Set.union code_ids t.code_ids_to_remember } let code_ids_to_remember t = t.code_ids_to_remember let with_code_ids_to_remember t ~code_ids_to_remember = { t with code_ids_to_remember } let are_rebuilding_terms t = DE.are_rebuilding_terms t.denv let demote_exn_handler t cont = { t with demoted_exn_handlers = Continuation.Set.add cont t.demoted_exn_handlers } let demoted_exn_handlers t = t.demoted_exn_handlers let slot_offsets t = t.slot_offsets let with_slot_offsets t ~slot_offsets = { t with slot_offsets }
null
https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/92dbdba868235321a48916b8f1bb3f04ee884d3f/middle_end/flambda2/simplify/env/downwards_acc.ml
ocaml
************************************************************************ OCaml Copyright 2013--2019 OCamlPro SAS All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
, OCamlPro and , Copyright 2014 - -2019 Jane Street Group LLC the GNU Lesser General Public License version 2.1 , with the module CUE = Continuation_uses_env module DE = Downwards_env module LCS = Lifted_constant_state module TE = Flambda2_types.Typing_env type t = { denv : DE.t; continuation_uses_env : CUE.t; shareable_constants : Symbol.t Static_const.Map.t; used_value_slots : Name_occurrences.t; lifted_constants : LCS.t; flow_acc : Flow.Acc.t; demoted_exn_handlers : Continuation.Set.t; code_ids_to_remember : Code_id.Set.t; slot_offsets : Slot_offsets.t Code_id.Map.t } let [@ocamlformat "disable"] print ppf { denv; continuation_uses_env; shareable_constants; used_value_slots; lifted_constants; flow_acc; demoted_exn_handlers; code_ids_to_remember; slot_offsets } = Format.fprintf ppf "@[<hov 1>(\ @[<hov 1>(denv@ %a)@]@ \ @[<hov 1>(continuation_uses_env@ %a)@]@ \ @[<hov 1>(shareable_constants@ %a)@]@ \ @[<hov 1>(used_value_slots@ %a)@]@ \ @[<hov 1>(lifted_constant_state@ %a)@]@ \ @[<hov 1>(flow_acc@ %a)@]@ \ @[<hov 1>(demoted_exn_handlers@ %a)@]@ \ @[<hov 1>(code_ids_to_remember@ %a)@]@ \ @[<hov 1>(slot_offsets@ %a)@]\ )@]" DE.print denv CUE.print continuation_uses_env (Static_const.Map.print Symbol.print) shareable_constants Name_occurrences.print used_value_slots LCS.print lifted_constants Flow.Acc.print flow_acc Continuation.Set.print demoted_exn_handlers Code_id.Set.print code_ids_to_remember (Code_id.Map.print Slot_offsets.print) slot_offsets let create denv continuation_uses_env = { denv; continuation_uses_env; slot_offsets = Code_id.Map.empty; shareable_constants = Static_const.Map.empty; used_value_slots = Name_occurrences.empty; lifted_constants = LCS.empty; flow_acc = Flow.Acc.empty (); demoted_exn_handlers = Continuation.Set.empty; code_ids_to_remember = Code_id.Set.empty } let denv t = t.denv let flow_acc t = t.flow_acc let[@inline always] map_flow_acc t ~f = { t with flow_acc = f t.flow_acc } let[@inline always] map_denv t ~f = { t with denv = f t.denv } let[@inline always] with_denv t denv = { t with denv } let with_continuation_uses_env t ~cont_uses_env = { t with continuation_uses_env = cont_uses_env } let record_continuation_use t cont use_kind ~env_at_use ~arg_types = let cont_uses_env, id = CUE.record_continuation_use t.continuation_uses_env cont use_kind ~env_at_use ~arg_types in with_continuation_uses_env t ~cont_uses_env, id let delete_continuation_uses t cont = let cont_uses_env = CUE.delete_continuation_uses t.continuation_uses_env cont in with_continuation_uses_env t ~cont_uses_env let num_continuation_uses t cont = CUE.num_continuation_uses t.continuation_uses_env cont let continuation_uses_env t = t.continuation_uses_env let code_age_relation t = TE.code_age_relation (DE.typing_env (denv t)) let with_code_age_relation t ~code_age_relation = let typing_env = TE.with_code_age_relation (DE.typing_env (denv t)) code_age_relation in with_denv t (DE.with_typing_env (denv t) typing_env) let typing_env t = DE.typing_env (denv t) let add_variable t var ty = with_denv t (DE.add_variable (denv t) var ty) let get_typing_env_no_more_than_one_use t k = CUE.get_typing_env_no_more_than_one_use t.continuation_uses_env k let add_to_lifted_constant_accumulator ?also_add_to_env t constants = let also_add_to_env = match also_add_to_env with None -> false | Some () -> true in let lifted_constants = LCS.union t.lifted_constants constants in let denv = if also_add_to_env then LCS.add_to_denv t.denv constants else t.denv in { t with lifted_constants; denv } let get_lifted_constants t = t.lifted_constants let clear_lifted_constants t = { t with lifted_constants = LCS.empty } let no_lifted_constants t = LCS.is_empty t.lifted_constants let get_and_clear_lifted_constants t = let constants = t.lifted_constants in let t = clear_lifted_constants t in t, constants let set_lifted_constants t consts = { t with lifted_constants = consts } let find_shareable_constant t static_const = Static_const.Map.find_opt static_const t.shareable_constants let consider_constant_for_sharing t symbol static_const = if not (Static_const.can_share static_const) then t else { t with shareable_constants = Static_const.Map.add static_const symbol t.shareable_constants } let with_shareable_constants t ~shareable_constants = { t with shareable_constants } let shareable_constants t = t.shareable_constants let add_use_of_value_slot t value_slot = { t with used_value_slots = Name_occurrences.add_value_slot_in_projection t.used_value_slots value_slot Name_mode.normal } let used_value_slots t = t.used_value_slots let all_continuations_used t = CUE.all_continuations_used t.continuation_uses_env let with_used_value_slots t ~used_value_slots = { t with used_value_slots } let add_code_ids_to_remember t code_ids = if DE.at_unit_toplevel t.denv then t else { t with code_ids_to_remember = Code_id.Set.union code_ids t.code_ids_to_remember } let code_ids_to_remember t = t.code_ids_to_remember let with_code_ids_to_remember t ~code_ids_to_remember = { t with code_ids_to_remember } let are_rebuilding_terms t = DE.are_rebuilding_terms t.denv let demote_exn_handler t cont = { t with demoted_exn_handlers = Continuation.Set.add cont t.demoted_exn_handlers } let demoted_exn_handlers t = t.demoted_exn_handlers let slot_offsets t = t.slot_offsets let with_slot_offsets t ~slot_offsets = { t with slot_offsets }
856aa9f3c074a905c4f85193b7a11b56b517225eaec018f370763a662095ff42
inhabitedtype/ocaml-aws
deleteInventory.mli
open Types type input = DeleteInventoryRequest.t type output = DeleteInventoryResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/deleteInventory.mli
ocaml
open Types type input = DeleteInventoryRequest.t type output = DeleteInventoryResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
c9445c2ecf13e16f5a9cbe2d5aad5561b12d1e754c5ff006734adf8c4c112acf
static-analysis-engineering/codehawk
jCHTemplateUtil.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHPretty (* chutil *) open CHXmlDocument (* jchlib *) open JCHBasicTypes open JCHBasicTypesAPI open JCHDictionary (* jchpre *) open JCHApplication module FieldSignatureCollections = CHCollections.Make ( struct type t = field_signature_int let compare fs1 fs2 = fs1#compare fs2 let toPretty fs = fs#toPretty end) let get_inherited_fields ?(allfields=true) (cn:class_name_int) = try let inheritedFields = new FieldSignatureCollections.table_t in let definedFields = new FieldSignatureCollections.set_t in let cInfo = ref (app#get_class cn) in let _ = List.iter definedFields#add !cInfo#get_fields_defined in begin while !cInfo#has_super_class do let sc = !cInfo#get_super_class in let _ = cInfo := app#get_class sc in let scDefined = !cInfo#get_fields_defined in List.iter (fun fs -> if !cInfo#defines_field fs then if definedFields#has fs || inheritedFields#has fs then () else let cfs = make_cfs sc fs in let _ = if app#has_field cfs then () else app#add_field (!cInfo#get_field cfs#field_signature) in let fInfo = app#get_field cfs in if allfields || fInfo#is_public then inheritedFields#set fs sc else ()) scDefined done; inheritedFields#listOfPairs end with | JCHFile.No_class_found s -> raise (JCH_failure (LBLOCK [ STR "get inherited fields: " ; cn#toPretty ; STR "; No class found: " ; STR s ])) let write_xmlx_inherited_field (node:xml_element_int) (fs:field_signature_int) (defining_class:class_name_int) = let append = node#appendChildren in let set = node#setAttribute in let sNode = xmlElement "signature" in begin write_xmlx_value_type sNode fs#descriptor ; append [ sNode ] ; set "name" fs#name ; set "inherited" "yes" ; set "from" defining_class#name ; node#setNameString ("(inherited) field:" ^ fs#name) end let write_xmlx_inherited_method (node:xml_element_int) (ms:method_signature_int) (defining_class:class_name_int) = let append = node#appendChildren in let set = node#setAttribute in let sNode = xmlElement "signature" in begin ms#write_xmlx sNode ; append [ sNode ] ; set "name" ms#name ; set "inherited" "yes" ; set "from" defining_class#name ; node#setNameString ("(inherited) " ^ ms#name) end
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchpre/jCHTemplateUtil.ml
ocaml
chutil jchlib jchpre
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHPretty open CHXmlDocument open JCHBasicTypes open JCHBasicTypesAPI open JCHDictionary open JCHApplication module FieldSignatureCollections = CHCollections.Make ( struct type t = field_signature_int let compare fs1 fs2 = fs1#compare fs2 let toPretty fs = fs#toPretty end) let get_inherited_fields ?(allfields=true) (cn:class_name_int) = try let inheritedFields = new FieldSignatureCollections.table_t in let definedFields = new FieldSignatureCollections.set_t in let cInfo = ref (app#get_class cn) in let _ = List.iter definedFields#add !cInfo#get_fields_defined in begin while !cInfo#has_super_class do let sc = !cInfo#get_super_class in let _ = cInfo := app#get_class sc in let scDefined = !cInfo#get_fields_defined in List.iter (fun fs -> if !cInfo#defines_field fs then if definedFields#has fs || inheritedFields#has fs then () else let cfs = make_cfs sc fs in let _ = if app#has_field cfs then () else app#add_field (!cInfo#get_field cfs#field_signature) in let fInfo = app#get_field cfs in if allfields || fInfo#is_public then inheritedFields#set fs sc else ()) scDefined done; inheritedFields#listOfPairs end with | JCHFile.No_class_found s -> raise (JCH_failure (LBLOCK [ STR "get inherited fields: " ; cn#toPretty ; STR "; No class found: " ; STR s ])) let write_xmlx_inherited_field (node:xml_element_int) (fs:field_signature_int) (defining_class:class_name_int) = let append = node#appendChildren in let set = node#setAttribute in let sNode = xmlElement "signature" in begin write_xmlx_value_type sNode fs#descriptor ; append [ sNode ] ; set "name" fs#name ; set "inherited" "yes" ; set "from" defining_class#name ; node#setNameString ("(inherited) field:" ^ fs#name) end let write_xmlx_inherited_method (node:xml_element_int) (ms:method_signature_int) (defining_class:class_name_int) = let append = node#appendChildren in let set = node#setAttribute in let sNode = xmlElement "signature" in begin ms#write_xmlx sNode ; append [ sNode ] ; set "name" ms#name ; set "inherited" "yes" ; set "from" defining_class#name ; node#setNameString ("(inherited) " ^ ms#name) end
cd0b2426518b45aea8d61033262cbcccd8dd3e7d2c89e574df2fade2df2563fe
callum-oakley/advent-of-code
17.clj
(ns aoc.2018.17 (:require [aoc.vector :refer [+v -v]] [clojure.test :refer [deftest is]]) (:import clojure.lang.PersistentQueue)) (defn parse [s] (->> (re-seq #"(x|y)=(\d+), (x|y)=(\d+)\.\.(\d+)" s) (map #(map read-string (rest %))) (reduce (fn [clay [axis-a a axis-b b0 b1]] (case [axis-b axis-a] [y x] (into clay (map (fn [y] [y a]) (range b0 (inc b1)))) [x y] (into clay (map (fn [x] [a x]) (range b0 (inc b1)))))) #{}))) (defn flow [clay flowing settled block] (remove #(or (clay %) (flowing %) (settled %)) [(-v block [0 1]) (+v block [0 1])])) (defn settle [clay flowing settled block] (let [settle* (fn [dir] (loop [block (+v block dir) settled* []] (let [down (+v block [1 0])] (cond (clay block) settled* (and (flowing block) (or (clay down) (settled down))) (recur (+v block dir) (conj settled* block)))))) left (settle* [0 -1]) right (settle* [0 1])] (when (and (vector? left) (vector? right)) (concat left [block] right)))) (defn part-* [clay] (let [min-y (apply min (map first clay)) max-y (apply max (map first clay))] (loop [flowing #{[0 500]} settled #{} queue (conj PersistentQueue/EMPTY [0 500])] (if-let [block (peek queue)] (let [down (+v block [1 0])] (cond (or (flowing down) (< max-y (first down))) (recur flowing settled (pop queue)) (or (clay down) (settled down)) (if-let [flowing* (seq (flow clay flowing settled block))] (recur (into flowing flowing*) settled (into (pop queue) flowing*)) (let [settled* (settle clay flowing settled block)] (recur (apply disj flowing settled*) (into settled settled*) (into (pop queue) (filter flowing (map #(-v % [1 0]) settled*)))))) :else (recur (conj flowing down) settled (conj (pop queue) down)))) (update-vals {:flowing flowing :settled settled} (fn [v] (count (filter #(<= min-y (first %) max-y) v)))))))) (defn part-1 [clay] (let [res (part-* clay)] (+ (:flowing res) (:settled res)))) (defn part-2 [clay] (:settled (part-* clay))) (def example "x=495, y=2..7 y=7, x=495..501 x=501, y=3..7 x=498, y=2..4 x=506, y=1..2 x=498, y=10..13 x=504, y=10..13 y=13, x=498..504") (deftest test-example [] (is (= 57 (part-1 (parse example)))) (is (= 29 (part-2 (parse example)))))
null
https://raw.githubusercontent.com/callum-oakley/advent-of-code/c8d9d912471415b0014707f768946b18f29b4531/src/aoc/2018/17.clj
clojure
(ns aoc.2018.17 (:require [aoc.vector :refer [+v -v]] [clojure.test :refer [deftest is]]) (:import clojure.lang.PersistentQueue)) (defn parse [s] (->> (re-seq #"(x|y)=(\d+), (x|y)=(\d+)\.\.(\d+)" s) (map #(map read-string (rest %))) (reduce (fn [clay [axis-a a axis-b b0 b1]] (case [axis-b axis-a] [y x] (into clay (map (fn [y] [y a]) (range b0 (inc b1)))) [x y] (into clay (map (fn [x] [a x]) (range b0 (inc b1)))))) #{}))) (defn flow [clay flowing settled block] (remove #(or (clay %) (flowing %) (settled %)) [(-v block [0 1]) (+v block [0 1])])) (defn settle [clay flowing settled block] (let [settle* (fn [dir] (loop [block (+v block dir) settled* []] (let [down (+v block [1 0])] (cond (clay block) settled* (and (flowing block) (or (clay down) (settled down))) (recur (+v block dir) (conj settled* block)))))) left (settle* [0 -1]) right (settle* [0 1])] (when (and (vector? left) (vector? right)) (concat left [block] right)))) (defn part-* [clay] (let [min-y (apply min (map first clay)) max-y (apply max (map first clay))] (loop [flowing #{[0 500]} settled #{} queue (conj PersistentQueue/EMPTY [0 500])] (if-let [block (peek queue)] (let [down (+v block [1 0])] (cond (or (flowing down) (< max-y (first down))) (recur flowing settled (pop queue)) (or (clay down) (settled down)) (if-let [flowing* (seq (flow clay flowing settled block))] (recur (into flowing flowing*) settled (into (pop queue) flowing*)) (let [settled* (settle clay flowing settled block)] (recur (apply disj flowing settled*) (into settled settled*) (into (pop queue) (filter flowing (map #(-v % [1 0]) settled*)))))) :else (recur (conj flowing down) settled (conj (pop queue) down)))) (update-vals {:flowing flowing :settled settled} (fn [v] (count (filter #(<= min-y (first %) max-y) v)))))))) (defn part-1 [clay] (let [res (part-* clay)] (+ (:flowing res) (:settled res)))) (defn part-2 [clay] (:settled (part-* clay))) (def example "x=495, y=2..7 y=7, x=495..501 x=501, y=3..7 x=498, y=2..4 x=506, y=1..2 x=498, y=10..13 x=504, y=10..13 y=13, x=498..504") (deftest test-example [] (is (= 57 (part-1 (parse example)))) (is (= 29 (part-2 (parse example)))))
620a566784649f2de79079db8c35dc0d7db9c9ab54cc202fe9956abafd1e5216
theodormoroianu/SecondYearCourses
Parsing.hs
module Parsing where import Data.Char import Data.List (intercalate) import Control.Applicative newtype Parser a = Parser { apply :: String -> [(a, String)] } satisfy :: (Char -> Bool) -> Parser Char satisfy p = Parser f where f [] = [] f (c:s) | p c = [(c, s)] | otherwise = [] parse :: Show a => Parser a -> String -> a parse m s = case parses of [] -> error "No valid parse." [a] -> a l -> error ("Ambiguity. Possible parses: \n\t" ++ intercalate "\n\t" (map show l)) where parses = [ x | (x,t) <- apply m s, t == "" ] instance Functor Parser where fmap f p = Parser (\s -> [(f a, r) | (a, r) <- apply p s]) instance Applicative Parser where pure a = Parser (\s -> [(a, s)]) pf <*> pa = Parser (\s -> [(f a, r) | (f, rf) <- apply pf s , (a, r) <- apply pa rf ]) instance Alternative Parser where empty = Parser (\s -> []) pa <|> pb = Parser (\s -> apply pa s ++ apply pb s) Recunoasterea unui anumit caracter char :: Char -> Parser Char char c = satisfy (== c) skipSpace :: Parser () skipSpace = many (satisfy isSpace) *> pure () token :: Parser a -> Parser a token p = skipSpace *> p <* skipSpace parseNat :: Parser Int parseNat = read <$> some (satisfy isDigit) Recunoasterea unui parseNeg :: Parser Int parseNeg = char '-' *> (negate <$> parseNat) Recunoasterea unui numar intreg parseInt :: Parser Int parseInt = parseNat <|> parseNeg
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/99185b0e97119135e7301c2c7be0f07ae7258006/Haskell/l/lab12/Parsing.hs
haskell
module Parsing where import Data.Char import Data.List (intercalate) import Control.Applicative newtype Parser a = Parser { apply :: String -> [(a, String)] } satisfy :: (Char -> Bool) -> Parser Char satisfy p = Parser f where f [] = [] f (c:s) | p c = [(c, s)] | otherwise = [] parse :: Show a => Parser a -> String -> a parse m s = case parses of [] -> error "No valid parse." [a] -> a l -> error ("Ambiguity. Possible parses: \n\t" ++ intercalate "\n\t" (map show l)) where parses = [ x | (x,t) <- apply m s, t == "" ] instance Functor Parser where fmap f p = Parser (\s -> [(f a, r) | (a, r) <- apply p s]) instance Applicative Parser where pure a = Parser (\s -> [(a, s)]) pf <*> pa = Parser (\s -> [(f a, r) | (f, rf) <- apply pf s , (a, r) <- apply pa rf ]) instance Alternative Parser where empty = Parser (\s -> []) pa <|> pb = Parser (\s -> apply pa s ++ apply pb s) Recunoasterea unui anumit caracter char :: Char -> Parser Char char c = satisfy (== c) skipSpace :: Parser () skipSpace = many (satisfy isSpace) *> pure () token :: Parser a -> Parser a token p = skipSpace *> p <* skipSpace parseNat :: Parser Int parseNat = read <$> some (satisfy isDigit) Recunoasterea unui parseNeg :: Parser Int parseNeg = char '-' *> (negate <$> parseNat) Recunoasterea unui numar intreg parseInt :: Parser Int parseInt = parseNat <|> parseNeg
6cef4227f66f9f4a82db59eb77272d9035c40500ccaf9416b155ed3a31890fcd
achirkin/qua-kit
Main.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE FlexibleContexts # # LANGUAGE TemplateHaskell # module Main (main) where -- import Foreign (withForeignPtr, peekByteOff, pokeByteOff) import Luci.Connect import Luci.Messages import Luci.Connect.Base import Control.Monad (void) import Data.Aeson as JSON import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Conduit import Data.Int import Data.Semigroup import Data . Monoid ( ( < > ) ) import Data.Maybe (fromMaybe) import Data.ByteString (ByteString) import qualified Data . ByteString . Internal as BSI import qualified Data.ByteString.Lazy as BSL import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import qualified Control.Lens as Lens import Control.Lens.Operators ((^.), (%=), (<+=)) import Data.List (stripPrefix) import Control . Monad . Logger import qualified Data.ByteString.Char8 as BSC import qualified Data.Char as Char import System.Environment (getArgs) import Lib . import Lib . Scenario -- import Numeric.EasyTensor import Numeric . Commons import Lib ---------------------------------------------------------------------------------------------------- data ServiceState = ServiceState { _tokenGen :: !Token , _connection :: !Connection , _subscribers :: !(HashMap Int64 [Token]) } Lens.makeLenses ''ServiceState genToken :: MonadState ServiceState m => m Token genToken = tokenGen <+= 1 -- | entry point main :: IO () main = withPostgres sets $ \conn -> void $ runLuciClient (ServiceState 0 conn HashMap.empty) processMessages where sets = PSSettings { uName = "siren" , uPass = "sirenpass" , dbHost = "localhost" , dbPort = 5432 , dbName = "sirendb" } data RunSettings = RunSettings { hostS :: ByteString , portS :: Int , logLevelS :: LogLevel } defaultRunSettings :: RunSettings defaultRunSettings = RunSettings { hostS = "localhost" , portS = 7654 , logLevelS = LevelInfo } ---------------------------------------------------------------------------------------------------- -- | The main program processMessages :: Conduit Message (LuciProgram ServiceState) ByteString processMessages = do send a first message to register as a service genToken >>= yield . headerBytes . registerGetList genToken >>= yield . headerBytes . registerGetScenario genToken >>= yield . headerBytes . registerCreateScenario "scenario.geojson.Create" genToken >>= yield . headerBytes . registerCreateScenario "scenario.Create" genToken >>= yield . headerBytes . registerUpdateScenario genToken >>= yield . headerBytes . registerDeleteScenario genToken >>= yield . headerBytes . registerRecoverScenario genToken >>= yield . headerBytes . registerSubscribeTo -- reply to all run requests awaitForever responseMsgs | Respond to one message at a time responseMsgs :: Message -> Conduit Message (LuciProgram ServiceState) ByteString -- Respond only to run messages with correct input responseMsgs m@(MsgRun token "scenario.GetList" _ _) = do conn <- Lens.use connection eresultBS <- liftIO $ listScenarios conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) yieldAnswer token eresultBS responseMsgs (MsgRun token "scenario.geojson.Get" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams , msrid <- (fromJSON <$> HashMap.lookup "srid" pams) >>= f = do conn <- Lens.use connection eresultBS <- liftIO $ getScenario conn (fromIntegral token) (ScenarioId scID) msrid yieldAnswer token eresultBS where f (Success x) = Just x f _ = Nothing responseMsgs m@(MsgRun token "scenario.geojson.Create" pams _) | Just (Success scName) <- fromJSON <$> HashMap.lookup "name" pams , geom_input <- fromMaybe "{}" $ BSL.toStrict . JSON.encode <$> HashMap.lookup "geometry_input" pams = do conn <- Lens.use connection eresultBS <- liftIO $ createScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (BSC.pack scName) geom_input yieldAnswer token eresultBS add alias to " scenario.geojson . Create " for better compatibility with responseMsgs (MsgRun token "scenario.Create" pams objs) = responseMsgs (MsgRun token "scenario.geojson.Create" pams objs) responseMsgs m@(MsgRun token "scenario.geojson.Update" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams , Just geom_input <- BSL.toStrict . JSON.encode <$> HashMap.lookup "geometry_input" pams = do conn <- Lens.use connection eresultBS <- liftIO $ updateScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (ScenarioId scID) geom_input yieldAnswer token eresultBS -- send update to all subscribers subTokens <- map fromIntegral . fromMaybe [] . HashMap.lookup scID <$> Lens.use subscribers eGetMsgs <- liftIO $ getLastScUpdates conn subTokens (ScenarioId scID) case eGetMsgs of Left errbs -> logWarnN $ Text.decodeUtf8 errbs Right rezs -> mapM_ yield rezs responseMsgs m@(MsgRun token "scenario.geojson.Delete" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams = do conn <- Lens.use connection eresultBS <- liftIO $ deleteScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (ScenarioId scID) yieldAnswer token eresultBS responseMsgs m@(MsgRun token "scenario.geojson.Recover" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams = do conn <- Lens.use connection eresultBS <- liftIO $ recoverScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (ScenarioId scID) yieldAnswer token eresultBS responseMsgs (MsgRun token "scenario.SubscribeTo" pams _) | Just (Success scIDs) <- fromJSON <$> HashMap.lookup "ScIDs" pams = do subscribers %= flip (foldr (HashMap.alter addSubscriber)) (scIDs :: [Int64]) yield . headerBytes $ MsgProgress token 0 Nothing [] where addSubscriber Nothing = Just [token] addSubscriber (Just xs) = Just (token:xs) responseMsgs (MsgRun token _ _ _) = yield . headerBytes $ MsgError token "Failed to understand scenario service request: incorrect input in the 'run' message." responseMsgs (MsgCancel token) = -- remove a subscriber with this token subscribers %= HashMap.map (filter (token /=)) responseMsgs (MsgError token s) = do -- remove a subscriber with this token subscribers %= HashMap.map (filter (token /=)) -- log a little logWarnN $ "[Luci error message] " <> s responseMsgs msg = logInfoN . ("[Ignore Luci message] " <>) . showJSON . toJSON . fst $ makeMessage msg ---------------------------------------------------------------------------------------------------- -- | A message we send to register in luci registerGetList :: Token -> Message registerGetList token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Get list of available scenarios" , "serviceName" .= String "scenario.GetList" , "inputs" .= object [] , "outputs" .= object [ "scenarios" .= String "list" ] , "exampleCall" .= object [ "run" .= String "scenario.GetList" ] ] -- | A message we send to register in luci registerGetScenario :: Token -> Message registerGetScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Get a scenario in GeoJSON format" , "serviceName" .= String "scenario.geojson.Get" , "inputs" .= object [ "ScID" .= String "number" ] , "outputs" .= object [ "created" .= String "number" , "lastmodified" .= String "number" , "geometry_output" .= object [ "format" .= String "'GeoJSON'" , "name" .= String "string" , "geometry" .= String "{FeatureCollection}" , "properties" .= String "object" ] ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Get" , "ScId" .= Number 1 ] ] -- | A message we send to register in luci registerCreateScenario :: Text -> Token -> Message registerCreateScenario funname token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Create a new scenario in GeoJSON format" , "serviceName" .= String funname , "inputs" .= object [ "name" .= String "string" , "geometry_input" .= object [ "geometry" .= String "FeatureCollection" , "OPT A: lat" .= String "number" , "OPT A: lon" .= String "number" , "OPT A: alt" .= String "number" , "OPT B: srid" .= String "number" , "properties" .= String "object" ] ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String funname , "name" .= String "My First Scenario" , "geometry_input" .= object [ "geometry" .= object [ "type" .= String "FeatureCollection" , "features" .= [object [ "type" .= String "Feature", "geometry" .= object []]] , "lat" .= Number 12.162 , "lon" .= Number 8.222 , "alt" .= Number 1200 ] ] ] ] -- | A message we send to register in luci registerDeleteScenario :: Token -> Message registerDeleteScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Delete a scenario (mark it as dead to make it invisible)." , "serviceName" .= String "scenario.geojson.Delete" , "inputs" .= object [ "ScID" .= String "number" ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Delete" , "ScID" .= Number 3 ] ] -- | A message we send to register in luci registerRecoverScenario :: Token -> Message registerRecoverScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Recover a scenario (mark it as alive to make it visible)." , "serviceName" .= String "scenario.geojson.Recover" , "inputs" .= object [ "ScID" .= String "number" ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Recover" , "ScID" .= Number 3 ] ] -- | A message we send to register in luci registerUpdateScenario :: Token -> Message registerUpdateScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Update a scenario in GeoJSON format" , "serviceName" .= String "scenario.geojson.Update" , "inputs" .= object [ "ScID" .= String "number" , "geometry_input" .= object [ "geometry" .= String "FeatureCollection" , "properties" .= String "object" ] ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Update" , "ScID" .= Number 3 , "geometry_input" .= object [ "geometry" .= object [ "type" .= String "FeatureCollection" , "features" .= [object [ "type" .= String "Feature", "geometry" .= object []]] ] ] ] ] -- | A message we send to register in luci registerSubscribeTo :: Token -> Message registerSubscribeTo token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= Text.unlines [ "Subscribe to all changes in listed scenarios" , "Note, this service never returns; instead, it send all updates in 'progress' messages" ] , "serviceName" .= String "scenario.SubscribeTo" , "nonBlocking" .= Bool True , "inputs" .= object [ "ScIDs" .= String "[ScID]" ] , "outputs" .= object [ "created" .= String "number" , "lastmodified" .= String "number" , "geometry_output" .= object [ "format" .= String "'GeoJSON'" , "name" .= String "string" , "geometry" .= String "{FeatureCollection}" , "properties" .= String "object" ] ] , "exampleCall" .= object [ "run" .= String "scenario.SubscribeTo" , "ScIDs" .= [Number 3, Number 6] ] ] -------------------------------------------------------------------------------- headerBytes :: Message -> ByteString headerBytes = BSL.toStrict . JSON.encode . fst . makeMessage yieldAnswer :: Token -> Either ByteString ByteString -> Conduit Message (LuciProgram ServiceState) ByteString yieldAnswer token eresultBS = yield $ case eresultBS of Left errbs -> headerBytes $ MsgError token (Text.decodeUtf8 errbs) Right resultBS -> resultBS -------------------------------------------------------------------------------- runLuciClient :: s -- ^ Initial state of a program set by user. -> Conduit Message (LuciProgram s) ByteString ^ How to process LuciMessage -> IO s -- ^ Program runs and in the end returns a final state. runLuciClient s0 pipe = do sets <- setSettings defaultRunSettings <$> getArgs putStrLn "[Info] SERVICE START - Running service with following command-line arguments:" putStrLn $ "\tport=" ++ show (portS sets) putStrLn $ "\thost=" ++ BSC.unpack (hostS sets) putStrLn $ "\tloglevel=" ++ showLevel (logLevelS sets) runLuciProgram s0 (logLevelS sets) $ talkToLuci (portS sets) (hostS sets) Nothing (logWarnNS "PIPELINE ERROR" . Text.pack . show) (Main.processTo =$= pipe =$= Main.processFrom) where showLevel (LevelOther l) = Text.unpack l showLevel lvl = map Char.toLower . drop 5 $ show lvl setSettings s [] = s setSettings s (par:xs) | Just x <- stripPrefix "port=" par = setSettings s{portS = read x} xs | Just x <- stripPrefix "host=" par = setSettings s{hostS = BSC.pack x} xs | Just x <- stripPrefix "loglevel=" par = case x of "debug" -> setSettings s{logLevelS = LevelDebug} xs "info" -> setSettings s{logLevelS = LevelInfo} xs "warn" -> setSettings s{logLevelS = LevelWarn} xs "warning" -> setSettings s{logLevelS = LevelWarn} xs "error" -> setSettings s{logLevelS = LevelError} xs h -> setSettings s{logLevelS = LevelOther $ Text.pack h} xs | otherwise = setSettings s xs -- | helper for parsing incoming messages processTo :: Conduit LuciMessage (LuciProgram s) Message processTo = awaitForever $ \lmsg -> case parseMessage lmsg of JSON.Error s -> logWarnN $ "[Parsing header] " <> Text.pack s <> " Received: " <> (showJSON . toJSON $ fst lmsg) JSON.Success m -> yield m -- | helper for sending outgoing messages processFrom :: Conduit ByteString (LuciProgram s) (LuciProcessing Text LuciMessage) processFrom = awaitForever $ yieldRawMessage . flip (,) []
null
https://raw.githubusercontent.com/achirkin/qua-kit/9f859e2078d5f059fb87b2f6baabcde7170d4e95/services/siren/app/Main.hs
haskell
# LANGUAGE OverloadedStrings # import Foreign (withForeignPtr, peekByteOff, pokeByteOff) import Numeric.EasyTensor -------------------------------------------------------------------------------------------------- | entry point -------------------------------------------------------------------------------------------------- | The main program reply to all run requests Respond only to run messages with correct input send update to all subscribers remove a subscriber with this token remove a subscriber with this token log a little -------------------------------------------------------------------------------------------------- | A message we send to register in luci | A message we send to register in luci | A message we send to register in luci | A message we send to register in luci | A message we send to register in luci | A message we send to register in luci | A message we send to register in luci ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ^ Initial state of a program set by user. ^ Program runs and in the end returns a final state. | helper for parsing incoming messages | helper for sending outgoing messages
# LANGUAGE FlexibleContexts # # LANGUAGE TemplateHaskell # module Main (main) where import Luci.Connect import Luci.Messages import Luci.Connect.Base import Control.Monad (void) import Data.Aeson as JSON import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Conduit import Data.Int import Data.Semigroup import Data . Monoid ( ( < > ) ) import Data.Maybe (fromMaybe) import Data.ByteString (ByteString) import qualified Data . ByteString . Internal as BSI import qualified Data.ByteString.Lazy as BSL import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import qualified Control.Lens as Lens import Control.Lens.Operators ((^.), (%=), (<+=)) import Data.List (stripPrefix) import Control . Monad . Logger import qualified Data.ByteString.Char8 as BSC import qualified Data.Char as Char import System.Environment (getArgs) import Lib . import Lib . Scenario import Numeric . Commons import Lib data ServiceState = ServiceState { _tokenGen :: !Token , _connection :: !Connection , _subscribers :: !(HashMap Int64 [Token]) } Lens.makeLenses ''ServiceState genToken :: MonadState ServiceState m => m Token genToken = tokenGen <+= 1 main :: IO () main = withPostgres sets $ \conn -> void $ runLuciClient (ServiceState 0 conn HashMap.empty) processMessages where sets = PSSettings { uName = "siren" , uPass = "sirenpass" , dbHost = "localhost" , dbPort = 5432 , dbName = "sirendb" } data RunSettings = RunSettings { hostS :: ByteString , portS :: Int , logLevelS :: LogLevel } defaultRunSettings :: RunSettings defaultRunSettings = RunSettings { hostS = "localhost" , portS = 7654 , logLevelS = LevelInfo } processMessages :: Conduit Message (LuciProgram ServiceState) ByteString processMessages = do send a first message to register as a service genToken >>= yield . headerBytes . registerGetList genToken >>= yield . headerBytes . registerGetScenario genToken >>= yield . headerBytes . registerCreateScenario "scenario.geojson.Create" genToken >>= yield . headerBytes . registerCreateScenario "scenario.Create" genToken >>= yield . headerBytes . registerUpdateScenario genToken >>= yield . headerBytes . registerDeleteScenario genToken >>= yield . headerBytes . registerRecoverScenario genToken >>= yield . headerBytes . registerSubscribeTo awaitForever responseMsgs | Respond to one message at a time responseMsgs :: Message -> Conduit Message (LuciProgram ServiceState) ByteString responseMsgs m@(MsgRun token "scenario.GetList" _ _) = do conn <- Lens.use connection eresultBS <- liftIO $ listScenarios conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) yieldAnswer token eresultBS responseMsgs (MsgRun token "scenario.geojson.Get" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams , msrid <- (fromJSON <$> HashMap.lookup "srid" pams) >>= f = do conn <- Lens.use connection eresultBS <- liftIO $ getScenario conn (fromIntegral token) (ScenarioId scID) msrid yieldAnswer token eresultBS where f (Success x) = Just x f _ = Nothing responseMsgs m@(MsgRun token "scenario.geojson.Create" pams _) | Just (Success scName) <- fromJSON <$> HashMap.lookup "name" pams , geom_input <- fromMaybe "{}" $ BSL.toStrict . JSON.encode <$> HashMap.lookup "geometry_input" pams = do conn <- Lens.use connection eresultBS <- liftIO $ createScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (BSC.pack scName) geom_input yieldAnswer token eresultBS add alias to " scenario.geojson . Create " for better compatibility with responseMsgs (MsgRun token "scenario.Create" pams objs) = responseMsgs (MsgRun token "scenario.geojson.Create" pams objs) responseMsgs m@(MsgRun token "scenario.geojson.Update" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams , Just geom_input <- BSL.toStrict . JSON.encode <$> HashMap.lookup "geometry_input" pams = do conn <- Lens.use connection eresultBS <- liftIO $ updateScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (ScenarioId scID) geom_input yieldAnswer token eresultBS subTokens <- map fromIntegral . fromMaybe [] . HashMap.lookup scID <$> Lens.use subscribers eGetMsgs <- liftIO $ getLastScUpdates conn subTokens (ScenarioId scID) case eGetMsgs of Left errbs -> logWarnN $ Text.decodeUtf8 errbs Right rezs -> mapM_ yield rezs responseMsgs m@(MsgRun token "scenario.geojson.Delete" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams = do conn <- Lens.use connection eresultBS <- liftIO $ deleteScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (ScenarioId scID) yieldAnswer token eresultBS responseMsgs m@(MsgRun token "scenario.geojson.Recover" pams _) | Just (Success scID) <- fromJSON <$> HashMap.lookup "ScID" pams = do conn <- Lens.use connection eresultBS <- liftIO $ recoverScenario conn (fromIntegral token) (m ^. msgSenderId) (m ^. msgSenderAuthRole) (ScenarioId scID) yieldAnswer token eresultBS responseMsgs (MsgRun token "scenario.SubscribeTo" pams _) | Just (Success scIDs) <- fromJSON <$> HashMap.lookup "ScIDs" pams = do subscribers %= flip (foldr (HashMap.alter addSubscriber)) (scIDs :: [Int64]) yield . headerBytes $ MsgProgress token 0 Nothing [] where addSubscriber Nothing = Just [token] addSubscriber (Just xs) = Just (token:xs) responseMsgs (MsgRun token _ _ _) = yield . headerBytes $ MsgError token "Failed to understand scenario service request: incorrect input in the 'run' message." responseMsgs (MsgCancel token) = subscribers %= HashMap.map (filter (token /=)) responseMsgs (MsgError token s) = do subscribers %= HashMap.map (filter (token /=)) logWarnN $ "[Luci error message] " <> s responseMsgs msg = logInfoN . ("[Ignore Luci message] " <>) . showJSON . toJSON . fst $ makeMessage msg registerGetList :: Token -> Message registerGetList token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Get list of available scenarios" , "serviceName" .= String "scenario.GetList" , "inputs" .= object [] , "outputs" .= object [ "scenarios" .= String "list" ] , "exampleCall" .= object [ "run" .= String "scenario.GetList" ] ] registerGetScenario :: Token -> Message registerGetScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Get a scenario in GeoJSON format" , "serviceName" .= String "scenario.geojson.Get" , "inputs" .= object [ "ScID" .= String "number" ] , "outputs" .= object [ "created" .= String "number" , "lastmodified" .= String "number" , "geometry_output" .= object [ "format" .= String "'GeoJSON'" , "name" .= String "string" , "geometry" .= String "{FeatureCollection}" , "properties" .= String "object" ] ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Get" , "ScId" .= Number 1 ] ] registerCreateScenario :: Text -> Token -> Message registerCreateScenario funname token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Create a new scenario in GeoJSON format" , "serviceName" .= String funname , "inputs" .= object [ "name" .= String "string" , "geometry_input" .= object [ "geometry" .= String "FeatureCollection" , "OPT A: lat" .= String "number" , "OPT A: lon" .= String "number" , "OPT A: alt" .= String "number" , "OPT B: srid" .= String "number" , "properties" .= String "object" ] ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String funname , "name" .= String "My First Scenario" , "geometry_input" .= object [ "geometry" .= object [ "type" .= String "FeatureCollection" , "features" .= [object [ "type" .= String "Feature", "geometry" .= object []]] , "lat" .= Number 12.162 , "lon" .= Number 8.222 , "alt" .= Number 1200 ] ] ] ] registerDeleteScenario :: Token -> Message registerDeleteScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Delete a scenario (mark it as dead to make it invisible)." , "serviceName" .= String "scenario.geojson.Delete" , "inputs" .= object [ "ScID" .= String "number" ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Delete" , "ScID" .= Number 3 ] ] registerRecoverScenario :: Token -> Message registerRecoverScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Recover a scenario (mark it as alive to make it visible)." , "serviceName" .= String "scenario.geojson.Recover" , "inputs" .= object [ "ScID" .= String "number" ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Recover" , "ScID" .= Number 3 ] ] registerUpdateScenario :: Token -> Message registerUpdateScenario token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= String "Update a scenario in GeoJSON format" , "serviceName" .= String "scenario.geojson.Update" , "inputs" .= object [ "ScID" .= String "number" , "geometry_input" .= object [ "geometry" .= String "FeatureCollection" , "properties" .= String "object" ] ] , "outputs" .= object [ "ScID" .= String "number" , "created" .= String "number" , "lastmodified" .= String "number" , "name" .= String "name" ] , "exampleCall" .= object [ "run" .= String "scenario.geojson.Update" , "ScID" .= Number 3 , "geometry_input" .= object [ "geometry" .= object [ "type" .= String "FeatureCollection" , "features" .= [object [ "type" .= String "Feature", "geometry" .= object []]] ] ] ] ] registerSubscribeTo :: Token -> Message registerSubscribeTo token = MsgRun token "RemoteRegister" o [] where o = HashMap.fromList [ "description" .= Text.unlines [ "Subscribe to all changes in listed scenarios" , "Note, this service never returns; instead, it send all updates in 'progress' messages" ] , "serviceName" .= String "scenario.SubscribeTo" , "nonBlocking" .= Bool True , "inputs" .= object [ "ScIDs" .= String "[ScID]" ] , "outputs" .= object [ "created" .= String "number" , "lastmodified" .= String "number" , "geometry_output" .= object [ "format" .= String "'GeoJSON'" , "name" .= String "string" , "geometry" .= String "{FeatureCollection}" , "properties" .= String "object" ] ] , "exampleCall" .= object [ "run" .= String "scenario.SubscribeTo" , "ScIDs" .= [Number 3, Number 6] ] ] headerBytes :: Message -> ByteString headerBytes = BSL.toStrict . JSON.encode . fst . makeMessage yieldAnswer :: Token -> Either ByteString ByteString -> Conduit Message (LuciProgram ServiceState) ByteString yieldAnswer token eresultBS = yield $ case eresultBS of Left errbs -> headerBytes $ MsgError token (Text.decodeUtf8 errbs) Right resultBS -> resultBS runLuciClient :: s -> Conduit Message (LuciProgram s) ByteString ^ How to process LuciMessage -> IO s runLuciClient s0 pipe = do sets <- setSettings defaultRunSettings <$> getArgs putStrLn "[Info] SERVICE START - Running service with following command-line arguments:" putStrLn $ "\tport=" ++ show (portS sets) putStrLn $ "\thost=" ++ BSC.unpack (hostS sets) putStrLn $ "\tloglevel=" ++ showLevel (logLevelS sets) runLuciProgram s0 (logLevelS sets) $ talkToLuci (portS sets) (hostS sets) Nothing (logWarnNS "PIPELINE ERROR" . Text.pack . show) (Main.processTo =$= pipe =$= Main.processFrom) where showLevel (LevelOther l) = Text.unpack l showLevel lvl = map Char.toLower . drop 5 $ show lvl setSettings s [] = s setSettings s (par:xs) | Just x <- stripPrefix "port=" par = setSettings s{portS = read x} xs | Just x <- stripPrefix "host=" par = setSettings s{hostS = BSC.pack x} xs | Just x <- stripPrefix "loglevel=" par = case x of "debug" -> setSettings s{logLevelS = LevelDebug} xs "info" -> setSettings s{logLevelS = LevelInfo} xs "warn" -> setSettings s{logLevelS = LevelWarn} xs "warning" -> setSettings s{logLevelS = LevelWarn} xs "error" -> setSettings s{logLevelS = LevelError} xs h -> setSettings s{logLevelS = LevelOther $ Text.pack h} xs | otherwise = setSettings s xs processTo :: Conduit LuciMessage (LuciProgram s) Message processTo = awaitForever $ \lmsg -> case parseMessage lmsg of JSON.Error s -> logWarnN $ "[Parsing header] " <> Text.pack s <> " Received: " <> (showJSON . toJSON $ fst lmsg) JSON.Success m -> yield m processFrom :: Conduit ByteString (LuciProgram s) (LuciProcessing Text LuciMessage) processFrom = awaitForever $ yieldRawMessage . flip (,) []
6e3a0ea0c090550137a52dfa85b490ef4168fd598eec9d3b269933ecb1231373
avsm/mirage-duniverse
segment.ml
* Copyright ( c ) 2010 - 2011 Anil Madhavapeddy < > * * 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) 2010-2011 Anil Madhavapeddy <> * * 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. *) [@@@ocaml.warning "-3"] open Lwt.Infix let src = Logs.Src.create "segment" ~doc:"Mirage TCP Segment module" module Log = (val Logs.src_log src : Logs.LOG) let lwt_sequence_add_l s seq = let (_:'a Lwt_dllist.node) = Lwt_dllist.add_l s seq in () let lwt_sequence_add_r s seq = let (_:'a Lwt_dllist.node) = Lwt_dllist.add_r s seq in () let peek_opt_l seq = match Lwt_dllist.take_opt_l seq with | None -> None | Some s -> lwt_sequence_add_l s seq; Some s let peek_l seq = match Lwt_dllist.take_opt_l seq with | None -> assert false | Some s -> let _ = Lwt_dllist.add_l s seq in s let rec reset_seq segs = match Lwt_dllist.take_opt_l segs with | None -> () | Some _ -> reset_seq segs (* The receive queue stores out-of-order segments, and can coalesece them on input and pass on an ordered list up the stack to the application. It also looks for control messages and dispatches them to the Rtx queue to ack messages or close channels. *) module Rx(Time:Mirage_time_lwt.S) = struct open Tcp_packet module StateTick = State.Make(Time) (* Individual received TCP segment TODO: this will change when IP fragments work *) type segment = { header: Tcp_packet.t; payload: Cstruct.t } let pp_segment fmt {header; payload} = Format.fprintf fmt "RX seg seq=%a acknum=%a ack=%b rst=%b syn=%b fin=%b win=%d len=%d" Sequence.pp header.sequence Sequence.pp header.ack_number header.ack header.rst header.syn header.fin header.window (Cstruct.len payload) let len seg = Sequence.of_int ((Cstruct.len seg.payload) + (if seg.header.fin then 1 else 0) + (if seg.header.syn then 1 else 0)) (* Set of segments, ordered by sequence number *) module S = Set.Make(struct type t = segment let compare a b = (Sequence.compare a.header.sequence b.header.sequence) end) type t = { mutable segs: S.t; rx_data: (Cstruct.t list option * Sequence.t option) Lwt_mvar.t; (* User receive channel *) tx_ack: (Sequence.t * int) Lwt_mvar.t; (* Acks of our transmitted segs *) wnd: Window.t; state: State.t; } let create ~rx_data ~wnd ~state ~tx_ack = let segs = S.empty in { segs; rx_data; tx_ack; wnd; state } let pp fmt t = let pp_v fmt seg = Format.fprintf fmt "%a[%a]" Sequence.pp seg.header.sequence Sequence.pp (len seg) in Format.pp_print_list pp_v fmt (S.elements t.segs) (* If there is a FIN flag at the end of this segment set. TODO: should look for a FIN and chop off the rest of the set as they may be orphan segments *) let fin q = try (S.max_elt q).header.fin with Not_found -> false let is_empty q = S.is_empty q.segs let check_valid_segment q seg = if seg.header.rst then if Sequence.compare seg.header.sequence (Window.rx_nxt q.wnd) = 0 then `Reset else if Window.valid q.wnd seg.header.sequence then `ChallengeAck else `Drop else if seg.header.syn then `ChallengeAck else if Window.valid q.wnd seg.header.sequence then let min = Sequence.(sub (Window.tx_una q.wnd) (of_int32 (Window.max_tx_wnd q.wnd))) in if Sequence.between seg.header.ack_number min (Window.tx_nxt q.wnd) then `Ok else rfc5961 5.2 `ChallengeAck else `Drop let send_challenge_ack q = TODO : rfc5961 ACK Throttling (* Is this the correct way trigger an ack? *) Lwt_mvar.put q.rx_data (Some [], Some Sequence.zero) (* Given an input segment, the window information, and a receive queue, update the window, extract any ready segments into the user receive queue, and signal any acks to the Tx queue *) let input (q:t) seg = match check_valid_segment q seg with | `Ok -> let force_ack = ref false in (* Insert the latest segment *) let segs = S.add seg q.segs in (* Walk through the set and get a list of contiguous segments *) let ready, waiting = S.fold (fun seg acc -> match Sequence.compare seg.header.sequence (Window.rx_nxt_inseq q.wnd) with | (-1) -> (* Sequence number is in the past, probably an overlapping segment. Drop it for now, but TODO segment coalescing *) force_ack := true; acc | 0 -> (* This is the next segment, so put it into the ready set and update the receive ack number *) let (ready,waiting) = acc in Window.rx_advance_inseq q.wnd (len seg); (S.add seg ready), waiting | 1 -> Sequence is in the future , so ca n't use it yet force_ack := true; let (ready,waiting) = acc in ready, (S.add seg waiting) | _ -> assert false ) segs (S.empty, S.empty) in q.segs <- waiting; (* If the segment has an ACK, tell the transmit side *) let tx_ack = if seg.header.ack && (Sequence.geq seg.header.ack_number (Window.ack_seq q.wnd)) then begin StateTick.tick q.state (State.Recv_ack seg.header.ack_number); let data_in_flight = Window.tx_inflight q.wnd in let ack_has_advanced = (Window.ack_seq q.wnd) <> seg.header.ack_number in let win_has_changed = (Window.ack_win q.wnd) <> seg.header.window in if ((data_in_flight && (Window.ack_serviced q.wnd || not ack_has_advanced)) || (not data_in_flight && win_has_changed)) then begin Window.set_ack_serviced q.wnd false; Window.set_ack_seq_win q.wnd seg.header.ack_number seg.header.window; Lwt_mvar.put q.tx_ack ((Window.ack_seq q.wnd), (Window.ack_win q.wnd)) end else begin Window.set_ack_seq_win q.wnd seg.header.ack_number seg.header.window; Lwt.return_unit end end else Lwt.return_unit in (* Inform the user application of new data *) let urx_inform = (* TODO: deal with overlapping fragments *) let elems_r, winadv = S.fold (fun seg (acc_l, acc_w) -> (if Cstruct.len seg.payload > 0 then seg.payload :: acc_l else acc_l), (Sequence.add (len seg) acc_w) ) ready ([], Sequence.zero) in let elems = List.rev elems_r in let w = if !force_ack || Sequence.(gt winadv zero) then Some winadv else None in Lwt_mvar.put q.rx_data (Some elems, w) >>= fun () -> (* If the last ready segment has a FIN, then mark the receive window as closed and tell the application *) (if fin ready then begin if S.cardinal waiting != 0 then Log.info (fun f -> f "application receive queue closed, but there are waiting segments."); Lwt_mvar.put q.rx_data (None, Some Sequence.zero) end else Lwt.return_unit) in tx_ack <&> urx_inform | `ChallengeAck -> send_challenge_ack q | `Drop -> Lwt.return_unit | `Reset -> StateTick.tick q.state State.Recv_rst; (* Abandon our current segments *) q.segs <- S.empty; (* Signal TX side *) let txalert ack_svcd = if not ack_svcd then Lwt.return_unit else Lwt_mvar.put q.tx_ack (Window.ack_seq q.wnd, Window.ack_win q.wnd) in txalert (Window.ack_serviced q.wnd) >>= fun () -> (* Use the fin path to inform the application of end of stream *) Lwt_mvar.put q.rx_data (None, Some Sequence.zero) end (* Transmitted segments are sent in-order, and may also be marked with control flags (such as urgent, or fin to mark the end). *) At most one of Syn / Fin / Rst / Psh allowed | No_flags | Syn | Fin | Rst | Psh module Tx (Time:Mirage_time_lwt.S) (Clock:Mirage_clock.MCLOCK) = struct module StateTick = State.Make(Time) module TT = Tcptimer.Make(Time) module TX = Window.Make(Clock) type ('a, 'b) xmit = flags:tx_flags -> wnd:Window.t -> options:Options.t list -> seq:Sequence.t -> Cstruct.t -> ('a, 'b) result Lwt.t type seg = { data: Cstruct.t; flags: tx_flags; seq: Sequence.t; } (* Sequence length of the segment *) let len seg = Sequence.of_int ((match seg.flags with | No_flags | Psh | Rst -> 0 | Syn | Fin -> 1) + (Cstruct.len seg.data)) (* Queue of pre-transmission segments *) type ('a, 'b) q = { Retransmitted segment queue xmit: ('a, 'b) xmit; (* Transmit packet to the wire *) RX Ack thread that we 've sent one wnd: Window.t; (* TCP Window information *) state: State.t; (* state of the TCP connection associated with this queue *) tx_wnd_update: int Lwt_mvar.t; (* Received updates to the transmit window *) rexmit_timer: Tcptimer.t; (* Retransmission timer for this connection *) clock: Clock.t; (* whom to ask for the time *) mutable dup_acks: int; (* dup ack count for re-xmits *) } type t = T: ('a, 'b) q -> t let ack_segment _ _ = () Take any action to the user transmit queue due to this being successfully ACKed successfully ACKed *) URG_TODO : Add sequence number to the Syn_rcvd rexmit to only rexmit most recent rexmit most recent *) let ontimer xmit st segs wnd seq = match State.state st with | State.Syn_rcvd _ | State.Established | State.Fin_wait_1 _ | State.Close_wait | State.Last_ack _ -> begin match peek_opt_l segs with | None -> Lwt.return Tcptimer.Stoptimer | Some rexmit_seg -> match rexmit_seg.seq = seq with | false -> Log.debug (fun fmt -> fmt "PUSHING TIMER - new time=%Lu, new seq=%a" (Window.rto wnd) Sequence.pp rexmit_seg.seq); let ret = Tcptimer.ContinueSetPeriod (Window.rto wnd, rexmit_seg.seq) in Lwt.return ret | true -> if (Window.max_rexmits_done wnd) then ( (* TODO - include more in log msg like ipaddrs *) Log.debug (fun f -> f "Max retransmits reached: %a" Window.pp wnd); Log.info (fun fmt -> fmt "Max retransmits reached for connection - terminating"); StateTick.tick st State.Timeout; Lwt.return Tcptimer.Stoptimer ) else ( let flags = rexmit_seg.flags in let options = [] in (* TODO: put the right options *) Log.debug (fun fmt -> fmt "TCP retransmission triggered by timer! seq = %d" (Sequence.to_int rexmit_seg.seq)); Lwt.async (fun () -> xmit ~flags ~wnd ~options ~seq rexmit_seg.data); Window.alert_fast_rexmit wnd rexmit_seg.seq; Window.backoff_rto wnd; Log.debug (fun fmt -> fmt "Backed off! %a" Window.pp wnd); Log.debug (fun fmt -> fmt "PUSHING TIMER - new time = %Lu, new seq = %a" (Window.rto wnd) Sequence.pp rexmit_seg.seq); let ret = Tcptimer.ContinueSetPeriod (Window.rto wnd, rexmit_seg.seq) in Lwt.return ret ) end | _ -> Lwt.return Tcptimer.Stoptimer let rec clearsegs q ack_remaining segs = match Sequence.(gt ack_remaining zero) with here we return 0l instead of ack_remaining in case the ack was an old packet in the network the ack was an old packet in the network *) | true -> match Lwt_dllist.take_opt_l segs with | None -> Log.debug (fun f -> f "Dubious ACK received"); ack_remaining | Some s -> let seg_len = (len s) in match Sequence.lt ack_remaining seg_len with | true -> Log.debug (fun f -> f "Partial ACK received"); (* return uncleared segment to the sequence *) lwt_sequence_add_l s segs; ack_remaining | false -> ack_segment q s; clearsegs q (Sequence.sub ack_remaining seg_len) segs let rto_t q tx_ack = Listen for incoming from the receive queue and ACK segments in our retransmission queue segments in our retransmission queue *) let rec tx_ack_t () = let serviceack dupack ack_len seq win = let partleft = clearsegs q ack_len q.segs in TX.tx_ack q.clock q.wnd (Sequence.sub seq partleft) win; match dupack || Window.fast_rec q.wnd with | true -> q.dup_acks <- q.dup_acks + 1; if q.dup_acks = 3 || (Sequence.to_int32 ack_len > 0l) then begin (* alert window module to fall into fast recovery *) Window.alert_fast_rexmit q.wnd seq; (* retransmit the bottom of the unacked list of packets *) let rexmit_seg = peek_l q.segs in Log.debug (fun fmt -> fmt "TCP fast retransmission seq=%a, dupack=%a" Sequence.pp rexmit_seg.seq Sequence.pp seq); let { wnd; _ } = q in let flags=rexmit_seg.flags in let options=[] in (* TODO: put the right options *) Lwt.async (fun () -> q.xmit ~flags ~wnd ~options ~seq rexmit_seg.data); Lwt.return_unit end else Lwt.return_unit | false -> q.dup_acks <- 0; Lwt.return_unit in Lwt_mvar.take tx_ack >>= fun _ -> Window.set_ack_serviced q.wnd true; let seq = Window.ack_seq q.wnd in let win = Window.ack_win q.wnd in begin match State.state q.state with | State.Reset -> Note : This is not stricly necessary , as the PCB will be GCed later on . However , it helps removing pressure on the GC . GCed later on. However, it helps removing pressure on the GC. *) reset_seq q.segs; Lwt.return_unit | _ -> let ack_len = Sequence.sub seq (Window.tx_una q.wnd) in let dupacktest () = 0l = Sequence.to_int32 ack_len && Window.tx_wnd_unscaled q.wnd = Int32.of_int win && not (Lwt_dllist.is_empty q.segs) in serviceack (dupacktest ()) ack_len seq win end >>= fun () -> (* Inform the window thread of updates to the transmit window *) Lwt_mvar.put q.tx_wnd_update win >>= fun () -> tx_ack_t () in tx_ack_t () let create ~clock ~xmit ~wnd ~state ~rx_ack ~tx_ack ~tx_wnd_update = let segs = Lwt_dllist.create () in let dup_acks = 0 in let expire = ontimer xmit state segs wnd in let period_ns = Window.rto wnd in let rexmit_timer = TT.t ~period_ns ~expire in let q = { clock; xmit; wnd; state; rx_ack; segs; tx_wnd_update; rexmit_timer; dup_acks } in let t = rto_t q tx_ack in T q, t Queue a segment for transmission . May block if : - There is no transmit window available . - The wire transmit function blocks . The transmitter should check that the segment size will will not be greater than the transmit window . - There is no transmit window available. - The wire transmit function blocks. The transmitter should check that the segment size will will not be greater than the transmit window. *) let output ?(flags=No_flags) ?(options=[]) (T q) data = Transmit the packet to the wire TODO : deal with transmission soft / hard errors here RFC5461 TODO: deal with transmission soft/hard errors here RFC5461 *) let { wnd; _ } = q in let ack = Window.rx_nxt wnd in let seq = Window.tx_nxt wnd in let seg = { data; flags; seq } in let seq_len = len seg in TX.tx_advance q.clock q.wnd seq_len; (* Queue up segment just sent for retransmission if needed *) let q_rexmit () = match Sequence.(gt seq_len zero) with | false -> Lwt.return_unit | true -> lwt_sequence_add_r seg q.segs; let p = Window.rto q.wnd in TT.start q.rexmit_timer ~p seg.seq in q_rexmit () >>= fun () -> q.xmit ~flags ~wnd ~options ~seq data >>= fun _ -> Inform the RX ack thread that we 've just sent one Lwt_mvar.put q.rx_ack ack end
null
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tcpip/src/tcp/segment.ml
ocaml
The receive queue stores out-of-order segments, and can coalesece them on input and pass on an ordered list up the stack to the application. It also looks for control messages and dispatches them to the Rtx queue to ack messages or close channels. Individual received TCP segment TODO: this will change when IP fragments work Set of segments, ordered by sequence number User receive channel Acks of our transmitted segs If there is a FIN flag at the end of this segment set. TODO: should look for a FIN and chop off the rest of the set as they may be orphan segments Is this the correct way trigger an ack? Given an input segment, the window information, and a receive queue, update the window, extract any ready segments into the user receive queue, and signal any acks to the Tx queue Insert the latest segment Walk through the set and get a list of contiguous segments Sequence number is in the past, probably an overlapping segment. Drop it for now, but TODO segment coalescing This is the next segment, so put it into the ready set and update the receive ack number If the segment has an ACK, tell the transmit side Inform the user application of new data TODO: deal with overlapping fragments If the last ready segment has a FIN, then mark the receive window as closed and tell the application Abandon our current segments Signal TX side Use the fin path to inform the application of end of stream Transmitted segments are sent in-order, and may also be marked with control flags (such as urgent, or fin to mark the end). Sequence length of the segment Queue of pre-transmission segments Transmit packet to the wire TCP Window information state of the TCP connection associated with this queue Received updates to the transmit window Retransmission timer for this connection whom to ask for the time dup ack count for re-xmits TODO - include more in log msg like ipaddrs TODO: put the right options return uncleared segment to the sequence alert window module to fall into fast recovery retransmit the bottom of the unacked list of packets TODO: put the right options Inform the window thread of updates to the transmit window Queue up segment just sent for retransmission if needed
* Copyright ( c ) 2010 - 2011 Anil Madhavapeddy < > * * 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) 2010-2011 Anil Madhavapeddy <> * * 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. *) [@@@ocaml.warning "-3"] open Lwt.Infix let src = Logs.Src.create "segment" ~doc:"Mirage TCP Segment module" module Log = (val Logs.src_log src : Logs.LOG) let lwt_sequence_add_l s seq = let (_:'a Lwt_dllist.node) = Lwt_dllist.add_l s seq in () let lwt_sequence_add_r s seq = let (_:'a Lwt_dllist.node) = Lwt_dllist.add_r s seq in () let peek_opt_l seq = match Lwt_dllist.take_opt_l seq with | None -> None | Some s -> lwt_sequence_add_l s seq; Some s let peek_l seq = match Lwt_dllist.take_opt_l seq with | None -> assert false | Some s -> let _ = Lwt_dllist.add_l s seq in s let rec reset_seq segs = match Lwt_dllist.take_opt_l segs with | None -> () | Some _ -> reset_seq segs module Rx(Time:Mirage_time_lwt.S) = struct open Tcp_packet module StateTick = State.Make(Time) type segment = { header: Tcp_packet.t; payload: Cstruct.t } let pp_segment fmt {header; payload} = Format.fprintf fmt "RX seg seq=%a acknum=%a ack=%b rst=%b syn=%b fin=%b win=%d len=%d" Sequence.pp header.sequence Sequence.pp header.ack_number header.ack header.rst header.syn header.fin header.window (Cstruct.len payload) let len seg = Sequence.of_int ((Cstruct.len seg.payload) + (if seg.header.fin then 1 else 0) + (if seg.header.syn then 1 else 0)) module S = Set.Make(struct type t = segment let compare a b = (Sequence.compare a.header.sequence b.header.sequence) end) type t = { mutable segs: S.t; wnd: Window.t; state: State.t; } let create ~rx_data ~wnd ~state ~tx_ack = let segs = S.empty in { segs; rx_data; tx_ack; wnd; state } let pp fmt t = let pp_v fmt seg = Format.fprintf fmt "%a[%a]" Sequence.pp seg.header.sequence Sequence.pp (len seg) in Format.pp_print_list pp_v fmt (S.elements t.segs) let fin q = try (S.max_elt q).header.fin with Not_found -> false let is_empty q = S.is_empty q.segs let check_valid_segment q seg = if seg.header.rst then if Sequence.compare seg.header.sequence (Window.rx_nxt q.wnd) = 0 then `Reset else if Window.valid q.wnd seg.header.sequence then `ChallengeAck else `Drop else if seg.header.syn then `ChallengeAck else if Window.valid q.wnd seg.header.sequence then let min = Sequence.(sub (Window.tx_una q.wnd) (of_int32 (Window.max_tx_wnd q.wnd))) in if Sequence.between seg.header.ack_number min (Window.tx_nxt q.wnd) then `Ok else rfc5961 5.2 `ChallengeAck else `Drop let send_challenge_ack q = TODO : rfc5961 ACK Throttling Lwt_mvar.put q.rx_data (Some [], Some Sequence.zero) let input (q:t) seg = match check_valid_segment q seg with | `Ok -> let force_ack = ref false in let segs = S.add seg q.segs in let ready, waiting = S.fold (fun seg acc -> match Sequence.compare seg.header.sequence (Window.rx_nxt_inseq q.wnd) with | (-1) -> force_ack := true; acc | 0 -> let (ready,waiting) = acc in Window.rx_advance_inseq q.wnd (len seg); (S.add seg ready), waiting | 1 -> Sequence is in the future , so ca n't use it yet force_ack := true; let (ready,waiting) = acc in ready, (S.add seg waiting) | _ -> assert false ) segs (S.empty, S.empty) in q.segs <- waiting; let tx_ack = if seg.header.ack && (Sequence.geq seg.header.ack_number (Window.ack_seq q.wnd)) then begin StateTick.tick q.state (State.Recv_ack seg.header.ack_number); let data_in_flight = Window.tx_inflight q.wnd in let ack_has_advanced = (Window.ack_seq q.wnd) <> seg.header.ack_number in let win_has_changed = (Window.ack_win q.wnd) <> seg.header.window in if ((data_in_flight && (Window.ack_serviced q.wnd || not ack_has_advanced)) || (not data_in_flight && win_has_changed)) then begin Window.set_ack_serviced q.wnd false; Window.set_ack_seq_win q.wnd seg.header.ack_number seg.header.window; Lwt_mvar.put q.tx_ack ((Window.ack_seq q.wnd), (Window.ack_win q.wnd)) end else begin Window.set_ack_seq_win q.wnd seg.header.ack_number seg.header.window; Lwt.return_unit end end else Lwt.return_unit in let urx_inform = let elems_r, winadv = S.fold (fun seg (acc_l, acc_w) -> (if Cstruct.len seg.payload > 0 then seg.payload :: acc_l else acc_l), (Sequence.add (len seg) acc_w) ) ready ([], Sequence.zero) in let elems = List.rev elems_r in let w = if !force_ack || Sequence.(gt winadv zero) then Some winadv else None in Lwt_mvar.put q.rx_data (Some elems, w) >>= fun () -> (if fin ready then begin if S.cardinal waiting != 0 then Log.info (fun f -> f "application receive queue closed, but there are waiting segments."); Lwt_mvar.put q.rx_data (None, Some Sequence.zero) end else Lwt.return_unit) in tx_ack <&> urx_inform | `ChallengeAck -> send_challenge_ack q | `Drop -> Lwt.return_unit | `Reset -> StateTick.tick q.state State.Recv_rst; q.segs <- S.empty; let txalert ack_svcd = if not ack_svcd then Lwt.return_unit else Lwt_mvar.put q.tx_ack (Window.ack_seq q.wnd, Window.ack_win q.wnd) in txalert (Window.ack_serviced q.wnd) >>= fun () -> Lwt_mvar.put q.rx_data (None, Some Sequence.zero) end At most one of Syn / Fin / Rst / Psh allowed | No_flags | Syn | Fin | Rst | Psh module Tx (Time:Mirage_time_lwt.S) (Clock:Mirage_clock.MCLOCK) = struct module StateTick = State.Make(Time) module TT = Tcptimer.Make(Time) module TX = Window.Make(Clock) type ('a, 'b) xmit = flags:tx_flags -> wnd:Window.t -> options:Options.t list -> seq:Sequence.t -> Cstruct.t -> ('a, 'b) result Lwt.t type seg = { data: Cstruct.t; flags: tx_flags; seq: Sequence.t; } let len seg = Sequence.of_int ((match seg.flags with | No_flags | Psh | Rst -> 0 | Syn | Fin -> 1) + (Cstruct.len seg.data)) type ('a, 'b) q = { Retransmitted segment queue RX Ack thread that we 've sent one } type t = T: ('a, 'b) q -> t let ack_segment _ _ = () Take any action to the user transmit queue due to this being successfully ACKed successfully ACKed *) URG_TODO : Add sequence number to the Syn_rcvd rexmit to only rexmit most recent rexmit most recent *) let ontimer xmit st segs wnd seq = match State.state st with | State.Syn_rcvd _ | State.Established | State.Fin_wait_1 _ | State.Close_wait | State.Last_ack _ -> begin match peek_opt_l segs with | None -> Lwt.return Tcptimer.Stoptimer | Some rexmit_seg -> match rexmit_seg.seq = seq with | false -> Log.debug (fun fmt -> fmt "PUSHING TIMER - new time=%Lu, new seq=%a" (Window.rto wnd) Sequence.pp rexmit_seg.seq); let ret = Tcptimer.ContinueSetPeriod (Window.rto wnd, rexmit_seg.seq) in Lwt.return ret | true -> if (Window.max_rexmits_done wnd) then ( Log.debug (fun f -> f "Max retransmits reached: %a" Window.pp wnd); Log.info (fun fmt -> fmt "Max retransmits reached for connection - terminating"); StateTick.tick st State.Timeout; Lwt.return Tcptimer.Stoptimer ) else ( let flags = rexmit_seg.flags in Log.debug (fun fmt -> fmt "TCP retransmission triggered by timer! seq = %d" (Sequence.to_int rexmit_seg.seq)); Lwt.async (fun () -> xmit ~flags ~wnd ~options ~seq rexmit_seg.data); Window.alert_fast_rexmit wnd rexmit_seg.seq; Window.backoff_rto wnd; Log.debug (fun fmt -> fmt "Backed off! %a" Window.pp wnd); Log.debug (fun fmt -> fmt "PUSHING TIMER - new time = %Lu, new seq = %a" (Window.rto wnd) Sequence.pp rexmit_seg.seq); let ret = Tcptimer.ContinueSetPeriod (Window.rto wnd, rexmit_seg.seq) in Lwt.return ret ) end | _ -> Lwt.return Tcptimer.Stoptimer let rec clearsegs q ack_remaining segs = match Sequence.(gt ack_remaining zero) with here we return 0l instead of ack_remaining in case the ack was an old packet in the network the ack was an old packet in the network *) | true -> match Lwt_dllist.take_opt_l segs with | None -> Log.debug (fun f -> f "Dubious ACK received"); ack_remaining | Some s -> let seg_len = (len s) in match Sequence.lt ack_remaining seg_len with | true -> Log.debug (fun f -> f "Partial ACK received"); lwt_sequence_add_l s segs; ack_remaining | false -> ack_segment q s; clearsegs q (Sequence.sub ack_remaining seg_len) segs let rto_t q tx_ack = Listen for incoming from the receive queue and ACK segments in our retransmission queue segments in our retransmission queue *) let rec tx_ack_t () = let serviceack dupack ack_len seq win = let partleft = clearsegs q ack_len q.segs in TX.tx_ack q.clock q.wnd (Sequence.sub seq partleft) win; match dupack || Window.fast_rec q.wnd with | true -> q.dup_acks <- q.dup_acks + 1; if q.dup_acks = 3 || (Sequence.to_int32 ack_len > 0l) then begin Window.alert_fast_rexmit q.wnd seq; let rexmit_seg = peek_l q.segs in Log.debug (fun fmt -> fmt "TCP fast retransmission seq=%a, dupack=%a" Sequence.pp rexmit_seg.seq Sequence.pp seq); let { wnd; _ } = q in let flags=rexmit_seg.flags in Lwt.async (fun () -> q.xmit ~flags ~wnd ~options ~seq rexmit_seg.data); Lwt.return_unit end else Lwt.return_unit | false -> q.dup_acks <- 0; Lwt.return_unit in Lwt_mvar.take tx_ack >>= fun _ -> Window.set_ack_serviced q.wnd true; let seq = Window.ack_seq q.wnd in let win = Window.ack_win q.wnd in begin match State.state q.state with | State.Reset -> Note : This is not stricly necessary , as the PCB will be GCed later on . However , it helps removing pressure on the GC . GCed later on. However, it helps removing pressure on the GC. *) reset_seq q.segs; Lwt.return_unit | _ -> let ack_len = Sequence.sub seq (Window.tx_una q.wnd) in let dupacktest () = 0l = Sequence.to_int32 ack_len && Window.tx_wnd_unscaled q.wnd = Int32.of_int win && not (Lwt_dllist.is_empty q.segs) in serviceack (dupacktest ()) ack_len seq win end >>= fun () -> Lwt_mvar.put q.tx_wnd_update win >>= fun () -> tx_ack_t () in tx_ack_t () let create ~clock ~xmit ~wnd ~state ~rx_ack ~tx_ack ~tx_wnd_update = let segs = Lwt_dllist.create () in let dup_acks = 0 in let expire = ontimer xmit state segs wnd in let period_ns = Window.rto wnd in let rexmit_timer = TT.t ~period_ns ~expire in let q = { clock; xmit; wnd; state; rx_ack; segs; tx_wnd_update; rexmit_timer; dup_acks } in let t = rto_t q tx_ack in T q, t Queue a segment for transmission . May block if : - There is no transmit window available . - The wire transmit function blocks . The transmitter should check that the segment size will will not be greater than the transmit window . - There is no transmit window available. - The wire transmit function blocks. The transmitter should check that the segment size will will not be greater than the transmit window. *) let output ?(flags=No_flags) ?(options=[]) (T q) data = Transmit the packet to the wire TODO : deal with transmission soft / hard errors here RFC5461 TODO: deal with transmission soft/hard errors here RFC5461 *) let { wnd; _ } = q in let ack = Window.rx_nxt wnd in let seq = Window.tx_nxt wnd in let seg = { data; flags; seq } in let seq_len = len seg in TX.tx_advance q.clock q.wnd seq_len; let q_rexmit () = match Sequence.(gt seq_len zero) with | false -> Lwt.return_unit | true -> lwt_sequence_add_r seg q.segs; let p = Window.rto q.wnd in TT.start q.rexmit_timer ~p seg.seq in q_rexmit () >>= fun () -> q.xmit ~flags ~wnd ~options ~seq data >>= fun _ -> Inform the RX ack thread that we 've just sent one Lwt_mvar.put q.rx_ack ack end
561b935d8ad00a4de2604548bd4807a695d55919cf5fe70adf9126221268e7e9
mirage/ocaml-tar
tar_gz.ml
* Copyright ( C ) 2022 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (C) 2022 Romain Calascibetta <> * * 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. *) module type READER = sig include Tar.READER val read : in_channel -> Cstruct.t -> int t end module Make (Async : Tar.ASYNC) (Writer : Tar.WRITER with type 'a t = 'a Async.t) (Reader : READER with type 'a t = 'a Async.t) = struct open Async module Gz_writer = struct type out_channel = { mutable gz : Gz.Def.encoder ; ic_buffer : Cstruct.t ; oc_buffer : Cstruct.t ; out_channel : Writer.out_channel } type 'a t = 'a Async.t let really_write ({ gz; oc_buffer; out_channel; _ } as state) cs = let rec until_await gz = match Gz.Def.encode gz with | `Await gz -> state.gz <- gz ; Async.return () | `Flush gz -> let max = Cstruct.length oc_buffer - Gz.Def.dst_rem gz in Writer.really_write out_channel (Cstruct.sub oc_buffer 0 max) >>= fun () -> let { Cstruct.buffer; off= cs_off; len= cs_len; } = oc_buffer in until_await (Gz.Def.dst gz buffer cs_off cs_len) | `End _gz -> assert false in if Cstruct.length cs = 0 then Async.return () else ( let { Cstruct.buffer; off; len; } = cs in let gz = Gz.Def.src gz buffer off len in until_await gz ) end module Gz_reader = struct type in_channel = { mutable gz : Gz.Inf.decoder ; ic_buffer : Cstruct.t ; oc_buffer : Cstruct.t ; in_channel : Reader.in_channel ; mutable pos : int } type 'a t = 'a Async.t let really_read : in_channel -> Cstruct.t -> unit t = fun ({ ic_buffer; oc_buffer; in_channel; _ } as state) res -> let rec until_full_or_end gz res = match Gz.Inf.decode gz with | `Flush gz -> let max = Cstruct.length oc_buffer - Gz.Inf.dst_rem gz in let len = min (Cstruct.length res) max in Cstruct.blit oc_buffer 0 res 0 len ; if len < max then ( state.pos <- len ; state.gz <- gz ; Async.return () ) else until_full_or_end (Gz.Inf.flush gz) (Cstruct.shift res len) | `End gz -> let max = Cstruct.length oc_buffer - Gz.Inf.dst_rem gz in let len = min (Cstruct.length res) max in Cstruct.blit oc_buffer 0 res 0 len ; if Cstruct.length res > len then raise End_of_file else ( state.pos <- len ; state.gz <- gz ; Async.return () ) | `Await gz -> Reader.read in_channel ic_buffer >>= fun len -> let { Cstruct.buffer; off; len= _; } = ic_buffer in let gz = Gz.Inf.src gz buffer off len in until_full_or_end gz res | `Malformed err -> failwith ("gzip: " ^ err) in let max = (Cstruct.length oc_buffer - Gz.Inf.dst_rem state.gz) - state.pos in let len = min (Cstruct.length res) max in Cstruct.blit oc_buffer state.pos res 0 len ; if len < max then ( state.pos <- state.pos + len ; Async.return () ) else ( let res = Cstruct.shift res len in until_full_or_end (Gz.Inf.flush state.gz) res ) let skip : in_channel -> int -> unit t = fun state len -> let oc_buffer = Cstruct.create len in really_read state oc_buffer end module TarGzHeaderWriter = Tar.HeaderWriter (Async) (Gz_writer) module TarGzHeaderReader = Tar.HeaderReader (Async) (Gz_reader) type in_channel = Gz_reader.in_channel let of_in_channel ~internal:oc_buffer in_channel = let { Cstruct.buffer; off; len; } = oc_buffer in let o = Bigarray.Array1.sub buffer off len in { Gz_reader.gz= Gz.Inf.decoder `Manual ~o ; oc_buffer ; ic_buffer= Cstruct.create 0x1000 ; in_channel ; pos= 0 } let get_next_header ?level ic = TarGzHeaderReader.read ?level ic >>= function | Ok hdr -> Async.return hdr | Error `Eof -> raise Tar.Header.End_of_stream let really_read = Gz_reader.really_read let skip = Gz_reader.skip type out_channel = Gz_writer.out_channel let of_out_channel ?bits:(w_bits= 15) ?q:(q_len= 0x1000) ~level ~mtime os out_channel = let ic_buffer = Cstruct.create (4 * 4 * 1024) in let oc_buffer = Cstruct.create 4096 in let gz = let w = De.Lz77.make_window ~bits:w_bits in let q = De.Queue.create q_len in Gz.Def.encoder `Manual `Manual ~mtime os ~q ~w ~level in let { Cstruct.buffer; off; len; } = oc_buffer in let gz = Gz.Def.dst gz buffer off len in { Gz_writer.gz; ic_buffer; oc_buffer; out_channel; } let write_block ?level hdr ({ Gz_writer.ic_buffer= buf; oc_buffer; out_channel; _ } as state) block = TarGzHeaderWriter.write ?level hdr state >>= fun () -> (* XXX(dinosaure): we can refactor this code with [Gz_writer.really_write] but this loop saves and uses [ic_buffer]/[buf] to avoid extra allocations on the case between [string] and [Cstruct.t]. *) let rec deflate (str, off, len) gz = match Gz.Def.encode gz with | `Await gz -> if len = 0 then block () >>= function | None -> state.gz <- gz ; Async.return () | Some str -> deflate (str, 0, String.length str) gz else ( let len' = min len (Cstruct.length buf) in Cstruct.blit_from_string str off buf 0 len' ; let { Cstruct.buffer; off= cs_off; len= _; } = buf in deflate (str, off + len', len - len') (Gz.Def.src gz buffer cs_off len') ) | `Flush gz -> let max = Cstruct.length oc_buffer - Gz.Def.dst_rem gz in Writer.really_write out_channel (Cstruct.sub oc_buffer 0 max) >>= fun () -> let { Cstruct.buffer; off= cs_off; len= cs_len; } = oc_buffer in deflate (str, off, len) (Gz.Def.dst gz buffer cs_off cs_len) | `End _gz -> assert false in deflate ("", 0, 0) state.gz >>= fun () -> Gz_writer.really_write state (Tar.Header.zero_padding hdr) let write_end ({ Gz_writer.oc_buffer; out_channel; _ } as state) = Gz_writer.really_write state Tar.Header.zero_block >>= fun () -> Gz_writer.really_write state Tar.Header.zero_block >>= fun () -> let rec until_end gz = match Gz.Def.encode gz with | `Await _gz -> assert false | `Flush gz | `End gz as flush_or_end -> let max = Cstruct.length oc_buffer - Gz.Def.dst_rem gz in Writer.really_write out_channel (Cstruct.sub oc_buffer 0 max) >>= fun () -> match flush_or_end with | `Flush gz -> let { Cstruct.buffer; off= cs_off; len= cs_len; } = oc_buffer in until_end (Gz.Def.dst gz buffer cs_off cs_len) | `End _gz -> Async.return () in until_end (Gz.Def.src state.gz De.bigstring_empty 0 0) end
null
https://raw.githubusercontent.com/mirage/ocaml-tar/dc427495f9dceadf924c4336d37c7b13c583c264/lib/tar_gz.ml
ocaml
XXX(dinosaure): we can refactor this code with [Gz_writer.really_write] but this loop saves and uses [ic_buffer]/[buf] to avoid extra allocations on the case between [string] and [Cstruct.t].
* Copyright ( C ) 2022 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (C) 2022 Romain Calascibetta <> * * 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. *) module type READER = sig include Tar.READER val read : in_channel -> Cstruct.t -> int t end module Make (Async : Tar.ASYNC) (Writer : Tar.WRITER with type 'a t = 'a Async.t) (Reader : READER with type 'a t = 'a Async.t) = struct open Async module Gz_writer = struct type out_channel = { mutable gz : Gz.Def.encoder ; ic_buffer : Cstruct.t ; oc_buffer : Cstruct.t ; out_channel : Writer.out_channel } type 'a t = 'a Async.t let really_write ({ gz; oc_buffer; out_channel; _ } as state) cs = let rec until_await gz = match Gz.Def.encode gz with | `Await gz -> state.gz <- gz ; Async.return () | `Flush gz -> let max = Cstruct.length oc_buffer - Gz.Def.dst_rem gz in Writer.really_write out_channel (Cstruct.sub oc_buffer 0 max) >>= fun () -> let { Cstruct.buffer; off= cs_off; len= cs_len; } = oc_buffer in until_await (Gz.Def.dst gz buffer cs_off cs_len) | `End _gz -> assert false in if Cstruct.length cs = 0 then Async.return () else ( let { Cstruct.buffer; off; len; } = cs in let gz = Gz.Def.src gz buffer off len in until_await gz ) end module Gz_reader = struct type in_channel = { mutable gz : Gz.Inf.decoder ; ic_buffer : Cstruct.t ; oc_buffer : Cstruct.t ; in_channel : Reader.in_channel ; mutable pos : int } type 'a t = 'a Async.t let really_read : in_channel -> Cstruct.t -> unit t = fun ({ ic_buffer; oc_buffer; in_channel; _ } as state) res -> let rec until_full_or_end gz res = match Gz.Inf.decode gz with | `Flush gz -> let max = Cstruct.length oc_buffer - Gz.Inf.dst_rem gz in let len = min (Cstruct.length res) max in Cstruct.blit oc_buffer 0 res 0 len ; if len < max then ( state.pos <- len ; state.gz <- gz ; Async.return () ) else until_full_or_end (Gz.Inf.flush gz) (Cstruct.shift res len) | `End gz -> let max = Cstruct.length oc_buffer - Gz.Inf.dst_rem gz in let len = min (Cstruct.length res) max in Cstruct.blit oc_buffer 0 res 0 len ; if Cstruct.length res > len then raise End_of_file else ( state.pos <- len ; state.gz <- gz ; Async.return () ) | `Await gz -> Reader.read in_channel ic_buffer >>= fun len -> let { Cstruct.buffer; off; len= _; } = ic_buffer in let gz = Gz.Inf.src gz buffer off len in until_full_or_end gz res | `Malformed err -> failwith ("gzip: " ^ err) in let max = (Cstruct.length oc_buffer - Gz.Inf.dst_rem state.gz) - state.pos in let len = min (Cstruct.length res) max in Cstruct.blit oc_buffer state.pos res 0 len ; if len < max then ( state.pos <- state.pos + len ; Async.return () ) else ( let res = Cstruct.shift res len in until_full_or_end (Gz.Inf.flush state.gz) res ) let skip : in_channel -> int -> unit t = fun state len -> let oc_buffer = Cstruct.create len in really_read state oc_buffer end module TarGzHeaderWriter = Tar.HeaderWriter (Async) (Gz_writer) module TarGzHeaderReader = Tar.HeaderReader (Async) (Gz_reader) type in_channel = Gz_reader.in_channel let of_in_channel ~internal:oc_buffer in_channel = let { Cstruct.buffer; off; len; } = oc_buffer in let o = Bigarray.Array1.sub buffer off len in { Gz_reader.gz= Gz.Inf.decoder `Manual ~o ; oc_buffer ; ic_buffer= Cstruct.create 0x1000 ; in_channel ; pos= 0 } let get_next_header ?level ic = TarGzHeaderReader.read ?level ic >>= function | Ok hdr -> Async.return hdr | Error `Eof -> raise Tar.Header.End_of_stream let really_read = Gz_reader.really_read let skip = Gz_reader.skip type out_channel = Gz_writer.out_channel let of_out_channel ?bits:(w_bits= 15) ?q:(q_len= 0x1000) ~level ~mtime os out_channel = let ic_buffer = Cstruct.create (4 * 4 * 1024) in let oc_buffer = Cstruct.create 4096 in let gz = let w = De.Lz77.make_window ~bits:w_bits in let q = De.Queue.create q_len in Gz.Def.encoder `Manual `Manual ~mtime os ~q ~w ~level in let { Cstruct.buffer; off; len; } = oc_buffer in let gz = Gz.Def.dst gz buffer off len in { Gz_writer.gz; ic_buffer; oc_buffer; out_channel; } let write_block ?level hdr ({ Gz_writer.ic_buffer= buf; oc_buffer; out_channel; _ } as state) block = TarGzHeaderWriter.write ?level hdr state >>= fun () -> let rec deflate (str, off, len) gz = match Gz.Def.encode gz with | `Await gz -> if len = 0 then block () >>= function | None -> state.gz <- gz ; Async.return () | Some str -> deflate (str, 0, String.length str) gz else ( let len' = min len (Cstruct.length buf) in Cstruct.blit_from_string str off buf 0 len' ; let { Cstruct.buffer; off= cs_off; len= _; } = buf in deflate (str, off + len', len - len') (Gz.Def.src gz buffer cs_off len') ) | `Flush gz -> let max = Cstruct.length oc_buffer - Gz.Def.dst_rem gz in Writer.really_write out_channel (Cstruct.sub oc_buffer 0 max) >>= fun () -> let { Cstruct.buffer; off= cs_off; len= cs_len; } = oc_buffer in deflate (str, off, len) (Gz.Def.dst gz buffer cs_off cs_len) | `End _gz -> assert false in deflate ("", 0, 0) state.gz >>= fun () -> Gz_writer.really_write state (Tar.Header.zero_padding hdr) let write_end ({ Gz_writer.oc_buffer; out_channel; _ } as state) = Gz_writer.really_write state Tar.Header.zero_block >>= fun () -> Gz_writer.really_write state Tar.Header.zero_block >>= fun () -> let rec until_end gz = match Gz.Def.encode gz with | `Await _gz -> assert false | `Flush gz | `End gz as flush_or_end -> let max = Cstruct.length oc_buffer - Gz.Def.dst_rem gz in Writer.really_write out_channel (Cstruct.sub oc_buffer 0 max) >>= fun () -> match flush_or_end with | `Flush gz -> let { Cstruct.buffer; off= cs_off; len= cs_len; } = oc_buffer in until_end (Gz.Def.dst gz buffer cs_off cs_len) | `End _gz -> Async.return () in until_end (Gz.Def.src state.gz De.bigstring_empty 0 0) end
e21c7fdb3ea1902669e308b11a85aa36b6294856559a143ffcb07f7945741eb0
danielfm/judgr
default_classifier.clj
(ns judgr.test.classifier.default-classifier (:use [judgr.classifier.default-classifier] [judgr.core] [judgr.test.util] [judgr.settings] [clojure.test]) (:import [judgr.classifier.default_classifier DefaultClassifier])) (def new-settings (update-settings settings [:database :type] :memory [:classifier :type] :default [:extractor :type] :brazilian-text)) (def-fixture empty-db [] (let [classifier (classifier-from new-settings)] (test-body))) (def-fixture classes [classes] (let [new-settings (update-settings new-settings [:classes] classes)] (test-body))) (def-fixture basic-db [] (let [classifier (classifier-from new-settings)] (doall (map (fn [[item class]] (.train! classifier item class)) '(["Você é um diabo, mesmo." :positive] ["Sai de ré, capeta." :negative] ["Vai pro inferno, diabo!" :negative] ["Sua filha é uma diaba, doido." :negative]))) (test-body))) (def-fixture smoothing-factor [factor] (let [new-settings (update-settings new-settings [:classifier :default :smoothing-factor] factor)] (test-body))) (def-fixture unbiased? [unbiased] (let [new-settings (update-settings new-settings [:classifier :default :unbiased?] unbiased)] (test-body))) (def-fixture thresholds [thresholds] (let [new-settings (update-settings new-settings [:classifier :default :threshold?] true [:classifier :default :thresholds] thresholds)] (test-body))) (def-fixture threshold-enabled? [threshold?] (let [new-settings (update-settings new-settings [:classifier :default :threshold?] threshold?)] (test-body))) (deftest ensure-default-classifier (with-fixture empty-db [] (is (instance? DefaultClassifier classifier)))) (deftest calculating-probabilities (testing "with smoothing enabled" (with-fixture smoothing-factor [1] (with-fixture empty-db [] (are [cls total v] (close-to? v (probability cls total 2 new-settings)) 3 100 4/102 0 100 1/102 0 0 1/2 nil 100 1/102)))) (testing "with smoothing disabled" (with-fixture smoothing-factor [0] (with-fixture empty-db [] (are [cls total v] (close-to? v (probability cls total 2 new-settings)) 3 100 3/100 0 100 0 nil 100 0) (testing "without training data" (is (thrown-with-msg? IllegalStateException #"no training data" (probability 10 0 2 new-settings)))))))) (deftest calculating-probability-of-class (testing "with no configured classes" (with-fixture classes [{}] (with-fixture empty-db [] (is (thrown-with-msg? IllegalStateException #"specify \[:classes\] setting" (.class-probability classifier :positive)))))) (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (are [cls v] (close-to? v (.class-probability classifier cls)) :positive 1/3 :negative 2/3)))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (are [cls v] (close-to? v (.class-probability classifier cls)) :positive 1/4 :negative 3/4)))) (testing "unbiased probability" (with-fixture unbiased? [true] (with-fixture basic-db [] (are [cls v] (close-to? v (.class-probability classifier cls)) :positive 1/2 :negative 1/2))))) (deftest calculating-probability-of-feature-given-class (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (are [f cls v] (close-to? v (.feature-probability-given-class classifier f cls)) "diab" :positive 1/6 "diab" :negative 3/14 "filh" :positive 1/12 "filh" :negative 1/7 "else" :positive 1/12)))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (are [f cls v] (close-to? v (.feature-probability-given-class classifier f cls)) "diab" :positive 1 "diab" :negative 2/3 "filh" :positive 0 "filh" :negative 1/3 "else" :positive 0))))) (deftest calculating-probability-of-feature (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (are [f v] (close-to? v (.feature-probability classifier f)) "diab" 4/15 "filh" 2/15 "else" 1/15)))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (are [f v] (close-to? v (.feature-probability classifier f)) "diab" 3/4 "filh" 1/4 "else" 0))))) (deftest calculating-probabilities-of-item (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (let [probs (.probabilities classifier "Filha do diabo.")] (are [cls v] (close-to? v (cls probs)) :negative 225/392 :positive 25/192))))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (let [probs (.probabilities classifier "Filha do diabo.")] (are [cls v] (close-to? v (cls probs)) :negative 8/9 :positive 0)))))) (deftest classifying-item (testing "threshold test enabled, but threshold for class is not specified" (with-fixture smoothing-factor [0] (with-fixture thresholds [{:offensive 2.5 :ok 1.2}] (with-fixture basic-db [] (is (thrown-with-msg? IllegalArgumentException #"specify \[:classifier :default :thresholds\] setting" (.classify classifier "Filha do diabo."))))))) (testing "class with greatest probability passes the threshold test" (with-fixture smoothing-factor [1] (with-fixture thresholds [{:negative 2.5 :positive 1.2}] (with-fixture basic-db [] (are [cls item] (= cls (.classify classifier item)) :negative "Filha do diabo."))))) (testing "unknown item due to failed threshold test" (with-fixture smoothing-factor [1] (with-fixture thresholds [{:negative 50 :positive 1}] (with-fixture basic-db [] (are [cls item] (= cls (.classify classifier item)) :unknown "Filha do diabo."))))) (testing "class with greatest probability without threshold test" (with-fixture smoothing-factor [1] (with-fixture thresholds [{:negative 50 :positive 1}] (with-fixture threshold-enabled? [false] (with-fixture basic-db [] (are [cls item] (= cls (.classify classifier item)) :negative "Filha do diabo."))))))) (deftest training (testing "training an individual item" (with-fixture empty-db [] (.train! classifier "Sai de ré, capeta." :negative) (testing "should add item" (let [item (last (.get-items (.db classifier)))] (is (= 1 (.count-items (.db classifier)))) (are [k v] (= v (k item)) :item "Sai de ré, capeta." :class :negative))) (testing "should add item's features" (is (= 3 (.count-features (.db classifier)))) (are [feature] (not (nil? (.get-feature (.db classifier) feature))) "sai" "ré" "capet")))) (testing "training several items at once" (testing "all belonging to a specific class" (with-fixture empty-db [] (.train-all! classifier ["Sai de ré, capeta.", "Vai pro inferno!"] :negative) (testing "should add items" (is (= 2 (.count-items-of-class (.db classifier) :negative))) (is (zero? (.count-items-of-class (.db classifier) :positive)))))) (testing "items belonging to different classes" (with-fixture empty-db [] (let [items [{:item "Você é um diabo, mesmo." :class :positive} {:item "Sai de ré, capeta." :class :negative}]] (.train-all! classifier items) (testing "should add items" (is (= 1 (.count-items-of-class (.db classifier) :negative))) (is (= 1 (.count-items-of-class (.db classifier) :positive)))))))))
null
https://raw.githubusercontent.com/danielfm/judgr/7b5dfeeb3bee85a42191a7f9e353b25ae2ee9fbd/test/judgr/test/classifier/default_classifier.clj
clojure
(ns judgr.test.classifier.default-classifier (:use [judgr.classifier.default-classifier] [judgr.core] [judgr.test.util] [judgr.settings] [clojure.test]) (:import [judgr.classifier.default_classifier DefaultClassifier])) (def new-settings (update-settings settings [:database :type] :memory [:classifier :type] :default [:extractor :type] :brazilian-text)) (def-fixture empty-db [] (let [classifier (classifier-from new-settings)] (test-body))) (def-fixture classes [classes] (let [new-settings (update-settings new-settings [:classes] classes)] (test-body))) (def-fixture basic-db [] (let [classifier (classifier-from new-settings)] (doall (map (fn [[item class]] (.train! classifier item class)) '(["Você é um diabo, mesmo." :positive] ["Sai de ré, capeta." :negative] ["Vai pro inferno, diabo!" :negative] ["Sua filha é uma diaba, doido." :negative]))) (test-body))) (def-fixture smoothing-factor [factor] (let [new-settings (update-settings new-settings [:classifier :default :smoothing-factor] factor)] (test-body))) (def-fixture unbiased? [unbiased] (let [new-settings (update-settings new-settings [:classifier :default :unbiased?] unbiased)] (test-body))) (def-fixture thresholds [thresholds] (let [new-settings (update-settings new-settings [:classifier :default :threshold?] true [:classifier :default :thresholds] thresholds)] (test-body))) (def-fixture threshold-enabled? [threshold?] (let [new-settings (update-settings new-settings [:classifier :default :threshold?] threshold?)] (test-body))) (deftest ensure-default-classifier (with-fixture empty-db [] (is (instance? DefaultClassifier classifier)))) (deftest calculating-probabilities (testing "with smoothing enabled" (with-fixture smoothing-factor [1] (with-fixture empty-db [] (are [cls total v] (close-to? v (probability cls total 2 new-settings)) 3 100 4/102 0 100 1/102 0 0 1/2 nil 100 1/102)))) (testing "with smoothing disabled" (with-fixture smoothing-factor [0] (with-fixture empty-db [] (are [cls total v] (close-to? v (probability cls total 2 new-settings)) 3 100 3/100 0 100 0 nil 100 0) (testing "without training data" (is (thrown-with-msg? IllegalStateException #"no training data" (probability 10 0 2 new-settings)))))))) (deftest calculating-probability-of-class (testing "with no configured classes" (with-fixture classes [{}] (with-fixture empty-db [] (is (thrown-with-msg? IllegalStateException #"specify \[:classes\] setting" (.class-probability classifier :positive)))))) (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (are [cls v] (close-to? v (.class-probability classifier cls)) :positive 1/3 :negative 2/3)))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (are [cls v] (close-to? v (.class-probability classifier cls)) :positive 1/4 :negative 3/4)))) (testing "unbiased probability" (with-fixture unbiased? [true] (with-fixture basic-db [] (are [cls v] (close-to? v (.class-probability classifier cls)) :positive 1/2 :negative 1/2))))) (deftest calculating-probability-of-feature-given-class (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (are [f cls v] (close-to? v (.feature-probability-given-class classifier f cls)) "diab" :positive 1/6 "diab" :negative 3/14 "filh" :positive 1/12 "filh" :negative 1/7 "else" :positive 1/12)))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (are [f cls v] (close-to? v (.feature-probability-given-class classifier f cls)) "diab" :positive 1 "diab" :negative 2/3 "filh" :positive 0 "filh" :negative 1/3 "else" :positive 0))))) (deftest calculating-probability-of-feature (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (are [f v] (close-to? v (.feature-probability classifier f)) "diab" 4/15 "filh" 2/15 "else" 1/15)))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (are [f v] (close-to? v (.feature-probability classifier f)) "diab" 3/4 "filh" 1/4 "else" 0))))) (deftest calculating-probabilities-of-item (testing "with smoothing" (with-fixture smoothing-factor [1] (with-fixture basic-db [] (let [probs (.probabilities classifier "Filha do diabo.")] (are [cls v] (close-to? v (cls probs)) :negative 225/392 :positive 25/192))))) (testing "without smoothing" (with-fixture smoothing-factor [0] (with-fixture basic-db [] (let [probs (.probabilities classifier "Filha do diabo.")] (are [cls v] (close-to? v (cls probs)) :negative 8/9 :positive 0)))))) (deftest classifying-item (testing "threshold test enabled, but threshold for class is not specified" (with-fixture smoothing-factor [0] (with-fixture thresholds [{:offensive 2.5 :ok 1.2}] (with-fixture basic-db [] (is (thrown-with-msg? IllegalArgumentException #"specify \[:classifier :default :thresholds\] setting" (.classify classifier "Filha do diabo."))))))) (testing "class with greatest probability passes the threshold test" (with-fixture smoothing-factor [1] (with-fixture thresholds [{:negative 2.5 :positive 1.2}] (with-fixture basic-db [] (are [cls item] (= cls (.classify classifier item)) :negative "Filha do diabo."))))) (testing "unknown item due to failed threshold test" (with-fixture smoothing-factor [1] (with-fixture thresholds [{:negative 50 :positive 1}] (with-fixture basic-db [] (are [cls item] (= cls (.classify classifier item)) :unknown "Filha do diabo."))))) (testing "class with greatest probability without threshold test" (with-fixture smoothing-factor [1] (with-fixture thresholds [{:negative 50 :positive 1}] (with-fixture threshold-enabled? [false] (with-fixture basic-db [] (are [cls item] (= cls (.classify classifier item)) :negative "Filha do diabo."))))))) (deftest training (testing "training an individual item" (with-fixture empty-db [] (.train! classifier "Sai de ré, capeta." :negative) (testing "should add item" (let [item (last (.get-items (.db classifier)))] (is (= 1 (.count-items (.db classifier)))) (are [k v] (= v (k item)) :item "Sai de ré, capeta." :class :negative))) (testing "should add item's features" (is (= 3 (.count-features (.db classifier)))) (are [feature] (not (nil? (.get-feature (.db classifier) feature))) "sai" "ré" "capet")))) (testing "training several items at once" (testing "all belonging to a specific class" (with-fixture empty-db [] (.train-all! classifier ["Sai de ré, capeta.", "Vai pro inferno!"] :negative) (testing "should add items" (is (= 2 (.count-items-of-class (.db classifier) :negative))) (is (zero? (.count-items-of-class (.db classifier) :positive)))))) (testing "items belonging to different classes" (with-fixture empty-db [] (let [items [{:item "Você é um diabo, mesmo." :class :positive} {:item "Sai de ré, capeta." :class :negative}]] (.train-all! classifier items) (testing "should add items" (is (= 1 (.count-items-of-class (.db classifier) :negative))) (is (= 1 (.count-items-of-class (.db classifier) :positive)))))))))
33e9018ee6ba79dfd684bf4152c7c459d72caef407848f0f1066e512a8ad9199
ocaml/ocaml-lsp
lev_fiber_threads.ml
open Stdune open Fiber.O let thread_yield () = Thread.yield () open Lev_fiber let%expect_test "create thread" = let f () = let* thread = Thread.create () in let task = match Thread.task thread ~f:(fun () -> print_endline "in thread") with | Ok s -> s | Error _ -> assert false in let+ result = Thread.await task in match result with Error _ -> assert false | Ok () -> Thread.close thread in run f |> Error.ok_exn; [%expect {| in thread |}] let%expect_test "cancellation" = let f () = let* thread = Thread.create () in let keep_running = Atomic.make false in let task = match Thread.task thread ~f:(fun () -> while Atomic.get keep_running do thread_yield () done) with | Ok s -> s | Error _ -> assert false in let to_cancel = match Thread.task thread ~f:(fun () -> assert false) with | Ok task -> task | Error _ -> assert false in let* () = Thread.cancel to_cancel in let* res = Thread.await to_cancel in (match res with | Error `Cancelled -> printfn "Successful cancellation"; Atomic.set keep_running false | Ok _ | Error (`Exn _) -> assert false); let+ res = Thread.await task in (match res with Ok () -> () | Error _ -> assert false); Thread.close thread in run f |> Error.ok_exn; [%expect {| Successful cancellation |}] let%expect_test "deadlock" = let f () = let+ _ = Fiber.never in () in try run f |> Error.ok_exn; assert false with Code_error.E e -> print_endline e.message; [%expect {| Deadlock |}]
null
https://raw.githubusercontent.com/ocaml/ocaml-lsp/226ae3e089ec95e8333bc19c9d113a537443412a/submodules/lev/lev-fiber/test/lev_fiber_threads.ml
ocaml
open Stdune open Fiber.O let thread_yield () = Thread.yield () open Lev_fiber let%expect_test "create thread" = let f () = let* thread = Thread.create () in let task = match Thread.task thread ~f:(fun () -> print_endline "in thread") with | Ok s -> s | Error _ -> assert false in let+ result = Thread.await task in match result with Error _ -> assert false | Ok () -> Thread.close thread in run f |> Error.ok_exn; [%expect {| in thread |}] let%expect_test "cancellation" = let f () = let* thread = Thread.create () in let keep_running = Atomic.make false in let task = match Thread.task thread ~f:(fun () -> while Atomic.get keep_running do thread_yield () done) with | Ok s -> s | Error _ -> assert false in let to_cancel = match Thread.task thread ~f:(fun () -> assert false) with | Ok task -> task | Error _ -> assert false in let* () = Thread.cancel to_cancel in let* res = Thread.await to_cancel in (match res with | Error `Cancelled -> printfn "Successful cancellation"; Atomic.set keep_running false | Ok _ | Error (`Exn _) -> assert false); let+ res = Thread.await task in (match res with Ok () -> () | Error _ -> assert false); Thread.close thread in run f |> Error.ok_exn; [%expect {| Successful cancellation |}] let%expect_test "deadlock" = let f () = let+ _ = Fiber.never in () in try run f |> Error.ok_exn; assert false with Code_error.E e -> print_endline e.message; [%expect {| Deadlock |}]
27f38c360b45228d8d433304870a62398204b5951e16782cc838068f8c3f75b2
askvortsov1/nittany_market
queries.ml
module type Query = sig type t type t_variables module Raw : sig type t type t_variables end val query : string val parse : Raw.t -> t val serialize : t -> Raw.t val serializeVariables : t_variables -> Raw.t_variables val unsafe_fromJson : Yojson.Basic.t -> Raw.t val toJson : Raw.t -> Yojson.Basic.t val variablesToJson : Raw.t_variables -> Yojson.Basic.t end module SerializableQuery (Q : Query) = struct include Q let t_of_sexp s = s |> Sexplib0.Sexp.to_string |> Yojson.Basic.from_string |> Q.unsafe_fromJson |> Q.parse let sexp_of_t t = let t_str = t |> Q.serialize |> Q.toJson |> Yojson.Basic.to_string in Sexplib0.Sexp.Atom t_str let equal a b = Sexplib0.Sexp.equal (sexp_of_t a) (sexp_of_t b) let yojson_of_t_variables vars = vars |> serializeVariables |> Q.variablesToJson |> Yojson.Basic.to_string |> Yojson.Safe.from_string end ;; [%graphql {| fragment CreditCardFields on credit_card { last_four_digits expires card_type } |}] ;; [%graphql {| fragment AddressFields on address { zipcode street_num street_name } |}] ;; [%graphql {| fragment ProductListingFields on product_listing { id title product_name product_description price quantity expires_at is_seller seller { email } category_name reviews { buyer_email description } } |}] ;; [%graphql {| fragment UserFields on user { email buyer_profile { first_name last_name gender age home_address { ...AddressFields } billing_address { ...AddressFields } } seller_profile { account_number routing_number balance } vendor_profile { business_name business_address { ...AddressFields } customer_service_number } credit_cards { ...CreditCardFields } } |}] ;; [%graphql {| query PayloadQuery { payload { current_user { ...UserFields } csrf_token } } |}] ;; [%graphql {| query UsersQuery { users { email } } |}];; [%graphql {| query ProductListingQuery($id: Int!) { product_listing(id: $id) { ...ProductListingFields } } |}] ;; [%graphql {| query MyListingsQuery { my_listings { ...ProductListingFields } } |}] ;; [%graphql {| query CategoryQuery($id: String!) { category(id: $id) { name parent { name } children { name } listings { ...ProductListingFields } } } |}] ;; [%graphql {| query CategoriesQuery { categories { name parent { name } children { name } } } |}] ;; [%graphql {| mutation LoginMutation($email: String!, $password: String!) { login(email: $email, password: $password) } |}] ;; [%graphql {| mutation LogoutMutation { logout } |}];; [%graphql {| mutation ChangePasswordMutation($old_pass: String!, $new_pass: String!) { change_password(old_password: $old_pass, new_password: $new_pass) } |}] ;; [%graphql {| mutation AddListingMutation($title: String!, $product_name: String!, $product_description: String!, $price: String!, $quantity: Int!, $category_name: String!, $expires_at: Int!) { add_listing( title: $title product_name: $product_name product_description: $product_description price: $price quantity: $quantity category: $category_name expires_at: $expires_at ) @ppxAs(type: int) } |}] ;; [%graphql {| mutation UpdateListingMutation($id: Int!, $title: String!, $product_name: String!, $product_description: String!, $price: String!, $quantity: Int!, $category_name: String!, $expires_at: Int!) { update_listing( id: $id title: $title product_name: $product_name product_description: $product_description price: $price quantity: $quantity category: $category_name expires_at: $expires_at ) @ppxAs(type: int) } |}]
null
https://raw.githubusercontent.com/askvortsov1/nittany_market/08ffcad2bb2ead9aaeb85b22b88aa2af879e36ad/frontend/graphql/queries.ml
ocaml
module type Query = sig type t type t_variables module Raw : sig type t type t_variables end val query : string val parse : Raw.t -> t val serialize : t -> Raw.t val serializeVariables : t_variables -> Raw.t_variables val unsafe_fromJson : Yojson.Basic.t -> Raw.t val toJson : Raw.t -> Yojson.Basic.t val variablesToJson : Raw.t_variables -> Yojson.Basic.t end module SerializableQuery (Q : Query) = struct include Q let t_of_sexp s = s |> Sexplib0.Sexp.to_string |> Yojson.Basic.from_string |> Q.unsafe_fromJson |> Q.parse let sexp_of_t t = let t_str = t |> Q.serialize |> Q.toJson |> Yojson.Basic.to_string in Sexplib0.Sexp.Atom t_str let equal a b = Sexplib0.Sexp.equal (sexp_of_t a) (sexp_of_t b) let yojson_of_t_variables vars = vars |> serializeVariables |> Q.variablesToJson |> Yojson.Basic.to_string |> Yojson.Safe.from_string end ;; [%graphql {| fragment CreditCardFields on credit_card { last_four_digits expires card_type } |}] ;; [%graphql {| fragment AddressFields on address { zipcode street_num street_name } |}] ;; [%graphql {| fragment ProductListingFields on product_listing { id title product_name product_description price quantity expires_at is_seller seller { email } category_name reviews { buyer_email description } } |}] ;; [%graphql {| fragment UserFields on user { email buyer_profile { first_name last_name gender age home_address { ...AddressFields } billing_address { ...AddressFields } } seller_profile { account_number routing_number balance } vendor_profile { business_name business_address { ...AddressFields } customer_service_number } credit_cards { ...CreditCardFields } } |}] ;; [%graphql {| query PayloadQuery { payload { current_user { ...UserFields } csrf_token } } |}] ;; [%graphql {| query UsersQuery { users { email } } |}];; [%graphql {| query ProductListingQuery($id: Int!) { product_listing(id: $id) { ...ProductListingFields } } |}] ;; [%graphql {| query MyListingsQuery { my_listings { ...ProductListingFields } } |}] ;; [%graphql {| query CategoryQuery($id: String!) { category(id: $id) { name parent { name } children { name } listings { ...ProductListingFields } } } |}] ;; [%graphql {| query CategoriesQuery { categories { name parent { name } children { name } } } |}] ;; [%graphql {| mutation LoginMutation($email: String!, $password: String!) { login(email: $email, password: $password) } |}] ;; [%graphql {| mutation LogoutMutation { logout } |}];; [%graphql {| mutation ChangePasswordMutation($old_pass: String!, $new_pass: String!) { change_password(old_password: $old_pass, new_password: $new_pass) } |}] ;; [%graphql {| mutation AddListingMutation($title: String!, $product_name: String!, $product_description: String!, $price: String!, $quantity: Int!, $category_name: String!, $expires_at: Int!) { add_listing( title: $title product_name: $product_name product_description: $product_description price: $price quantity: $quantity category: $category_name expires_at: $expires_at ) @ppxAs(type: int) } |}] ;; [%graphql {| mutation UpdateListingMutation($id: Int!, $title: String!, $product_name: String!, $product_description: String!, $price: String!, $quantity: Int!, $category_name: String!, $expires_at: Int!) { update_listing( id: $id title: $title product_name: $product_name product_description: $product_description price: $price quantity: $quantity category: $category_name expires_at: $expires_at ) @ppxAs(type: int) } |}]
d6bc0a28b7b5aa0fb86641788406e97fe8f051c1b9ab19ebd4a518a568077505
strint/sicpAns
2080_generic_arithmetic_system_equal_zero.scm
; ***************operation-and-type table********************** (define op-type-table (make-hash-table)) (define (put op-name data-type procdure) (hash-table/put! op-type-table (list op-name data-type) procdure)) (define (get op-name data-type) (hash-table/get op-type-table (list op-name data-type) #f)) ; ***************operation-and-type table(end)******************* * * * * * * * * * * * * * * * * * * * * * * attech type tag * * * * * * * * * * * * * * * * * * * * (define (attach-tag tag-name contents) (if (eq? tag-name 'scheme-number) contents (cons tag-name contents))) * * * * * * * * * * * * * * * * * * * * * * attech type tag(end ) * * * * * * * * * * * * * * * * * * * * ; **********************rectangular package********************** (define (install-rectangular-package) ; internal procedures 因为scheme中自带real - part等方法 , (define (real-part-x z) (car z)) (define (imag-part-x z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude-x z) (sqrt (+ (square (real-part-x z)) (square (imag-part-x z))))) (define (angle-x z) (atan (imag-part-x z) (real-part-x z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) ;; interface to the rest of the system (define (tag x) (attach-tag 'rectangular x)) (put 'real-part-x '(rectangular) real-part-x) (put 'imag-part-x '(rectangular) imag-part-x) (put 'magnitude-x '(rectangular) magnitude-x) (put 'angle-x '(rectangular) angle-x) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) ; *******************rectangular package(end)********************** ; **********************polar package*************************** (define (install-polar-package) ;; internal procedures (define (magnitude-x z) (car z)) (define (angle-x z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part-x z) (* (magnitude-x z) (cos (angle-x z)))) (define (imag-part-x z) (* (magnitude-x z) (sin (angle-x z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) ;; interface to the rest of the system (define (tag x) (attach-tag 'polar x)) (put 'real-part-x '(polar) real-part-x) (put 'imag-part-x '(polar) imag-part-x) (put 'magnitude-x '(polar) magnitude-x) (put 'angle-x '(polar) angle-x) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) ; *******************polar package(end)*************************** ; ******************complex package******************** (define (install-complex-package) ;; imported procedures from rectangular and polar packages (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) NOTIC ! , add - complex need the methods below (define (real-part-x c) (apply-generic 'real-part-x c)) (define (imag-part-x c) (apply-generic 'imag-part-x c)) (define (magnitude-x c) (apply-generic 'magnitude-x c)) (define (angle-x c) (apply-generic 'angle-x c)) ;; internal procedures (define (add-complex z1 z2) (make-from-real-imag (+ (real-part-x z1) (real-part-x z2)) (+ (imag-part-x z1) (imag-part-x z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part-x z1) (real-part-x z2)) (- (imag-part-x z1) (imag-part-x z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude-x z1) (magnitude-x z2)) (+ (angle-x z1) (angle-x z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude-x z1) (magnitude-x z2)) (- (angle-x z1) (angle-x z2)))) (define (equ?-complex z1 z2) (and (= (real-part-x z1) (real-part-x z2)) (= (imag-part-x z1) (imag-part-x z2)))) (define (=zero?-complex z) (and (= (real-part-x z) 0) (= (imag-part-x z) 0))) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put 'real-part-x '(complex) real-part-x) (put 'imag-part-x '(complex) imag-part-x) (put 'magnitude-x '(complex) magnitude-x) (put 'angle-x '(complex) angle-x) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'equ? '(complex complex) equ?-complex) (put '=zero? '(complex) =zero?-complex) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) ; ******************complex package(end)******************** ; ******************scheme number package******************** (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'equ? '(scheme-number scheme-number) =) (put '=zero? '(scheme-number) (lambda (x) (= x 0))) (put 'make 'scheme-number (lambda (x) (tag x))) 'done) ; ******************scheme number package(end)***************** ; ****************retional number package*************** (define (install-rational-package) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (equ?-rat x y) (and (= (numer x) (numer y)) (= (denom x) (denom y)))) (define (=zero?-rat x) (= (numer x) 0)) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'equ? '(rational rational) equ?-rat) (put '=zero? '(rational) =zero?-rat) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) 'done) ; ****************retional number package(end)*************** ; *****************apply generic***************** (define (type-tag datum) (cond ((pair? datum) (car datum)) ((number? datum) 'scheme-number) (else (error "Bad tagged datum -- TYPE-TAG" datum)))) (define (contents datum) (cond ((pair? datum) (cdr datum)) ((number? datum) datum) (else (error "Bad tagged datum -- CONTENTS" datum)))) (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (error "No method for these types -- APPLY-GENERIC" (list op type-tags)))))) ; *****************apply generic(end)***************** ; *************set generic arithmetic interface************** ; install packages (install-rectangular-package) (install-polar-package) (install-complex-package) (install-scheme-number-package) (install-rational-package) ; define number constructors (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (make-rational n d) ((get 'make 'rational) n d)) ; define number selectors (define (real-part-x c) (apply-generic 'real-part-x c)) (define (imag-part-x c) (apply-generic 'imag-part-x c)) (define (magnitude-x c) (apply-generic 'magnitude-x c)) (define (angle-x c) (apply-generic 'angle-x c)) ; define arithmetic operations (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x)) ; *************set generic arithmetic interface(end)************** ; *************debug******************** ;(trace-both magnitude-x) ;(trace-both apply-generic) ; *************debug(end)*******************
null
https://raw.githubusercontent.com/strint/sicpAns/efc4bdfaab7583117d42f2141d4b3b9e12792b79/2.5.1-2_GenericArithmeticSystem/2080_generic_arithmetic_system_equal_zero.scm
scheme
***************operation-and-type table********************** ***************operation-and-type table(end)******************* **********************rectangular package********************** internal procedures interface to the rest of the system *******************rectangular package(end)********************** **********************polar package*************************** internal procedures interface to the rest of the system *******************polar package(end)*************************** ******************complex package******************** imported procedures from rectangular and polar packages internal procedures interface to rest of the system ******************complex package(end)******************** ******************scheme number package******************** ******************scheme number package(end)***************** ****************retional number package*************** internal procedures interface to rest of the system ****************retional number package(end)*************** *****************apply generic***************** *****************apply generic(end)***************** *************set generic arithmetic interface************** install packages define number constructors define number selectors define arithmetic operations *************set generic arithmetic interface(end)************** *************debug******************** (trace-both magnitude-x) (trace-both apply-generic) *************debug(end)*******************
(define op-type-table (make-hash-table)) (define (put op-name data-type procdure) (hash-table/put! op-type-table (list op-name data-type) procdure)) (define (get op-name data-type) (hash-table/get op-type-table (list op-name data-type) #f)) * * * * * * * * * * * * * * * * * * * * * * attech type tag * * * * * * * * * * * * * * * * * * * * (define (attach-tag tag-name contents) (if (eq? tag-name 'scheme-number) contents (cons tag-name contents))) * * * * * * * * * * * * * * * * * * * * * * attech type tag(end ) * * * * * * * * * * * * * * * * * * * * (define (install-rectangular-package) 因为scheme中自带real - part等方法 , (define (real-part-x z) (car z)) (define (imag-part-x z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude-x z) (sqrt (+ (square (real-part-x z)) (square (imag-part-x z))))) (define (angle-x z) (atan (imag-part-x z) (real-part-x z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) (define (tag x) (attach-tag 'rectangular x)) (put 'real-part-x '(rectangular) real-part-x) (put 'imag-part-x '(rectangular) imag-part-x) (put 'magnitude-x '(rectangular) magnitude-x) (put 'angle-x '(rectangular) angle-x) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (install-polar-package) (define (magnitude-x z) (car z)) (define (angle-x z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part-x z) (* (magnitude-x z) (cos (angle-x z)))) (define (imag-part-x z) (* (magnitude-x z) (sin (angle-x z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) (define (tag x) (attach-tag 'polar x)) (put 'real-part-x '(polar) real-part-x) (put 'imag-part-x '(polar) imag-part-x) (put 'magnitude-x '(polar) magnitude-x) (put 'angle-x '(polar) angle-x) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (install-complex-package) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) NOTIC ! , add - complex need the methods below (define (real-part-x c) (apply-generic 'real-part-x c)) (define (imag-part-x c) (apply-generic 'imag-part-x c)) (define (magnitude-x c) (apply-generic 'magnitude-x c)) (define (angle-x c) (apply-generic 'angle-x c)) (define (add-complex z1 z2) (make-from-real-imag (+ (real-part-x z1) (real-part-x z2)) (+ (imag-part-x z1) (imag-part-x z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part-x z1) (real-part-x z2)) (- (imag-part-x z1) (imag-part-x z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude-x z1) (magnitude-x z2)) (+ (angle-x z1) (angle-x z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude-x z1) (magnitude-x z2)) (- (angle-x z1) (angle-x z2)))) (define (equ?-complex z1 z2) (and (= (real-part-x z1) (real-part-x z2)) (= (imag-part-x z1) (imag-part-x z2)))) (define (=zero?-complex z) (and (= (real-part-x z) 0) (= (imag-part-x z) 0))) (define (tag z) (attach-tag 'complex z)) (put 'real-part-x '(complex) real-part-x) (put 'imag-part-x '(complex) imag-part-x) (put 'magnitude-x '(complex) magnitude-x) (put 'angle-x '(complex) angle-x) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'equ? '(complex complex) equ?-complex) (put '=zero? '(complex) =zero?-complex) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'equ? '(scheme-number scheme-number) =) (put '=zero? '(scheme-number) (lambda (x) (= x 0))) (put 'make 'scheme-number (lambda (x) (tag x))) 'done) (define (install-rational-package) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (equ?-rat x y) (and (= (numer x) (numer y)) (= (denom x) (denom y)))) (define (=zero?-rat x) (= (numer x) 0)) (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'equ? '(rational rational) equ?-rat) (put '=zero? '(rational) =zero?-rat) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) 'done) (define (type-tag datum) (cond ((pair? datum) (car datum)) ((number? datum) 'scheme-number) (else (error "Bad tagged datum -- TYPE-TAG" datum)))) (define (contents datum) (cond ((pair? datum) (cdr datum)) ((number? datum) datum) (else (error "Bad tagged datum -- CONTENTS" datum)))) (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (error "No method for these types -- APPLY-GENERIC" (list op type-tags)))))) (install-rectangular-package) (install-polar-package) (install-complex-package) (install-scheme-number-package) (install-rational-package) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (make-rational n d) ((get 'make 'rational) n d)) (define (real-part-x c) (apply-generic 'real-part-x c)) (define (imag-part-x c) (apply-generic 'imag-part-x c)) (define (magnitude-x c) (apply-generic 'magnitude-x c)) (define (angle-x c) (apply-generic 'angle-x c)) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x))
593fcd8d4e657d78ed7a38d6014bf15a3ac1025cf79a26e785bfcee4a5da9936
rescript-association/genType
EmitType.ml
open GenTypeCommon type flowError = UntypedImport | UnclearType let flowExpectedError flowError = let errorStr = match flowError with | UntypedImport -> "untyped-import" | UnclearType -> "unclear-type" in "// $FlowExpectedError[" ^ errorStr ^ "]: Reason checked type sufficiently\n" let flowTypeAny = flowExpectedError UnclearType ^ "type $any = any;\n" let fileHeader ~config ~sourceFile = let makeHeader ~lines = match lines with | [line] -> "/* " ^ line ^ " */\n" | _ -> "/** \n" ^ (lines |> List.map (fun line -> " * " ^ line) |> String.concat "\n") ^ "\n */\n" in match config.language with | Flow -> ( makeHeader ~lines:["@flow strict"; "@" ^ "generated from " ^ sourceFile; "@nolint"] ^ "/* eslint-disable */\n" ^ match config.emitFlowAny with true -> flowTypeAny | false -> "") | TypeScript -> makeHeader ~lines:["TypeScript file generated from " ^ sourceFile ^ " by genType."] ^ "/* eslint-disable import/first */\n\n" | Untyped -> makeHeader ~lines:["Untyped file generated from " ^ sourceFile ^ " by genType."] ^ "/* eslint-disable */\n" let generatedFilesExtension ~config = match config.generatedFileExtension with | Some s -> (* from .foo.bar to .foo *) Filename.remove_extension s | None -> ".gen" let outputFileSuffix ~config = match config.generatedFileExtension with | Some s when Filename.extension s <> "" (* double extension *) -> s | _ -> ( match config.language with | Flow | Untyped -> generatedFilesExtension ~config ^ ".js" | TypeScript -> generatedFilesExtension ~config ^ ".tsx") let generatedModuleExtension ~config = generatedFilesExtension ~config let shimExtension ~config = match config.language with | Flow -> ".shim.js" | TypeScript -> ".shim.ts" | Untyped -> ".shim.not.used" let interfaceName ~config name = match config.exportInterfaces with true -> "I" ^ name | false -> name let typeAny ~config = ident ~builtin:true (match config.language = Flow with | true -> config.emitFlowAny <- true; "$any" | false -> "any") let typeReactComponent ~config ~propsType = (match config.language = Flow with | true -> "React$ComponentType" | false -> "React.ComponentType") |> ident ~builtin:true ~typeArgs:[propsType] let typeReactContext ~config ~type_ = (match config.language = Flow with | true -> "React$Context" | false -> "React.Context") |> ident ~builtin:true ~typeArgs:[type_] let typeReactElementFlow = ident ~builtin:true "React$Node" let typeReactElementTypeScript = ident ~builtin:true "JSX.Element" let typeReactChildTypeScript = ident ~builtin:true "React.ReactNode" let typeReactElement ~config = match config.language = Flow with | true -> typeReactElementFlow | false -> typeReactElementTypeScript let typeReactChild ~config = match config.language = Flow with | true -> typeReactElementFlow | false -> typeReactChildTypeScript let isTypeReactElement ~config type_ = type_ == typeReactElement ~config let typeReactDOMRef ~config = (match config.language = Flow with | true -> "React$Ref" | false -> "React.Ref") |> ident ~builtin:true ~typeArgs:[mixedOrUnknown ~config] let typeReactEventMouseT ~config = if config.language = Flow then "SyntheticMouseEvent" |> ident ~builtin:true ~typeArgs:[typeAny ~config] else "MouseEvent" |> ident ~builtin:true let reactRefCurrent = "current" let typeReactRef ~type_ = Object ( Open, [ { mutable_ = Mutable; nameJS = reactRefCurrent; nameRE = reactRefCurrent; optional = Mandatory; type_ = Null type_; }; ] ) let isTypeReactRef ~fields = match fields with | [{mutable_ = Mutable; nameJS; nameRE; optional = Mandatory}] -> nameJS == reactRefCurrent && nameJS == nameRE | _ -> false let isTypeFunctionComponent ~config ~fields type_ = type_ |> isTypeReactElement ~config && not (isTypeReactRef ~fields) let rec renderType ~config ?(indent = None) ~typeNameIsInterface ~inFunType type0 = match type0 with | Array (t, arrayKind) -> let typeIsSimple = match t with Ident _ | TypeVar _ -> true | _ -> false in if config.language = TypeScript && typeIsSimple && arrayKind = Mutable then (t |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ "[]" else let arrayName = match arrayKind = Mutable with | true -> "Array" | false -> ( match config.language = Flow with | true -> "$ReadOnlyArray" | false -> "ReadonlyArray") in arrayName ^ "<" ^ (t |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ">" | Function {argTypes = [{aType = Object (closedFlag, fields)}]; retType; typeVars} when retType |> isTypeFunctionComponent ~config ~fields -> let fields = fields |> List.map (fun field -> { field with type_ = field.type_ |> TypeVars.substitute ~f:(fun s -> if typeVars |> List.mem s then Some (typeAny ~config) else None); }) in let componentType = typeReactComponent ~config ~propsType:(Object (closedFlag, fields)) in componentType |> renderType ~config ~indent ~typeNameIsInterface ~inFunType | Function {argTypes; retType; typeVars} -> renderFunType ~config ~indent ~inFunType ~typeNameIsInterface ~typeVars argTypes retType | GroupOfLabeledArgs fields | Object (_, fields) | Record fields -> let indent1 = fields |> Indent.heuristicFields ~indent in let closedFlag = match type0 with Object (closedFlag, _) -> closedFlag | _ -> Closed in fields |> renderFields ~closedFlag ~config ~indent:indent1 ~inFunType ~typeNameIsInterface | Ident {builtin; name; typeArgs} -> let name = name |> sanitizeTypeName in (match (not builtin) && config.exportInterfaces && name |> typeNameIsInterface with | true -> name |> interfaceName ~config | false -> name) ^ EmitText.genericsString ~typeVars: (typeArgs |> List.map (renderType ~config ~indent ~typeNameIsInterface ~inFunType)) | Null type_ -> "(null | " ^ (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ")" | Nullable type_ | Option type_ -> ( let useParens x = match type_ with Function _ | Variant _ -> EmitText.parens [x] | _ -> x in match config.language with | Flow | Untyped -> "?" ^ useParens (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) | TypeScript -> "(null | undefined | " ^ useParens (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ")") | Promise type_ -> "Promise" ^ "<" ^ (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ">" | Tuple innerTypes -> "[" ^ (innerTypes |> List.map (renderType ~config ~indent ~typeNameIsInterface ~inFunType) |> String.concat ", ") ^ "]" | TypeVar s -> s | Variant {inherits; noPayloads; payloads; polymorphic; unboxed} -> let inheritsRendered = inherits |> List.map (fun type_ -> type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) in let noPayloadsRendered = noPayloads |> List.map labelJSToString in let field ~name value = { mutable_ = Mutable; nameJS = name; nameRE = name; optional = Mandatory; type_ = TypeVar value; } in let fields fields = fields |> renderFields ~closedFlag:Closed ~config ~indent ~inFunType ~typeNameIsInterface in let payloadsRendered = payloads |> List.map (fun {case; t = type_} -> let typeRendered = type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType in match unboxed with | true -> typeRendered | false -> [ case |> labelJSToString |> field ~name:(Runtime.jsVariantTag ~polymorphic); typeRendered |> field ~name:(Runtime.jsVariantValue ~polymorphic); ] |> fields) in let rendered = inheritsRendered @ noPayloadsRendered @ payloadsRendered in let indent1 = rendered |> Indent.heuristicVariants ~indent in (match indent1 = None with | true -> "" | false -> Indent.break ~indent:indent1 ^ " ") ^ (rendered |> String.concat ((match indent1 = None with | true -> " " | false -> Indent.break ~indent:indent1) ^ "| ")) and renderField ~config ~indent ~typeNameIsInterface ~inFunType {mutable_; nameJS = lbl; optional; type_} = let optMarker = match optional == Optional with true -> "?" | false -> "" in let mutMarker = match mutable_ = Immutable with | true -> ( match config.language = Flow with true -> "+" | false -> "readonly ") | false -> "" in let lbl = match isJSSafePropertyName lbl with | true -> lbl | false -> EmitText.quotes lbl in Indent.break ~indent ^ mutMarker ^ lbl ^ optMarker ^ ": " ^ (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) and renderFields ~closedFlag ~config ~indent ~inFunType ~typeNameIsInterface fields = let indent1 = indent |> Indent.more in let exact = config.language = Flow && (not config.exportInterfaces) && closedFlag = Closed in let space = match indent = None && fields <> [] with true -> " " | false -> "" in let renderedFields = fields |> List.map (renderField ~config ~indent:indent1 ~typeNameIsInterface ~inFunType) in let dotdotdot = match config.language = Flow && not exact with | true -> [Indent.break ~indent:indent1 ^ "..."] | false -> [] in ((match exact with true -> "{|" | false -> "{") ^ space) ^ String.concat (match config.language = TypeScript with true -> "; " | false -> ", ") (renderedFields @ dotdotdot) ^ Indent.break ~indent ^ space ^ match exact with true -> "|}" | false -> "}" and renderFunType ~config ~indent ~inFunType ~typeNameIsInterface ~typeVars argTypes retType = (match inFunType with true -> "(" | false -> "") ^ EmitText.genericsString ~typeVars ^ "(" ^ String.concat ", " (List.mapi (fun i {aName; aType} -> let parameterName = if config.language = Flow then "" else (match aName = "" with | true -> "_" ^ string_of_int (i + 1) | false -> aName) ^ ":" in parameterName ^ (aType |> renderType ~config ~indent ~typeNameIsInterface ~inFunType:true )) argTypes) ^ ") => " ^ (retType |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ match inFunType with true -> ")" | false -> "" let typeToString ~config ~typeNameIsInterface type_ = type_ |> renderType ~config ~typeNameIsInterface ~inFunType:false let ofType ~config ?(typeNameIsInterface = fun _ -> false) ~type_ s = match config.language = Untyped with | true -> s | false -> s ^ ": " ^ (type_ |> typeToString ~config ~typeNameIsInterface) let emitExportConst_ ~early ?(comment = "") ~config ?(docString = "") ~emitters ~name ~type_ ~typeNameIsInterface line = ((match comment = "" with true -> comment | false -> "// " ^ comment ^ "\n") ^ docString ^ match (config.module_, config.language) with | _, TypeScript | ES6, _ -> "export const " ^ (name |> ofType ~config ~typeNameIsInterface ~type_) ^ " = " ^ line | CommonJS, _ -> "const " ^ (name |> ofType ~config ~typeNameIsInterface ~type_) ^ " = " ^ line ^ ";\nexports." ^ name ^ " = " ^ name) |> (match early with | true -> Emitters.exportEarly | false -> Emitters.export) ~emitters let emitExportConst = emitExportConst_ ~early:false let emitExportConstEarly = emitExportConst_ ~early:true let emitExportDefault ~emitters ~config name = match (config.module_, config.language) with | _, TypeScript | ES6, _ -> "export default " ^ name ^ ";" |> Emitters.export ~emitters | CommonJS, _ -> "exports.default = " ^ name ^ ";" |> Emitters.export ~emitters let emitExportType ?(early = false) ~config ~emitters ~nameAs ~opaque ~type_ ~typeNameIsInterface ~typeVars resolvedTypeName = let export = match early with true -> Emitters.exportEarly | false -> Emitters.export in let typeParamsString = EmitText.genericsString ~typeVars in let isInterface = resolvedTypeName |> typeNameIsInterface in let resolvedTypeName = match config.exportInterfaces && isInterface with | true -> resolvedTypeName |> interfaceName ~config | false -> resolvedTypeName in let exportNameAs = match nameAs with | None -> "" | Some s -> "\nexport type " ^ s ^ typeParamsString ^ " = " ^ resolvedTypeName ^ typeParamsString ^ ";" in match config.language with | Flow -> if config.exportInterfaces && isInterface && not opaque then "export interface " ^ resolvedTypeName ^ typeParamsString ^ " " ^ ((match opaque with true -> mixedOrUnknown ~config | false -> type_) |> typeToString ~config ~typeNameIsInterface) ^ ";" ^ exportNameAs |> export ~emitters else "export" ^ (match opaque with true -> " opaque " | false -> " ") ^ "type " ^ resolvedTypeName ^ typeParamsString ^ " = " ^ ((match opaque with true -> mixedOrUnknown ~config | false -> type_) |> typeToString ~config ~typeNameIsInterface) ^ ";" ^ exportNameAs |> export ~emitters | TypeScript -> if opaque then (* Represent an opaque type as an absract class with a field called 'opaque'. Any type parameters must occur in the type of opaque, so that different instantiations are considered different types. *) let typeOfOpaqueField = match typeVars = [] with | true -> "any" | false -> typeVars |> String.concat " | " in "// tslint:disable-next-line:max-classes-per-file \n" ^ (match String.capitalize_ascii resolvedTypeName <> resolvedTypeName with | true -> "// tslint:disable-next-line:class-name\n" | false -> "") ^ "export abstract class " ^ resolvedTypeName ^ typeParamsString ^ " { protected opaque!: " ^ typeOfOpaqueField ^ " }; /* simulate opaque types */" ^ exportNameAs |> export ~emitters else (if isInterface && config.exportInterfaces then "export interface " ^ resolvedTypeName ^ typeParamsString ^ " " else "// tslint:disable-next-line:interface-over-type-literal\n" ^ "export type " ^ resolvedTypeName ^ typeParamsString ^ " = ") ^ (match type_ with | _ -> type_ |> typeToString ~config ~typeNameIsInterface) ^ ";" ^ exportNameAs |> export ~emitters | Untyped -> emitters let emitImportValueAsEarly ~config ~emitters ~name ~nameAs importPath = let commentBeforeImport = match config.language = Flow with | true -> "// flowlint-next-line nonstrict-import:off\n" | false -> "" in commentBeforeImport ^ "import " ^ (match nameAs with | Some nameAs -> "{" ^ name ^ " as " ^ nameAs ^ "}" | None -> name) ^ " from " ^ "'" ^ (importPath |> ImportPath.emit ~config) ^ "';" |> Emitters.requireEarly ~emitters let emitRequire ~importedValueOrComponent ~early ~emitters ~config ~moduleName ~strict importPath = let commentBeforeRequire = match config.language with | TypeScript -> ( match importedValueOrComponent with | true -> "// tslint:disable-next-line:no-var-requires\n" | false -> "// @ts-ignore: Implicit any on import\n") | Flow -> ( match strict with | true -> ( match early with | true -> "// flowlint-next-line nonstrict-import:off\n" | false -> "") | false -> flowExpectedError UntypedImport) | Untyped -> "" in match config.module_ with | ES6 when not importedValueOrComponent -> let moduleNameString = ModuleName.toString moduleName in (if config.language = TypeScript then let es6ImportModule = moduleNameString ^ "__Es6Import" in commentBeforeRequire ^ "import * as " ^ es6ImportModule ^ " from '" ^ (importPath |> ImportPath.emit ~config) ^ "';\n" ^ "const " ^ moduleNameString ^ ": any = " ^ es6ImportModule ^ ";" else commentBeforeRequire ^ "import * as " ^ moduleNameString ^ " from '" ^ (importPath |> ImportPath.emit ~config) ^ "';") |> (match early with | true -> Emitters.requireEarly | false -> Emitters.require) ~emitters | _ -> commentBeforeRequire ^ "const " ^ ModuleName.toString moduleName ^ " = require('" ^ (importPath |> ImportPath.emit ~config) ^ "');" |> (match early with | true -> Emitters.requireEarly | false -> Emitters.require) ~emitters let require ~early = match early with true -> Emitters.requireEarly | false -> Emitters.require let emitImportReact ~emitters ~config = match config.language with | Flow | Untyped -> emitRequire ~importedValueOrComponent:false ~early:true ~emitters ~config ~moduleName:ModuleName.react ~strict:false ImportPath.react | TypeScript -> "import * as React from 'react';" |> require ~early:true ~emitters let emitImportTypeAs ~emitters ~config ~typeName ~asTypeName ~typeNameIsInterface ~importPath = let typeName = sanitizeTypeName typeName in let asTypeName = match asTypeName with | None -> asTypeName | Some s -> Some (sanitizeTypeName s) in let typeName, asTypeName = match asTypeName with | Some asName -> ( match asName |> typeNameIsInterface with | true -> ( typeName |> interfaceName ~config, Some (asName |> interfaceName ~config) ) | false -> (typeName, asTypeName)) | None -> (typeName, asTypeName) in let importPathString = importPath |> ImportPath.emit ~config in let strictLocalPrefix = match (not (Filename.check_suffix importPathString (generatedFilesExtension ~config))) && config.language = Flow with | true -> "// flowlint-next-line nonstrict-import:off\n" | false -> "" in let importPrefix = if config.language = TypeScript then "import type" else "import" in match config.language with | Flow | TypeScript -> strictLocalPrefix ^ importPrefix ^ " " ^ (match config.language = Flow with true -> "type " | false -> "") ^ "{" ^ typeName ^ (match asTypeName with Some asT -> " as " ^ asT | None -> "") ^ "} from '" ^ importPathString ^ "';" |> Emitters.import ~emitters | Untyped -> emitters let ofTypeAny ~config s = s |> ofType ~config ~type_:(typeAny ~config) let emitTypeCast ~config ~type_ ~typeNameIsInterface s = match config.language with | TypeScript -> s ^ " as " ^ (type_ |> typeToString ~config ~typeNameIsInterface) | Untyped | Flow -> s
null
https://raw.githubusercontent.com/rescript-association/genType/7a82735febf3a3fbff07139c305d7bb92b2e4595/src/EmitType.ml
ocaml
from .foo.bar to .foo double extension Represent an opaque type as an absract class with a field called 'opaque'. Any type parameters must occur in the type of opaque, so that different instantiations are considered different types.
open GenTypeCommon type flowError = UntypedImport | UnclearType let flowExpectedError flowError = let errorStr = match flowError with | UntypedImport -> "untyped-import" | UnclearType -> "unclear-type" in "// $FlowExpectedError[" ^ errorStr ^ "]: Reason checked type sufficiently\n" let flowTypeAny = flowExpectedError UnclearType ^ "type $any = any;\n" let fileHeader ~config ~sourceFile = let makeHeader ~lines = match lines with | [line] -> "/* " ^ line ^ " */\n" | _ -> "/** \n" ^ (lines |> List.map (fun line -> " * " ^ line) |> String.concat "\n") ^ "\n */\n" in match config.language with | Flow -> ( makeHeader ~lines:["@flow strict"; "@" ^ "generated from " ^ sourceFile; "@nolint"] ^ "/* eslint-disable */\n" ^ match config.emitFlowAny with true -> flowTypeAny | false -> "") | TypeScript -> makeHeader ~lines:["TypeScript file generated from " ^ sourceFile ^ " by genType."] ^ "/* eslint-disable import/first */\n\n" | Untyped -> makeHeader ~lines:["Untyped file generated from " ^ sourceFile ^ " by genType."] ^ "/* eslint-disable */\n" let generatedFilesExtension ~config = match config.generatedFileExtension with | Some s -> Filename.remove_extension s | None -> ".gen" let outputFileSuffix ~config = match config.generatedFileExtension with | _ -> ( match config.language with | Flow | Untyped -> generatedFilesExtension ~config ^ ".js" | TypeScript -> generatedFilesExtension ~config ^ ".tsx") let generatedModuleExtension ~config = generatedFilesExtension ~config let shimExtension ~config = match config.language with | Flow -> ".shim.js" | TypeScript -> ".shim.ts" | Untyped -> ".shim.not.used" let interfaceName ~config name = match config.exportInterfaces with true -> "I" ^ name | false -> name let typeAny ~config = ident ~builtin:true (match config.language = Flow with | true -> config.emitFlowAny <- true; "$any" | false -> "any") let typeReactComponent ~config ~propsType = (match config.language = Flow with | true -> "React$ComponentType" | false -> "React.ComponentType") |> ident ~builtin:true ~typeArgs:[propsType] let typeReactContext ~config ~type_ = (match config.language = Flow with | true -> "React$Context" | false -> "React.Context") |> ident ~builtin:true ~typeArgs:[type_] let typeReactElementFlow = ident ~builtin:true "React$Node" let typeReactElementTypeScript = ident ~builtin:true "JSX.Element" let typeReactChildTypeScript = ident ~builtin:true "React.ReactNode" let typeReactElement ~config = match config.language = Flow with | true -> typeReactElementFlow | false -> typeReactElementTypeScript let typeReactChild ~config = match config.language = Flow with | true -> typeReactElementFlow | false -> typeReactChildTypeScript let isTypeReactElement ~config type_ = type_ == typeReactElement ~config let typeReactDOMRef ~config = (match config.language = Flow with | true -> "React$Ref" | false -> "React.Ref") |> ident ~builtin:true ~typeArgs:[mixedOrUnknown ~config] let typeReactEventMouseT ~config = if config.language = Flow then "SyntheticMouseEvent" |> ident ~builtin:true ~typeArgs:[typeAny ~config] else "MouseEvent" |> ident ~builtin:true let reactRefCurrent = "current" let typeReactRef ~type_ = Object ( Open, [ { mutable_ = Mutable; nameJS = reactRefCurrent; nameRE = reactRefCurrent; optional = Mandatory; type_ = Null type_; }; ] ) let isTypeReactRef ~fields = match fields with | [{mutable_ = Mutable; nameJS; nameRE; optional = Mandatory}] -> nameJS == reactRefCurrent && nameJS == nameRE | _ -> false let isTypeFunctionComponent ~config ~fields type_ = type_ |> isTypeReactElement ~config && not (isTypeReactRef ~fields) let rec renderType ~config ?(indent = None) ~typeNameIsInterface ~inFunType type0 = match type0 with | Array (t, arrayKind) -> let typeIsSimple = match t with Ident _ | TypeVar _ -> true | _ -> false in if config.language = TypeScript && typeIsSimple && arrayKind = Mutable then (t |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ "[]" else let arrayName = match arrayKind = Mutable with | true -> "Array" | false -> ( match config.language = Flow with | true -> "$ReadOnlyArray" | false -> "ReadonlyArray") in arrayName ^ "<" ^ (t |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ">" | Function {argTypes = [{aType = Object (closedFlag, fields)}]; retType; typeVars} when retType |> isTypeFunctionComponent ~config ~fields -> let fields = fields |> List.map (fun field -> { field with type_ = field.type_ |> TypeVars.substitute ~f:(fun s -> if typeVars |> List.mem s then Some (typeAny ~config) else None); }) in let componentType = typeReactComponent ~config ~propsType:(Object (closedFlag, fields)) in componentType |> renderType ~config ~indent ~typeNameIsInterface ~inFunType | Function {argTypes; retType; typeVars} -> renderFunType ~config ~indent ~inFunType ~typeNameIsInterface ~typeVars argTypes retType | GroupOfLabeledArgs fields | Object (_, fields) | Record fields -> let indent1 = fields |> Indent.heuristicFields ~indent in let closedFlag = match type0 with Object (closedFlag, _) -> closedFlag | _ -> Closed in fields |> renderFields ~closedFlag ~config ~indent:indent1 ~inFunType ~typeNameIsInterface | Ident {builtin; name; typeArgs} -> let name = name |> sanitizeTypeName in (match (not builtin) && config.exportInterfaces && name |> typeNameIsInterface with | true -> name |> interfaceName ~config | false -> name) ^ EmitText.genericsString ~typeVars: (typeArgs |> List.map (renderType ~config ~indent ~typeNameIsInterface ~inFunType)) | Null type_ -> "(null | " ^ (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ")" | Nullable type_ | Option type_ -> ( let useParens x = match type_ with Function _ | Variant _ -> EmitText.parens [x] | _ -> x in match config.language with | Flow | Untyped -> "?" ^ useParens (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) | TypeScript -> "(null | undefined | " ^ useParens (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ")") | Promise type_ -> "Promise" ^ "<" ^ (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ ">" | Tuple innerTypes -> "[" ^ (innerTypes |> List.map (renderType ~config ~indent ~typeNameIsInterface ~inFunType) |> String.concat ", ") ^ "]" | TypeVar s -> s | Variant {inherits; noPayloads; payloads; polymorphic; unboxed} -> let inheritsRendered = inherits |> List.map (fun type_ -> type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) in let noPayloadsRendered = noPayloads |> List.map labelJSToString in let field ~name value = { mutable_ = Mutable; nameJS = name; nameRE = name; optional = Mandatory; type_ = TypeVar value; } in let fields fields = fields |> renderFields ~closedFlag:Closed ~config ~indent ~inFunType ~typeNameIsInterface in let payloadsRendered = payloads |> List.map (fun {case; t = type_} -> let typeRendered = type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType in match unboxed with | true -> typeRendered | false -> [ case |> labelJSToString |> field ~name:(Runtime.jsVariantTag ~polymorphic); typeRendered |> field ~name:(Runtime.jsVariantValue ~polymorphic); ] |> fields) in let rendered = inheritsRendered @ noPayloadsRendered @ payloadsRendered in let indent1 = rendered |> Indent.heuristicVariants ~indent in (match indent1 = None with | true -> "" | false -> Indent.break ~indent:indent1 ^ " ") ^ (rendered |> String.concat ((match indent1 = None with | true -> " " | false -> Indent.break ~indent:indent1) ^ "| ")) and renderField ~config ~indent ~typeNameIsInterface ~inFunType {mutable_; nameJS = lbl; optional; type_} = let optMarker = match optional == Optional with true -> "?" | false -> "" in let mutMarker = match mutable_ = Immutable with | true -> ( match config.language = Flow with true -> "+" | false -> "readonly ") | false -> "" in let lbl = match isJSSafePropertyName lbl with | true -> lbl | false -> EmitText.quotes lbl in Indent.break ~indent ^ mutMarker ^ lbl ^ optMarker ^ ": " ^ (type_ |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) and renderFields ~closedFlag ~config ~indent ~inFunType ~typeNameIsInterface fields = let indent1 = indent |> Indent.more in let exact = config.language = Flow && (not config.exportInterfaces) && closedFlag = Closed in let space = match indent = None && fields <> [] with true -> " " | false -> "" in let renderedFields = fields |> List.map (renderField ~config ~indent:indent1 ~typeNameIsInterface ~inFunType) in let dotdotdot = match config.language = Flow && not exact with | true -> [Indent.break ~indent:indent1 ^ "..."] | false -> [] in ((match exact with true -> "{|" | false -> "{") ^ space) ^ String.concat (match config.language = TypeScript with true -> "; " | false -> ", ") (renderedFields @ dotdotdot) ^ Indent.break ~indent ^ space ^ match exact with true -> "|}" | false -> "}" and renderFunType ~config ~indent ~inFunType ~typeNameIsInterface ~typeVars argTypes retType = (match inFunType with true -> "(" | false -> "") ^ EmitText.genericsString ~typeVars ^ "(" ^ String.concat ", " (List.mapi (fun i {aName; aType} -> let parameterName = if config.language = Flow then "" else (match aName = "" with | true -> "_" ^ string_of_int (i + 1) | false -> aName) ^ ":" in parameterName ^ (aType |> renderType ~config ~indent ~typeNameIsInterface ~inFunType:true )) argTypes) ^ ") => " ^ (retType |> renderType ~config ~indent ~typeNameIsInterface ~inFunType) ^ match inFunType with true -> ")" | false -> "" let typeToString ~config ~typeNameIsInterface type_ = type_ |> renderType ~config ~typeNameIsInterface ~inFunType:false let ofType ~config ?(typeNameIsInterface = fun _ -> false) ~type_ s = match config.language = Untyped with | true -> s | false -> s ^ ": " ^ (type_ |> typeToString ~config ~typeNameIsInterface) let emitExportConst_ ~early ?(comment = "") ~config ?(docString = "") ~emitters ~name ~type_ ~typeNameIsInterface line = ((match comment = "" with true -> comment | false -> "// " ^ comment ^ "\n") ^ docString ^ match (config.module_, config.language) with | _, TypeScript | ES6, _ -> "export const " ^ (name |> ofType ~config ~typeNameIsInterface ~type_) ^ " = " ^ line | CommonJS, _ -> "const " ^ (name |> ofType ~config ~typeNameIsInterface ~type_) ^ " = " ^ line ^ ";\nexports." ^ name ^ " = " ^ name) |> (match early with | true -> Emitters.exportEarly | false -> Emitters.export) ~emitters let emitExportConst = emitExportConst_ ~early:false let emitExportConstEarly = emitExportConst_ ~early:true let emitExportDefault ~emitters ~config name = match (config.module_, config.language) with | _, TypeScript | ES6, _ -> "export default " ^ name ^ ";" |> Emitters.export ~emitters | CommonJS, _ -> "exports.default = " ^ name ^ ";" |> Emitters.export ~emitters let emitExportType ?(early = false) ~config ~emitters ~nameAs ~opaque ~type_ ~typeNameIsInterface ~typeVars resolvedTypeName = let export = match early with true -> Emitters.exportEarly | false -> Emitters.export in let typeParamsString = EmitText.genericsString ~typeVars in let isInterface = resolvedTypeName |> typeNameIsInterface in let resolvedTypeName = match config.exportInterfaces && isInterface with | true -> resolvedTypeName |> interfaceName ~config | false -> resolvedTypeName in let exportNameAs = match nameAs with | None -> "" | Some s -> "\nexport type " ^ s ^ typeParamsString ^ " = " ^ resolvedTypeName ^ typeParamsString ^ ";" in match config.language with | Flow -> if config.exportInterfaces && isInterface && not opaque then "export interface " ^ resolvedTypeName ^ typeParamsString ^ " " ^ ((match opaque with true -> mixedOrUnknown ~config | false -> type_) |> typeToString ~config ~typeNameIsInterface) ^ ";" ^ exportNameAs |> export ~emitters else "export" ^ (match opaque with true -> " opaque " | false -> " ") ^ "type " ^ resolvedTypeName ^ typeParamsString ^ " = " ^ ((match opaque with true -> mixedOrUnknown ~config | false -> type_) |> typeToString ~config ~typeNameIsInterface) ^ ";" ^ exportNameAs |> export ~emitters | TypeScript -> if opaque then let typeOfOpaqueField = match typeVars = [] with | true -> "any" | false -> typeVars |> String.concat " | " in "// tslint:disable-next-line:max-classes-per-file \n" ^ (match String.capitalize_ascii resolvedTypeName <> resolvedTypeName with | true -> "// tslint:disable-next-line:class-name\n" | false -> "") ^ "export abstract class " ^ resolvedTypeName ^ typeParamsString ^ " { protected opaque!: " ^ typeOfOpaqueField ^ " }; /* simulate opaque types */" ^ exportNameAs |> export ~emitters else (if isInterface && config.exportInterfaces then "export interface " ^ resolvedTypeName ^ typeParamsString ^ " " else "// tslint:disable-next-line:interface-over-type-literal\n" ^ "export type " ^ resolvedTypeName ^ typeParamsString ^ " = ") ^ (match type_ with | _ -> type_ |> typeToString ~config ~typeNameIsInterface) ^ ";" ^ exportNameAs |> export ~emitters | Untyped -> emitters let emitImportValueAsEarly ~config ~emitters ~name ~nameAs importPath = let commentBeforeImport = match config.language = Flow with | true -> "// flowlint-next-line nonstrict-import:off\n" | false -> "" in commentBeforeImport ^ "import " ^ (match nameAs with | Some nameAs -> "{" ^ name ^ " as " ^ nameAs ^ "}" | None -> name) ^ " from " ^ "'" ^ (importPath |> ImportPath.emit ~config) ^ "';" |> Emitters.requireEarly ~emitters let emitRequire ~importedValueOrComponent ~early ~emitters ~config ~moduleName ~strict importPath = let commentBeforeRequire = match config.language with | TypeScript -> ( match importedValueOrComponent with | true -> "// tslint:disable-next-line:no-var-requires\n" | false -> "// @ts-ignore: Implicit any on import\n") | Flow -> ( match strict with | true -> ( match early with | true -> "// flowlint-next-line nonstrict-import:off\n" | false -> "") | false -> flowExpectedError UntypedImport) | Untyped -> "" in match config.module_ with | ES6 when not importedValueOrComponent -> let moduleNameString = ModuleName.toString moduleName in (if config.language = TypeScript then let es6ImportModule = moduleNameString ^ "__Es6Import" in commentBeforeRequire ^ "import * as " ^ es6ImportModule ^ " from '" ^ (importPath |> ImportPath.emit ~config) ^ "';\n" ^ "const " ^ moduleNameString ^ ": any = " ^ es6ImportModule ^ ";" else commentBeforeRequire ^ "import * as " ^ moduleNameString ^ " from '" ^ (importPath |> ImportPath.emit ~config) ^ "';") |> (match early with | true -> Emitters.requireEarly | false -> Emitters.require) ~emitters | _ -> commentBeforeRequire ^ "const " ^ ModuleName.toString moduleName ^ " = require('" ^ (importPath |> ImportPath.emit ~config) ^ "');" |> (match early with | true -> Emitters.requireEarly | false -> Emitters.require) ~emitters let require ~early = match early with true -> Emitters.requireEarly | false -> Emitters.require let emitImportReact ~emitters ~config = match config.language with | Flow | Untyped -> emitRequire ~importedValueOrComponent:false ~early:true ~emitters ~config ~moduleName:ModuleName.react ~strict:false ImportPath.react | TypeScript -> "import * as React from 'react';" |> require ~early:true ~emitters let emitImportTypeAs ~emitters ~config ~typeName ~asTypeName ~typeNameIsInterface ~importPath = let typeName = sanitizeTypeName typeName in let asTypeName = match asTypeName with | None -> asTypeName | Some s -> Some (sanitizeTypeName s) in let typeName, asTypeName = match asTypeName with | Some asName -> ( match asName |> typeNameIsInterface with | true -> ( typeName |> interfaceName ~config, Some (asName |> interfaceName ~config) ) | false -> (typeName, asTypeName)) | None -> (typeName, asTypeName) in let importPathString = importPath |> ImportPath.emit ~config in let strictLocalPrefix = match (not (Filename.check_suffix importPathString (generatedFilesExtension ~config))) && config.language = Flow with | true -> "// flowlint-next-line nonstrict-import:off\n" | false -> "" in let importPrefix = if config.language = TypeScript then "import type" else "import" in match config.language with | Flow | TypeScript -> strictLocalPrefix ^ importPrefix ^ " " ^ (match config.language = Flow with true -> "type " | false -> "") ^ "{" ^ typeName ^ (match asTypeName with Some asT -> " as " ^ asT | None -> "") ^ "} from '" ^ importPathString ^ "';" |> Emitters.import ~emitters | Untyped -> emitters let ofTypeAny ~config s = s |> ofType ~config ~type_:(typeAny ~config) let emitTypeCast ~config ~type_ ~typeNameIsInterface s = match config.language with | TypeScript -> s ^ " as " ^ (type_ |> typeToString ~config ~typeNameIsInterface) | Untyped | Flow -> s
33ad28f50a8cff313f41160d2c2e2a8ef9e193aaef8669b387cac098867e84f8
chansey97/clprosette-miniKanren
radif.rkt
#lang racket (require "../mk.rkt") (provide (all-defined-out)) A terminating 0cfa abstract interpreter via ADI caching based on work by For ADI , see -definitional-interpreters/adi.pdf ' icache ' stands for " inner cache " ;;; ;;; 'ocache' stands for "outer cache" (define (conso x xs r) (== (cons x xs) r)) (define (mapo r xs f) (conde [(== xs '()) (== r '())] [(fresh [y ys z zs] (conso y ys xs) (conso z zs r) (f y z) (mapo zs ys f))])) (define (foldlo f x xs r) (conde [(== xs '()) (== x r)] [(fresh [y ys z] (conso y ys xs) (f x y z) (foldlo f z ys r))])) (define (lookupo x bs out) (conde ;; #f is never bound as a value in the store, ;; we don't have booleans. [(== bs '()) (== out #f)] [(fresh [b br y v] (conso b br bs) (== `(,y ,v) b) (conde [(== y x) (== v out)] [(=/= y x) (lookupo x br out)]))])) ;;; WEB ensure x occurs exactly once in xs (define (ino x xs) (fresh [y ys] (conso y ys xs) (conde [(== y x) (not-ino x ys)] [(=/= y x) (ino x ys)]))) (define (not-ino x xs) (conde [(== xs '())] [(fresh [y ys] (conso y ys xs) (=/= y x) (not-ino x ys))])) (define (includo a b) (conde [(== a '())] [(fresh [a1 ar] (conso a1 ar a) (ino a1 b) (includo ar b))])) (define (set-equivo a b) (fresh () (includo a b) (includo b a))) (define (excludo a b) (fresh [a1 ar] (conso a1 ar a) (conde [(not-ino a1 b)] [(ino a1 b) (excludo ar b)]))) (define (not-set-equivo a b) (conde [(excludo a b)] [(includo a b) (excludo b a)])) (define (set-uniono a b c) (conde [(== a '()) (== b c)] [(fresh [xa ra] (conso xa ra a) (conde [(ino xa b) (set-uniono ra b c)] [(not-ino xa b) (fresh [rc] (conso xa rc c) (set-uniono ra b rc))]))])) (define (set-unionso xs out) (foldlo set-uniono '() xs out)) (define (set-unionso2 xs out) (foldlo (lambda (a b c) (set-uniono a `(,b) c)) '() xs out)) (define (injo i a) (conde [(== -1 i) (== a 'neg)] [(== i 0) (== a 'zer)] [(== 1 i) (== a 'pos)])) (define (combo f u os1 s1 s2 s3) (conde [(== '() s2) (== '() s3)] [(== s1 '()) (fresh [a2 r2] (conso a2 r2 s2) (combo f u os1 os1 r2 s3))] [(fresh [a1 r1 a2 r2 sa sm] (conso a1 r1 s1) (conso a2 r2 s2) (f a1 a2 sa) (combo f u os1 r1 s2 sm) (u sa sm s3))])) (define (combino f s1 s2 s3) (combo f set-uniono s1 s1 s2 s3)) (define (plusdo a b s) (conde [(== a 'neg) (== b 'neg) (== s `(neg))] [(== a 'neg) (== b 'zer) (== s `(neg))] [(== a 'neg) (== b 'pos) (== s `(neg zer pos))] [(== a 'zer) (== b 'neg) (== s `(neg))] [(== a 'zer) (== b 'zer) (== s `(zer))] [(== a 'zer) (== b 'pos) (== s `(pos))] [(== a 'pos) (== b 'neg) (== s `(neg zer pos))] [(== a 'pos) (== b 'zer) (== s `(pos))] [(== a 'pos) (== b 'pos) (== s `(pos))])) (define (plusso s1 s2 s3) (combino plusdo s1 s2 s3)) (define (timeso a b c) (conde [(== a 'zer) (== c 'zer)] [(=/= a 'zer) (== b 'zer) (== c 'zer)] [(== a 'neg) (== b 'neg) (== c 'pos)] [(== a 'neg) (== b 'pos) (== c 'neg)] [(== a 'pos) (== b 'neg) (== c 'neg)] [(== a 'pos) (== b 'pos) (== c 'pos)])) (define (timesdo a b s) (fresh [c] (timeso a b c) (== s `(,c)))) (define (timesso s1 s2 s3) (combino timesdo s1 s2 s3)) (define (lubo a1 a2 a3) (fresh [is1 cs1 is2 cs2 is3 cs3] (== `(aval ,is1 ,cs1) a1) (== `(aval ,is2 ,cs2) a2) (== `(aval ,is3 ,cs3) a3) (set-uniono is1 is2 is3) (set-uniono cs1 cs2 cs3))) (define (replaceo x vo bs out) (fresh [b br y v] (conso b br bs) (== b `(,y ,v)) (conde [(== y x) (conso `(,x ,vo) br out)] [(=/= y x) (fresh [r-out] (conso b r-out out) (replaceo x vo br r-out))]))) (define (add-lubo x v s out) (fresh [l] (lookupo x s l) (conde [(== l #f) (== out `((,x ,v) . ,s))] [(=/= l #f) (fresh [vo] (lubo v l vo) (replaceo x vo s out))]))) (define (add-uniono x v s out) (fresh [l] (lookupo x s l) (conde [(== l #f) (== out `((,x ,v) . ,s))] [(=/= l #f) (fresh [vo] (set-uniono v l vo) (replaceo x vo s out))]))) (define (adivalo-op2 opo e1 e2 s ocache icache out) (fresh [s1 r1] (adivalpto e1 s ocache icache s1) (mapo r1 s1 (lambda (a1 o) (fresh [is1 cs1 sp icachep s2 r2] (== `((aval ,is1 ,cs1) ,sp ,icachep) a1) (adivalpto e2 sp ocache icachep s2) (mapo r2 s2 (lambda (a2 o2) (fresh [is2 cs2 sp2 icachep2 is3] (== `((aval ,is2 ,cs2) ,sp2 ,icachep2) a2) (== `((aval ,is3 ()) ,sp2 ,icachep2) o2) (opo is1 is2 is3)))) (set-unionso2 r2 o)))) (set-unionso r1 out))) (define (adivalo-condo c e r icachep ocache out) (fresh [s] (mapo s r (lambda (a o) (fresh [is cs sp] (== `((aval ,is ,cs) ,sp) a) (conde [(ino c is) (adivalpto e sp ocache icachep o)] [(not-ino c is) (== '() o)])))) (set-unionso s out))) ;; AVal is of the form (aval (Set AInt) (Set (Symbol,Symbol,Exp))) AInt is one of ;; e: Exp ;; s: ASto (Map from symbol to AVal) ocache : Cache ( Map from ( Exp , ASto ) to ( Set ( AVal , ASto ) ) ) icache : Cache out : Set ( AVal , ASto , Cache ) (define (adivalo e s ocache icache out) (conde [(fresh [x l] (== `(var ,x) e) (lookupo x s l) (conde [(== l #f) (== '() out)] [(=/= l #f) (== `((,l ,s ,icache)) out)]))] [(fresh [i a] (== `(int ,i) e) (== `(((aval (,a) ()) ,s ,icache)) out) (injo i a))] [(fresh [e1 e2 s1 s2] (== `(plus ,e1 ,e2) e) (adivalo-op2 plusso e1 e2 s ocache icache out))] [(fresh [e1 e2 s1 s2] (== `(times ,e1 ,e2) e) (adivalo-op2 timesso e1 e2 s ocache icache out))] [(fresh [x y e0] (== `(lam ,x ,y ,e0) e) (== `(((aval () ((,x ,y ,e0))) ,s ,icache)) out))] [(fresh [e1 e2] (== `(app ,e1 ,e2) e) (fresh [r1 s1] (adivalpto e1 s ocache icache s1) (mapo r1 s1 (lambda (a1 o) (fresh [r2 is1 cs1 sp icachep s2] (== `((aval ,is1 ,cs1) ,sp ,icachep) a1) (adivalpto e2 sp ocache icachep s2) (mapo r2 s2 (lambda (a2 o2) (fresh [r3 v2 sp2 icachep2 is3] (== `(,v2 ,sp2 ,icachep2) a2) (mapo r3 cs1 (lambda (a3 o3) (fresh [x y e0 s0 sp2y] (== `(,x ,y ,e0) a3) (add-lubo y v2 sp2 sp2y) (add-lubo x `(aval () ((,x ,y ,e0))) sp2y s0) (adivalpto e0 s0 ocache icachep2 o3)))) (set-unionso r3 o2)))) (set-unionso r2 o)))) (set-unionso r1 out)))] [(fresh [e1 e2 e3] (== `(if0 ,e1 ,e2 ,e3) e) (fresh [r1 icachep s1 s2 s3 si] (adivalpo e1 s ocache icache `(,r1 ,icachep)) (adivalo-condo 'zer e2 r1 icachep ocache s1) (adivalo-condo 'pos e3 r1 icachep ocache s2) (adivalo-condo 'neg e3 r1 icachep ocache s3) (set-uniono s2 s3 si) (set-uniono s1 si out)))])) ;; out: (Set (AVal,ASto),Cache) (define (adivalwo e s ocache icache out) (fresh [res r c r-out c-out] (== `(,r-out ,c-out) out) (adivalo e s ocache icache res) (mapo r res (lambda (a o) (fresh [x y z] (== a `(,x ,y ,z)) (== o `(,x ,y))))) (mapo c res (lambda (a o) (fresh [x y z] (== a `(,x ,y ,z)) (== o z)))) (set-unionso2 r r-out) (set-unionso c c-out))) ;; out: (Set (Aval,Asto),Cache) (define (adivalpo e s ocache icache out) (fresh [r] (lookupo `(,e ,s) icache r) (conde [(=/= r #f) (== `(,r ,icache) out)] [(== r #f) (fresh [r0 o icachep r icachepp icacheppp] (== `(,r ,icacheppp) out) (conde [(== o #f) (== r0 '())] [(=/= o #f) (== r0 o)]) (lookupo `(,e ,s) ocache o) (add-uniono `(,e ,s) r0 icache icachep) (adivalwo e s ocache icachep `(,r ,icachepp)) (add-uniono `(,e ,s) r icachepp icacheppp))]))) out : Set ( Aval , ASto , Cache ) (define (adivalpto e s ocache icache out) (fresh [r icachep] (adivalpo e s ocache icache `(,r ,icachep)) (mapo out r (lambda (a o) (fresh [vs sp] (== `(,vs ,sp) a) (== `(,vs ,sp ,icachep) o)))))) ;; out: Cache (define (lfppo e cache out) (fresh [r cachep] (adivalpo e '() cache '() `(,r ,cachep)) (conde [(== out cache) (set-equivo cache cachep)] [(not-set-equivo cache cachep) (lfppo e cachep out)]))) ;; out: Cache (define (lfpo e out) (lfppo e '() out)) out : Set ( AVal , Asto ) (define (analyzeo e out) (fresh [cache] (lfpo e cache) (lookupo `(,e ()) cache out)))
null
https://raw.githubusercontent.com/chansey97/clprosette-miniKanren/d322f688312fa9481b22c2729018d383f493cb82/clprosette-miniKanren/tests/radif.rkt
racket
'ocache' stands for "outer cache" #f is never bound as a value in the store, we don't have booleans. WEB ensure x occurs exactly once in xs AVal is of the form (aval (Set AInt) (Set (Symbol,Symbol,Exp))) e: Exp s: ASto (Map from symbol to AVal) out: (Set (AVal,ASto),Cache) out: (Set (Aval,Asto),Cache) out: Cache out: Cache
#lang racket (require "../mk.rkt") (provide (all-defined-out)) A terminating 0cfa abstract interpreter via ADI caching based on work by For ADI , see -definitional-interpreters/adi.pdf ' icache ' stands for " inner cache " (define (conso x xs r) (== (cons x xs) r)) (define (mapo r xs f) (conde [(== xs '()) (== r '())] [(fresh [y ys z zs] (conso y ys xs) (conso z zs r) (f y z) (mapo zs ys f))])) (define (foldlo f x xs r) (conde [(== xs '()) (== x r)] [(fresh [y ys z] (conso y ys xs) (f x y z) (foldlo f z ys r))])) (define (lookupo x bs out) (conde [(== bs '()) (== out #f)] [(fresh [b br y v] (conso b br bs) (== `(,y ,v) b) (conde [(== y x) (== v out)] [(=/= y x) (lookupo x br out)]))])) (define (ino x xs) (fresh [y ys] (conso y ys xs) (conde [(== y x) (not-ino x ys)] [(=/= y x) (ino x ys)]))) (define (not-ino x xs) (conde [(== xs '())] [(fresh [y ys] (conso y ys xs) (=/= y x) (not-ino x ys))])) (define (includo a b) (conde [(== a '())] [(fresh [a1 ar] (conso a1 ar a) (ino a1 b) (includo ar b))])) (define (set-equivo a b) (fresh () (includo a b) (includo b a))) (define (excludo a b) (fresh [a1 ar] (conso a1 ar a) (conde [(not-ino a1 b)] [(ino a1 b) (excludo ar b)]))) (define (not-set-equivo a b) (conde [(excludo a b)] [(includo a b) (excludo b a)])) (define (set-uniono a b c) (conde [(== a '()) (== b c)] [(fresh [xa ra] (conso xa ra a) (conde [(ino xa b) (set-uniono ra b c)] [(not-ino xa b) (fresh [rc] (conso xa rc c) (set-uniono ra b rc))]))])) (define (set-unionso xs out) (foldlo set-uniono '() xs out)) (define (set-unionso2 xs out) (foldlo (lambda (a b c) (set-uniono a `(,b) c)) '() xs out)) (define (injo i a) (conde [(== -1 i) (== a 'neg)] [(== i 0) (== a 'zer)] [(== 1 i) (== a 'pos)])) (define (combo f u os1 s1 s2 s3) (conde [(== '() s2) (== '() s3)] [(== s1 '()) (fresh [a2 r2] (conso a2 r2 s2) (combo f u os1 os1 r2 s3))] [(fresh [a1 r1 a2 r2 sa sm] (conso a1 r1 s1) (conso a2 r2 s2) (f a1 a2 sa) (combo f u os1 r1 s2 sm) (u sa sm s3))])) (define (combino f s1 s2 s3) (combo f set-uniono s1 s1 s2 s3)) (define (plusdo a b s) (conde [(== a 'neg) (== b 'neg) (== s `(neg))] [(== a 'neg) (== b 'zer) (== s `(neg))] [(== a 'neg) (== b 'pos) (== s `(neg zer pos))] [(== a 'zer) (== b 'neg) (== s `(neg))] [(== a 'zer) (== b 'zer) (== s `(zer))] [(== a 'zer) (== b 'pos) (== s `(pos))] [(== a 'pos) (== b 'neg) (== s `(neg zer pos))] [(== a 'pos) (== b 'zer) (== s `(pos))] [(== a 'pos) (== b 'pos) (== s `(pos))])) (define (plusso s1 s2 s3) (combino plusdo s1 s2 s3)) (define (timeso a b c) (conde [(== a 'zer) (== c 'zer)] [(=/= a 'zer) (== b 'zer) (== c 'zer)] [(== a 'neg) (== b 'neg) (== c 'pos)] [(== a 'neg) (== b 'pos) (== c 'neg)] [(== a 'pos) (== b 'neg) (== c 'neg)] [(== a 'pos) (== b 'pos) (== c 'pos)])) (define (timesdo a b s) (fresh [c] (timeso a b c) (== s `(,c)))) (define (timesso s1 s2 s3) (combino timesdo s1 s2 s3)) (define (lubo a1 a2 a3) (fresh [is1 cs1 is2 cs2 is3 cs3] (== `(aval ,is1 ,cs1) a1) (== `(aval ,is2 ,cs2) a2) (== `(aval ,is3 ,cs3) a3) (set-uniono is1 is2 is3) (set-uniono cs1 cs2 cs3))) (define (replaceo x vo bs out) (fresh [b br y v] (conso b br bs) (== b `(,y ,v)) (conde [(== y x) (conso `(,x ,vo) br out)] [(=/= y x) (fresh [r-out] (conso b r-out out) (replaceo x vo br r-out))]))) (define (add-lubo x v s out) (fresh [l] (lookupo x s l) (conde [(== l #f) (== out `((,x ,v) . ,s))] [(=/= l #f) (fresh [vo] (lubo v l vo) (replaceo x vo s out))]))) (define (add-uniono x v s out) (fresh [l] (lookupo x s l) (conde [(== l #f) (== out `((,x ,v) . ,s))] [(=/= l #f) (fresh [vo] (set-uniono v l vo) (replaceo x vo s out))]))) (define (adivalo-op2 opo e1 e2 s ocache icache out) (fresh [s1 r1] (adivalpto e1 s ocache icache s1) (mapo r1 s1 (lambda (a1 o) (fresh [is1 cs1 sp icachep s2 r2] (== `((aval ,is1 ,cs1) ,sp ,icachep) a1) (adivalpto e2 sp ocache icachep s2) (mapo r2 s2 (lambda (a2 o2) (fresh [is2 cs2 sp2 icachep2 is3] (== `((aval ,is2 ,cs2) ,sp2 ,icachep2) a2) (== `((aval ,is3 ()) ,sp2 ,icachep2) o2) (opo is1 is2 is3)))) (set-unionso2 r2 o)))) (set-unionso r1 out))) (define (adivalo-condo c e r icachep ocache out) (fresh [s] (mapo s r (lambda (a o) (fresh [is cs sp] (== `((aval ,is ,cs) ,sp) a) (conde [(ino c is) (adivalpto e sp ocache icachep o)] [(not-ino c is) (== '() o)])))) (set-unionso s out))) AInt is one of ocache : Cache ( Map from ( Exp , ASto ) to ( Set ( AVal , ASto ) ) ) icache : Cache out : Set ( AVal , ASto , Cache ) (define (adivalo e s ocache icache out) (conde [(fresh [x l] (== `(var ,x) e) (lookupo x s l) (conde [(== l #f) (== '() out)] [(=/= l #f) (== `((,l ,s ,icache)) out)]))] [(fresh [i a] (== `(int ,i) e) (== `(((aval (,a) ()) ,s ,icache)) out) (injo i a))] [(fresh [e1 e2 s1 s2] (== `(plus ,e1 ,e2) e) (adivalo-op2 plusso e1 e2 s ocache icache out))] [(fresh [e1 e2 s1 s2] (== `(times ,e1 ,e2) e) (adivalo-op2 timesso e1 e2 s ocache icache out))] [(fresh [x y e0] (== `(lam ,x ,y ,e0) e) (== `(((aval () ((,x ,y ,e0))) ,s ,icache)) out))] [(fresh [e1 e2] (== `(app ,e1 ,e2) e) (fresh [r1 s1] (adivalpto e1 s ocache icache s1) (mapo r1 s1 (lambda (a1 o) (fresh [r2 is1 cs1 sp icachep s2] (== `((aval ,is1 ,cs1) ,sp ,icachep) a1) (adivalpto e2 sp ocache icachep s2) (mapo r2 s2 (lambda (a2 o2) (fresh [r3 v2 sp2 icachep2 is3] (== `(,v2 ,sp2 ,icachep2) a2) (mapo r3 cs1 (lambda (a3 o3) (fresh [x y e0 s0 sp2y] (== `(,x ,y ,e0) a3) (add-lubo y v2 sp2 sp2y) (add-lubo x `(aval () ((,x ,y ,e0))) sp2y s0) (adivalpto e0 s0 ocache icachep2 o3)))) (set-unionso r3 o2)))) (set-unionso r2 o)))) (set-unionso r1 out)))] [(fresh [e1 e2 e3] (== `(if0 ,e1 ,e2 ,e3) e) (fresh [r1 icachep s1 s2 s3 si] (adivalpo e1 s ocache icache `(,r1 ,icachep)) (adivalo-condo 'zer e2 r1 icachep ocache s1) (adivalo-condo 'pos e3 r1 icachep ocache s2) (adivalo-condo 'neg e3 r1 icachep ocache s3) (set-uniono s2 s3 si) (set-uniono s1 si out)))])) (define (adivalwo e s ocache icache out) (fresh [res r c r-out c-out] (== `(,r-out ,c-out) out) (adivalo e s ocache icache res) (mapo r res (lambda (a o) (fresh [x y z] (== a `(,x ,y ,z)) (== o `(,x ,y))))) (mapo c res (lambda (a o) (fresh [x y z] (== a `(,x ,y ,z)) (== o z)))) (set-unionso2 r r-out) (set-unionso c c-out))) (define (adivalpo e s ocache icache out) (fresh [r] (lookupo `(,e ,s) icache r) (conde [(=/= r #f) (== `(,r ,icache) out)] [(== r #f) (fresh [r0 o icachep r icachepp icacheppp] (== `(,r ,icacheppp) out) (conde [(== o #f) (== r0 '())] [(=/= o #f) (== r0 o)]) (lookupo `(,e ,s) ocache o) (add-uniono `(,e ,s) r0 icache icachep) (adivalwo e s ocache icachep `(,r ,icachepp)) (add-uniono `(,e ,s) r icachepp icacheppp))]))) out : Set ( Aval , ASto , Cache ) (define (adivalpto e s ocache icache out) (fresh [r icachep] (adivalpo e s ocache icache `(,r ,icachep)) (mapo out r (lambda (a o) (fresh [vs sp] (== `(,vs ,sp) a) (== `(,vs ,sp ,icachep) o)))))) (define (lfppo e cache out) (fresh [r cachep] (adivalpo e '() cache '() `(,r ,cachep)) (conde [(== out cache) (set-equivo cache cachep)] [(not-set-equivo cache cachep) (lfppo e cachep out)]))) (define (lfpo e out) (lfppo e '() out)) out : Set ( AVal , Asto ) (define (analyzeo e out) (fresh [cache] (lfpo e cache) (lookupo `(,e ()) cache out)))
ddfe5a2c6f05eec73a829f066026e3313c4fa971ade1b6968ce7c4b05c899ea6
sdiehl/elliptic-curve
E521.hs
module Data.Curve.Edwards.E521 ( module Data.Curve.Edwards , Point(..) -- * E521 curve , module Data.Curve.Edwards.E521 ) where import Protolude import Data.Field.Galois import GHC.Natural (Natural) import Data.Curve.Edwards ------------------------------------------------------------------------------- -- Types ------------------------------------------------------------------------------- -- | E521 curve. data E521 | Field of points of E521 curve . type Fq = Prime Q type Q = 0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff | Field of coefficients of E521 curve . type Fr = Prime R type R = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd15b6c64746fc85f736b8af5e7ec53f04fbd8c4569a8f1f4540ea2435f5180d6b E521 curve is an curve . instance Curve 'Edwards c E521 Fq Fr => ECurve c E521 Fq Fr where a_ = const _a {-# INLINABLE a_ #-} d_ = const _d {-# INLINABLE d_ #-} h_ = const _h {-# INLINABLE h_ #-} q_ = const _q # INLINABLE q _ # r_ = const _r # INLINABLE r _ # | Affine E521 curve point . type PA = EAPoint E521 Fq Fr Affine E521 curve is an Edwards affine curve . instance EACurve E521 Fq Fr where gA_ = gA # INLINABLE gA _ # -- | Projective E521 point. type PP = EPPoint E521 Fq Fr Projective E521 curve is an projective curve . instance EPCurve E521 Fq Fr where gP_ = gP # INLINABLE gP _ # ------------------------------------------------------------------------------- -- Parameters ------------------------------------------------------------------------------- | Coefficient @A@ of E521 curve . _a :: Fq _a = 0x1 # INLINABLE _ a # | Coefficient @D@ of E521 curve . _d :: Fq _d = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa4331 {-# INLINABLE _d #-} | Cofactor of E521 curve . _h :: Natural _h = 0x4 # INLINABLE _ h # | Characteristic of E521 curve . _q :: Natural _q = 0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff {-# INLINABLE _q #-} | Order of E521 curve . _r :: Natural _r = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd15b6c64746fc85f736b8af5e7ec53f04fbd8c4569a8f1f4540ea2435f5180d6b {-# INLINABLE _r #-} | Coordinate @X@ of E521 curve . _x :: Fq _x = 0x752cb45c48648b189df90cb2296b2878a3bfd9f42fc6c818ec8bf3c9c0c6203913f6ecc5ccc72434b1ae949d568fc99c6059d0fb13364838aa302a940a2f19ba6c {-# INLINABLE _x #-} | Coordinate @Y@ of E521 curve . _y :: Fq _y = 0xc {-# INLINABLE _y #-} | Generator of affine E521 curve . gA :: PA gA = A _x _y # INLINABLE gA # | Generator of projective E521 curve . gP :: PP gP = P _x _y 1 # INLINABLE gP #
null
https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Edwards/E521.hs
haskell
* E521 curve ----------------------------------------------------------------------------- Types ----------------------------------------------------------------------------- | E521 curve. # INLINABLE a_ # # INLINABLE d_ # # INLINABLE h_ # | Projective E521 point. ----------------------------------------------------------------------------- Parameters ----------------------------------------------------------------------------- # INLINABLE _d # # INLINABLE _q # # INLINABLE _r # # INLINABLE _x # # INLINABLE _y #
module Data.Curve.Edwards.E521 ( module Data.Curve.Edwards , Point(..) , module Data.Curve.Edwards.E521 ) where import Protolude import Data.Field.Galois import GHC.Natural (Natural) import Data.Curve.Edwards data E521 | Field of points of E521 curve . type Fq = Prime Q type Q = 0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff | Field of coefficients of E521 curve . type Fr = Prime R type R = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd15b6c64746fc85f736b8af5e7ec53f04fbd8c4569a8f1f4540ea2435f5180d6b E521 curve is an curve . instance Curve 'Edwards c E521 Fq Fr => ECurve c E521 Fq Fr where a_ = const _a d_ = const _d h_ = const _h q_ = const _q # INLINABLE q _ # r_ = const _r # INLINABLE r _ # | Affine E521 curve point . type PA = EAPoint E521 Fq Fr Affine E521 curve is an Edwards affine curve . instance EACurve E521 Fq Fr where gA_ = gA # INLINABLE gA _ # type PP = EPPoint E521 Fq Fr Projective E521 curve is an projective curve . instance EPCurve E521 Fq Fr where gP_ = gP # INLINABLE gP _ # | Coefficient @A@ of E521 curve . _a :: Fq _a = 0x1 # INLINABLE _ a # | Coefficient @D@ of E521 curve . _d :: Fq _d = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa4331 | Cofactor of E521 curve . _h :: Natural _h = 0x4 # INLINABLE _ h # | Characteristic of E521 curve . _q :: Natural _q = 0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff | Order of E521 curve . _r :: Natural _r = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd15b6c64746fc85f736b8af5e7ec53f04fbd8c4569a8f1f4540ea2435f5180d6b | Coordinate @X@ of E521 curve . _x :: Fq _x = 0x752cb45c48648b189df90cb2296b2878a3bfd9f42fc6c818ec8bf3c9c0c6203913f6ecc5ccc72434b1ae949d568fc99c6059d0fb13364838aa302a940a2f19ba6c | Coordinate @Y@ of E521 curve . _y :: Fq _y = 0xc | Generator of affine E521 curve . gA :: PA gA = A _x _y # INLINABLE gA # | Generator of projective E521 curve . gP :: PP gP = P _x _y 1 # INLINABLE gP #
75fad905f6468cb0cb1d41c4289f44b355ae6c1aa2810cb48f5e8ad4c84d6586
fulcro-legacy/semantic-ui-wrapper
ui_transitionable_portal.cljs
(ns fulcrologic.semantic-ui.addons.transitionableportal.ui-transitionable-portal (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/addons/TransitionablePortal/TransitionablePortal" :default TransitionablePortal])) (def ui-transitionable-portal "A sugar for `Portal` and `Transition`. Props: - children (node): Primary content. - onClose (func): Called when a close event happens. - onHide (func): Callback on each transition that changes visibility to hidden. - onOpen (func): Called when an open event happens. - onStart (func): Callback on animation start. - open (bool): Controls whether or not the portal is displayed. - transition (object): Transition props." (h/factory-apply TransitionablePortal))
null
https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/addons/transitionableportal/ui_transitionable_portal.cljs
clojure
(ns fulcrologic.semantic-ui.addons.transitionableportal.ui-transitionable-portal (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/addons/TransitionablePortal/TransitionablePortal" :default TransitionablePortal])) (def ui-transitionable-portal "A sugar for `Portal` and `Transition`. Props: - children (node): Primary content. - onClose (func): Called when a close event happens. - onHide (func): Callback on each transition that changes visibility to hidden. - onOpen (func): Called when an open event happens. - onStart (func): Callback on animation start. - open (bool): Controls whether or not the portal is displayed. - transition (object): Transition props." (h/factory-apply TransitionablePortal))
e68bceda9faa47f0d565679610e52178821aa30f93d0eae4c671821750389651
namin/pink
matcher-tests.scm
(load "base.scm") (load "pink.scm") (load "matcher.scm") (load "test-check.scm") (test "matcher-1" (evalms (list `(let maybe-lift (lambda _ e e) ,matcher-src) `(_ * a _ * done) `(b a done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'yes ) (test "matcher-2" (evalms (list `(let maybe-lift (lambda _ e e) ,matcher-src) `(_ * a _ * done) `(b b done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'no ) (test "matcher-c-1" (let ((c (reifyc (lambda () (evalms (list `(let maybe-lift (lambda _ e (lift e)) ,matcher-src) `(_ * a _ * done)) `(((,pink-eval-exp2 (var 0)) nil-env) (var 1))))))) (run (lambda () (let ((v (evalms '() c))) (evalms (list `(b a done) v) `((var 1) (var 0))))))) 'yes ) (test "matcher-c-2" (let ((c (reifyc (lambda () (evalms (list `(let maybe-lift (lambda _ e (lift e)) ,matcher-src) `(_ * a _ * done)) `(((,pink-eval-exp2 (var 0)) nil-env) (var 1))))))) (run (lambda () (let ((v (evalms '() c))) (evalms (list `(b b done) v) `((var 1) (var 0))))))) 'no ) (test "matcher-trace-1" (evalms (list `(delta-eval (lambda _ tie (lambda _ eval (lambda ev l (lambda _ exp (lambda _ env (if (symbol? exp) (let _ (log 0 exp) (log 0 (((eval l) exp) env))) ((((tie ev) l) exp) env))))))) (let maybe-lift (lambda _ e e) ,matcher-src)) `(_ * a _ * done) `(b a done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'yes ) (test "matcher-trace-2" (evalms (list `(delta-eval (lambda _ tie (lambda _ eval (lambda ev l (lambda _ exp (lambda _ env (if (symbol? exp) (let _ (log 0 exp) (log 0 (((eval l) exp) env))) ((((tie ev) l) exp) env))))))) (let maybe-lift (lambda _ e e) ,matcher-src)) `(_ * a _ * done) `(b b done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'no ) (define tracing-matcher-transformer (lambda (r) (let ((c (reifyc (lambda () (evalms (list `(delta-eval (lambda _ tie (lambda _ eval (lambda ev l (lambda _ exp (lambda _ env (if (symbol? exp) (let _ (log (lift 0) exp) (let r (((eval l) exp) env) (let _ (log (lift 0) r) r))) ((((tie ev) l) exp) env))))))) (let maybe-lift (lambda _ e (lift e)) ,matcher-src)) r) `(((,pink-eval-exp2 (var 0)) nil-env) (var 1))))))) (run (lambda () (let ((v (evalms '() c))) v)))))) (test "matcher-trace-c-1" (evalms (list `(b a done) (tracing-matcher-transformer '(_ * a _ * done))) `((var 1) (var 0))) 'yes ) (test "matcher-trace-c-2" (evalms (list `(b b done) (tracing-matcher-transformer '(_ * a _ * done))) `((var 1) (var 0))) 'no )
null
https://raw.githubusercontent.com/namin/pink/ace6697dacbf0d08cb044e2cfe5b8434044b9572/matcher-tests.scm
scheme
(load "base.scm") (load "pink.scm") (load "matcher.scm") (load "test-check.scm") (test "matcher-1" (evalms (list `(let maybe-lift (lambda _ e e) ,matcher-src) `(_ * a _ * done) `(b a done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'yes ) (test "matcher-2" (evalms (list `(let maybe-lift (lambda _ e e) ,matcher-src) `(_ * a _ * done) `(b b done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'no ) (test "matcher-c-1" (let ((c (reifyc (lambda () (evalms (list `(let maybe-lift (lambda _ e (lift e)) ,matcher-src) `(_ * a _ * done)) `(((,pink-eval-exp2 (var 0)) nil-env) (var 1))))))) (run (lambda () (let ((v (evalms '() c))) (evalms (list `(b a done) v) `((var 1) (var 0))))))) 'yes ) (test "matcher-c-2" (let ((c (reifyc (lambda () (evalms (list `(let maybe-lift (lambda _ e (lift e)) ,matcher-src) `(_ * a _ * done)) `(((,pink-eval-exp2 (var 0)) nil-env) (var 1))))))) (run (lambda () (let ((v (evalms '() c))) (evalms (list `(b b done) v) `((var 1) (var 0))))))) 'no ) (test "matcher-trace-1" (evalms (list `(delta-eval (lambda _ tie (lambda _ eval (lambda ev l (lambda _ exp (lambda _ env (if (symbol? exp) (let _ (log 0 exp) (log 0 (((eval l) exp) env))) ((((tie ev) l) exp) env))))))) (let maybe-lift (lambda _ e e) ,matcher-src)) `(_ * a _ * done) `(b a done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'yes ) (test "matcher-trace-2" (evalms (list `(delta-eval (lambda _ tie (lambda _ eval (lambda ev l (lambda _ exp (lambda _ env (if (symbol? exp) (let _ (log 0 exp) (log 0 (((eval l) exp) env))) ((((tie ev) l) exp) env))))))) (let maybe-lift (lambda _ e e) ,matcher-src)) `(_ * a _ * done) `(b b done)) `((((,pink-eval-exp3 (var 0)) nil-env) (var 1)) (var 2))) 'no ) (define tracing-matcher-transformer (lambda (r) (let ((c (reifyc (lambda () (evalms (list `(delta-eval (lambda _ tie (lambda _ eval (lambda ev l (lambda _ exp (lambda _ env (if (symbol? exp) (let _ (log (lift 0) exp) (let r (((eval l) exp) env) (let _ (log (lift 0) r) r))) ((((tie ev) l) exp) env))))))) (let maybe-lift (lambda _ e (lift e)) ,matcher-src)) r) `(((,pink-eval-exp2 (var 0)) nil-env) (var 1))))))) (run (lambda () (let ((v (evalms '() c))) v)))))) (test "matcher-trace-c-1" (evalms (list `(b a done) (tracing-matcher-transformer '(_ * a _ * done))) `((var 1) (var 0))) 'yes ) (test "matcher-trace-c-2" (evalms (list `(b b done) (tracing-matcher-transformer '(_ * a _ * done))) `((var 1) (var 0))) 'no )
f7c287af73f5e250a333083891fe3d91a5919f703f64db700fc388283fdda1da
dtgoitia/civil-autolisp
ImportPlotLevels.lsp
(defun c:2 ( / ss ) Convert point block to plot level (if (setq ss (ssget '(( 0 . "INSERT")))) (foreach a (ssnamex ss) (if (= 'ename (type (cadr a))) (DT:BlockToPlotLevel (cadr a)) );END if );END foreach );END if v0.0 - 2017.07.13 - First issue Author : Last revision : 2017.07.13 ) (defun DT:BlockToPlotLevel ( ename / z xy insertionPoint return ) ; Get passed ename block "LEVEL" attribute and create a plot level in its coordinates with such level as content (if (DT:Arg 'DT:BlockToPlotLevel '((ename 'ename))) (progn (setq z (LM:vl-getattributevalue (vlax-ename->vla-object ename) "LEVEL")) (setq xy (cdr (assoc 10 (entget ename)))) (setq insertionPoint (list (nth 0 xy) (nth 1 xy) 0.0) ) (setq return (DT:DrawPlotLevel xy (atof z) )) );END progn nil );END if v0.0 - 2017.07.13 - First issue Author : Last revision : 2017.07.13 )
null
https://raw.githubusercontent.com/dtgoitia/civil-autolisp/72d68139d372c84014d160f8e4918f062356349f/Dump%20folder/ImportPlotLevels.lsp
lisp
END if END foreach END if Get passed ename block "LEVEL" attribute and create a plot level in its coordinates with such level as content END progn END if
(defun c:2 ( / ss ) Convert point block to plot level (if (setq ss (ssget '(( 0 . "INSERT")))) (foreach a (ssnamex ss) (if (= 'ename (type (cadr a))) (DT:BlockToPlotLevel (cadr a)) v0.0 - 2017.07.13 - First issue Author : Last revision : 2017.07.13 ) (defun DT:BlockToPlotLevel ( ename / z xy insertionPoint return ) (if (DT:Arg 'DT:BlockToPlotLevel '((ename 'ename))) (progn (setq z (LM:vl-getattributevalue (vlax-ename->vla-object ename) "LEVEL")) (setq xy (cdr (assoc 10 (entget ename)))) (setq insertionPoint (list (nth 0 xy) (nth 1 xy) 0.0) ) (setq return (DT:DrawPlotLevel xy (atof z) )) nil v0.0 - 2017.07.13 - First issue Author : Last revision : 2017.07.13 )
bea2fdefaf43e6733d5dd2beab28a75f6705e739f671dc4f45f3ec602fd3cb1f
psholtz/MIT-SICP
exercise2-75.scm
;; Exercise 2.75 ;; ;; Implement the constructor "make-from-mag-ang" in message-passing style. This procedure should be ;; analogous to the "make-from-real-imag" procedure given above. ;; (load "complex-package.scm") ;; ;; The definition of "make-from-real-imag" given in the text is as follows: ;; (define (make-from-real-imag x y) (define (dispatch op) (cond ((eq? op 'real-part) x) ((eq? op 'imag-part) y) ((eq? op 'magnitude) (sqrt (+ (square x) (square y)))) ((eq? op 'angle) (atan y x)) (else (error "Unknown op -- MAKE-FROM-REAL-IMAG" op)))) dispatch) ;; ;; And we also need to change the "apply-generic" procedure: ;; (define (apply-generic op arg) (arg op)) ;; ;; Let's run some unit tests. ;; One thing we notice right away is that constructing numbers ;; no longer returns an ordinary data structure that we can ;; easily introspect from the interpreter, but rather returns ;; a procedure (i.e., closure): ;; (define test1 (make-from-real-imag 1 2)) ;; ==> #[compound procedure] (real-part test1) = = > 1 (imag-part test1) = = > 2 (magnitude test1) = = > 2.23607 (angle test1) = = > 1.10715 ;; ;; For interpreting angles, it's nice to have a radian->degree converter: ;; (define (radian->degree angle) (define PI 3.14159) (* (/ angle PI) 180.0)) (radian->degree (angle test1)) = = > 63.435 (define test2 (make-from-real-imag 0 1)) ;; ==> #[compound procedure] (real-part test2) ;; ==> 0 (imag-part test2) = = > 1 (magnitude test2) = = > 1 (radian->degree (angle test2)) = = > 90.000 (define test3 (add-complex test1 test2)) ;; ==> #[compound procedure] (real-part test3) = = > 1 (imag-part test3) = = > 3 ;; ;; Now, define the constructor "make-from-mag-ang" as requested: ;; (define (make-from-mag-ang r a) (define (dispatch op) (cond ((eq? op 'magnitude) r) ((eq? op 'angle) a) ((eq? op 'real-part) (* r (cos a))) ((eq? op 'imag-part) (* r (sin a))) (else (error "Unknown op -- MAKE-FROM-MAG-ANG" op)))) dispatch) ;; ;; Let's run some unit tests: ;; (define c1 (make-from-mag-ang 1 0)) ;; ==> #[compound procedure] (real-part c1) = = > 1 (imag-part c1) ;; ==> 0 (define PI 3.14159) (define c2 (make-from-mag-ang 1 (/ PI 2))) ;; ==> #[compound procedure] (real-part c2) ;; ==> 0 (imag-part c2) = = > 1 (define c3 (make-from-real-imag 2 1)) ;; ==> #[compound procedure] (magnitude c3) = = > 2.236068 (angle c3) = = > 0.463648 (define c4 (add-complex c1 c2)) ;; ==> #[compound procedure] (real-part c4) = = > 1 (imag-part c4) = = > 1 ;; ;; These results correspond with what we obtained earlier. ;;
null
https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Section-2.4/mit-scheme/exercise2-75.scm
scheme
Implement the constructor "make-from-mag-ang" in message-passing style. This procedure should be analogous to the "make-from-real-imag" procedure given above. The definition of "make-from-real-imag" given in the text is as follows: And we also need to change the "apply-generic" procedure: Let's run some unit tests. no longer returns an ordinary data structure that we can easily introspect from the interpreter, but rather returns a procedure (i.e., closure): ==> #[compound procedure] For interpreting angles, it's nice to have a radian->degree converter: ==> #[compound procedure] ==> 0 ==> #[compound procedure] Now, define the constructor "make-from-mag-ang" as requested: Let's run some unit tests: ==> #[compound procedure] ==> 0 ==> #[compound procedure] ==> 0 ==> #[compound procedure] ==> #[compound procedure] These results correspond with what we obtained earlier.
Exercise 2.75 (load "complex-package.scm") (define (make-from-real-imag x y) (define (dispatch op) (cond ((eq? op 'real-part) x) ((eq? op 'imag-part) y) ((eq? op 'magnitude) (sqrt (+ (square x) (square y)))) ((eq? op 'angle) (atan y x)) (else (error "Unknown op -- MAKE-FROM-REAL-IMAG" op)))) dispatch) (define (apply-generic op arg) (arg op)) One thing we notice right away is that constructing numbers (define test1 (make-from-real-imag 1 2)) (real-part test1) = = > 1 (imag-part test1) = = > 2 (magnitude test1) = = > 2.23607 (angle test1) = = > 1.10715 (define (radian->degree angle) (define PI 3.14159) (* (/ angle PI) 180.0)) (radian->degree (angle test1)) = = > 63.435 (define test2 (make-from-real-imag 0 1)) (real-part test2) (imag-part test2) = = > 1 (magnitude test2) = = > 1 (radian->degree (angle test2)) = = > 90.000 (define test3 (add-complex test1 test2)) (real-part test3) = = > 1 (imag-part test3) = = > 3 (define (make-from-mag-ang r a) (define (dispatch op) (cond ((eq? op 'magnitude) r) ((eq? op 'angle) a) ((eq? op 'real-part) (* r (cos a))) ((eq? op 'imag-part) (* r (sin a))) (else (error "Unknown op -- MAKE-FROM-MAG-ANG" op)))) dispatch) (define c1 (make-from-mag-ang 1 0)) (real-part c1) = = > 1 (imag-part c1) (define PI 3.14159) (define c2 (make-from-mag-ang 1 (/ PI 2))) (real-part c2) (imag-part c2) = = > 1 (define c3 (make-from-real-imag 2 1)) (magnitude c3) = = > 2.236068 (angle c3) = = > 0.463648 (define c4 (add-complex c1 c2)) (real-part c4) = = > 1 (imag-part c4) = = > 1
4dbfeb213ae06ba44ffae72787d4b3dba5c70cddf7e0367b5261b32805070ca0
paurkedal/ocaml-caqti
caqti_dynload.mli
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 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) (** Dynamic linker for database drivers. This module registers a dynamic linker for loading database drivers. *)
null
https://raw.githubusercontent.com/paurkedal/ocaml-caqti/264e4259aa41cc99a21c989faa932eb4daabcdb8/caqti-dynload/lib/caqti_dynload.mli
ocaml
* Dynamic linker for database drivers. This module registers a dynamic linker for loading database drivers.
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 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *)
517d953917e5a8a0149a1d98473d80fa8e2e44ba8d74c88710af403936f428e9
bcc32/advent-of-code
main.ml
open! Core open! Async open! Import let input = Lazy_deferred.create (fun () -> Reader.file_contents "input.txt" >>| String.strip) ;; let hash ~secret_key ~number = Md5.digest_string (secret_key ^ Int.to_string number) |> Md5.to_hex ;; let mine secret_key = let rec loop number = if String.is_prefix (hash ~secret_key ~number) ~prefix:"00000" then number else loop (number + 1) in loop 1 ;; let%expect_test "abcdef609043" = print_s [%sexp (hash ~secret_key:"abcdef" ~number:609043 : string)]; [%expect {| 000001dbbfa3a5c83a2d506429c7b00e |}]; return () ;; let%expect_test "mine(abcdef)" = print_s [%sexp (mine "abcdef" : int)]; [%expect {| 609043 |}]; return () ;; let%expect_test "mine(pqrstuv)" = print_s [%sexp (mine "pqrstuv" : int)]; [%expect {| 1048970 |}]; return () ;; let a () = let%bind secret_key = Lazy_deferred.force_exn input in let ans = mine secret_key in print_s [%sexp (ans : int)]; return () ;; let%expect_test "a" = let%bind () = a () in [%expect {| 117946 |}]; return () ;; let mine secret_key = let rec loop number = if String.is_prefix (hash ~secret_key ~number) ~prefix:"000000" then number else loop (number + 1) in loop 1 ;; let b () = let%bind secret_key = Lazy_deferred.force_exn input in let ans = mine secret_key in print_s [%sexp (ans : int)]; return () ;; let%expect_test "b" = let%bind () = b () in [%expect {| 3938038 |}]; return () ;;
null
https://raw.githubusercontent.com/bcc32/advent-of-code/86a9387c3d6be2afe07d2657a0607749217b1b77/2015/day_4/main.ml
ocaml
open! Core open! Async open! Import let input = Lazy_deferred.create (fun () -> Reader.file_contents "input.txt" >>| String.strip) ;; let hash ~secret_key ~number = Md5.digest_string (secret_key ^ Int.to_string number) |> Md5.to_hex ;; let mine secret_key = let rec loop number = if String.is_prefix (hash ~secret_key ~number) ~prefix:"00000" then number else loop (number + 1) in loop 1 ;; let%expect_test "abcdef609043" = print_s [%sexp (hash ~secret_key:"abcdef" ~number:609043 : string)]; [%expect {| 000001dbbfa3a5c83a2d506429c7b00e |}]; return () ;; let%expect_test "mine(abcdef)" = print_s [%sexp (mine "abcdef" : int)]; [%expect {| 609043 |}]; return () ;; let%expect_test "mine(pqrstuv)" = print_s [%sexp (mine "pqrstuv" : int)]; [%expect {| 1048970 |}]; return () ;; let a () = let%bind secret_key = Lazy_deferred.force_exn input in let ans = mine secret_key in print_s [%sexp (ans : int)]; return () ;; let%expect_test "a" = let%bind () = a () in [%expect {| 117946 |}]; return () ;; let mine secret_key = let rec loop number = if String.is_prefix (hash ~secret_key ~number) ~prefix:"000000" then number else loop (number + 1) in loop 1 ;; let b () = let%bind secret_key = Lazy_deferred.force_exn input in let ans = mine secret_key in print_s [%sexp (ans : int)]; return () ;; let%expect_test "b" = let%bind () = b () in [%expect {| 3938038 |}]; return () ;;
f77aaac5648a6b3bc6dd2063046c7e97658b2a6af44ee9907a98a737d5fafdd0
alavrik/piqi
piq_piqi.ml
module Piqirun = Piqi_piqirun module rec Piq_piqi: sig type float64 = float type uint64 = int64 type float = Piq_piqi.float64 type binary = string type word = string type name = Piq_piqi.word type piq = [ | `int of int64 | `uint of Piq_piqi.uint64 | `float of Piq_piqi.float | `bool of bool | `binary of Piq_piqi.binary | `string of string | `word of Piq_piqi.word | `text of string | `raw_string of Piq_piqi.binary | `name of Piq_piqi.name | `named of Piq_piqi.named | `typename of Piq_piqi.name | `typed of Piq_piqi.typed | `list of Piq_piqi.piq_list | `splice of Piq_piqi.splice ] type piq_node = Piq_node.t type loc = Loc.t type piq_list = Piq_piqi.piq_node list type named = Named.t type splice = Splice.t type typed = Typed.t end = Piq_piqi and Piq_node: sig type t = { mutable piq: Piq_piqi.piq; mutable loc: Piq_piqi.loc option; } end = Piq_node and Loc: sig type t = { mutable file: string; mutable line: int; mutable column: int; } end = Loc and Named: sig type t = { mutable name: Piq_piqi.name; mutable value: Piq_piqi.piq_node; } end = Named and Splice: sig type t = { mutable name: Piq_piqi.name; mutable item: Piq_piqi.piq_node list; } end = Splice and Typed: sig type t = { mutable typename: Piq_piqi.name; mutable value: Piq_piqi.piq_node; } end = Typed let rec parse_float64 x = Piqirun.float_of_fixed64 x and packed_parse_float64 x = Piqirun.float_of_packed_fixed64 x and parse_int64 x = Piqirun.int64_of_zigzag_varint x and packed_parse_int64 x = Piqirun.int64_of_packed_zigzag_varint x and parse_uint64 x = Piqirun.int64_of_varint x and packed_parse_uint64 x = Piqirun.int64_of_packed_varint x and parse_float x = parse_float64 x and packed_parse_float x = packed_parse_float64 x and parse_bool x = Piqirun.bool_of_varint x and packed_parse_bool x = Piqirun.bool_of_packed_varint x and parse_binary x = Piqirun.string_of_block x and parse_string x = Piqirun.string_of_block x and parse_int x = Piqirun.int_of_zigzag_varint x and packed_parse_int x = Piqirun.int_of_packed_zigzag_varint x and parse_piq x = let code, x = Piqirun.parse_variant x in match code with | 1 -> let res = parse_int64 x in `int res | 2 -> let res = parse_uint64 x in `uint res | 3 -> let res = parse_float x in `float res | 4 -> let res = parse_bool x in `bool res | 5 -> let res = parse_binary x in `binary res | 6 -> let res = parse_string x in `string res | 7 -> let res = parse_word x in `word res | 8 -> let res = parse_string x in `text res | 9 -> let res = parse_binary x in `raw_string res | 10 -> let res = parse_name x in `name res | 11 -> let res = parse_named x in `named res | 12 -> let res = parse_name x in `typename res | 13 -> let res = parse_typed x in `typed res | 14 -> let res = parse_piq_list x in `list res | 15 -> let res = parse_splice x in `splice res | _ -> Piqirun.error_variant x code and parse_piq_node x = let x = Piqirun.parse_record x in let _piq, x = Piqirun.parse_required_field 1 parse_piq x in let _loc, x = Piqirun.parse_optional_field 2 parse_loc x in Piqirun.check_unparsed_fields x; { Piq_node.piq = _piq; Piq_node.loc = _loc; } and parse_loc x = let x = Piqirun.parse_record x in let _file, x = Piqirun.parse_required_field 1 parse_string x in let _line, x = Piqirun.parse_required_field 2 parse_int x in let _column, x = Piqirun.parse_required_field 3 parse_int x in Piqirun.check_unparsed_fields x; { Loc.file = _file; Loc.line = _line; Loc.column = _column; } and parse_word x = parse_string x and parse_name x = parse_word x and parse_piq_list x = Piqirun.parse_list (parse_piq_node) x and parse_named x = let x = Piqirun.parse_record x in let _name, x = Piqirun.parse_required_field 1 parse_name x in let _value, x = Piqirun.parse_required_field 2 parse_piq_node x in Piqirun.check_unparsed_fields x; { Named.name = _name; Named.value = _value; } and parse_splice x = let x = Piqirun.parse_record x in let _name, x = Piqirun.parse_required_field 1 parse_name x in let _item, x = Piqirun.parse_repeated_field 2 parse_piq_node x in Piqirun.check_unparsed_fields x; { Splice.name = _name; Splice.item = _item; } and parse_typed x = let x = Piqirun.parse_record x in let _typename, x = Piqirun.parse_required_field 1 parse_name x in let _value, x = Piqirun.parse_required_field 2 parse_piq_node x in Piqirun.check_unparsed_fields x; { Typed.typename = _typename; Typed.value = _value; } let rec gen__float64 code x = Piqirun.float_to_fixed64 code x and packed_gen__float64 x = Piqirun.float_to_packed_fixed64 x and gen__int64 code x = Piqirun.int64_to_zigzag_varint code x and packed_gen__int64 x = Piqirun.int64_to_packed_zigzag_varint x and gen__uint64 code x = Piqirun.int64_to_varint code x and packed_gen__uint64 x = Piqirun.int64_to_packed_varint x and gen__float code x = gen__float64 code x and packed_gen__float x = packed_gen__float64 x and gen__bool code x = Piqirun.bool_to_varint code x and packed_gen__bool x = Piqirun.bool_to_packed_varint x and gen__binary code x = Piqirun.string_to_block code x and gen__string code x = Piqirun.string_to_block code x and gen__int code x = Piqirun.int_to_zigzag_varint code x and packed_gen__int x = Piqirun.int_to_packed_zigzag_varint x and gen__piq code (x:Piq_piqi.piq) = Piqirun.gen_record code [(match x with | `int x -> gen__int64 1 x | `uint x -> gen__uint64 2 x | `float x -> gen__float 3 x | `bool x -> gen__bool 4 x | `binary x -> gen__binary 5 x | `string x -> gen__string 6 x | `word x -> gen__word 7 x | `text x -> gen__string 8 x | `raw_string x -> gen__binary 9 x | `name x -> gen__name 10 x | `named x -> gen__named 11 x | `typename x -> gen__name 12 x | `typed x -> gen__typed 13 x | `list x -> gen__piq_list 14 x | `splice x -> gen__splice 15 x )] and gen__piq_node code x = let _piq = Piqirun.gen_required_field 1 gen__piq x.Piq_node.piq in let _loc = Piqirun.gen_optional_field 2 gen__loc x.Piq_node.loc in Piqirun.gen_record code (_piq :: _loc :: []) and gen__loc code x = let _file = Piqirun.gen_required_field 1 gen__string x.Loc.file in let _line = Piqirun.gen_required_field 2 gen__int x.Loc.line in let _column = Piqirun.gen_required_field 3 gen__int x.Loc.column in Piqirun.gen_record code (_file :: _line :: _column :: []) and gen__word code x = gen__string code x and gen__name code x = gen__word code x and gen__piq_list code x = (Piqirun.gen_list (gen__piq_node)) code x and gen__named code x = let _name = Piqirun.gen_required_field 1 gen__name x.Named.name in let _value = Piqirun.gen_required_field 2 gen__piq_node x.Named.value in Piqirun.gen_record code (_name :: _value :: []) and gen__splice code x = let _name = Piqirun.gen_required_field 1 gen__name x.Splice.name in let _item = Piqirun.gen_repeated_field 2 gen__piq_node x.Splice.item in Piqirun.gen_record code (_name :: _item :: []) and gen__typed code x = let _typename = Piqirun.gen_required_field 1 gen__name x.Typed.typename in let _value = Piqirun.gen_required_field 2 gen__piq_node x.Typed.value in Piqirun.gen_record code (_typename :: _value :: []) let gen_float64 x = gen__float64 (-1) x let gen_int64 x = gen__int64 (-1) x let gen_uint64 x = gen__uint64 (-1) x let gen_float x = gen__float (-1) x let gen_bool x = gen__bool (-1) x let gen_binary x = gen__binary (-1) x let gen_string x = gen__string (-1) x let gen_int x = gen__int (-1) x let gen_piq x = gen__piq (-1) x let gen_piq_node x = gen__piq_node (-1) x let gen_loc x = gen__loc (-1) x let gen_word x = gen__word (-1) x let gen_name x = gen__name (-1) x let gen_piq_list x = gen__piq_list (-1) x let gen_named x = gen__named (-1) x let gen_splice x = gen__splice (-1) x let gen_typed x = gen__typed (-1) x let rec default_float64 () = 0.0 and default_int64 () = 0L and default_uint64 () = 0L and default_float () = default_float64 () and default_bool () = false and default_binary () = "" and default_string () = "" and default_int () = 0 and default_piq () = `int (default_int64 ()) and default_piq_node () = { Piq_node.piq = default_piq (); Piq_node.loc = None; } and default_loc () = { Loc.file = default_string (); Loc.line = default_int (); Loc.column = default_int (); } and default_word () = default_string () and default_name () = default_word () and default_piq_list () = [] and default_named () = { Named.name = default_name (); Named.value = default_piq_node (); } and default_splice () = { Splice.name = default_name (); Splice.item = []; } and default_typed () = { Typed.typename = default_name (); Typed.value = default_piq_node (); } include Piq_piqi
null
https://raw.githubusercontent.com/alavrik/piqi/bcea4d44997966198dc295df0609591fa787b1d2/piqilib/piq_piqi.ml
ocaml
module Piqirun = Piqi_piqirun module rec Piq_piqi: sig type float64 = float type uint64 = int64 type float = Piq_piqi.float64 type binary = string type word = string type name = Piq_piqi.word type piq = [ | `int of int64 | `uint of Piq_piqi.uint64 | `float of Piq_piqi.float | `bool of bool | `binary of Piq_piqi.binary | `string of string | `word of Piq_piqi.word | `text of string | `raw_string of Piq_piqi.binary | `name of Piq_piqi.name | `named of Piq_piqi.named | `typename of Piq_piqi.name | `typed of Piq_piqi.typed | `list of Piq_piqi.piq_list | `splice of Piq_piqi.splice ] type piq_node = Piq_node.t type loc = Loc.t type piq_list = Piq_piqi.piq_node list type named = Named.t type splice = Splice.t type typed = Typed.t end = Piq_piqi and Piq_node: sig type t = { mutable piq: Piq_piqi.piq; mutable loc: Piq_piqi.loc option; } end = Piq_node and Loc: sig type t = { mutable file: string; mutable line: int; mutable column: int; } end = Loc and Named: sig type t = { mutable name: Piq_piqi.name; mutable value: Piq_piqi.piq_node; } end = Named and Splice: sig type t = { mutable name: Piq_piqi.name; mutable item: Piq_piqi.piq_node list; } end = Splice and Typed: sig type t = { mutable typename: Piq_piqi.name; mutable value: Piq_piqi.piq_node; } end = Typed let rec parse_float64 x = Piqirun.float_of_fixed64 x and packed_parse_float64 x = Piqirun.float_of_packed_fixed64 x and parse_int64 x = Piqirun.int64_of_zigzag_varint x and packed_parse_int64 x = Piqirun.int64_of_packed_zigzag_varint x and parse_uint64 x = Piqirun.int64_of_varint x and packed_parse_uint64 x = Piqirun.int64_of_packed_varint x and parse_float x = parse_float64 x and packed_parse_float x = packed_parse_float64 x and parse_bool x = Piqirun.bool_of_varint x and packed_parse_bool x = Piqirun.bool_of_packed_varint x and parse_binary x = Piqirun.string_of_block x and parse_string x = Piqirun.string_of_block x and parse_int x = Piqirun.int_of_zigzag_varint x and packed_parse_int x = Piqirun.int_of_packed_zigzag_varint x and parse_piq x = let code, x = Piqirun.parse_variant x in match code with | 1 -> let res = parse_int64 x in `int res | 2 -> let res = parse_uint64 x in `uint res | 3 -> let res = parse_float x in `float res | 4 -> let res = parse_bool x in `bool res | 5 -> let res = parse_binary x in `binary res | 6 -> let res = parse_string x in `string res | 7 -> let res = parse_word x in `word res | 8 -> let res = parse_string x in `text res | 9 -> let res = parse_binary x in `raw_string res | 10 -> let res = parse_name x in `name res | 11 -> let res = parse_named x in `named res | 12 -> let res = parse_name x in `typename res | 13 -> let res = parse_typed x in `typed res | 14 -> let res = parse_piq_list x in `list res | 15 -> let res = parse_splice x in `splice res | _ -> Piqirun.error_variant x code and parse_piq_node x = let x = Piqirun.parse_record x in let _piq, x = Piqirun.parse_required_field 1 parse_piq x in let _loc, x = Piqirun.parse_optional_field 2 parse_loc x in Piqirun.check_unparsed_fields x; { Piq_node.piq = _piq; Piq_node.loc = _loc; } and parse_loc x = let x = Piqirun.parse_record x in let _file, x = Piqirun.parse_required_field 1 parse_string x in let _line, x = Piqirun.parse_required_field 2 parse_int x in let _column, x = Piqirun.parse_required_field 3 parse_int x in Piqirun.check_unparsed_fields x; { Loc.file = _file; Loc.line = _line; Loc.column = _column; } and parse_word x = parse_string x and parse_name x = parse_word x and parse_piq_list x = Piqirun.parse_list (parse_piq_node) x and parse_named x = let x = Piqirun.parse_record x in let _name, x = Piqirun.parse_required_field 1 parse_name x in let _value, x = Piqirun.parse_required_field 2 parse_piq_node x in Piqirun.check_unparsed_fields x; { Named.name = _name; Named.value = _value; } and parse_splice x = let x = Piqirun.parse_record x in let _name, x = Piqirun.parse_required_field 1 parse_name x in let _item, x = Piqirun.parse_repeated_field 2 parse_piq_node x in Piqirun.check_unparsed_fields x; { Splice.name = _name; Splice.item = _item; } and parse_typed x = let x = Piqirun.parse_record x in let _typename, x = Piqirun.parse_required_field 1 parse_name x in let _value, x = Piqirun.parse_required_field 2 parse_piq_node x in Piqirun.check_unparsed_fields x; { Typed.typename = _typename; Typed.value = _value; } let rec gen__float64 code x = Piqirun.float_to_fixed64 code x and packed_gen__float64 x = Piqirun.float_to_packed_fixed64 x and gen__int64 code x = Piqirun.int64_to_zigzag_varint code x and packed_gen__int64 x = Piqirun.int64_to_packed_zigzag_varint x and gen__uint64 code x = Piqirun.int64_to_varint code x and packed_gen__uint64 x = Piqirun.int64_to_packed_varint x and gen__float code x = gen__float64 code x and packed_gen__float x = packed_gen__float64 x and gen__bool code x = Piqirun.bool_to_varint code x and packed_gen__bool x = Piqirun.bool_to_packed_varint x and gen__binary code x = Piqirun.string_to_block code x and gen__string code x = Piqirun.string_to_block code x and gen__int code x = Piqirun.int_to_zigzag_varint code x and packed_gen__int x = Piqirun.int_to_packed_zigzag_varint x and gen__piq code (x:Piq_piqi.piq) = Piqirun.gen_record code [(match x with | `int x -> gen__int64 1 x | `uint x -> gen__uint64 2 x | `float x -> gen__float 3 x | `bool x -> gen__bool 4 x | `binary x -> gen__binary 5 x | `string x -> gen__string 6 x | `word x -> gen__word 7 x | `text x -> gen__string 8 x | `raw_string x -> gen__binary 9 x | `name x -> gen__name 10 x | `named x -> gen__named 11 x | `typename x -> gen__name 12 x | `typed x -> gen__typed 13 x | `list x -> gen__piq_list 14 x | `splice x -> gen__splice 15 x )] and gen__piq_node code x = let _piq = Piqirun.gen_required_field 1 gen__piq x.Piq_node.piq in let _loc = Piqirun.gen_optional_field 2 gen__loc x.Piq_node.loc in Piqirun.gen_record code (_piq :: _loc :: []) and gen__loc code x = let _file = Piqirun.gen_required_field 1 gen__string x.Loc.file in let _line = Piqirun.gen_required_field 2 gen__int x.Loc.line in let _column = Piqirun.gen_required_field 3 gen__int x.Loc.column in Piqirun.gen_record code (_file :: _line :: _column :: []) and gen__word code x = gen__string code x and gen__name code x = gen__word code x and gen__piq_list code x = (Piqirun.gen_list (gen__piq_node)) code x and gen__named code x = let _name = Piqirun.gen_required_field 1 gen__name x.Named.name in let _value = Piqirun.gen_required_field 2 gen__piq_node x.Named.value in Piqirun.gen_record code (_name :: _value :: []) and gen__splice code x = let _name = Piqirun.gen_required_field 1 gen__name x.Splice.name in let _item = Piqirun.gen_repeated_field 2 gen__piq_node x.Splice.item in Piqirun.gen_record code (_name :: _item :: []) and gen__typed code x = let _typename = Piqirun.gen_required_field 1 gen__name x.Typed.typename in let _value = Piqirun.gen_required_field 2 gen__piq_node x.Typed.value in Piqirun.gen_record code (_typename :: _value :: []) let gen_float64 x = gen__float64 (-1) x let gen_int64 x = gen__int64 (-1) x let gen_uint64 x = gen__uint64 (-1) x let gen_float x = gen__float (-1) x let gen_bool x = gen__bool (-1) x let gen_binary x = gen__binary (-1) x let gen_string x = gen__string (-1) x let gen_int x = gen__int (-1) x let gen_piq x = gen__piq (-1) x let gen_piq_node x = gen__piq_node (-1) x let gen_loc x = gen__loc (-1) x let gen_word x = gen__word (-1) x let gen_name x = gen__name (-1) x let gen_piq_list x = gen__piq_list (-1) x let gen_named x = gen__named (-1) x let gen_splice x = gen__splice (-1) x let gen_typed x = gen__typed (-1) x let rec default_float64 () = 0.0 and default_int64 () = 0L and default_uint64 () = 0L and default_float () = default_float64 () and default_bool () = false and default_binary () = "" and default_string () = "" and default_int () = 0 and default_piq () = `int (default_int64 ()) and default_piq_node () = { Piq_node.piq = default_piq (); Piq_node.loc = None; } and default_loc () = { Loc.file = default_string (); Loc.line = default_int (); Loc.column = default_int (); } and default_word () = default_string () and default_name () = default_word () and default_piq_list () = [] and default_named () = { Named.name = default_name (); Named.value = default_piq_node (); } and default_splice () = { Splice.name = default_name (); Splice.item = []; } and default_typed () = { Typed.typename = default_name (); Typed.value = default_piq_node (); } include Piq_piqi
496008d1941b18f0864070b180d37267c1314a1aebda4a4e06db34bb5a2233c6
haskell-repa/repa
Base.hs
module Data.Repa.Chain.Base ( Step (..) , Chain (..) , liftChain , resumeChain) where import qualified Data.Vector.Fusion.Stream.Size as S import Control.Monad.Identity #include "repa-stream.h" -- | A chain is an abstract, stateful producer of elements. It is similar -- a stream as used in stream fusion, except that internal state is visible -- in its type. This allows the computation to be paused and resumed at a -- later point. data Chain m s a = Chain { -- | Expected size of the output. mchainSize :: S.Size -- | Starting state. , mchainState :: s -- | Step the chain computation. , mchainStep :: s -> m (Step s a) } -- | Result of a chain computation step. data Step s a -- | Yield an output value and a new seed. = Yield !a !s -- | Provide just a new seed. | Skip !s -- | Signal that the computation has finished. | Done !s deriving Show -- | Lift a pure chain to a monadic chain. liftChain :: Monad m => Chain Identity s a -> Chain m s a liftChain (Chain sz s step) = Chain sz s (return . runIdentity . step) # INLINE_STREAM liftChain # -- | Resume a chain computation from a previous state. resumeChain :: s -> Chain m s a -> Chain m s a resumeChain s' (Chain sz _s step) = Chain sz s' step # INLINE_STREAM resumeChain #
null
https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-stream/Data/Repa/Chain/Base.hs
haskell
| A chain is an abstract, stateful producer of elements. It is similar a stream as used in stream fusion, except that internal state is visible in its type. This allows the computation to be paused and resumed at a later point. | Expected size of the output. | Starting state. | Step the chain computation. | Result of a chain computation step. | Yield an output value and a new seed. | Provide just a new seed. | Signal that the computation has finished. | Lift a pure chain to a monadic chain. | Resume a chain computation from a previous state.
module Data.Repa.Chain.Base ( Step (..) , Chain (..) , liftChain , resumeChain) where import qualified Data.Vector.Fusion.Stream.Size as S import Control.Monad.Identity #include "repa-stream.h" data Chain m s a = Chain mchainSize :: S.Size , mchainState :: s , mchainStep :: s -> m (Step s a) } data Step s a = Yield !a !s | Skip !s | Done !s deriving Show liftChain :: Monad m => Chain Identity s a -> Chain m s a liftChain (Chain sz s step) = Chain sz s (return . runIdentity . step) # INLINE_STREAM liftChain # resumeChain :: s -> Chain m s a -> Chain m s a resumeChain s' (Chain sz _s step) = Chain sz s' step # INLINE_STREAM resumeChain #
4281081c1831557e2d79ff0c3098446f7fb302236c031113680f6b7a8daa1032
Jell/euroclojure-2016
hacks.cljs
(ns euroclojure.hacks) (defn slide [context] [:div.slide.left [:h1.centered "Hacks"] [:ul [:li "Run single test var from REPL"] [:a {:href "" :target "_blank"} ""] [:li "Use " [:code "gulp-watch"] " to touch cljs file on related assets changes"] [:li "Use " [:code "window.open()"] " to popup dev window/controls"]]])
null
https://raw.githubusercontent.com/Jell/euroclojure-2016/a8ca883e8480a4616ede19995aaacd4a495608af/src/euroclojure/hacks.cljs
clojure
(ns euroclojure.hacks) (defn slide [context] [:div.slide.left [:h1.centered "Hacks"] [:ul [:li "Run single test var from REPL"] [:a {:href "" :target "_blank"} ""] [:li "Use " [:code "gulp-watch"] " to touch cljs file on related assets changes"] [:li "Use " [:code "window.open()"] " to popup dev window/controls"]]])
f380c89eb1c0faaeec568b693bb1e4b8bf4ef1b6fd44be3dc048785f27c78185
cljs-audio/cljs-audio
utils.cljc
(ns cljs-audio.utils (:require [camel-snake-kebab.core :refer [->camelCase]]))
null
https://raw.githubusercontent.com/cljs-audio/cljs-audio/75b8326ff0d5d610be3ea1b39979eac45dfd5b4b/src/main/cljs_audio/utils.cljc
clojure
(ns cljs-audio.utils (:require [camel-snake-kebab.core :refer [->camelCase]]))
977d85f61ae8d8cc2a76dca7c83f2ca121b478731604b7c5119cb28bd2603a6c
astro/prittorrent
hasher_app.erl
-module(hasher_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> hasher_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/astro/prittorrent/5173eeb8b00fd9ab7c0d347c9e361052023faebd/apps/hasher/src/hasher_app.erl
erlang
Application callbacks =================================================================== Application callbacks ===================================================================
-module(hasher_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> hasher_sup:start_link(). stop(_State) -> ok.
eb8bc521b8d6fdd6138bff9a975b66918045216a0ed99402ab4f3579d8a6350f
vonzhou/LearnYouHaskellForGreatGood
FoodDrink.hs
import Data.Monoid type Food = String type Price = Sum Int applyLog :: (Monoid m) => (a, m) -> (a -> (b, m)) -> (b, m) applyLog (x, log) f = let (y, newLog) = f x in (y, log `mappend` newLog) addDrink :: Food -> (Food, Price) addDrink "beans" = ("milk", Sum 25) addDrink "jerky" = ("whiskey", Sum 99) addDrink _ = ("beer", Sum 30)
null
https://raw.githubusercontent.com/vonzhou/LearnYouHaskellForGreatGood/439d848deac53ef6da6df433078b7f1dcf54d18d/chapter14/FoodDrink.hs
haskell
import Data.Monoid type Food = String type Price = Sum Int applyLog :: (Monoid m) => (a, m) -> (a -> (b, m)) -> (b, m) applyLog (x, log) f = let (y, newLog) = f x in (y, log `mappend` newLog) addDrink :: Food -> (Food, Price) addDrink "beans" = ("milk", Sum 25) addDrink "jerky" = ("whiskey", Sum 99) addDrink _ = ("beer", Sum 30)
aa97c7654bae415aca7a2c38d27524a3bb3590a7db8498b679a93e9308c1bb0c
wireless-net/erlang-nommu
wxStdDialogButtonSizer.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="">wxStdDialogButtonSizer</a>. %% <p>This class is derived (and can use functions) from: %% <br />{@link wxBoxSizer} %% <br />{@link wxSizer} %% </p> %% @type wxStdDialogButtonSizer(). 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(wxStdDialogButtonSizer). -include("wxe.hrl"). -export([addButton/2,destroy/1,new/0,realize/1,setAffirmativeButton/2,setCancelButton/2, setNegativeButton/2]). %% inherited exports -export([add/2,add/3,add/4,addSpacer/2,addStretchSpacer/1,addStretchSpacer/2, calcMin/1,clear/1,clear/2,detach/2,fit/2,fitInside/2,getChildren/1,getItem/2, getItem/3,getMinSize/1,getOrientation/1,getPosition/1,getSize/1,hide/2, hide/3,insert/3,insert/4,insert/5,insertSpacer/3,insertStretchSpacer/2, insertStretchSpacer/3,isShown/2,layout/1,parent_class/1,prepend/2, prepend/3,prepend/4,prependSpacer/2,prependStretchSpacer/1,prependStretchSpacer/2, recalcSizes/1,remove/2,replace/3,replace/4,setDimension/5,setItemMinSize/3, setItemMinSize/4,setMinSize/2,setMinSize/3,setSizeHints/2,setVirtualSizeHints/2, show/2,show/3]). -export_type([wxStdDialogButtonSizer/0]). %% @hidden parent_class(wxBoxSizer) -> true; parent_class(wxSizer) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -type wxStdDialogButtonSizer() :: wx:wx_object(). %% @doc See <a href="#wxstddialogbuttonsizerwxstddialogbuttonsizer">external documentation</a>. -spec new() -> wxStdDialogButtonSizer(). new() -> wxe_util:construct(?wxStdDialogButtonSizer_new, <<>>). %% @doc See <a href="#wxstddialogbuttonsizeraddbutton">external documentation</a>. -spec addButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). addButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_AddButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). %% @doc See <a href="#wxstddialogbuttonsizerrealize">external documentation</a>. -spec realize(This) -> ok when This::wxStdDialogButtonSizer(). realize(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), wxe_util:cast(?wxStdDialogButtonSizer_Realize, <<ThisRef:32/?UI>>). %% @doc See <a href="#wxstddialogbuttonsizersetaffirmativebutton">external documentation</a>. -spec setAffirmativeButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). setAffirmativeButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_SetAffirmativeButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). %% @doc See <a href="#wxstddialogbuttonsizersetcancelbutton">external documentation</a>. -spec setCancelButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). setCancelButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_SetCancelButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). %% @doc See <a href="#wxstddialogbuttonsizersetnegativebutton">external documentation</a>. -spec setNegativeButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). setNegativeButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_SetNegativeButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). %% @doc Destroys this object, do not use object again -spec destroy(This::wxStdDialogButtonSizer()) -> ok. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxStdDialogButtonSizer), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. From %% @hidden getOrientation(This) -> wxBoxSizer:getOrientation(This). From wxSizer %% @hidden show(This,Index, Options) -> wxSizer:show(This,Index, Options). %% @hidden show(This,Index) -> wxSizer:show(This,Index). %% @hidden setVirtualSizeHints(This,Window) -> wxSizer:setVirtualSizeHints(This,Window). %% @hidden setSizeHints(This,Window) -> wxSizer:setSizeHints(This,Window). %% @hidden setItemMinSize(This,Index,Width,Height) -> wxSizer:setItemMinSize(This,Index,Width,Height). %% @hidden setItemMinSize(This,Index,Size) -> wxSizer:setItemMinSize(This,Index,Size). %% @hidden setMinSize(This,Width,Height) -> wxSizer:setMinSize(This,Width,Height). %% @hidden setMinSize(This,Size) -> wxSizer:setMinSize(This,Size). %% @hidden setDimension(This,X,Y,Width,Height) -> wxSizer:setDimension(This,X,Y,Width,Height). %% @hidden replace(This,Oldwin,Newwin, Options) -> wxSizer:replace(This,Oldwin,Newwin, Options). %% @hidden replace(This,Oldwin,Newwin) -> wxSizer:replace(This,Oldwin,Newwin). %% @hidden remove(This,Index) -> wxSizer:remove(This,Index). %% @hidden recalcSizes(This) -> wxSizer:recalcSizes(This). %% @hidden prependStretchSpacer(This, Options) -> wxSizer:prependStretchSpacer(This, Options). %% @hidden prependStretchSpacer(This) -> wxSizer:prependStretchSpacer(This). %% @hidden prependSpacer(This,Size) -> wxSizer:prependSpacer(This,Size). %% @hidden prepend(This,Width,Height, Options) -> wxSizer:prepend(This,Width,Height, Options). %% @hidden prepend(This,Width,Height) -> wxSizer:prepend(This,Width,Height). %% @hidden prepend(This,Item) -> wxSizer:prepend(This,Item). %% @hidden layout(This) -> wxSizer:layout(This). %% @hidden isShown(This,Index) -> wxSizer:isShown(This,Index). %% @hidden insertStretchSpacer(This,Index, Options) -> wxSizer:insertStretchSpacer(This,Index, Options). %% @hidden insertStretchSpacer(This,Index) -> wxSizer:insertStretchSpacer(This,Index). %% @hidden insertSpacer(This,Index,Size) -> wxSizer:insertSpacer(This,Index,Size). %% @hidden insert(This,Index,Width,Height, Options) -> wxSizer:insert(This,Index,Width,Height, Options). %% @hidden insert(This,Index,Width,Height) -> wxSizer:insert(This,Index,Width,Height). %% @hidden insert(This,Index,Item) -> wxSizer:insert(This,Index,Item). %% @hidden hide(This,Window, Options) -> wxSizer:hide(This,Window, Options). %% @hidden hide(This,Window) -> wxSizer:hide(This,Window). %% @hidden getMinSize(This) -> wxSizer:getMinSize(This). %% @hidden getPosition(This) -> wxSizer:getPosition(This). %% @hidden getSize(This) -> wxSizer:getSize(This). %% @hidden getItem(This,Window, Options) -> wxSizer:getItem(This,Window, Options). %% @hidden getItem(This,Window) -> wxSizer:getItem(This,Window). %% @hidden getChildren(This) -> wxSizer:getChildren(This). %% @hidden fitInside(This,Window) -> wxSizer:fitInside(This,Window). %% @hidden fit(This,Window) -> wxSizer:fit(This,Window). %% @hidden detach(This,Index) -> wxSizer:detach(This,Index). %% @hidden clear(This, Options) -> wxSizer:clear(This, Options). %% @hidden clear(This) -> wxSizer:clear(This). %% @hidden calcMin(This) -> wxSizer:calcMin(This). %% @hidden addStretchSpacer(This, Options) -> wxSizer:addStretchSpacer(This, Options). %% @hidden addStretchSpacer(This) -> wxSizer:addStretchSpacer(This). %% @hidden addSpacer(This,Size) -> wxSizer:addSpacer(This,Size). %% @hidden add(This,Width,Height, Options) -> wxSizer:add(This,Width,Height, Options). %% @hidden add(This,Width,Height) -> wxSizer:add(This,Width,Height). %% @hidden add(This,Window) -> wxSizer:add(This,Window).
null
https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/wx/src/gen/wxStdDialogButtonSizer.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="">wxStdDialogButtonSizer</a>. <p>This class is derived (and can use functions) from: <br />{@link wxBoxSizer} <br />{@link wxSizer} </p> @type wxStdDialogButtonSizer(). 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 @doc See <a href="#wxstddialogbuttonsizerwxstddialogbuttonsizer">external documentation</a>. @doc See <a href="#wxstddialogbuttonsizeraddbutton">external documentation</a>. @doc See <a href="#wxstddialogbuttonsizerrealize">external documentation</a>. @doc See <a href="#wxstddialogbuttonsizersetaffirmativebutton">external documentation</a>. @doc See <a href="#wxstddialogbuttonsizersetcancelbutton">external documentation</a>. @doc See <a href="#wxstddialogbuttonsizersetnegativebutton">external documentation</a>. @doc Destroys this object, do not use object again @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden
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(wxStdDialogButtonSizer). -include("wxe.hrl"). -export([addButton/2,destroy/1,new/0,realize/1,setAffirmativeButton/2,setCancelButton/2, setNegativeButton/2]). -export([add/2,add/3,add/4,addSpacer/2,addStretchSpacer/1,addStretchSpacer/2, calcMin/1,clear/1,clear/2,detach/2,fit/2,fitInside/2,getChildren/1,getItem/2, getItem/3,getMinSize/1,getOrientation/1,getPosition/1,getSize/1,hide/2, hide/3,insert/3,insert/4,insert/5,insertSpacer/3,insertStretchSpacer/2, insertStretchSpacer/3,isShown/2,layout/1,parent_class/1,prepend/2, prepend/3,prepend/4,prependSpacer/2,prependStretchSpacer/1,prependStretchSpacer/2, recalcSizes/1,remove/2,replace/3,replace/4,setDimension/5,setItemMinSize/3, setItemMinSize/4,setMinSize/2,setMinSize/3,setSizeHints/2,setVirtualSizeHints/2, show/2,show/3]). -export_type([wxStdDialogButtonSizer/0]). parent_class(wxBoxSizer) -> true; parent_class(wxSizer) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -type wxStdDialogButtonSizer() :: wx:wx_object(). -spec new() -> wxStdDialogButtonSizer(). new() -> wxe_util:construct(?wxStdDialogButtonSizer_new, <<>>). -spec addButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). addButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_AddButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). -spec realize(This) -> ok when This::wxStdDialogButtonSizer(). realize(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), wxe_util:cast(?wxStdDialogButtonSizer_Realize, <<ThisRef:32/?UI>>). -spec setAffirmativeButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). setAffirmativeButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_SetAffirmativeButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). -spec setCancelButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). setCancelButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_SetCancelButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). -spec setNegativeButton(This, Button) -> ok when This::wxStdDialogButtonSizer(), Button::wxButton:wxButton(). setNegativeButton(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ButtonT,ref=ButtonRef}) -> ?CLASS(ThisT,wxStdDialogButtonSizer), ?CLASS(ButtonT,wxButton), wxe_util:cast(?wxStdDialogButtonSizer_SetNegativeButton, <<ThisRef:32/?UI,ButtonRef:32/?UI>>). -spec destroy(This::wxStdDialogButtonSizer()) -> ok. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxStdDialogButtonSizer), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. From getOrientation(This) -> wxBoxSizer:getOrientation(This). From wxSizer show(This,Index, Options) -> wxSizer:show(This,Index, Options). show(This,Index) -> wxSizer:show(This,Index). setVirtualSizeHints(This,Window) -> wxSizer:setVirtualSizeHints(This,Window). setSizeHints(This,Window) -> wxSizer:setSizeHints(This,Window). setItemMinSize(This,Index,Width,Height) -> wxSizer:setItemMinSize(This,Index,Width,Height). setItemMinSize(This,Index,Size) -> wxSizer:setItemMinSize(This,Index,Size). setMinSize(This,Width,Height) -> wxSizer:setMinSize(This,Width,Height). setMinSize(This,Size) -> wxSizer:setMinSize(This,Size). setDimension(This,X,Y,Width,Height) -> wxSizer:setDimension(This,X,Y,Width,Height). replace(This,Oldwin,Newwin, Options) -> wxSizer:replace(This,Oldwin,Newwin, Options). replace(This,Oldwin,Newwin) -> wxSizer:replace(This,Oldwin,Newwin). remove(This,Index) -> wxSizer:remove(This,Index). recalcSizes(This) -> wxSizer:recalcSizes(This). prependStretchSpacer(This, Options) -> wxSizer:prependStretchSpacer(This, Options). prependStretchSpacer(This) -> wxSizer:prependStretchSpacer(This). prependSpacer(This,Size) -> wxSizer:prependSpacer(This,Size). prepend(This,Width,Height, Options) -> wxSizer:prepend(This,Width,Height, Options). prepend(This,Width,Height) -> wxSizer:prepend(This,Width,Height). prepend(This,Item) -> wxSizer:prepend(This,Item). layout(This) -> wxSizer:layout(This). isShown(This,Index) -> wxSizer:isShown(This,Index). insertStretchSpacer(This,Index, Options) -> wxSizer:insertStretchSpacer(This,Index, Options). insertStretchSpacer(This,Index) -> wxSizer:insertStretchSpacer(This,Index). insertSpacer(This,Index,Size) -> wxSizer:insertSpacer(This,Index,Size). insert(This,Index,Width,Height, Options) -> wxSizer:insert(This,Index,Width,Height, Options). insert(This,Index,Width,Height) -> wxSizer:insert(This,Index,Width,Height). insert(This,Index,Item) -> wxSizer:insert(This,Index,Item). hide(This,Window, Options) -> wxSizer:hide(This,Window, Options). hide(This,Window) -> wxSizer:hide(This,Window). getMinSize(This) -> wxSizer:getMinSize(This). getPosition(This) -> wxSizer:getPosition(This). getSize(This) -> wxSizer:getSize(This). getItem(This,Window, Options) -> wxSizer:getItem(This,Window, Options). getItem(This,Window) -> wxSizer:getItem(This,Window). getChildren(This) -> wxSizer:getChildren(This). fitInside(This,Window) -> wxSizer:fitInside(This,Window). fit(This,Window) -> wxSizer:fit(This,Window). detach(This,Index) -> wxSizer:detach(This,Index). clear(This, Options) -> wxSizer:clear(This, Options). clear(This) -> wxSizer:clear(This). calcMin(This) -> wxSizer:calcMin(This). addStretchSpacer(This, Options) -> wxSizer:addStretchSpacer(This, Options). addStretchSpacer(This) -> wxSizer:addStretchSpacer(This). addSpacer(This,Size) -> wxSizer:addSpacer(This,Size). add(This,Width,Height, Options) -> wxSizer:add(This,Width,Height, Options). add(This,Width,Height) -> wxSizer:add(This,Width,Height). add(This,Window) -> wxSizer:add(This,Window).
8406f8cbb64a30d37a22c683ef2bd9819171ae31125f3ac1ca4c7db140302df2
everpeace/programming-erlang-code
vshlr1.erl
-module(vshlr1). -export([start/0, stop/0, handle_event/2, i_am_at/2, find/1]). -import(server1, [start/3, stop/1, rpc/2]). -import(dict, [new/0, store/3, find/2]). start() -> start(vshlr, fun handle_event/2, new()). stop() -> stop(vshlr). i_am_at(Who, Where) -> rpc(vshlr, {i_am_at, Who, Where}). find(Who) -> rpc(vshlr, {find, Who}). handle_event({i_am_at, Who, Where}, Dict) -> {ok, store(Who, Where, Dict)}; handle_event({find, Who}, Dict) -> {find(Who, Dict), Dict}.
null
https://raw.githubusercontent.com/everpeace/programming-erlang-code/8ef31aa13d15b41754dda225c50284915c29cb48/code/vshlr1.erl
erlang
-module(vshlr1). -export([start/0, stop/0, handle_event/2, i_am_at/2, find/1]). -import(server1, [start/3, stop/1, rpc/2]). -import(dict, [new/0, store/3, find/2]). start() -> start(vshlr, fun handle_event/2, new()). stop() -> stop(vshlr). i_am_at(Who, Where) -> rpc(vshlr, {i_am_at, Who, Where}). find(Who) -> rpc(vshlr, {find, Who}). handle_event({i_am_at, Who, Where}, Dict) -> {ok, store(Who, Where, Dict)}; handle_event({find, Who}, Dict) -> {find(Who, Dict), Dict}.
9b0a028eeff831079796f881456a234a4e2905aa4ac46bd3ef6fe7d2886d7628
brendanhay/gogol
TestIamPermissions.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . Storage . Objects . TestIamPermissions Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- -- Tests a set of permissions on the given object to see which, if any, are held by the caller. -- -- /See:/ </ Cloud Storage JSON API Reference> for @storage.objects.testIamPermissions@. module Gogol.Storage.Objects.TestIamPermissions ( -- * Resource StorageObjectsTestIamPermissionsResource, -- ** Constructing a Request StorageObjectsTestIamPermissions (..), newStorageObjectsTestIamPermissions, ) where import qualified Gogol.Prelude as Core import Gogol.Storage.Types -- | A resource alias for @storage.objects.testIamPermissions@ method which the ' StorageObjectsTestIamPermissions ' request conforms to . type StorageObjectsTestIamPermissionsResource = "storage" Core.:> "v1" Core.:> "b" Core.:> Core.Capture "bucket" Core.Text Core.:> "o" Core.:> Core.Capture "object" Core.Text Core.:> "iam" Core.:> "testPermissions" Core.:> Core.QueryParams "permissions" Core.Text Core.:> Core.QueryParam "generation" Core.Int64 Core.:> Core.QueryParam "provisionalUserProject" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "userProject" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.Get '[Core.JSON] TestIamPermissionsResponse -- | Tests a set of permissions on the given object to see which, if any, are held by the caller. -- -- /See:/ 'newStorageObjectsTestIamPermissions' smart constructor. data StorageObjectsTestIamPermissions = StorageObjectsTestIamPermissions { -- | Name of the bucket in which the object resides. bucket :: Core.Text, -- | If present, selects a specific revision of this object (as opposed to the latest version, the default). generation :: (Core.Maybe Core.Int64), -- | Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. object :: Core.Text, -- | Permissions to test. permissions :: [Core.Text], -- | The project to be billed for this request if the target bucket is requester-pays bucket. provisionalUserProject :: (Core.Maybe Core.Text), | Upload protocol for media ( e.g. \"media\ " , \"multipart\ " , \"resumable\ " ) . uploadType :: (Core.Maybe Core.Text), -- | The project to be billed for this request. Required for Requester Pays buckets. userProject :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' StorageObjectsTestIamPermissions ' with the minimum fields required to make a request . newStorageObjectsTestIamPermissions :: -- | Name of the bucket in which the object resides. See 'bucket'. Core.Text -> -- | Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. See 'object'. Core.Text -> -- | Permissions to test. See 'permissions'. [Core.Text] -> StorageObjectsTestIamPermissions newStorageObjectsTestIamPermissions bucket object permissions = StorageObjectsTestIamPermissions { bucket = bucket, generation = Core.Nothing, object = object, permissions = permissions, provisionalUserProject = Core.Nothing, uploadType = Core.Nothing, userProject = Core.Nothing } instance Core.GoogleRequest StorageObjectsTestIamPermissions where type Rs StorageObjectsTestIamPermissions = TestIamPermissionsResponse type Scopes StorageObjectsTestIamPermissions = '[ CloudPlatform'FullControl, CloudPlatform'ReadOnly, Devstorage'FullControl, Devstorage'ReadOnly, Devstorage'ReadWrite ] requestClient StorageObjectsTestIamPermissions {..} = go bucket object permissions generation provisionalUserProject uploadType userProject (Core.Just Core.AltJSON) storageService where go = Core.buildClient ( Core.Proxy :: Core.Proxy StorageObjectsTestIamPermissionsResource ) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-storage/gen/Gogol/Storage/Objects/TestIamPermissions.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated Tests a set of permissions on the given object to see which, if any, are held by the caller. /See:/ </ Cloud Storage JSON API Reference> for @storage.objects.testIamPermissions@. * Resource ** Constructing a Request | A resource alias for @storage.objects.testIamPermissions@ method which the | Tests a set of permissions on the given object to see which, if any, are held by the caller. /See:/ 'newStorageObjectsTestIamPermissions' smart constructor. | Name of the bucket in which the object resides. | If present, selects a specific revision of this object (as opposed to the latest version, the default). | Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. | Permissions to test. | The project to be billed for this request if the target bucket is requester-pays bucket. | The project to be billed for this request. Required for Requester Pays buckets. | Name of the bucket in which the object resides. See 'bucket'. | Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. See 'object'. | Permissions to test. See 'permissions'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . Storage . Objects . TestIamPermissions Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Gogol.Storage.Objects.TestIamPermissions StorageObjectsTestIamPermissionsResource, StorageObjectsTestIamPermissions (..), newStorageObjectsTestIamPermissions, ) where import qualified Gogol.Prelude as Core import Gogol.Storage.Types ' StorageObjectsTestIamPermissions ' request conforms to . type StorageObjectsTestIamPermissionsResource = "storage" Core.:> "v1" Core.:> "b" Core.:> Core.Capture "bucket" Core.Text Core.:> "o" Core.:> Core.Capture "object" Core.Text Core.:> "iam" Core.:> "testPermissions" Core.:> Core.QueryParams "permissions" Core.Text Core.:> Core.QueryParam "generation" Core.Int64 Core.:> Core.QueryParam "provisionalUserProject" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "userProject" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.Get '[Core.JSON] TestIamPermissionsResponse data StorageObjectsTestIamPermissions = StorageObjectsTestIamPermissions bucket :: Core.Text, generation :: (Core.Maybe Core.Int64), object :: Core.Text, permissions :: [Core.Text], provisionalUserProject :: (Core.Maybe Core.Text), | Upload protocol for media ( e.g. \"media\ " , \"multipart\ " , \"resumable\ " ) . uploadType :: (Core.Maybe Core.Text), userProject :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' StorageObjectsTestIamPermissions ' with the minimum fields required to make a request . newStorageObjectsTestIamPermissions :: Core.Text -> Core.Text -> [Core.Text] -> StorageObjectsTestIamPermissions newStorageObjectsTestIamPermissions bucket object permissions = StorageObjectsTestIamPermissions { bucket = bucket, generation = Core.Nothing, object = object, permissions = permissions, provisionalUserProject = Core.Nothing, uploadType = Core.Nothing, userProject = Core.Nothing } instance Core.GoogleRequest StorageObjectsTestIamPermissions where type Rs StorageObjectsTestIamPermissions = TestIamPermissionsResponse type Scopes StorageObjectsTestIamPermissions = '[ CloudPlatform'FullControl, CloudPlatform'ReadOnly, Devstorage'FullControl, Devstorage'ReadOnly, Devstorage'ReadWrite ] requestClient StorageObjectsTestIamPermissions {..} = go bucket object permissions generation provisionalUserProject uploadType userProject (Core.Just Core.AltJSON) storageService where go = Core.buildClient ( Core.Proxy :: Core.Proxy StorageObjectsTestIamPermissionsResource ) Core.mempty
8f1794c431ef0cb2ecd48c08bc609c235a882b9e997315b0184999821fbec04c
kit-ty-kate/visitors
VisitorsAnalysis.ml
open Ppxlib open Result open Asttypes open Parsetree open Ast_helper open Ppx_deriving open VisitorsPlugin (* This module offers helper functions for abstract syntax tree analysis. *) (* -------------------------------------------------------------------------- *) type tycon = string type tyvar = string type tyvars = tyvar list (* -------------------------------------------------------------------------- *) (* Testing whether an identifier is valid. *) We use 's lexer to analyze the string and check if it is a valid identifier . This method is slightly unorthodox , as the lexer can have undesired side effects , such as raising an [ Error ] exception or printing warnings . We do our best to hide these effects . The strength of this approach is to give us ( at little cost ) a correct criterion for deciding if an identifier is valid . identifier. This method is slightly unorthodox, as the lexer can have undesired side effects, such as raising an [Error] exception or printing warnings. We do our best to hide these effects. The strength of this approach is to give us (at little cost) a correct criterion for deciding if an identifier is valid. *) Note : [ Location.formatter_for_warnings ] appeared in OCaml 4.02.2 . type classification = | LIDENT | UIDENT | OTHER let classify (s : string) : classification = let lexbuf = Lexing.from_string s in let backup = !Ocaml_common.Location.formatter_for_warnings in let null = Format.formatter_of_buffer (Buffer.create 0) in Ocaml_common.Location.formatter_for_warnings := null; let result = try let token1 = Lexer.token lexbuf in let token2 = Lexer.token lexbuf in match token1, token2 with | Parser.LIDENT _, Parser.EOF -> LIDENT | Parser.UIDENT _, Parser.EOF -> UIDENT | _, _ -> OTHER with Lexer.Error _ -> OTHER in Ocaml_common.Location.formatter_for_warnings := backup; result (* -------------------------------------------------------------------------- *) (* Testing if a string is a valid [mod_longident], i.e., a possibly-qualified module identifier. *) We might wish to use 's parser for this purpose , but [ mod_longident ] is not declared as a start symbol . Furthermore , that would be perhaps slightly too lenient , e.g. , allowing whitespace and comments inside . Our solution is to split at the dots and check that every piece is a valid module name . not declared as a start symbol. Furthermore, that would be perhaps slightly too lenient, e.g., allowing whitespace and comments inside. Our solution is to split at the dots and check that every piece is a valid module name. *) We used to use [ ] to do the splitting , but this function has been deprecated as of 4.11.0 , and its suggested replacements do not go as far back in time as we need . So , we use our own variant of this code . been deprecated as of 4.11.0, and its suggested replacements do not go as far back in time as we need. So, we use our own variant of this code. *) let rec parse s n = (* Parse the substring that extends from offset 0 to offset [n] excluded. *) try let i = String.rindex_from s (n - 1) '.' in let segment = String.sub s (i + 1) (n - (i + 1)) in Ldot (parse s i, segment) with Not_found -> Lident (String.sub s 0 n) let parse s = parse s (String.length s) let is_valid_mod_longident (m : string) : bool = String.length m > 0 && let ms = Longident.flatten_exn (parse m) in List.for_all (fun m -> classify m = UIDENT) ms (* -------------------------------------------------------------------------- *) (* Testing if a string is a valid [class_longident], i.e., a possibly-qualified class identifier. *) let is_valid_class_longident (m : string) : bool = String.length m > 0 && match parse m with | Lident c -> classify c = LIDENT | Ldot (m, c) -> List.for_all (fun m -> classify m = UIDENT) (Longident.flatten_exn m) && classify c = LIDENT | Lapply _ -> assert false (* this cannot happen *) (* -------------------------------------------------------------------------- *) (* Testing if a string is a valid method name prefix. *) let is_valid_method_name_prefix (m : string) : bool = String.length m > 0 && classify m = LIDENT (* -------------------------------------------------------------------------- *) (* Testing for the presence of attributes. *) (* We use [ppx_deriving] to extract a specific attribute from an attribute list. By convention, an attribute named [foo] can also be referred to as [visitors.foo] or as [deriving.visitors.foo]. *) (* [select foo attrs] extracts the attribute named [foo] from the attribute list [attrs]. *) let select (foo : string) (attrs : attributes) : attribute option = attr ~deriver:plugin foo attrs (* [present foo attrs] tests whether an attribute named [foo] is present (with no argument) in the list [attrs]. *) let present (foo : string) (attrs : attributes) : bool = Arg.get_flag ~deriver:plugin (select foo attrs) (* [opacity attrs] tests for the presence of an [@opaque] attribute. *) type opacity = | Opaque | NonOpaque let opacity (attrs : attributes) : opacity = if present "opaque" attrs then Opaque else NonOpaque (* [name attrs] tests for the presence of a [@name] attribute, carrying a payload of type [string]. We check that the payload is a valid (lowercase or uppercase) identifier, because we intend to use it as the basis of a method name. *) let identifier : string Arg.conv = fun e -> match Arg.string e with | Error msg -> Error msg | Ok s -> match classify s with | LIDENT | UIDENT -> Ok s | OTHER -> Error "identifier" let name (attrs : attributes) : string option = Arg.get_attr ~deriver:plugin identifier (select "name" attrs) [ build attrs ] tests for the presence of a [ @build ] attribute , carrying a payload that is an arbitrary OCaml expression . carrying a payload that is an arbitrary OCaml expression. *) let build (attrs : attributes) : expression option = Arg.get_attr ~deriver:plugin Arg.expr (select "build" attrs) (* [maybe ox y] returns [x] if present, otherwise [y]. *) let maybe (ox : 'a option) (y : 'a) : 'a = match ox with Some x -> x | None -> y (* -------------------------------------------------------------------------- *) (* When parsing a record declaration, the OCaml parser attaches attributes with field labels, whereas the user might naturally expect them to be attached with the type. We rectify this situation by copying all attributes from the label to the type. This might seem dangerous, but we use it only to test for the presence of an [@opaque] attribute. *) let paste (ty : core_type) (attrs : attributes) : core_type = { ty with ptyp_attributes = attrs @ ty.ptyp_attributes } let fix (ld : label_declaration) : label_declaration = { ld with pld_type = paste ld.pld_type ld.pld_attributes } let fix = List.map fix (* -------------------------------------------------------------------------- *) (* [type_param_to_tyvar] expects a type parameter as found in the field [ptype_params] of a type definition, and returns the underlying type variable. *) let type_param_to_tyvar ((ty, _) : core_type * variance) : tyvar = match ty.ptyp_desc with | Ptyp_var tv -> tv | Ptyp_any -> This error occurs if a formal type parameter is a wildcard [ _ ] . We could support this form , but it makes life slightly simpler to disallow it . It is usually used only in GADTs anyway . We could support this form, but it makes life slightly simpler to disallow it. It is usually used only in GADTs anyway. *) raise_errorf ~loc:ty.ptyp_loc "%s: every formal type parameter should be named." plugin | _ -> assert false let type_params_to_tyvars = List.map type_param_to_tyvar [ decl_params decl ] returns the type parameters of the declaration [ ] . let decl_params (decl : type_declaration) : tyvars = type_params_to_tyvars decl.ptype_params (* [is_local decls tycon] tests whether the type constructor [tycon] is declared by the type declarations [decls]. If so, it returns the corresponding declaration. *) let rec is_local (decls : type_declaration list) (tycon : tycon) : type_declaration option = match decls with | [] -> None | decl :: decls -> if decl.ptype_name.txt = tycon then Some decl else is_local decls tycon let is_local (decls : type_declaration list) (tycon : Longident.t) : type_declaration option = match tycon with | Lident tycon -> is_local decls tycon | Ldot _ | Lapply _ -> None (* -------------------------------------------------------------------------- *) (* [occurs_type alpha ty] tests whether the type variable [alpha] occurs in the type [ty]. This function goes down into all OCaml types, even those that are not supported by [visitors]. *) exception Occurs of loc let rec occurs_type (alpha : tyvar) (ty : core_type) : unit = match ty.ptyp_desc with | Ptyp_any -> () | Ptyp_var beta -> if alpha = beta then raise (Occurs ty.ptyp_loc) | Ptyp_alias (ty, _) -> (* This is not a binder; just go down into it. *) occurs_type alpha ty | Ptyp_arrow (_, ty1, ty2) -> occurs_types alpha [ ty1; ty2 ] | Ptyp_tuple tys | Ptyp_constr (_, tys) | Ptyp_class (_, tys) -> occurs_types alpha tys | Ptyp_object (fields, _) -> fields |> List.map VisitorsCompatibility.object_field_to_core_type |> occurs_types alpha | Ptyp_variant (fields, _, _) -> List.iter (occurs_row_field alpha) fields | Ptyp_poly (qs, ty) -> let qs : string list = VisitorsCompatibility.quantifiers qs in (* The type variables in [qs] are bound. *) if not (occurs_quantifiers alpha qs) then occurs_type alpha ty | Ptyp_package (_, ltys) -> List.iter (fun (_, ty) -> occurs_type alpha ty) ltys | Ptyp_extension (_, payload) -> occurs_payload alpha payload and occurs_types alpha tys = List.iter (occurs_type alpha) tys and occurs_row_field alpha field = field |> VisitorsCompatibility.row_field_to_core_types |> occurs_types alpha and occurs_quantifiers alpha (qs : string list) = List.mem alpha qs and occurs_payload alpha = function | PTyp ty -> occurs_type alpha ty (* | PStr _ | PPat _ *) | PSig _ ( * > = 4.03 | _ -> (* We assume that these cases won't arise or won't have any free type variables in them. *) () (* -------------------------------------------------------------------------- *) (* An error message about an unsupported type. *) let unsupported ty = let loc = ty.ptyp_loc in raise_errorf ~loc "%s: cannot deal with the type %s.\n\ Consider annotating it with [@opaque]." plugin (string_of_core_type ty) (* -------------------------------------------------------------------------- *) (* [at_opaque f ty] applies the function [f] to every [@opaque] component of the type [ty]. *) let rec at_opaque (f : core_type -> unit) (ty : core_type) : unit = match opacity ty.ptyp_attributes, ty.ptyp_desc with | NonOpaque, Ptyp_any | NonOpaque, Ptyp_var _ -> () | NonOpaque, Ptyp_tuple tys | NonOpaque, Ptyp_constr (_, tys) -> List.iter (at_opaque f) tys | Opaque, _ -> f ty | NonOpaque, Ptyp_arrow _ | NonOpaque, Ptyp_object _ | NonOpaque, Ptyp_class _ | NonOpaque, Ptyp_alias _ | NonOpaque, Ptyp_variant _ | NonOpaque, Ptyp_poly _ | NonOpaque, Ptyp_package _ | NonOpaque, Ptyp_extension _ -> unsupported ty (* -------------------------------------------------------------------------- *) (* [check_poly_under_opaque alphas tys] checks that none of the type variables [alphas] appears under [@opaque] in the types [tys]. *) let check_poly_under_opaque alphas tys = List.iter (fun alpha -> List.iter (fun ty -> at_opaque (fun ty -> try occurs_type alpha ty with Occurs loc -> raise_errorf ~loc "%s: a [polymorphic] type variable must not appear under @opaque." plugin ) ty ) tys ) alphas (* -------------------------------------------------------------------------- *) (* [subst_type sigma ty] applies [sigma], a substitution of types for type variables, to the type [ty]. [rename_type rho ty] applies [rho], a renaming of type variables, to the type [ty]. *) (* We do not go down into [@opaque] types. We replace every opaque type with a wildcard [_]. Because we have checked that [poly] variables do not appear under [@opaque], this is good enough: there is never a need for an explicitly named/quantified type variable to describe an opaque component. *) type substitution = tyvar -> core_type type renaming = tyvar -> tyvar let rec subst_type (sigma : substitution) (ty : core_type) : core_type = match opacity ty.ptyp_attributes, ty.ptyp_desc with | NonOpaque, Ptyp_any -> ty | NonOpaque, Ptyp_var alpha -> sigma alpha | NonOpaque, Ptyp_tuple tys -> { ty with ptyp_desc = Ptyp_tuple (subst_types sigma tys) } | NonOpaque, Ptyp_constr (tycon, tys) -> { ty with ptyp_desc = Ptyp_constr (tycon, subst_types sigma tys) } | Opaque, _ -> Typ.any() | NonOpaque, Ptyp_arrow _ | NonOpaque, Ptyp_object _ | NonOpaque, Ptyp_class _ | NonOpaque, Ptyp_alias _ | NonOpaque, Ptyp_variant _ | NonOpaque, Ptyp_poly _ | NonOpaque, Ptyp_package _ | NonOpaque, Ptyp_extension _ -> unsupported ty and subst_types sigma tys = List.map (subst_type sigma) tys let rename_type (rho : renaming) (ty : core_type) : core_type = subst_type (fun alpha -> Typ.var (rho alpha)) ty
null
https://raw.githubusercontent.com/kit-ty-kate/visitors/fc53cc486178781e0b1e581eced98e07facb7d29/src/VisitorsAnalysis.ml
ocaml
This module offers helper functions for abstract syntax tree analysis. -------------------------------------------------------------------------- -------------------------------------------------------------------------- Testing whether an identifier is valid. -------------------------------------------------------------------------- Testing if a string is a valid [mod_longident], i.e., a possibly-qualified module identifier. Parse the substring that extends from offset 0 to offset [n] excluded. -------------------------------------------------------------------------- Testing if a string is a valid [class_longident], i.e., a possibly-qualified class identifier. this cannot happen -------------------------------------------------------------------------- Testing if a string is a valid method name prefix. -------------------------------------------------------------------------- Testing for the presence of attributes. We use [ppx_deriving] to extract a specific attribute from an attribute list. By convention, an attribute named [foo] can also be referred to as [visitors.foo] or as [deriving.visitors.foo]. [select foo attrs] extracts the attribute named [foo] from the attribute list [attrs]. [present foo attrs] tests whether an attribute named [foo] is present (with no argument) in the list [attrs]. [opacity attrs] tests for the presence of an [@opaque] attribute. [name attrs] tests for the presence of a [@name] attribute, carrying a payload of type [string]. We check that the payload is a valid (lowercase or uppercase) identifier, because we intend to use it as the basis of a method name. [maybe ox y] returns [x] if present, otherwise [y]. -------------------------------------------------------------------------- When parsing a record declaration, the OCaml parser attaches attributes with field labels, whereas the user might naturally expect them to be attached with the type. We rectify this situation by copying all attributes from the label to the type. This might seem dangerous, but we use it only to test for the presence of an [@opaque] attribute. -------------------------------------------------------------------------- [type_param_to_tyvar] expects a type parameter as found in the field [ptype_params] of a type definition, and returns the underlying type variable. [is_local decls tycon] tests whether the type constructor [tycon] is declared by the type declarations [decls]. If so, it returns the corresponding declaration. -------------------------------------------------------------------------- [occurs_type alpha ty] tests whether the type variable [alpha] occurs in the type [ty]. This function goes down into all OCaml types, even those that are not supported by [visitors]. This is not a binder; just go down into it. The type variables in [qs] are bound. | PStr _ | PPat _ We assume that these cases won't arise or won't have any free type variables in them. -------------------------------------------------------------------------- An error message about an unsupported type. -------------------------------------------------------------------------- [at_opaque f ty] applies the function [f] to every [@opaque] component of the type [ty]. -------------------------------------------------------------------------- [check_poly_under_opaque alphas tys] checks that none of the type variables [alphas] appears under [@opaque] in the types [tys]. -------------------------------------------------------------------------- [subst_type sigma ty] applies [sigma], a substitution of types for type variables, to the type [ty]. [rename_type rho ty] applies [rho], a renaming of type variables, to the type [ty]. We do not go down into [@opaque] types. We replace every opaque type with a wildcard [_]. Because we have checked that [poly] variables do not appear under [@opaque], this is good enough: there is never a need for an explicitly named/quantified type variable to describe an opaque component.
open Ppxlib open Result open Asttypes open Parsetree open Ast_helper open Ppx_deriving open VisitorsPlugin type tycon = string type tyvar = string type tyvars = tyvar list We use 's lexer to analyze the string and check if it is a valid identifier . This method is slightly unorthodox , as the lexer can have undesired side effects , such as raising an [ Error ] exception or printing warnings . We do our best to hide these effects . The strength of this approach is to give us ( at little cost ) a correct criterion for deciding if an identifier is valid . identifier. This method is slightly unorthodox, as the lexer can have undesired side effects, such as raising an [Error] exception or printing warnings. We do our best to hide these effects. The strength of this approach is to give us (at little cost) a correct criterion for deciding if an identifier is valid. *) Note : [ Location.formatter_for_warnings ] appeared in OCaml 4.02.2 . type classification = | LIDENT | UIDENT | OTHER let classify (s : string) : classification = let lexbuf = Lexing.from_string s in let backup = !Ocaml_common.Location.formatter_for_warnings in let null = Format.formatter_of_buffer (Buffer.create 0) in Ocaml_common.Location.formatter_for_warnings := null; let result = try let token1 = Lexer.token lexbuf in let token2 = Lexer.token lexbuf in match token1, token2 with | Parser.LIDENT _, Parser.EOF -> LIDENT | Parser.UIDENT _, Parser.EOF -> UIDENT | _, _ -> OTHER with Lexer.Error _ -> OTHER in Ocaml_common.Location.formatter_for_warnings := backup; result We might wish to use 's parser for this purpose , but [ mod_longident ] is not declared as a start symbol . Furthermore , that would be perhaps slightly too lenient , e.g. , allowing whitespace and comments inside . Our solution is to split at the dots and check that every piece is a valid module name . not declared as a start symbol. Furthermore, that would be perhaps slightly too lenient, e.g., allowing whitespace and comments inside. Our solution is to split at the dots and check that every piece is a valid module name. *) We used to use [ ] to do the splitting , but this function has been deprecated as of 4.11.0 , and its suggested replacements do not go as far back in time as we need . So , we use our own variant of this code . been deprecated as of 4.11.0, and its suggested replacements do not go as far back in time as we need. So, we use our own variant of this code. *) let rec parse s n = try let i = String.rindex_from s (n - 1) '.' in let segment = String.sub s (i + 1) (n - (i + 1)) in Ldot (parse s i, segment) with Not_found -> Lident (String.sub s 0 n) let parse s = parse s (String.length s) let is_valid_mod_longident (m : string) : bool = String.length m > 0 && let ms = Longident.flatten_exn (parse m) in List.for_all (fun m -> classify m = UIDENT) ms let is_valid_class_longident (m : string) : bool = String.length m > 0 && match parse m with | Lident c -> classify c = LIDENT | Ldot (m, c) -> List.for_all (fun m -> classify m = UIDENT) (Longident.flatten_exn m) && classify c = LIDENT | Lapply _ -> let is_valid_method_name_prefix (m : string) : bool = String.length m > 0 && classify m = LIDENT let select (foo : string) (attrs : attributes) : attribute option = attr ~deriver:plugin foo attrs let present (foo : string) (attrs : attributes) : bool = Arg.get_flag ~deriver:plugin (select foo attrs) type opacity = | Opaque | NonOpaque let opacity (attrs : attributes) : opacity = if present "opaque" attrs then Opaque else NonOpaque let identifier : string Arg.conv = fun e -> match Arg.string e with | Error msg -> Error msg | Ok s -> match classify s with | LIDENT | UIDENT -> Ok s | OTHER -> Error "identifier" let name (attrs : attributes) : string option = Arg.get_attr ~deriver:plugin identifier (select "name" attrs) [ build attrs ] tests for the presence of a [ @build ] attribute , carrying a payload that is an arbitrary OCaml expression . carrying a payload that is an arbitrary OCaml expression. *) let build (attrs : attributes) : expression option = Arg.get_attr ~deriver:plugin Arg.expr (select "build" attrs) let maybe (ox : 'a option) (y : 'a) : 'a = match ox with Some x -> x | None -> y let paste (ty : core_type) (attrs : attributes) : core_type = { ty with ptyp_attributes = attrs @ ty.ptyp_attributes } let fix (ld : label_declaration) : label_declaration = { ld with pld_type = paste ld.pld_type ld.pld_attributes } let fix = List.map fix let type_param_to_tyvar ((ty, _) : core_type * variance) : tyvar = match ty.ptyp_desc with | Ptyp_var tv -> tv | Ptyp_any -> This error occurs if a formal type parameter is a wildcard [ _ ] . We could support this form , but it makes life slightly simpler to disallow it . It is usually used only in GADTs anyway . We could support this form, but it makes life slightly simpler to disallow it. It is usually used only in GADTs anyway. *) raise_errorf ~loc:ty.ptyp_loc "%s: every formal type parameter should be named." plugin | _ -> assert false let type_params_to_tyvars = List.map type_param_to_tyvar [ decl_params decl ] returns the type parameters of the declaration [ ] . let decl_params (decl : type_declaration) : tyvars = type_params_to_tyvars decl.ptype_params let rec is_local (decls : type_declaration list) (tycon : tycon) : type_declaration option = match decls with | [] -> None | decl :: decls -> if decl.ptype_name.txt = tycon then Some decl else is_local decls tycon let is_local (decls : type_declaration list) (tycon : Longident.t) : type_declaration option = match tycon with | Lident tycon -> is_local decls tycon | Ldot _ | Lapply _ -> None exception Occurs of loc let rec occurs_type (alpha : tyvar) (ty : core_type) : unit = match ty.ptyp_desc with | Ptyp_any -> () | Ptyp_var beta -> if alpha = beta then raise (Occurs ty.ptyp_loc) | Ptyp_alias (ty, _) -> occurs_type alpha ty | Ptyp_arrow (_, ty1, ty2) -> occurs_types alpha [ ty1; ty2 ] | Ptyp_tuple tys | Ptyp_constr (_, tys) | Ptyp_class (_, tys) -> occurs_types alpha tys | Ptyp_object (fields, _) -> fields |> List.map VisitorsCompatibility.object_field_to_core_type |> occurs_types alpha | Ptyp_variant (fields, _, _) -> List.iter (occurs_row_field alpha) fields | Ptyp_poly (qs, ty) -> let qs : string list = VisitorsCompatibility.quantifiers qs in if not (occurs_quantifiers alpha qs) then occurs_type alpha ty | Ptyp_package (_, ltys) -> List.iter (fun (_, ty) -> occurs_type alpha ty) ltys | Ptyp_extension (_, payload) -> occurs_payload alpha payload and occurs_types alpha tys = List.iter (occurs_type alpha) tys and occurs_row_field alpha field = field |> VisitorsCompatibility.row_field_to_core_types |> occurs_types alpha and occurs_quantifiers alpha (qs : string list) = List.mem alpha qs and occurs_payload alpha = function | PTyp ty -> occurs_type alpha ty | PSig _ ( * > = 4.03 | _ -> () let unsupported ty = let loc = ty.ptyp_loc in raise_errorf ~loc "%s: cannot deal with the type %s.\n\ Consider annotating it with [@opaque]." plugin (string_of_core_type ty) let rec at_opaque (f : core_type -> unit) (ty : core_type) : unit = match opacity ty.ptyp_attributes, ty.ptyp_desc with | NonOpaque, Ptyp_any | NonOpaque, Ptyp_var _ -> () | NonOpaque, Ptyp_tuple tys | NonOpaque, Ptyp_constr (_, tys) -> List.iter (at_opaque f) tys | Opaque, _ -> f ty | NonOpaque, Ptyp_arrow _ | NonOpaque, Ptyp_object _ | NonOpaque, Ptyp_class _ | NonOpaque, Ptyp_alias _ | NonOpaque, Ptyp_variant _ | NonOpaque, Ptyp_poly _ | NonOpaque, Ptyp_package _ | NonOpaque, Ptyp_extension _ -> unsupported ty let check_poly_under_opaque alphas tys = List.iter (fun alpha -> List.iter (fun ty -> at_opaque (fun ty -> try occurs_type alpha ty with Occurs loc -> raise_errorf ~loc "%s: a [polymorphic] type variable must not appear under @opaque." plugin ) ty ) tys ) alphas type substitution = tyvar -> core_type type renaming = tyvar -> tyvar let rec subst_type (sigma : substitution) (ty : core_type) : core_type = match opacity ty.ptyp_attributes, ty.ptyp_desc with | NonOpaque, Ptyp_any -> ty | NonOpaque, Ptyp_var alpha -> sigma alpha | NonOpaque, Ptyp_tuple tys -> { ty with ptyp_desc = Ptyp_tuple (subst_types sigma tys) } | NonOpaque, Ptyp_constr (tycon, tys) -> { ty with ptyp_desc = Ptyp_constr (tycon, subst_types sigma tys) } | Opaque, _ -> Typ.any() | NonOpaque, Ptyp_arrow _ | NonOpaque, Ptyp_object _ | NonOpaque, Ptyp_class _ | NonOpaque, Ptyp_alias _ | NonOpaque, Ptyp_variant _ | NonOpaque, Ptyp_poly _ | NonOpaque, Ptyp_package _ | NonOpaque, Ptyp_extension _ -> unsupported ty and subst_types sigma tys = List.map (subst_type sigma) tys let rename_type (rho : renaming) (ty : core_type) : core_type = subst_type (fun alpha -> Typ.var (rho alpha)) ty
605b6e4f8ca7570edcf2c7afe6ab836801b95b9c62ca24b936beef7353a49086
noinia/hgeometry
Induction.hs
# LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # module Geometry.Vector.Induction( induction , induction' , inductionPeano , inductionPeano' , All, AllPeano ) where import Data.Kind (Type) import Data.Proxy import Data.Vector.Fixed.Cont (Peano, PeanoNum(..)) import Data.Vinyl.Core import GHC.Exts import GHC.TypeLits import Geometry.Vector.VectorFamilyPeano (FromPeano, ImplicitPeano(..), SingPeano(..)) -------------------------------------------------------------------------------- -- | Induction principle on natural numbers. induction :: forall proxy c p n. ( All c n , ImplicitPeano (Peano n), n ~ FromPeano (Peano n)) => proxy c -> p 0 -- ^ the base case -> (forall (m :: Nat). c (1+m) => p m -> p (1+m)) -- ^ the step case. Items in the step case should satisfy constraint c -> p n induction pc baseCase step = runP $ inductionPeano' (Proxy @(LiftC c)) (P baseCase) step' sn where lift ' step ' to working on numbers step' :: forall (m :: PeanoNum). LiftC c (S m) => (P p) m -> (P p) (S m) step' = case conjure pc (Proxy @(S m)) of DictOnly -> P . step . runP sn :: SingPeano (Peano n) sn = implicitPeano -- | Induction principle for the case that the step does not require -- any additional constraints. induction' :: forall p n. ( ImplicitPeano (Peano n) , n ~ FromPeano (Peano n) , All Unconstrained n ) => p 0 -> (forall (m :: Nat). p m -> p (1+m)) -> p n induction' = induction (Proxy @Unconstrained) -------------------------------------------------------------------------------- | Induction principle on numbers inductionPeano :: forall proxy c p n. (AllPeano c n, ImplicitPeano n) => proxy c -> p Z -> (forall (m :: PeanoNum). c (S m) => p m -> p (S m)) -> p n inductionPeano pc baseCase step = inductionPeano' pc baseCase step (implicitPeano @n) -- | The actual implementation of the induction principle inductionPeano' :: forall proxy c p n. AllPeano c n => proxy c -> p Z -> (forall (m :: PeanoNum). c (S m) => p m -> p (S m)) -> SingPeano n -> p n inductionPeano' _ baseCase step = go where go :: AllPeano c k => SingPeano k -> p k go = \case SZ -> baseCase SS sm -> step $ go sm -------------------------------------------------------------------------------- -- | All numbers [1,n] satisfy the constraint c type All (c :: Nat -> Constraint) n = AllPeano (LiftC c) (Peano n) type family AllPeano (c :: PeanoNum -> Constraint) n :: Constraint where AllPeano c Z = () AllPeano c (S n) = (c (S n), AllPeano c n) -------------------------------------------------------------------------------- * Connecting GHC 's fancy natural numbers with Peano Numbers doing -- the actual work. | We essentially use LiftC as partially applied function lifting a ' Nat - > Constraint ' into a -- 'PeanoNum -> Constraint' class LiftC (c :: Nat -> Constraint) (n :: PeanoNum) where | Helper function to lift the constraint from to PeanoNum conjure :: proxy' c -> proxy n -> DictOnly c (FromPeano n) instance (c (FromPeano n)) => LiftC c n where conjure _ _ = DictOnly | Similary , we lift a ' Nat - > Type ' into a ' PeanoNum - > Type ' newtype P (p :: Nat -> Type) (n :: PeanoNum) = P { runP :: p (FromPeano n) } -------------------------------------------------------------------------------- class Unconstrained (n :: k) instance Unconstrained n
null
https://raw.githubusercontent.com/noinia/hgeometry/e686ab0709fa7d8cbd5c60e416b996aa240a4d0f/hgeometry/src/Geometry/Vector/Induction.hs
haskell
------------------------------------------------------------------------------ | Induction principle on natural numbers. ^ the base case ^ the step case. Items in the step case should satisfy constraint c | Induction principle for the case that the step does not require any additional constraints. ------------------------------------------------------------------------------ | The actual implementation of the induction principle ------------------------------------------------------------------------------ | All numbers [1,n] satisfy the constraint c ------------------------------------------------------------------------------ the actual work. 'PeanoNum -> Constraint' ------------------------------------------------------------------------------
# LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # module Geometry.Vector.Induction( induction , induction' , inductionPeano , inductionPeano' , All, AllPeano ) where import Data.Kind (Type) import Data.Proxy import Data.Vector.Fixed.Cont (Peano, PeanoNum(..)) import Data.Vinyl.Core import GHC.Exts import GHC.TypeLits import Geometry.Vector.VectorFamilyPeano (FromPeano, ImplicitPeano(..), SingPeano(..)) induction :: forall proxy c p n. ( All c n , ImplicitPeano (Peano n), n ~ FromPeano (Peano n)) => proxy c -> p 0 -> (forall (m :: Nat). c (1+m) => p m -> p (1+m)) -> p n induction pc baseCase step = runP $ inductionPeano' (Proxy @(LiftC c)) (P baseCase) step' sn where lift ' step ' to working on numbers step' :: forall (m :: PeanoNum). LiftC c (S m) => (P p) m -> (P p) (S m) step' = case conjure pc (Proxy @(S m)) of DictOnly -> P . step . runP sn :: SingPeano (Peano n) sn = implicitPeano induction' :: forall p n. ( ImplicitPeano (Peano n) , n ~ FromPeano (Peano n) , All Unconstrained n ) => p 0 -> (forall (m :: Nat). p m -> p (1+m)) -> p n induction' = induction (Proxy @Unconstrained) | Induction principle on numbers inductionPeano :: forall proxy c p n. (AllPeano c n, ImplicitPeano n) => proxy c -> p Z -> (forall (m :: PeanoNum). c (S m) => p m -> p (S m)) -> p n inductionPeano pc baseCase step = inductionPeano' pc baseCase step (implicitPeano @n) inductionPeano' :: forall proxy c p n. AllPeano c n => proxy c -> p Z -> (forall (m :: PeanoNum). c (S m) => p m -> p (S m)) -> SingPeano n -> p n inductionPeano' _ baseCase step = go where go :: AllPeano c k => SingPeano k -> p k go = \case SZ -> baseCase SS sm -> step $ go sm type All (c :: Nat -> Constraint) n = AllPeano (LiftC c) (Peano n) type family AllPeano (c :: PeanoNum -> Constraint) n :: Constraint where AllPeano c Z = () AllPeano c (S n) = (c (S n), AllPeano c n) * Connecting GHC 's fancy natural numbers with Peano Numbers doing | We essentially use LiftC as partially applied function lifting a ' Nat - > Constraint ' into a class LiftC (c :: Nat -> Constraint) (n :: PeanoNum) where | Helper function to lift the constraint from to PeanoNum conjure :: proxy' c -> proxy n -> DictOnly c (FromPeano n) instance (c (FromPeano n)) => LiftC c n where conjure _ _ = DictOnly | Similary , we lift a ' Nat - > Type ' into a ' PeanoNum - > Type ' newtype P (p :: Nat -> Type) (n :: PeanoNum) = P { runP :: p (FromPeano n) } class Unconstrained (n :: k) instance Unconstrained n
b12c29e63c854f1dbb1ad2407963b0182c57b35ef5b88724198341fd0e4a0927
manuel-serrano/bigloo
pproto.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / comptime / Coerce / pproto.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Fri Jan 20 10:45:07 1995 * / * Last change : Mon May 15 07:40:41 2000 ( serrano ) * / * Copyright : 1995 - 2000 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* We print prototype */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module coerce_pproto (include "Tools/verbose.sch") (import tools_speek tools_shape type_type type_pptype ast_var) (export (pfunction-proto ::long ::variable) (pvariable-proto ::long ::variable) (reset-ppmarge!) (inc-ppmarge!) (dec-ppmarge!))) ;*---------------------------------------------------------------------*/ ;* reset-ppmarge! ... */ ;*---------------------------------------------------------------------*/ (define (reset-ppmarge!) (set! *pp-marge* 8)) ;*---------------------------------------------------------------------*/ ;* inc-ppmarge! ... */ ;*---------------------------------------------------------------------*/ (define (inc-ppmarge!) (set! *pp-marge* (+fx 1 *pp-marge*))) ;*---------------------------------------------------------------------*/ ;* dec-ppmarge! ... */ ;*---------------------------------------------------------------------*/ (define (dec-ppmarge!) (set! *pp-marge* (-fx *pp-marge* 1))) ;*---------------------------------------------------------------------*/ ;* *pp-marge* ... */ ;*---------------------------------------------------------------------*/ (define *pp-marge* 8) (define old-marge -1) (define old-marge-string "") ;*---------------------------------------------------------------------*/ ;* pfunction-proto ... */ ;*---------------------------------------------------------------------*/ (define (pfunction-proto level variable) (let ((marge (if (=fx old-marge *pp-marge*) old-marge-string (let ((marge (make-string *pp-marge* #\space))) (set! old-marge *pp-marge*) (set! old-marge-string marge) marge)))) (verbose level marge (shape variable) " : " (function-type->string variable) #\Newline))) ;*---------------------------------------------------------------------*/ ;* pvariable-proto ... */ ;*---------------------------------------------------------------------*/ (define (pvariable-proto level variable) (let ((marge (make-string *pp-marge* #\space))) (verbose level marge (shape variable) " : " (variable-type->string variable) #\Newline)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/comptime/Coerce/pproto.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * We print prototype */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * reset-ppmarge! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * inc-ppmarge! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dec-ppmarge! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *pp-marge* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * pfunction-proto ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * pvariable-proto ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / comptime / Coerce / pproto.scm * / * Author : * / * Creation : Fri Jan 20 10:45:07 1995 * / * Last change : Mon May 15 07:40:41 2000 ( serrano ) * / * Copyright : 1995 - 2000 , see LICENSE file * / (module coerce_pproto (include "Tools/verbose.sch") (import tools_speek tools_shape type_type type_pptype ast_var) (export (pfunction-proto ::long ::variable) (pvariable-proto ::long ::variable) (reset-ppmarge!) (inc-ppmarge!) (dec-ppmarge!))) (define (reset-ppmarge!) (set! *pp-marge* 8)) (define (inc-ppmarge!) (set! *pp-marge* (+fx 1 *pp-marge*))) (define (dec-ppmarge!) (set! *pp-marge* (-fx *pp-marge* 1))) (define *pp-marge* 8) (define old-marge -1) (define old-marge-string "") (define (pfunction-proto level variable) (let ((marge (if (=fx old-marge *pp-marge*) old-marge-string (let ((marge (make-string *pp-marge* #\space))) (set! old-marge *pp-marge*) (set! old-marge-string marge) marge)))) (verbose level marge (shape variable) " : " (function-type->string variable) #\Newline))) (define (pvariable-proto level variable) (let ((marge (make-string *pp-marge* #\space))) (verbose level marge (shape variable) " : " (variable-type->string variable) #\Newline)))
2b0ac1cf6e1db4d950dac7f7cec66e331086b8950aef41a91d27b89ad723aa31
biocad/math-grads
GenericGraph.hs
# LANGUAGE DeriveGeneric # # LANGUAGE InstanceSigs # # LANGUAGE ViewPatterns # -- | Module that provides abstract implementation of graph-like data structure -- 'GenericGraph' and many helpful functions for interaction with 'GenericGraph'. -- module Math.Grads.GenericGraph ( GenericGraph (..) , addEdges , addVertices , applyG , applyV , getVertices , getEdge , isConnected , removeEdges , removeVertices , safeAt , safeIdx , subgraph, subgraphWithReindex , sumGraphs , typeOfEdge ) where import Control.Arrow (first) import Data.Aeson (FromJSON (..), ToJSON (..), defaultOptions, genericParseJSON, genericToJSON) import Data.Array (Array) import qualified Data.Array as A import Data.Bimap (Bimap) import qualified Data.Bimap as BM import Data.List (find, groupBy, sortBy) import Data.Map.Strict (Map, mapKeys, member, (!)) import qualified Data.Map.Strict as M import Data.Maybe (fromJust, fromMaybe, isJust) import qualified Data.Set as S import GHC.Generics (Generic) import Math.Grads.Graph (Graph (..)) -- | Generic undirected graph which stores elements of type v in its vertices (e.g. labels, atoms, states etc) -- and elements of type e in its edges (e.g. weights, bond types, functions over states etc). Note that loops and multiple edges between two vertices are allowed . -- data GenericGraph v e = GenericGraph { gIndex :: Array Int v -- ^ 'Array' that contains vrtices of graph , gRevIndex :: Map v Int -- ^ 'Map' that maps vertices to their indices , gAdjacency :: Array Int [(Int, e)] -- ^ adjacency 'Array' of graph } deriving (Generic) instance (Ord v, Eq e, ToJSON v, ToJSON e) => ToJSON (GenericGraph v e) where toJSON (toList -> l) = genericToJSON defaultOptions l instance (Ord v, Eq e, FromJSON v, FromJSON e) => FromJSON (GenericGraph v e) where parseJSON v = fromList <$> genericParseJSON defaultOptions v instance Graph GenericGraph where fromList :: (Ord v, Eq v) => ([v], [(Int, Int, e)]) -> GenericGraph v e fromList (vertices, edges) = GenericGraph idxArr revMap adjArr where count = length vertices idxArr = A.listArray (0, count - 1) vertices revMap = M.fromList $ zip vertices [0..] indices = concatMap insertFunc edges insertFunc (at, other, b) | at == other = [(at, (other, b))] | otherwise = [(at, (other, b)), (other, (at, b))] adjArr = A.accumArray (flip (:)) [] (0, count - 1) indices toList :: (Ord v, Eq v) => GenericGraph v e -> ([v], [(Int, Int, e)]) toList (GenericGraph idxArr _ adjArr) = (snd <$> A.assocs idxArr, edges) where edges = distinct . concatMap toEdges . A.assocs $ adjArr toEdges (k, v) = map (toAscending k) v toAscending k (a, b) | k > a = (a, k, b) | otherwise = (k, a, b) compare3 (at1, other1, _) (at2, other2, _) = compare (at1, other1) (at2, other2) eq3 v1 v2 = compare3 v1 v2 == EQ distinct = map head . groupBy eq3 . sortBy compare3 vCount :: GenericGraph v e -> Int vCount (GenericGraph idxArr _ _) = length idxArr (!>) :: (Ord v, Eq v) => GenericGraph v e -> v -> [(v, e)] (GenericGraph idxArr revMap adjArr) !> at = first (idxArr A.!) <$> adjacent where idx = revMap ! at adjacent = adjArr A.! idx (?>) :: (Ord v, Eq v) => GenericGraph v e -> v -> Maybe [(v, e)] gr@(GenericGraph _ revMap _) ?> at | at `member` revMap = Just (gr !> at) | otherwise = Nothing (!.) :: GenericGraph v e -> Int -> [(Int, e)] (!.) (GenericGraph _ _ adjArr) = (adjArr A.!) (?.) :: GenericGraph v e -> Int -> Maybe [(Int, e)] gr@(GenericGraph _ _ adjArr) ?. idx | idx `inBounds` A.bounds adjArr = Just (gr !. idx) | otherwise = Nothing where -- | Check whether or not given value is betwen bounds. -- inBounds :: Ord a => a -> (a, a) -> Bool inBounds i (lo, hi) = (i >= lo) && (i <= hi) instance (Ord v, Eq v, Show v, Show e) => Show (GenericGraph v e) where show gr = unlines . map fancyShow . filter (\(a, b, _) -> a < b) . snd . toList $ gr where idxArr = gIndex gr fancyShow (at, other, bond) = concat [show $ idxArr A.! at, "\t", show bond, "\t", show $ idxArr A.! other] instance Functor (GenericGraph v) where fmap f (GenericGraph idxArr revMap adjArr) = GenericGraph idxArr revMap (((f <$>) <$>) <$> adjArr) instance Ord v => Semigroup (GenericGraph v e) where (<>) = sumGraphs instance (Ord v, Eq v) => Monoid (GenericGraph v e) where mempty = fromList ([], []) -- | 'fmap' which acts on adjacency lists of each vertex. -- applyG :: ([(Int, e1)] -> [(Int, e2)]) -> GenericGraph v e1 -> GenericGraph v e2 applyG f (GenericGraph idxArr revMap adjArr) = GenericGraph idxArr revMap (f <$> adjArr) -- | 'fmap' which acts on vertices. -- applyV :: Ord v2 => (v1 -> v2) -> GenericGraph v1 e -> GenericGraph v2 e applyV f (GenericGraph idxArr revMap adjArr) = GenericGraph (f <$> idxArr) (mapKeys f revMap) adjArr -- | Get all vertices of the graph. -- getVertices :: GenericGraph v e -> [v] getVertices (GenericGraph idxArr _ _) = map snd $ A.assocs idxArr -- | Get subgraph on given vertices. Note that indexation will be CHANGED. -- Be careful with !. and ?. operators. -- subgraph :: Ord v => GenericGraph v e -> [Int] -> GenericGraph v e subgraph graph = snd . subgraphWithReindex graph -- | Get subgraph on given vertices and mapping from old `toKeep` indices to -- new indices of resulting subgraph. -- subgraphWithReindex :: Ord v => GenericGraph v e -> [Int] -> (Bimap Int Int, GenericGraph v e) subgraphWithReindex graph toKeep = (vMap, fromList (newVertices, newEdges)) where vSet :: S.Set Int vSet = S.fromList toKeep eRemain :: (Int, Int, e) -> Bool eRemain (at, other, _) = (at `S.member` vSet) && (other `S.member` vSet) (oldVertices, edges) = filter eRemain <$> toList graph (newVertices, oldIdx) = unzip . filter (\(_, ix) -> ix `S.member` vSet) $ zip oldVertices [0..] vMap :: Bimap Int Int vMap = BM.fromList $ zip oldIdx [0 ..] newEdges = map (\(at, other, bond) -> (vMap BM.! at, vMap BM.! other, bond)) edges -- | Add given vertices to graph. -- addVertices :: Ord v => GenericGraph v e -> [v] -> GenericGraph v e addVertices graph toAdd = fromList (first (++ toAdd) (toList graph)) -- | Remove given vertices from the graph. Note that indexation will be CHANGED. -- Be careful with !. and ?. operators. -- removeVertices :: Ord v => GenericGraph v e -> [Int] -> GenericGraph v e removeVertices graph toRemove = fromList (newVertices, newEdges) where vSet :: S.Set Int vSet = S.fromList toRemove eRemove :: (Int, Int, e) -> Bool eRemove (at, other, _) = (at `S.notMember` vSet) && (other `S.notMember` vSet) (oldVertices, edges) = filter eRemove <$> toList graph (newVertices, oldIdx) = unzip . filter ((`S.notMember` vSet) . snd) $ zip oldVertices [0..] vMap :: Map Int Int vMap = M.fromList $ zip oldIdx [0 ..] newEdges = map (\(at, other, bond) -> (vMap ! at, vMap ! other, bond)) edges -- | Remove given edges from the graph. Note that isolated vertices are allowed. -- This will NOT affect indexation. -- removeEdges :: Ord v => GenericGraph v e -> [(Int, Int)] -> GenericGraph v e removeEdges graph toRemove = fromList (vertices, edges) where eSet :: S.Set (Int, Int) eSet = S.fromList toRemove (vertices, edges) = filter eRemove <$> toList graph eRemove (at, other, _) = ((at, other) `S.notMember` eSet) && ((other, at) `S.notMember` eSet) -- | Add given edges to the graph. -- addEdges :: Ord v => GenericGraph v e -> [(Int, Int, e)] -> GenericGraph v e addEdges (GenericGraph inds rinds edges) toAdd = GenericGraph inds rinds res where accumList = foldl (\x (a, b, t) -> x ++ [(a, (b, t)), (b, (a, t))]) [] toAdd res = A.accum (flip (:)) edges accumList -- | Returns type of edge with given starting and ending indices. -- typeOfEdge :: Ord v => GenericGraph v e -> Int -> Int -> e typeOfEdge graph fromInd toInd = res where neighbors = gAdjacency graph A.! fromInd res = snd (fromJust (find ((== toInd) . fst) neighbors)) -- | Safe extraction from the graph. If there is no requested key in it, -- empty list is returned. -- safeIdx :: GenericGraph v e -> Int -> [Int] safeIdx graph = map fst . fromMaybe [] . (graph ?.) -- | Safe extraction from the graph. If there is no requested key in it, -- empty list is returned. -- safeAt :: GenericGraph v e -> Int -> [(Int, e)] safeAt graph = fromMaybe [] . (graph ?.) -- | Get edge from graph, which starting and ending indices match -- given indices. -- getEdge :: GenericGraph v e -> Int -> Int -> e getEdge graph from to = found where neighbors = graph !. from found = snd (fromJust (find ((== to) . fst) neighbors)) | Check that two vertices with given indexes have edge between them . -- isConnected :: GenericGraph v e -> Int -> Int -> Bool isConnected g fInd tInd = isJust $ find ((==) tInd . fst) $ safeAt g fInd | Returns graph that is the sum of two given graphs assuming that they are disjoint . -- sumGraphs :: Ord v => GenericGraph v e -> GenericGraph v e -> GenericGraph v e sumGraphs graphA graphB = res where (vertA, edgeA) = toList graphA (vertB, edgeB) = toList graphB renameMapB = M.fromList (zip [0..length vertB - 1] [length vertA..length vertA + length vertB - 1]) renameFunc = (renameMapB M.!) newVertices = vertA ++ vertB newEdges = edgeA ++ fmap (\(a, b, t) -> (renameFunc a, renameFunc b, t)) edgeB res = fromList (newVertices, newEdges)
null
https://raw.githubusercontent.com/biocad/math-grads/df7bdc48f86f57f3d011991c64188489e8d73bc1/src/Math/Grads/GenericGraph.hs
haskell
| Module that provides abstract implementation of graph-like data structure 'GenericGraph' and many helpful functions for interaction with 'GenericGraph'. | Generic undirected graph which stores elements of type v in its vertices (e.g. labels, atoms, states etc) and elements of type e in its edges (e.g. weights, bond types, functions over states etc). ^ 'Array' that contains vrtices of graph ^ 'Map' that maps vertices to their indices ^ adjacency 'Array' of graph | Check whether or not given value is betwen bounds. | 'fmap' which acts on adjacency lists of each vertex. | 'fmap' which acts on vertices. | Get all vertices of the graph. | Get subgraph on given vertices. Note that indexation will be CHANGED. Be careful with !. and ?. operators. | Get subgraph on given vertices and mapping from old `toKeep` indices to new indices of resulting subgraph. | Add given vertices to graph. | Remove given vertices from the graph. Note that indexation will be CHANGED. Be careful with !. and ?. operators. | Remove given edges from the graph. Note that isolated vertices are allowed. This will NOT affect indexation. | Add given edges to the graph. | Returns type of edge with given starting and ending indices. | Safe extraction from the graph. If there is no requested key in it, empty list is returned. | Safe extraction from the graph. If there is no requested key in it, empty list is returned. | Get edge from graph, which starting and ending indices match given indices.
# LANGUAGE DeriveGeneric # # LANGUAGE InstanceSigs # # LANGUAGE ViewPatterns # module Math.Grads.GenericGraph ( GenericGraph (..) , addEdges , addVertices , applyG , applyV , getVertices , getEdge , isConnected , removeEdges , removeVertices , safeAt , safeIdx , subgraph, subgraphWithReindex , sumGraphs , typeOfEdge ) where import Control.Arrow (first) import Data.Aeson (FromJSON (..), ToJSON (..), defaultOptions, genericParseJSON, genericToJSON) import Data.Array (Array) import qualified Data.Array as A import Data.Bimap (Bimap) import qualified Data.Bimap as BM import Data.List (find, groupBy, sortBy) import Data.Map.Strict (Map, mapKeys, member, (!)) import qualified Data.Map.Strict as M import Data.Maybe (fromJust, fromMaybe, isJust) import qualified Data.Set as S import GHC.Generics (Generic) import Math.Grads.Graph (Graph (..)) Note that loops and multiple edges between two vertices are allowed . } deriving (Generic) instance (Ord v, Eq e, ToJSON v, ToJSON e) => ToJSON (GenericGraph v e) where toJSON (toList -> l) = genericToJSON defaultOptions l instance (Ord v, Eq e, FromJSON v, FromJSON e) => FromJSON (GenericGraph v e) where parseJSON v = fromList <$> genericParseJSON defaultOptions v instance Graph GenericGraph where fromList :: (Ord v, Eq v) => ([v], [(Int, Int, e)]) -> GenericGraph v e fromList (vertices, edges) = GenericGraph idxArr revMap adjArr where count = length vertices idxArr = A.listArray (0, count - 1) vertices revMap = M.fromList $ zip vertices [0..] indices = concatMap insertFunc edges insertFunc (at, other, b) | at == other = [(at, (other, b))] | otherwise = [(at, (other, b)), (other, (at, b))] adjArr = A.accumArray (flip (:)) [] (0, count - 1) indices toList :: (Ord v, Eq v) => GenericGraph v e -> ([v], [(Int, Int, e)]) toList (GenericGraph idxArr _ adjArr) = (snd <$> A.assocs idxArr, edges) where edges = distinct . concatMap toEdges . A.assocs $ adjArr toEdges (k, v) = map (toAscending k) v toAscending k (a, b) | k > a = (a, k, b) | otherwise = (k, a, b) compare3 (at1, other1, _) (at2, other2, _) = compare (at1, other1) (at2, other2) eq3 v1 v2 = compare3 v1 v2 == EQ distinct = map head . groupBy eq3 . sortBy compare3 vCount :: GenericGraph v e -> Int vCount (GenericGraph idxArr _ _) = length idxArr (!>) :: (Ord v, Eq v) => GenericGraph v e -> v -> [(v, e)] (GenericGraph idxArr revMap adjArr) !> at = first (idxArr A.!) <$> adjacent where idx = revMap ! at adjacent = adjArr A.! idx (?>) :: (Ord v, Eq v) => GenericGraph v e -> v -> Maybe [(v, e)] gr@(GenericGraph _ revMap _) ?> at | at `member` revMap = Just (gr !> at) | otherwise = Nothing (!.) :: GenericGraph v e -> Int -> [(Int, e)] (!.) (GenericGraph _ _ adjArr) = (adjArr A.!) (?.) :: GenericGraph v e -> Int -> Maybe [(Int, e)] gr@(GenericGraph _ _ adjArr) ?. idx | idx `inBounds` A.bounds adjArr = Just (gr !. idx) | otherwise = Nothing where inBounds :: Ord a => a -> (a, a) -> Bool inBounds i (lo, hi) = (i >= lo) && (i <= hi) instance (Ord v, Eq v, Show v, Show e) => Show (GenericGraph v e) where show gr = unlines . map fancyShow . filter (\(a, b, _) -> a < b) . snd . toList $ gr where idxArr = gIndex gr fancyShow (at, other, bond) = concat [show $ idxArr A.! at, "\t", show bond, "\t", show $ idxArr A.! other] instance Functor (GenericGraph v) where fmap f (GenericGraph idxArr revMap adjArr) = GenericGraph idxArr revMap (((f <$>) <$>) <$> adjArr) instance Ord v => Semigroup (GenericGraph v e) where (<>) = sumGraphs instance (Ord v, Eq v) => Monoid (GenericGraph v e) where mempty = fromList ([], []) applyG :: ([(Int, e1)] -> [(Int, e2)]) -> GenericGraph v e1 -> GenericGraph v e2 applyG f (GenericGraph idxArr revMap adjArr) = GenericGraph idxArr revMap (f <$> adjArr) applyV :: Ord v2 => (v1 -> v2) -> GenericGraph v1 e -> GenericGraph v2 e applyV f (GenericGraph idxArr revMap adjArr) = GenericGraph (f <$> idxArr) (mapKeys f revMap) adjArr getVertices :: GenericGraph v e -> [v] getVertices (GenericGraph idxArr _ _) = map snd $ A.assocs idxArr subgraph :: Ord v => GenericGraph v e -> [Int] -> GenericGraph v e subgraph graph = snd . subgraphWithReindex graph subgraphWithReindex :: Ord v => GenericGraph v e -> [Int] -> (Bimap Int Int, GenericGraph v e) subgraphWithReindex graph toKeep = (vMap, fromList (newVertices, newEdges)) where vSet :: S.Set Int vSet = S.fromList toKeep eRemain :: (Int, Int, e) -> Bool eRemain (at, other, _) = (at `S.member` vSet) && (other `S.member` vSet) (oldVertices, edges) = filter eRemain <$> toList graph (newVertices, oldIdx) = unzip . filter (\(_, ix) -> ix `S.member` vSet) $ zip oldVertices [0..] vMap :: Bimap Int Int vMap = BM.fromList $ zip oldIdx [0 ..] newEdges = map (\(at, other, bond) -> (vMap BM.! at, vMap BM.! other, bond)) edges addVertices :: Ord v => GenericGraph v e -> [v] -> GenericGraph v e addVertices graph toAdd = fromList (first (++ toAdd) (toList graph)) removeVertices :: Ord v => GenericGraph v e -> [Int] -> GenericGraph v e removeVertices graph toRemove = fromList (newVertices, newEdges) where vSet :: S.Set Int vSet = S.fromList toRemove eRemove :: (Int, Int, e) -> Bool eRemove (at, other, _) = (at `S.notMember` vSet) && (other `S.notMember` vSet) (oldVertices, edges) = filter eRemove <$> toList graph (newVertices, oldIdx) = unzip . filter ((`S.notMember` vSet) . snd) $ zip oldVertices [0..] vMap :: Map Int Int vMap = M.fromList $ zip oldIdx [0 ..] newEdges = map (\(at, other, bond) -> (vMap ! at, vMap ! other, bond)) edges removeEdges :: Ord v => GenericGraph v e -> [(Int, Int)] -> GenericGraph v e removeEdges graph toRemove = fromList (vertices, edges) where eSet :: S.Set (Int, Int) eSet = S.fromList toRemove (vertices, edges) = filter eRemove <$> toList graph eRemove (at, other, _) = ((at, other) `S.notMember` eSet) && ((other, at) `S.notMember` eSet) addEdges :: Ord v => GenericGraph v e -> [(Int, Int, e)] -> GenericGraph v e addEdges (GenericGraph inds rinds edges) toAdd = GenericGraph inds rinds res where accumList = foldl (\x (a, b, t) -> x ++ [(a, (b, t)), (b, (a, t))]) [] toAdd res = A.accum (flip (:)) edges accumList typeOfEdge :: Ord v => GenericGraph v e -> Int -> Int -> e typeOfEdge graph fromInd toInd = res where neighbors = gAdjacency graph A.! fromInd res = snd (fromJust (find ((== toInd) . fst) neighbors)) safeIdx :: GenericGraph v e -> Int -> [Int] safeIdx graph = map fst . fromMaybe [] . (graph ?.) safeAt :: GenericGraph v e -> Int -> [(Int, e)] safeAt graph = fromMaybe [] . (graph ?.) getEdge :: GenericGraph v e -> Int -> Int -> e getEdge graph from to = found where neighbors = graph !. from found = snd (fromJust (find ((== to) . fst) neighbors)) | Check that two vertices with given indexes have edge between them . isConnected :: GenericGraph v e -> Int -> Int -> Bool isConnected g fInd tInd = isJust $ find ((==) tInd . fst) $ safeAt g fInd | Returns graph that is the sum of two given graphs assuming that they are disjoint . sumGraphs :: Ord v => GenericGraph v e -> GenericGraph v e -> GenericGraph v e sumGraphs graphA graphB = res where (vertA, edgeA) = toList graphA (vertB, edgeB) = toList graphB renameMapB = M.fromList (zip [0..length vertB - 1] [length vertA..length vertA + length vertB - 1]) renameFunc = (renameMapB M.!) newVertices = vertA ++ vertB newEdges = edgeA ++ fmap (\(a, b, t) -> (renameFunc a, renameFunc b, t)) edgeB res = fromList (newVertices, newEdges)
576e96f4b0a73617ce27a0e42d4d3313c2a3a4005784add374ed9947d3634488
hackwaly/ocamlearlybird
time_travel.ml
* * Copyright ( C ) 2021 * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation , either version 3 of the * License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Affero General Public License for more details . * * You should have received a copy of the GNU Affero General Public License * along with this program . If not , see < / > . * Copyright (C) 2021 Yuxiang Wen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see </>. *) open Debug_protocol_ex let run ~init_args ~launch_args ~dbg rpc = ignore init_args; ignore launch_args; Lwt.pause ();%lwt Debug_rpc.set_command_handler rpc (module Pause_command) (fun _ -> Debugger.pause dbg); Debug_rpc.set_command_handler rpc (module Continue_command) (fun _ -> Debugger.run dbg;%lwt Lwt.return (Continue_command.Result.make ())); Debug_rpc.set_command_handler rpc (module Step_in_command) (fun _ -> Debugger.step_in dbg); Debug_rpc.set_command_handler rpc (module Step_out_command) (fun _ -> Debugger.step_out dbg); Debug_rpc.set_command_handler rpc (module Next_command) (fun _ -> Debugger.next dbg); Lwt.return ()
null
https://raw.githubusercontent.com/hackwaly/ocamlearlybird/165174e3cc749ba416ec7ebfb4b521e5fac744db/src/adapter/time_travel.ml
ocaml
* * Copyright ( C ) 2021 * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation , either version 3 of the * License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Affero General Public License for more details . * * You should have received a copy of the GNU Affero General Public License * along with this program . If not , see < / > . * Copyright (C) 2021 Yuxiang Wen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see </>. *) open Debug_protocol_ex let run ~init_args ~launch_args ~dbg rpc = ignore init_args; ignore launch_args; Lwt.pause ();%lwt Debug_rpc.set_command_handler rpc (module Pause_command) (fun _ -> Debugger.pause dbg); Debug_rpc.set_command_handler rpc (module Continue_command) (fun _ -> Debugger.run dbg;%lwt Lwt.return (Continue_command.Result.make ())); Debug_rpc.set_command_handler rpc (module Step_in_command) (fun _ -> Debugger.step_in dbg); Debug_rpc.set_command_handler rpc (module Step_out_command) (fun _ -> Debugger.step_out dbg); Debug_rpc.set_command_handler rpc (module Next_command) (fun _ -> Debugger.next dbg); Lwt.return ()
6739e5a3ae9a986c1fa88b4b64cf13f0c9f9ca74ad9c3827bac70e21f75e9716
ajchemist/rum-mdl
badges.cljc
(ns rum.mdl.examples.badges (:require [rum.core :as rum] [rum.mdl :as mdl] [rum.mdl.demo :as demo])) (def counter (volatile! 0)) (rum/defcc my-badge [comp vref] (mdl/badge {:mdl [:overlap] :style {:cursor "pointer"} :data-badge (str @vref) :on-click #(do (vswap! vref inc) (.forceUpdate comp))} "CLICK ME")) (rum/defc examples [] (demo/section (demo/intro "Badges") (demo/oneliner (my-badge counter) "My Badge" (mdl/badge {:mdl [:icon :overlap] :data-badge "1"} "account_box") "Number" (mdl/badge {:mdl [:icon :overlap] :data-badge "♥"} "account_box") "Icon" (mdl/badge {:data-badge "4"} "Inbox") "Number" (mdl/badge {:mdl [:no-background] :data-badge "♥"} "Mood") "Icon")))
null
https://raw.githubusercontent.com/ajchemist/rum-mdl/87376da0f73c5bcafa64bed0fa10c7b653bcf149/examples/rum/mdl/examples/badges.cljc
clojure
(ns rum.mdl.examples.badges (:require [rum.core :as rum] [rum.mdl :as mdl] [rum.mdl.demo :as demo])) (def counter (volatile! 0)) (rum/defcc my-badge [comp vref] (mdl/badge {:mdl [:overlap] :style {:cursor "pointer"} :data-badge (str @vref) :on-click #(do (vswap! vref inc) (.forceUpdate comp))} "CLICK ME")) (rum/defc examples [] (demo/section (demo/intro "Badges") (demo/oneliner (my-badge counter) "My Badge" (mdl/badge {:mdl [:icon :overlap] :data-badge "1"} "account_box") "Number" (mdl/badge {:mdl [:icon :overlap] :data-badge "♥"} "account_box") "Icon" (mdl/badge {:data-badge "4"} "Inbox") "Number" (mdl/badge {:mdl [:no-background] :data-badge "♥"} "Mood") "Icon")))
294eb76c3ccbfc82b9f09d69ac6ae3df7395bb420677bc6936ad0c03c187cb3c
TokTok/hs-toxcore
NonceSpec.hs
# LANGUAGE StrictData # # LANGUAGE Trustworthy # module Network.Tox.Crypto.NonceSpec where import Control.Monad.IO.Class (liftIO) import Test.Hspec import Test.QuickCheck import qualified Network.Tox.Crypto.Nonce as Nonce spec :: Spec spec = do describe "newNonce" $ it "generates a different nonce on subsequent calls to newNonce" $ do nonce1 <- Nonce.newNonce nonce2 <- Nonce.newNonce liftIO $ nonce1 `shouldNotBe` nonce2 describe "nudge" $ it "creates a nonce that is different from the passed nonce" $ property $ \nonce -> Nonce.nudge nonce `shouldNotBe` nonce describe "increment" $ do it "generates a different nonce for arbitrary nonces" $ property $ \nonce -> do let incremented = Nonce.increment nonce incremented `shouldNotBe` nonce it "increments a 0 nonce to 1" $ do let nonce = read "\"000000000000000000000000000000000000000000000000\"" let nonce' = read "\"000000000000000000000000000000000000000000000001\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce' it "increments a max nonce to 0" $ do let nonce = read "\"ffffffffffffffffffffffffffffffffffffffffffffffff\"" let nonce' = read "\"000000000000000000000000000000000000000000000000\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce' it "increments a max-1 nonce to max" $ do let nonce = read "\"fffffffffffffffffffffffffffffffffffffffffffffffe\"" let nonce' = read "\"ffffffffffffffffffffffffffffffffffffffffffffffff\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce' it "increments a little endian max-1 nonce to little endian 255" $ do let nonce = read "\"feffffffffffffffffffffffffffffffffffffffffffffff\"" let nonce' = read "\"ff0000000000000000000000000000000000000000000000\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce'
null
https://raw.githubusercontent.com/TokTok/hs-toxcore/3ceab5974c36c4c5dbf7518ba733ec2b6084ce5d/test/Network/Tox/Crypto/NonceSpec.hs
haskell
# LANGUAGE StrictData # # LANGUAGE Trustworthy # module Network.Tox.Crypto.NonceSpec where import Control.Monad.IO.Class (liftIO) import Test.Hspec import Test.QuickCheck import qualified Network.Tox.Crypto.Nonce as Nonce spec :: Spec spec = do describe "newNonce" $ it "generates a different nonce on subsequent calls to newNonce" $ do nonce1 <- Nonce.newNonce nonce2 <- Nonce.newNonce liftIO $ nonce1 `shouldNotBe` nonce2 describe "nudge" $ it "creates a nonce that is different from the passed nonce" $ property $ \nonce -> Nonce.nudge nonce `shouldNotBe` nonce describe "increment" $ do it "generates a different nonce for arbitrary nonces" $ property $ \nonce -> do let incremented = Nonce.increment nonce incremented `shouldNotBe` nonce it "increments a 0 nonce to 1" $ do let nonce = read "\"000000000000000000000000000000000000000000000000\"" let nonce' = read "\"000000000000000000000000000000000000000000000001\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce' it "increments a max nonce to 0" $ do let nonce = read "\"ffffffffffffffffffffffffffffffffffffffffffffffff\"" let nonce' = read "\"000000000000000000000000000000000000000000000000\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce' it "increments a max-1 nonce to max" $ do let nonce = read "\"fffffffffffffffffffffffffffffffffffffffffffffffe\"" let nonce' = read "\"ffffffffffffffffffffffffffffffffffffffffffffffff\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce' it "increments a little endian max-1 nonce to little endian 255" $ do let nonce = read "\"feffffffffffffffffffffffffffffffffffffffffffffff\"" let nonce' = read "\"ff0000000000000000000000000000000000000000000000\"" let incremented = Nonce.increment nonce incremented `shouldBe` nonce'
1341c4ced051f1d56572ef93011bc0e001c80f40d4aca61899a3268fd380519a
Drup/LILiS
lisCairo.mli
* Draw with { { : } cairo } . * A turtle that can draw on any Cairo surface . val cairo_turtle : float -> float -> Cairo.context -> unit Glilis.turtle (** A turtle that write to a png file. *) val png_turtle : int -> int -> (string -> unit) Glilis.turtle (** A turtle that write to a svg file. Buggy for now. *) val svg_turtle : string -> int -> int -> unit Glilis.turtle (** A turtle that write on a gtk surface. *) val gtk_turtle : GMisc.drawing_area -> unit Glilis.turtle
null
https://raw.githubusercontent.com/Drup/LILiS/df63fbc3ee77b3378ae1ef27715828c3ad892475/glilis/cairo/lisCairo.mli
ocaml
* A turtle that write to a png file. * A turtle that write to a svg file. Buggy for now. * A turtle that write on a gtk surface.
* Draw with { { : } cairo } . * A turtle that can draw on any Cairo surface . val cairo_turtle : float -> float -> Cairo.context -> unit Glilis.turtle val png_turtle : int -> int -> (string -> unit) Glilis.turtle val svg_turtle : string -> int -> int -> unit Glilis.turtle val gtk_turtle : GMisc.drawing_area -> unit Glilis.turtle
be57df61849c0740b9394a424d1e8a4d6bfe593df03528c524bcdd5c3725fa19
zcaudate/hara
class_test.clj
(ns hara.object.element.class-test (:use hara.test) (:require [hara.object.element.class :refer :all])) ^{:refer hara.object.element.class/type->raw :added "3.0"} (fact "converts to the raw representation" (type->raw Class) => "java.lang.Class" (type->raw 'byte) => "B") ^{:refer hara.object.element.class/raw-array->string :added "3.0"} (fact "converts the raw representation to a more readable form" (raw-array->string "[[B") => "byte[][]" (raw-array->string "[Ljava.lang.Class;") => "java.lang.Class[]") ^{:refer hara.object.element.class/raw->string :added "3.0"} (fact "converts the raw array representation to a human readable form" (raw->string "[[V") => "void[][]" (raw->string "[Ljava.lang.String;") => "java.lang.String[]") ^{:refer hara.object.element.class/string-array->raw :added "3.0"} (fact "converts the human readable form to a raw string" (string-array->raw "java.lang.String[]") "[Ljava.lang.String;") ^{:refer hara.object.element.class/string->raw :added "3.0"} (fact "converts any string to it's raw representation" (string->raw "java.lang.String[]") => "[Ljava.lang.String;" (string->raw "int[][][]") => "[[[I") ^{:refer hara.object.element.class/-class-convert :added "3.0"} (fact "converts a string to its representation. Implementation function" (-class-convert Class :string) => "java.lang.Class" (-class-convert "byte" :class) => Byte/TYPE (-class-convert "byte" :container) => Byte) ^{:refer hara.object.element.class/class-convert :added "3.0"} (fact "Converts a class to its representation." (class-convert "byte") => Byte/TYPE (class-convert 'byte :string) => "byte" (class-convert (Class/forName "[[B") :string) => "byte[][]")
null
https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/test/hara/object/element/class_test.clj
clojure
(ns hara.object.element.class-test (:use hara.test) (:require [hara.object.element.class :refer :all])) ^{:refer hara.object.element.class/type->raw :added "3.0"} (fact "converts to the raw representation" (type->raw Class) => "java.lang.Class" (type->raw 'byte) => "B") ^{:refer hara.object.element.class/raw-array->string :added "3.0"} (fact "converts the raw representation to a more readable form" (raw-array->string "[[B") => "byte[][]" (raw-array->string "[Ljava.lang.Class;") => "java.lang.Class[]") ^{:refer hara.object.element.class/raw->string :added "3.0"} (fact "converts the raw array representation to a human readable form" (raw->string "[[V") => "void[][]" (raw->string "[Ljava.lang.String;") => "java.lang.String[]") ^{:refer hara.object.element.class/string-array->raw :added "3.0"} (fact "converts the human readable form to a raw string" (string-array->raw "java.lang.String[]") "[Ljava.lang.String;") ^{:refer hara.object.element.class/string->raw :added "3.0"} (fact "converts any string to it's raw representation" (string->raw "java.lang.String[]") => "[Ljava.lang.String;" (string->raw "int[][][]") => "[[[I") ^{:refer hara.object.element.class/-class-convert :added "3.0"} (fact "converts a string to its representation. Implementation function" (-class-convert Class :string) => "java.lang.Class" (-class-convert "byte" :class) => Byte/TYPE (-class-convert "byte" :container) => Byte) ^{:refer hara.object.element.class/class-convert :added "3.0"} (fact "Converts a class to its representation." (class-convert "byte") => Byte/TYPE (class-convert 'byte :string) => "byte" (class-convert (Class/forName "[[B") :string) => "byte[][]")
fb6cd8ea85d3f3262ab0053459978f4ac1851fa16bf1009b0c667e482aaa33ef
nextjournal/clerk
dev_launcher.clj
(ns nextjournal.clerk.dev-launcher "A dev launcher that launches nrepl, shadow-cljs and once the first cljs compliation completes, Clerk. Avoiding other ns requires here so the REPL comes up early." (:require [nrepl.cmdline :as nrepl]) (:import (java.lang.management ManagementFactory) (java.util Locale))) (defn start [serve-opts] (future (nrepl/dispatch-commands {:middleware '[cider.nrepl/cider-middleware]})) (require 'shadow.cljs.silence-default-loggers) ((requiring-resolve 'shadow.cljs.devtools.server/start!)) ((requiring-resolve 'shadow.cljs.devtools.api/watch) :viewer) ((requiring-resolve 'nextjournal.clerk/serve!) serve-opts) (set! *print-namespace-maps* false) (println "Clerk dev system ready in" (String/format (Locale. "en-US") "%.2fs" (to-array [(/ (.. ManagementFactory getRuntimeMXBean getUptime) 1000.0)]))))
null
https://raw.githubusercontent.com/nextjournal/clerk/82c35e2fc23a492ad1dd4ff201b39ed141098a1f/dev/nextjournal/clerk/dev_launcher.clj
clojure
(ns nextjournal.clerk.dev-launcher "A dev launcher that launches nrepl, shadow-cljs and once the first cljs compliation completes, Clerk. Avoiding other ns requires here so the REPL comes up early." (:require [nrepl.cmdline :as nrepl]) (:import (java.lang.management ManagementFactory) (java.util Locale))) (defn start [serve-opts] (future (nrepl/dispatch-commands {:middleware '[cider.nrepl/cider-middleware]})) (require 'shadow.cljs.silence-default-loggers) ((requiring-resolve 'shadow.cljs.devtools.server/start!)) ((requiring-resolve 'shadow.cljs.devtools.api/watch) :viewer) ((requiring-resolve 'nextjournal.clerk/serve!) serve-opts) (set! *print-namespace-maps* false) (println "Clerk dev system ready in" (String/format (Locale. "en-US") "%.2fs" (to-array [(/ (.. ManagementFactory getRuntimeMXBean getUptime) 1000.0)]))))
9438a868641e51fa574153fe22a340864d5d3cf7389385ff5f4cfdd2666d26ae
haskell/cabal
Lens.hs
module Distribution.Types.PackageId.Lens ( PackageIdentifier, module Distribution.Types.PackageId.Lens, ) where import Distribution.Compat.Lens import Distribution.Compat.Prelude import Prelude () import Distribution.Types.PackageId (PackageIdentifier) import Distribution.Types.PackageName (PackageName) import Distribution.Version (Version) import qualified Distribution.Types.PackageId as T pkgName :: Lens' PackageIdentifier PackageName pkgName f s = fmap (\x -> s { T.pkgName = x }) (f (T.pkgName s)) # INLINE pkgName # pkgVersion :: Lens' PackageIdentifier Version pkgVersion f s = fmap (\x -> s { T.pkgVersion = x }) (f (T.pkgVersion s)) # INLINE pkgVersion #
null
https://raw.githubusercontent.com/haskell/cabal/0abbe37187f708e0a5daac8d388167f72ca0db7e/Cabal-syntax/src/Distribution/Types/PackageId/Lens.hs
haskell
module Distribution.Types.PackageId.Lens ( PackageIdentifier, module Distribution.Types.PackageId.Lens, ) where import Distribution.Compat.Lens import Distribution.Compat.Prelude import Prelude () import Distribution.Types.PackageId (PackageIdentifier) import Distribution.Types.PackageName (PackageName) import Distribution.Version (Version) import qualified Distribution.Types.PackageId as T pkgName :: Lens' PackageIdentifier PackageName pkgName f s = fmap (\x -> s { T.pkgName = x }) (f (T.pkgName s)) # INLINE pkgName # pkgVersion :: Lens' PackageIdentifier Version pkgVersion f s = fmap (\x -> s { T.pkgVersion = x }) (f (T.pkgVersion s)) # INLINE pkgVersion #
e24667adbb85c80f6c9db59f25dede87ad88c2b4e67a9b6e499cc4ce36e59dd8
SNePS/SNePS2
message.lisp
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNIP ; Base : 10 -*- Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : message.lisp , v 1.2 2013/08/28 19:07:27 shapiro Exp $ ;; This file is part of SNePS. $ BEGIN LICENSE$ The contents of this file are subject to the University at Buffalo Public License Version 1.0 ( the " License " ) ; you may ;;; not use this file except in compliance with the License. You ;;; may obtain a copy of the License at ;;; . edu/sneps/Downloads/ubpl.pdf. ;;; 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 gov ;;; erning rights and limitations under the License. ;;; The Original Code is SNePS 2.8 . ;;; The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . ;;; Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :snip) ; ============================================================================= ; ; try-to-send-report ; ------------------ ; ; arguments : rep - <report> ; ch - <channel> ; ; returns : <boolean> ; ; description : tests "rep" against the <filter> of "ch", and ; filters all supports not passing "ch". ; sends all those versions which pass through "ch". ; written : rgh 07/29/85 ; modified: rgh 08/19/85 ; rgh 08/21/85 ; scs 06/17/88 ; njm 10/23/88 ; ; Interchange the two arguments of and ;;; for faster failure. (defun try-to-send-report (rep ch) (let ((newsup (filter.sup (support.rep rep) (context.ch ch)))) (when (and newsup (filter (subst.rep rep) (filter.ch ch))) (send-reports (makeone.repset (make.rep (subst.rep rep) newsup (sign.rep rep) (signature.rep rep) (node.rep rep) (context.rep rep))) ch)))) (defparameter *depthCutoffForward* 10 "Maximum height of SNIP subgoal.") (export '*depthCutoffForward*) (import '*depthCutoffForward* :snepsul) ; ; ; ============================================================================= ; ; send-reports ; ------------ ; ; arguments : repset - <report set> ; ch - <channel> ; ; returns : <boolean> ; ; description : sends all the <report>s in "repset" through "ch" ; ; implementation: it is assumed that all of the <report>s in "repset" ; have passed through the <filter> and the <context> ; of "ch" ; ; written : rgh 7/29/85 modified : rgh 8/19/85 rgh 11/24/85 ; rgh 3/08/86 rgh 4/20/86 scs 6/22/88 ; njm 10/23/88 ; ; (defun send-reports (repset ch) (let ((d (destination.ch ch))) (cond ((is-user.dest d) (let ((pr *user-process*) (swrep (switch-reports repset ch))) (regstore pr '*reports* (union.repset (regfetch pr '*reports*) swrep)) (regstore pr '*priority* 'high) (initiate pr) swrep)) (t (when *depthCutoffForward* (setf repset (filter-repset repset))) (unless (isnew.repset repset) (activate.n d) (let ((pr (activation.n d)) (swrep (switch-reports repset ch))) (regstore pr '*reports* (union.repset (regfetch pr '*reports*) swrep)) (regstore pr '*priority* 'high) (initiate pr) swrep)))))) (defun filter-repset (repset) "Retuns a repset like REPSET, but without any that exceed *depthCutoffForward*." (let ((filteredrepset (new.repset))) (do.repset (rep repset filteredrepset) (if (or (> (sneps::node-height (signature.rep rep)) *depthCutoffForward*) (> (max-height-sub (subst.rep rep)) *depthCutoffForward*)) (remark (format nil "~&Forward inference cutoff of ~A{~A} beyond *depthcutoffforward* = ~A~%" (signature.rep rep) (subst.rep rep) *depthCutoffForward*) nil nil) (setf filteredrepset (insert.repset rep filteredrepset)))))) ; ; ============================================================================= ; ; switch-reports ; -------------- ; ; arguments : repset - <report set> ; sw - <switch> ; ; returns : <report set> ; ; description : switches variable context for all <reports> in "repset" ; from that of the sending nodefun to that of the ; receiving node. ; written : rgh 07/29/85 modified : rgh 08/02/85 ; ; (defun switch-reports (repset ch) (let ((result (new.repset))) (do.repset (next-rep repset result) (let ((newrep (switch-one-report next-rep ch))) (if newrep (setq result (insert.repset newrep result))))))) ; ; ; ============================================================================= ; switch - one - report ; ----------------- ; ; arguments : rep - <report> ; ch - <channel> ; ; returns : <report> ; ; description : switches the variable context of the report "rep". ; If the instance contained in the report is a previously ; unkown one, a new node is built. ; The new support is added to the node. ; ; ; written : rgh 07/30/85 modified : rgh 8/05/85 rgh 3/09/86 scs 6/22/88 cpf / njm 10/24/88 ; scs 05/05/99 ; scs/flj 06/20/04 ; Latest change: ;;; If about to build (min 0 max 0 arg P), ;;; and P is (min 0 max 0 Q), returns Q instead of building ~(~Q ) ) . ; ; (defun switch-one-report (rep ch) (declare (special *name*)) (let* ((d (destination.ch ch)) (signature (signature.rep rep)) (situation (cond ((is-user.dest d) 'to-user) ((ismemb.ns d (all-consequents signature)) 'to-cq) ((let ((*node* d)) (is-ant-to-rule.rep rep)) 'to-rule) ((let ((*node* d)) (is-cq-to-rule.rep rep)) 'from-cq) (t 'to-nonrule))) (newsub (case situation ((to-nonrule) (match::substituteinterms (switch.ch ch) (subst.rep rep))) ((to-rule to-user from-cq) (subst.rep rep)) (to-cq (match::substituteinterms (match::initbind d) (subst.rep rep)))))) (unless (match::violates-uvbr newsub) (let* ((patnode (case situation ((to-user to-rule from-cq) signature) ((to-nonrule to-cq) d))) (newnode (if (quantified-vars.n patnode) (choose.ns (sneps:find-or-build (sneps::clean-quantifiers.cs (apply-subst.cs newsub (n-to-downcs patnode))))) (match::applysubst patnode newsub))) (support (funcall (if (eql signature newnode) #'identity #'non-hyp) (case situation ((to-rule from-cq) (support.rep rep)) ((to-user to-cq) (if (and (eq *name* 'rule) (eq *type* 'nor) (instanciated-quantified-vars.n signature ch newsub)) (change-tag-support (support.rep rep)) (support.rep rep))) ((to-nonrule) (if (or (instanciated-quantified-vars.n signature ch newsub) (nor-to-nor-with-different-args signature d)) (change-tag-support (support.rep rep)) (support.rep rep))))))) (declare (special newnode)) ( format t " ~% situation = ~s substitution = ~s ~% " situation ) ;;; (format t "~% newnode = ~s new support = ~s ~% " newnode support) (setq newsub (adjoin (cons patnode newnode) newsub :test #'equal)) (when (isneg.rep rep) (setf newnode (sneps:negate.n newnode))) (when (and (or (ismol.n newnode) (ispat.n newnode)) (not (and (equal *name* 'rule) (equal *type* 'nor) (isneg.rep rep) (eql 1 (cardinality.ns (all-consequents signature))) (eq newnode *node*)))) (addsupport.n support newnode) (snebr:ck-contradiction newnode (context.ch ch) 'sneps:snip)) (make.rep newsub support (sign.rep rep) signature newnode (context.rep rep)))))) ; ; ; ============================================================================= ; ; fill-out-substitution ; --------------------- ; ; arguments : rsub - <substitution> ; dest - <node> ; ; returns : <substitution> ; ; description : adds to a switched report any additional bindings ; which may apply to the destination nodefun "dest" ; ; written : rgh 07/30/85 modified : rgh 08/05/85 ; ; (defun fill-out-substitution (rsub dest) (let ((result (new.sbst))) (do.sbst (mb rsub result) (when (dominates.n dest (mvar.mb mb)) (setq result (putin.sbst mb result)))))) ; ; ; ============================================================================= ; ; install-channel ; --------------- ; ; arguments : ch - <channel> ; ; returns : <channel set> ; ; nonlocal-vars : OUTGOING-CHANNELS: ; ; description : if "ch" is not already in OUTGOING-CHANNELS:, it ; is put in. If "ch" is in OUTGOING-CHANNELS:, but ; is closed, it is reopened. ; ; side-effects : updates the OUTGOING-CHANNELS: register of the ; current node. ; written : rgh 10/06/85 ; modified: rgh 11/30/85 rgh 4/13/86 ; ; (defun install-channel (ch) (let ((dest (destination.ch ch))) (setq *OUTGOING-CHANNELS* (insert.chset ch *OUTGOING-CHANNELS*)) (unless (is-user.dest dest) (activate.n dest)))) ; ESTA e ' PARA SAIR DAQUI ; ============================================================================= ; ; instanciated-quantified-vars.n ; ------------------------------ ; ; arguments : node - <node> ; ch - <channel> ; subst - <substitution> ; ; returns : <boolean> ; ; description : if "ch" does not "instanciate" any quantified variable of ' node ' returns NIL , otherwise ; returns T. ; written : njm 11/24/88 ; modified: ; ; ; (defun instanciated-quantified-vars.n (node ch subst) (let ((vars (quantified-vars.n node))) (when vars (or (do.ns (var vars nil) (when (match:bindingOF var (filter.ch ch)) (return t))) (do.ns (var vars nil) (when (match:bindingOF var subst) (return t))))))) ; ; ; ============================================================================= ; ESTA e ' PARA SAIR DAQUI ; ============================================================================= ; ; nor-to-nor-with-different-args ; ------------------------------ ; ; arguments : n1 - <node> ; n2 - <node> ; ; returns : <boolean> ; ; description : if "n1" and "n2" are NOR nodes with different number of ; arguments returns T, otherwise returns T. ; ; written : njm 11/25/88 ; modified: ; ; ; (defun nor-to-nor-with-different-args (n1 n2) (and (is-nor.n n1) (is-nor.n n2) (not (eql (cardinality.ns (nodeset.n n1 'sneps:arg)) (cardinality.ns (nodeset.n n2 'sneps:arg))))))
null
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/snip/fns/message.lisp
lisp
Syntax : Common - Lisp ; Package : SNIP ; Base : 10 -*- This file is part of SNePS. you may not use this file except in compliance with the License. You may obtain a copy of the License at . edu/sneps/Downloads/ubpl.pdf. or implied. See the License for the specific language gov erning rights and limitations under the License. ============================================================================= try-to-send-report ------------------ arguments : rep - <report> ch - <channel> returns : <boolean> description : tests "rep" against the <filter> of "ch", and filters all supports not passing "ch". sends all those versions which pass through "ch". modified: rgh 08/19/85 rgh 08/21/85 scs 06/17/88 njm 10/23/88 for faster failure. ============================================================================= send-reports ------------ arguments : repset - <report set> ch - <channel> returns : <boolean> description : sends all the <report>s in "repset" through "ch" implementation: it is assumed that all of the <report>s in "repset" have passed through the <filter> and the <context> of "ch" written : rgh 7/29/85 rgh 3/08/86 njm 10/23/88 ============================================================================= switch-reports -------------- arguments : repset - <report set> sw - <switch> returns : <report set> description : switches variable context for all <reports> in "repset" from that of the sending nodefun to that of the receiving node. ============================================================================= ----------------- arguments : rep - <report> ch - <channel> returns : <report> description : switches the variable context of the report "rep". If the instance contained in the report is a previously unkown one, a new node is built. The new support is added to the node. written : rgh 07/30/85 scs 05/05/99 scs/flj 06/20/04 Latest change: If about to build (min 0 max 0 arg P), and P is (min 0 max 0 Q), (format t "~% newnode = ~s new support = ~s ~% " newnode support) ============================================================================= fill-out-substitution --------------------- arguments : rsub - <substitution> dest - <node> returns : <substitution> description : adds to a switched report any additional bindings which may apply to the destination nodefun "dest" written : rgh 07/30/85 ============================================================================= install-channel --------------- arguments : ch - <channel> returns : <channel set> nonlocal-vars : OUTGOING-CHANNELS: description : if "ch" is not already in OUTGOING-CHANNELS:, it is put in. If "ch" is in OUTGOING-CHANNELS:, but is closed, it is reopened. side-effects : updates the OUTGOING-CHANNELS: register of the current node. modified: rgh 11/30/85 ============================================================================= instanciated-quantified-vars.n ------------------------------ arguments : node - <node> ch - <channel> subst - <substitution> returns : <boolean> description : if "ch" does not "instanciate" any quantified returns T. modified: ============================================================================= ============================================================================= nor-to-nor-with-different-args ------------------------------ arguments : n1 - <node> n2 - <node> returns : <boolean> description : if "n1" and "n2" are NOR nodes with different number of arguments returns T, otherwise returns T. written : njm 11/25/88 modified:
Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : message.lisp , v 1.2 2013/08/28 19:07:27 shapiro Exp $ $ BEGIN LICENSE$ The contents of this file are subject to the University at Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express The Original Code is SNePS 2.8 . The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :snip) written : rgh 07/29/85 Interchange the two arguments of and (defun try-to-send-report (rep ch) (let ((newsup (filter.sup (support.rep rep) (context.ch ch)))) (when (and newsup (filter (subst.rep rep) (filter.ch ch))) (send-reports (makeone.repset (make.rep (subst.rep rep) newsup (sign.rep rep) (signature.rep rep) (node.rep rep) (context.rep rep))) ch)))) (defparameter *depthCutoffForward* 10 "Maximum height of SNIP subgoal.") (export '*depthCutoffForward*) (import '*depthCutoffForward* :snepsul) modified : rgh 8/19/85 rgh 11/24/85 rgh 4/20/86 scs 6/22/88 (defun send-reports (repset ch) (let ((d (destination.ch ch))) (cond ((is-user.dest d) (let ((pr *user-process*) (swrep (switch-reports repset ch))) (regstore pr '*reports* (union.repset (regfetch pr '*reports*) swrep)) (regstore pr '*priority* 'high) (initiate pr) swrep)) (t (when *depthCutoffForward* (setf repset (filter-repset repset))) (unless (isnew.repset repset) (activate.n d) (let ((pr (activation.n d)) (swrep (switch-reports repset ch))) (regstore pr '*reports* (union.repset (regfetch pr '*reports*) swrep)) (regstore pr '*priority* 'high) (initiate pr) swrep)))))) (defun filter-repset (repset) "Retuns a repset like REPSET, but without any that exceed *depthCutoffForward*." (let ((filteredrepset (new.repset))) (do.repset (rep repset filteredrepset) (if (or (> (sneps::node-height (signature.rep rep)) *depthCutoffForward*) (> (max-height-sub (subst.rep rep)) *depthCutoffForward*)) (remark (format nil "~&Forward inference cutoff of ~A{~A} beyond *depthcutoffforward* = ~A~%" (signature.rep rep) (subst.rep rep) *depthCutoffForward*) nil nil) (setf filteredrepset (insert.repset rep filteredrepset)))))) written : rgh 07/29/85 modified : rgh 08/02/85 (defun switch-reports (repset ch) (let ((result (new.repset))) (do.repset (next-rep repset result) (let ((newrep (switch-one-report next-rep ch))) (if newrep (setq result (insert.repset newrep result))))))) switch - one - report modified : rgh 8/05/85 rgh 3/09/86 scs 6/22/88 cpf / njm 10/24/88 returns Q instead of building ~(~Q ) ) . (defun switch-one-report (rep ch) (declare (special *name*)) (let* ((d (destination.ch ch)) (signature (signature.rep rep)) (situation (cond ((is-user.dest d) 'to-user) ((ismemb.ns d (all-consequents signature)) 'to-cq) ((let ((*node* d)) (is-ant-to-rule.rep rep)) 'to-rule) ((let ((*node* d)) (is-cq-to-rule.rep rep)) 'from-cq) (t 'to-nonrule))) (newsub (case situation ((to-nonrule) (match::substituteinterms (switch.ch ch) (subst.rep rep))) ((to-rule to-user from-cq) (subst.rep rep)) (to-cq (match::substituteinterms (match::initbind d) (subst.rep rep)))))) (unless (match::violates-uvbr newsub) (let* ((patnode (case situation ((to-user to-rule from-cq) signature) ((to-nonrule to-cq) d))) (newnode (if (quantified-vars.n patnode) (choose.ns (sneps:find-or-build (sneps::clean-quantifiers.cs (apply-subst.cs newsub (n-to-downcs patnode))))) (match::applysubst patnode newsub))) (support (funcall (if (eql signature newnode) #'identity #'non-hyp) (case situation ((to-rule from-cq) (support.rep rep)) ((to-user to-cq) (if (and (eq *name* 'rule) (eq *type* 'nor) (instanciated-quantified-vars.n signature ch newsub)) (change-tag-support (support.rep rep)) (support.rep rep))) ((to-nonrule) (if (or (instanciated-quantified-vars.n signature ch newsub) (nor-to-nor-with-different-args signature d)) (change-tag-support (support.rep rep)) (support.rep rep))))))) (declare (special newnode)) ( format t " ~% situation = ~s substitution = ~s ~% " situation ) (setq newsub (adjoin (cons patnode newnode) newsub :test #'equal)) (when (isneg.rep rep) (setf newnode (sneps:negate.n newnode))) (when (and (or (ismol.n newnode) (ispat.n newnode)) (not (and (equal *name* 'rule) (equal *type* 'nor) (isneg.rep rep) (eql 1 (cardinality.ns (all-consequents signature))) (eq newnode *node*)))) (addsupport.n support newnode) (snebr:ck-contradiction newnode (context.ch ch) 'sneps:snip)) (make.rep newsub support (sign.rep rep) signature newnode (context.rep rep)))))) modified : rgh 08/05/85 (defun fill-out-substitution (rsub dest) (let ((result (new.sbst))) (do.sbst (mb rsub result) (when (dominates.n dest (mvar.mb mb)) (setq result (putin.sbst mb result)))))) written : rgh 10/06/85 rgh 4/13/86 (defun install-channel (ch) (let ((dest (destination.ch ch))) (setq *OUTGOING-CHANNELS* (insert.chset ch *OUTGOING-CHANNELS*)) (unless (is-user.dest dest) (activate.n dest)))) ESTA e ' PARA SAIR DAQUI variable of ' node ' returns NIL , otherwise written : njm 11/24/88 (defun instanciated-quantified-vars.n (node ch subst) (let ((vars (quantified-vars.n node))) (when vars (or (do.ns (var vars nil) (when (match:bindingOF var (filter.ch ch)) (return t))) (do.ns (var vars nil) (when (match:bindingOF var subst) (return t))))))) ESTA e ' PARA SAIR DAQUI (defun nor-to-nor-with-different-args (n1 n2) (and (is-nor.n n1) (is-nor.n n2) (not (eql (cardinality.ns (nodeset.n n1 'sneps:arg)) (cardinality.ns (nodeset.n n2 'sneps:arg))))))