_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
|
---|---|---|---|---|---|---|---|---|
6182865ab81b9700e47a9d8da68942dc5690da44420cc9d9602a82dd216f6612 | ocaml/ocaml-lsp | w.ml | open Import
open Pp.O
open Pp
type t = unit Pp.t
type w = t
(* This module contains all the writing primitives *)
let ident = verbatim
let i = verbatim
let quoted s = i (sprintf "%S" s)
let surround delim a =
let start, finish =
match delim with
| `Paren -> (i "(", i ")")
| `Curly -> (i "{", i "}")
| `Square -> (i "[", i "]")
in
Pp.concat [ start; a; finish ]
module Json = struct
let invalid_pat name =
(ident "json", Pp.textf "Json.error \"invalid %s\" json" name)
let typ = "Json.t"
module Literal = struct
let str n = sprintf "`String %S" n
let int i = sprintf "`Int (%d)" i
let null = "`Null"
let bool b = sprintf "`Bool %b" b
end
let str = sprintf "`String %s"
let int = sprintf "`Int %s"
let bool = sprintf "`Bool %s"
end
module Gen = struct
let record ~delim fields =
let sep = Pp.concat [ Pp.verbatim ";"; Pp.newline ] in
Pp.text "{"
++ Pp.concat_map ~sep fields ~f:(fun (name, f) ->
Pp.concat [ Pp.textf "%s %s " name delim; f ])
++ Pp.verbatim "}"
let clause ~delim l r = Pp.concat [ l; Pp.verbatim (sprintf " %s " delim); r ]
end
module Attr = struct
type t =
{ name : string
; payload : w list
}
let make name payload = { name; payload }
let pp kind { name; payload } =
let kind =
match kind with
| `Field -> "@"
| `Type -> "@@"
in
Pp.concat [ i kind; i name; Pp.space; Pp.concat ~sep:Pp.space payload ]
|> surround `Square
end
module Type = struct
let string = i "string"
let int = i "int"
let name = i
let bool = i "bool"
let gen_decl kw name body =
Pp.concat [ Pp.textf "%s %s =" kw name; Pp.newline; body ]
let and_ name body = gen_decl "and" name body
let decl name body = gen_decl "type" name body
let record fields = Gen.record ~delim:":" fields
let field_attrs ~field ~attrs =
match attrs with
| [] -> field
| attrs ->
let attrs = Pp.concat_map attrs ~sep:Pp.space ~f:(Attr.pp `Field) in
Pp.concat [ field; Pp.space; attrs ]
let var typ = Pp.textf "'%s" typ
let app typ = function
| [] -> assert false
| [ x ] -> Pp.concat [ x; Pp.space; typ ]
| xs ->
let args =
let sep = Pp.verbatim "," in
Pp.concat [ Pp.verbatim "("; Pp.concat ~sep xs; Pp.verbatim ")" ]
in
Pp.concat [ args; Pp.space; typ ]
let tuple fields =
let sep = i "*" in
i "(" ++ Pp.concat ~sep fields ++ i ")"
let rec_decls xs =
match xs with
| [] -> Pp.concat []
| (name, body) :: xs ->
decl name body ++ newline
++ Pp.concat_map xs ~sep:Pp.newline ~f:(fun (name, body) ->
and_ name body)
let deriving td ~record =
let fields =
if record then space ++ i "[@@yojson.allow_extra_fields]" else space
in
Pp.concat
[ td
; Pp.newline
; Pp.text "[@@deriving_inline yojson]"
; fields
; space
; Pp.text "[@@@end]"
]
let opt_attr = ident "option [@yojson.option]"
let opt_field f = Pp.seq f opt_attr
let default f def = Pp.concat [ f; ident "[@default "; ident def; ident "]" ]
let key name = concat [ ident "[@key "; quoted name; ident "]" ]
let gen_variant ~poly constrs =
let sep = Pp.concat [ Pp.newline; i "| " ] in
Pp.concat_map constrs ~sep ~f:(fun (name, arg) ->
let name =
let name = String.capitalize_ascii name in
if poly then "`" ^ name else name
in
match arg with
| [] -> i name
| xs ->
let xs =
match xs with
| [ x ] -> x
| xs -> tuple xs
in
Gen.clause ~delim:"of" (ident name) xs)
let poly constrs = concat [ i "["; gen_variant ~poly:true constrs; i "]" ]
let variant constrs = gen_variant ~poly:false constrs
end
let gen_module kw name body =
Pp.concat
[ Pp.textf "module %s %s" name kw
; Pp.newline
; body
; newline
; verbatim "end"
; newline
]
module Sig = struct
let module_ name body = gen_module ": sig" name body
let include_ name destructive_subs =
let inc_ = Pp.textf "include %s" name in
match destructive_subs with
| [] -> inc_
| substs ->
let substs =
let sep = Pp.text " and " in
Pp.concat_map ~sep substs ~f:(fun (l, r) ->
Pp.concat
[ Pp.text "type"
; Pp.space
; l
; Pp.space
; Pp.verbatim ":="
; Pp.space
; r
])
in
Pp.concat [ inc_; Pp.space; Pp.text "with"; Pp.space; substs ]
let val_ name b =
let sep = Pp.concat [ space; i "->"; space ] in
let b = Pp.concat ~sep b in
Pp.concat [ textf "val %s : " name; b; Pp.newline ]
let assoc k v = Pp.concat [ Type.tuple [ k; v ]; Pp.space; i "list" ]
end
let warnings codes = seq (textf "[@@@warning %S]" codes) newline
let opens names =
Pp.concat_map names ~f:(fun name ->
Pp.concat [ textf "open! %s" name; newline ])
let module_ name body = gen_module "= struct" name body
let record fields = Gen.record ~delim:"=" fields
| null | https://raw.githubusercontent.com/ocaml/ocaml-lsp/6a38d66c57930c6ef5ac67d740a51e2d9551f93f/lsp/bin/ocaml/w.ml | ocaml | This module contains all the writing primitives | open Import
open Pp.O
open Pp
type t = unit Pp.t
type w = t
let ident = verbatim
let i = verbatim
let quoted s = i (sprintf "%S" s)
let surround delim a =
let start, finish =
match delim with
| `Paren -> (i "(", i ")")
| `Curly -> (i "{", i "}")
| `Square -> (i "[", i "]")
in
Pp.concat [ start; a; finish ]
module Json = struct
let invalid_pat name =
(ident "json", Pp.textf "Json.error \"invalid %s\" json" name)
let typ = "Json.t"
module Literal = struct
let str n = sprintf "`String %S" n
let int i = sprintf "`Int (%d)" i
let null = "`Null"
let bool b = sprintf "`Bool %b" b
end
let str = sprintf "`String %s"
let int = sprintf "`Int %s"
let bool = sprintf "`Bool %s"
end
module Gen = struct
let record ~delim fields =
let sep = Pp.concat [ Pp.verbatim ";"; Pp.newline ] in
Pp.text "{"
++ Pp.concat_map ~sep fields ~f:(fun (name, f) ->
Pp.concat [ Pp.textf "%s %s " name delim; f ])
++ Pp.verbatim "}"
let clause ~delim l r = Pp.concat [ l; Pp.verbatim (sprintf " %s " delim); r ]
end
module Attr = struct
type t =
{ name : string
; payload : w list
}
let make name payload = { name; payload }
let pp kind { name; payload } =
let kind =
match kind with
| `Field -> "@"
| `Type -> "@@"
in
Pp.concat [ i kind; i name; Pp.space; Pp.concat ~sep:Pp.space payload ]
|> surround `Square
end
module Type = struct
let string = i "string"
let int = i "int"
let name = i
let bool = i "bool"
let gen_decl kw name body =
Pp.concat [ Pp.textf "%s %s =" kw name; Pp.newline; body ]
let and_ name body = gen_decl "and" name body
let decl name body = gen_decl "type" name body
let record fields = Gen.record ~delim:":" fields
let field_attrs ~field ~attrs =
match attrs with
| [] -> field
| attrs ->
let attrs = Pp.concat_map attrs ~sep:Pp.space ~f:(Attr.pp `Field) in
Pp.concat [ field; Pp.space; attrs ]
let var typ = Pp.textf "'%s" typ
let app typ = function
| [] -> assert false
| [ x ] -> Pp.concat [ x; Pp.space; typ ]
| xs ->
let args =
let sep = Pp.verbatim "," in
Pp.concat [ Pp.verbatim "("; Pp.concat ~sep xs; Pp.verbatim ")" ]
in
Pp.concat [ args; Pp.space; typ ]
let tuple fields =
let sep = i "*" in
i "(" ++ Pp.concat ~sep fields ++ i ")"
let rec_decls xs =
match xs with
| [] -> Pp.concat []
| (name, body) :: xs ->
decl name body ++ newline
++ Pp.concat_map xs ~sep:Pp.newline ~f:(fun (name, body) ->
and_ name body)
let deriving td ~record =
let fields =
if record then space ++ i "[@@yojson.allow_extra_fields]" else space
in
Pp.concat
[ td
; Pp.newline
; Pp.text "[@@deriving_inline yojson]"
; fields
; space
; Pp.text "[@@@end]"
]
let opt_attr = ident "option [@yojson.option]"
let opt_field f = Pp.seq f opt_attr
let default f def = Pp.concat [ f; ident "[@default "; ident def; ident "]" ]
let key name = concat [ ident "[@key "; quoted name; ident "]" ]
let gen_variant ~poly constrs =
let sep = Pp.concat [ Pp.newline; i "| " ] in
Pp.concat_map constrs ~sep ~f:(fun (name, arg) ->
let name =
let name = String.capitalize_ascii name in
if poly then "`" ^ name else name
in
match arg with
| [] -> i name
| xs ->
let xs =
match xs with
| [ x ] -> x
| xs -> tuple xs
in
Gen.clause ~delim:"of" (ident name) xs)
let poly constrs = concat [ i "["; gen_variant ~poly:true constrs; i "]" ]
let variant constrs = gen_variant ~poly:false constrs
end
let gen_module kw name body =
Pp.concat
[ Pp.textf "module %s %s" name kw
; Pp.newline
; body
; newline
; verbatim "end"
; newline
]
module Sig = struct
let module_ name body = gen_module ": sig" name body
let include_ name destructive_subs =
let inc_ = Pp.textf "include %s" name in
match destructive_subs with
| [] -> inc_
| substs ->
let substs =
let sep = Pp.text " and " in
Pp.concat_map ~sep substs ~f:(fun (l, r) ->
Pp.concat
[ Pp.text "type"
; Pp.space
; l
; Pp.space
; Pp.verbatim ":="
; Pp.space
; r
])
in
Pp.concat [ inc_; Pp.space; Pp.text "with"; Pp.space; substs ]
let val_ name b =
let sep = Pp.concat [ space; i "->"; space ] in
let b = Pp.concat ~sep b in
Pp.concat [ textf "val %s : " name; b; Pp.newline ]
let assoc k v = Pp.concat [ Type.tuple [ k; v ]; Pp.space; i "list" ]
end
let warnings codes = seq (textf "[@@@warning %S]" codes) newline
let opens names =
Pp.concat_map names ~f:(fun name ->
Pp.concat [ textf "open! %s" name; newline ])
let module_ name body = gen_module "= struct" name body
let record fields = Gen.record ~delim:"=" fields
|
08920ddd2efe7905547dc341022fe938edb98d80e4a41e649a169f64ca9c053a | owainlewis/ocaml-datastructures-algorithms | sorting.ml | module Algorithms =
struct
let rec bubble: 'a list -> 'a list = fun xs ->
let rec aux ys = match ys with
| [] -> []
| x::[] -> [x]
| x::y::xs when x > y -> y::aux(x::xs)
| x::y::xs -> x :: aux(y::xs)
in
let sweep = aux xs in
if sweep = xs
then sweep
else bubble sweep
let rec selection_sort = function
| [] -> []
| h::t ->
let rec aux y ys = function
| [] -> y :: selection_sort ys
| x::xs when x < y -> aux x (y::ys) xs
| x::xs -> aux y (x::ys) xs
in aux h [] t
let rec insertion xs =
let rec aux v ys =
match ys with
| [] -> [v]
| z::zs as l ->
if v < z
then v :: l
else z :: (aux v zs)
in match xs with
| [] -> []
| [x] -> [x]
| v::vs -> aux v (insertion vs)
let rec quick_sort: 'a list -> 'a list = function
| [] -> []
| x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
in let x = (quick_sort smaller)
and y = (x::quick_sort larger)
in x @ y
end
| null | https://raw.githubusercontent.com/owainlewis/ocaml-datastructures-algorithms/4696fa4f5a015fc18e903b0b9ba2a1a8013a40ce/src/sorting.ml | ocaml | module Algorithms =
struct
let rec bubble: 'a list -> 'a list = fun xs ->
let rec aux ys = match ys with
| [] -> []
| x::[] -> [x]
| x::y::xs when x > y -> y::aux(x::xs)
| x::y::xs -> x :: aux(y::xs)
in
let sweep = aux xs in
if sweep = xs
then sweep
else bubble sweep
let rec selection_sort = function
| [] -> []
| h::t ->
let rec aux y ys = function
| [] -> y :: selection_sort ys
| x::xs when x < y -> aux x (y::ys) xs
| x::xs -> aux y (x::ys) xs
in aux h [] t
let rec insertion xs =
let rec aux v ys =
match ys with
| [] -> [v]
| z::zs as l ->
if v < z
then v :: l
else z :: (aux v zs)
in match xs with
| [] -> []
| [x] -> [x]
| v::vs -> aux v (insertion vs)
let rec quick_sort: 'a list -> 'a list = function
| [] -> []
| x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
in let x = (quick_sort smaller)
and y = (x::quick_sort larger)
in x @ y
end
|
|
670792eb4f61b62fcb471aee7a988729f5c80fabd832e8cf0413d9b540d918c4 | rizo/snowflake-os | printlinear.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(* Pretty-printing of linearized machine code *)
open Format
open Linearize
val instr: formatter -> instruction -> unit
val fundecl: formatter -> fundecl -> unit
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/ocamlopt.opt/asmcomp/printlinear.mli | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Pretty-printing of linearized machine code | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Format
open Linearize
val instr: formatter -> instruction -> unit
val fundecl: formatter -> fundecl -> unit
|
0da333c93c8491d4662e55a5f5f736870359ac2444989dd2b858199c6c859e0f | openmusic-project/OMChroma | specenv-model.lisp | ;=====================================================
; CHROMA
;=====================================================
part of the OMChroma library
- > High - level control of sound synthesis in OM
;=====================================================
;
;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.
;
;See file LICENSE for further informations on licensing terms.
;
;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.
;
;=====================================================
(in-package :chroma)
(defclass model-specenv
(chroma-model)
((timelist :accessor timelist
:documentation "temps des enveloppes")
(envlist :accessor envlist
:documentation "liste de fun"))
(:documentation "Spectral Surface Model"))
(defmethod initialize-instance :after ((x model-specenv) &rest initargs &key analysis)
(declare (ignore initargs))
(if analysis
(progn (setf (timelist x) (mapcar #'first (cdr (data analysis))))
(setf (envlist x) (mapcar #'envtofun (cdr (data analysis))))
)))
(defun envtofun (l)
(let((result nil)(l (cdr l)))
(loop for i from 0 to (length l)
for e in l
do (push (lintodb e) result)
(push i result))
(make_fun (nreverse result))))
( envtofun ' ( 1 2 3 4 ) )
| null | https://raw.githubusercontent.com/openmusic-project/OMChroma/5ded34f22b59a1a93ea7b87e182c9dbdfa95e047/sources/chroma/models/specenv-model.lisp | lisp | =====================================================
CHROMA
=====================================================
=====================================================
This program is free software; you can redistribute it and/or
either version 2
of the License, or (at your option) any later version.
See file LICENSE for further informations on licensing terms.
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.
===================================================== | part of the OMChroma library
- > High - level control of sound synthesis in OM
modify it under the terms of the GNU General Public License
(in-package :chroma)
(defclass model-specenv
(chroma-model)
((timelist :accessor timelist
:documentation "temps des enveloppes")
(envlist :accessor envlist
:documentation "liste de fun"))
(:documentation "Spectral Surface Model"))
(defmethod initialize-instance :after ((x model-specenv) &rest initargs &key analysis)
(declare (ignore initargs))
(if analysis
(progn (setf (timelist x) (mapcar #'first (cdr (data analysis))))
(setf (envlist x) (mapcar #'envtofun (cdr (data analysis))))
)))
(defun envtofun (l)
(let((result nil)(l (cdr l)))
(loop for i from 0 to (length l)
for e in l
do (push (lintodb e) result)
(push i result))
(make_fun (nreverse result))))
( envtofun ' ( 1 2 3 4 ) )
|
2b51316962a24ca52c982647469c571a493f9a818e33e633ae8756931d1cbf02 | dym/movitz | integers.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
;;;;
;;;; Filename: integers.lisp
Description : Arithmetics .
Author : < >
;;;; Created at: Wed Nov 8 18:44:57 2000
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : , v 1.128 2008 - 04 - 27 19:41:10 Exp $
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(require :muerte/typep)
(require :muerte/arithmetic-macros)
(provide :muerte/integers)
(in-package muerte)
(defconstant most-positive-fixnum #.movitz::+movitz-most-positive-fixnum+)
(defconstant most-negative-fixnum #.movitz::+movitz-most-negative-fixnum+)
Comparison
(define-primitive-function fast-compare-two-reals (n1 n2)
"Compare two numbers (i.e. set EFLAGS accordingly)."
(macrolet
((do-it ()
`(with-inline-assembly (:returns :nothing) ; unspecified
(:testb ,movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'n1-not-fixnum)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum-but-n1-is)
(:cmpl :ebx :eax) ; both were fixnum
(:ret)
n1-not-fixnum ; but we don't know about n2
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'neither-is-fixnum)
;; n2 is fixnum
(:locally (:jmp (:edi (:edi-offset fast-compare-real-fixnum))))
n2-not-fixnum-but-n1-is
(:locally (:jmp (:edi (:edi-offset fast-compare-fixnum-real))))
neither-is-fixnum
;; Check that both numbers are bignums, and compare them.
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
If they are EQ , they are certainly =
(:je '(:sub-program (n1-and-n2-are-eq)
(:ret)))
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz 'go-complicated)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
(:cmpb :ch (:eax (:offset movitz-bignum sign)))
(:jne '(:sub-program (different-signs)
;; Comparing the sign-bytes sets up EFLAGS correctly!
(:ret)))
(:testl #xff00 :ecx)
(:jnz 'compare-negatives)
Both n1 and n2 are positive bignums .
(:shrl 16 :ecx)
(:movzxw (:eax (:offset movitz-bignum length)) :edx)
(: cmpw : cx (: eax (: offset ) ) )
(:cmpl :ecx :edx)
(:jne '(:sub-program (positive-different-sizes)
(:ret)))
Both n1 and n2 are positive bignums of the same size , namely ECX .
(: : ecx : edx ) ; counter
positive-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'positive-compare-lsb)
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:je 'positive-compare-loop)
positive-compare-lsb
;; Now we have to make the compare act as unsigned, which is why
we compare zero - extended 16 - bit quantities .
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0 2)) :ecx)
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
(:jne 'upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
upper-16-decisive
(:ret)
compare-negatives
;; Moth n1 and n2 are negative bignums.
(:shrl 16 :ecx)
(:cmpw (:eax (:offset movitz-bignum length)) :cx)
(:jne '(:sub-program (negative-different-sizes)
(:ret)))
Both n1 and n2 are negative bignums of the same size , namely ECX .
(:movl :ecx :edx) ; counter
negative-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'negative-compare-lsb)
(:movl (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0)))
(:je 'negative-compare-loop)
(:ret)
it 's down to .
;; Now we have to make the compare act as unsigned, which is why
we compare zero - extended 16 - bit quantities .
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0 2))
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
(:jne 'negative-upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
negative-upper-16-decisive
(:ret))))
(do-it)))
(defun complicated-eql (x y)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :multiple-values) ; well..
(:compile-two-forms (:eax :ebx) x y)
(:cmpl :eax :ebx) ; EQ?
(:je 'done)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'not-bignum)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
Ok .. we have two bignums of identical sign and size .
(:shrl 16 :ecx)
(:leal (:ecx 4) :edx) ; counter
compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'done)
(:movl (:eax :edx (:offset movitz-bignum bigit0 -4)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:je 'compare-loop)
(:jmp 'done)
not-bignum
(:cmpb ,(movitz:tag :ratio) :cl)
(:jne 'not-ratio)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
(:movl (:eax (:offset movitz-ratio numerator)) :eax)
(:movl (:ebx (:offset movitz-ratio numerator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jne 'done)
(:compile-two-forms (:eax :ebx) x y)
(:movl (:eax (:offset movitz-ratio denominator)) :eax)
(:movl (:ebx (:offset movitz-ratio denominator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jmp 'done)
not-ratio
done
(:movl :edi :eax)
(:clc)
)))
(do-it)))
(define-primitive-function fast-compare-fixnum-real (n1 n2)
"Compare (known) fixnum <n1> with real <n2>."
(macrolet
((do-it ()
`(with-inline-assembly (:returns :nothing) ; unspecified
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum)
(:cmpl :ebx :eax)
(:ret)
n2-not-fixnum
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpw ,(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
;; compare eax with something bigger
(:cmpl #x10000000 :edi)
(:ret)
not-plusbignum
(:cmpw ,(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
;; compare ebx with something bigger
(:cmpl #x-10000000 :edi)
(:ret))))
(do-it)))
(define-primitive-function fast-compare-real-fixnum (n1 n2)
"Compare real <n1> with fixnum <n2>."
(with-inline-assembly (:returns :nothing) ; unspecified
(:testb #.movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'not-fixnum)
(:cmpl :ebx :eax)
(:ret)
not-fixnum
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax #.movitz:+other-type-offset+) :ecx)
(:cmpw #.(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
;; compare ebx with something bigger
(:cmpl #x-10000000 :edi)
(:ret)
not-plusbignum
(:cmpw #.(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
;; compare ebx with something bigger
(:cmpl #x10000000 :edi)
(:ret)))
(defun complicated-compare (x y)
(let ((ix (* (numerator x) (denominator y)))
(iy (* (numerator y) (denominator x))))
(with-inline-assembly (:returns :multiple-values)
(:compile-two-forms (:eax :ebx) ix iy)
(:call-global-pf fast-compare-two-reals)
(:movl 1 :ecx) ; The real result is in EFLAGS.
(:movl :edi :eax))))
;;;
;;; Unsigned
(defun below (x max)
"Is x between 0 and max?"
(compiler-macro-call below x max))
;;; Equality
(define-compiler-macro =%2op (n1 n2 &environment env)
(cond
#+ignore
((movitz:movitz-constantp n1 env)
(let ((n1 (movitz:movitz-eval n1 env)))
(etypecase n1
((eql 0)
`(do-result-mode-case ()
(:booleans
(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:testl :eax :eax)))
(t (with-inline-assembly (:returns :boolean-cf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:cmpl 1 :eax)))))
((signed-byte 30)
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-fixnum-real)))
(integer
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-two-reals))))))
#+ignore
((movitz:movitz-constantp n2 env)
`(=%2op ,n2 ,n1))
(t `(eql ,n1 ,n2))))
(define-number-relational = =%2op nil :defun-p nil)
(defun = (first-number &rest numbers)
(declare (dynamic-extent numbers))
(dolist (n numbers t)
(unless (= first-number n)
(return nil))))
(define-compiler-macro /=%2op (n1 n2)
`(not (= ,n1 ,n2)))
(define-number-relational /= /=%2op nil :defun-p nil)
(defun /= (first-number &rest more-numbers)
(numargs-case
(1 (x)
(declare (ignore x))
t)
(2 (x y)
(/=%2op x y))
(t (first-number &rest more-numbers)
(declare (dynamic-extent more-numbers))
(dolist (y more-numbers)
(when (= first-number y)
(return nil)))
(do ((p more-numbers (cdr p)))
((null p) t)
(dolist (q (cdr p))
(when (= (car p) q)
(return nil)))))))
;;;;
(deftype positive-fixnum ()
'(integer 0 #.movitz:+movitz-most-positive-fixnum+))
(deftype positive-bignum ()
`(integer #.(cl:1+ movitz:+movitz-most-positive-fixnum+) *))
(deftype negative-fixnum ()
`(integer #.movitz:+movitz-most-negative-fixnum+ -1))
(deftype negative-bignum ()
`(integer * #.(cl:1- movitz::+movitz-most-negative-fixnum+)))
(defun fixnump (x)
(typep x 'fixnum))
(defun evenp (x)
(compiler-macro-call evenp x))
(defun oddp (x)
(compiler-macro-call oddp x))
;;;
(defun %negatef (x p0 p1)
"Negate x. If x is not eq to p0 or p1, negate x destructively."
(etypecase x
(fixnum (- x))
(bignum
(if (or (eq x p0) (eq x p1))
(- x)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:xorl #xff00 (:eax #.movitz:+other-type-offset+)))))))
;;; Addition
(defun + (&rest terms)
(declare (without-check-stack-limit))
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:compile-form (:result-mode :ebx) y)
(:addl :ebx :eax)
(:jo '(:sub-program (fix-fix-overflow)
(:movl :eax :ecx)
(:jns 'fix-fix-negative)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'fix-fix-ok)
fix-fix-negative
(:jz 'fix-double-negative)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:movl ,(dpb 4 (byte 16 16)
(movitz:tag :bignum #xff))
(:eax ,movitz:+other-type-offset+))
(:jmp 'fix-fix-ok)
fix-double-negative
(:compile-form (:result-mode :eax)
,(* 2 movitz:+movitz-most-negative-fixnum+))
(:jmp 'fix-fix-ok)))
fix-fix-ok))
((positive-bignum positive-fixnum)
(+ y x))
((positive-fixnum positive-bignum)
(bignum-add-fixnum y x))
((positive-bignum negative-fixnum)
(+ y x))
((negative-fixnum positive-bignum)
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done))
(:compile-two-forms (:eax :ebx) y x)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl 4 :ecx)
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set retry-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:leal ((:ecx 1) ,(* 1 movitz:+movitz-fixnum-factor+))
:eax) ; Number of words
(:call-local-pf cons-pointer)
(:load-lexical (:lexical-binding y) :ebx) ; bignum
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ebx :ebx) ; counter
(:negl :ecx)
(:subl :ecx (:eax (:offset movitz-bignum bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :ebx)
(:subl 1 (:eax :ebx (:offset movitz-bignum bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx) ; result bignum word-size
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-expansion)
(:subl #x40000 (:eax ,movitz:+other-type-offset+))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(+ y x)
;; Assume x is smallest.
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done
zero-padding-loop))
(:compile-two-forms (:eax :ebx) y x)
(:testl :ebx :ebx)
(:jz 'pfix-pbig-done)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl ,movitz:+movitz-fixnum-factor+ :ecx)
(:jne 'not-size1)
(:movl (:ebx (:offset movitz-bignum bigit0)) :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:jc 'not-size1)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+))
:eax) ; Number of words
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-non-pointer)
(:load-lexical (:lexical-binding y) :ebx) ; bignum
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
MSB
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ebx)
(:xorl :edx :edx) ; counter
(:xorl :ecx :ecx) ; Carry
add-bignum-loop
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (zero-padding-loop)
(:addl :ecx (:eax :edx (:offset movitz-bignum
bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'zero-padding-loop)
(:jmp 'add-bignum-done)))
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (term1-carry)
The digit + carry carried over , ECX = 0
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
(:jmp 'add-bignum-done)))
(:addl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4)))
(:je 'no-expansion)
(:addl #x40000 (:eax ,movitz:+other-type-offset+))
(:addl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done)
))
(((integer * -1) (integer 0 *))
(- y (- x)))
(((integer 0 *) (integer * -1))
(- x (- y)))
(((integer * -1) (integer * -1))
(%negatef (+ (- x) (- y)) x y))
((rational rational)
(/ (+ (* (numerator x) (denominator y))
(* (numerator y) (denominator x)))
(* (denominator x) (denominator y))))
)))
(do-it)))
(t (&rest terms)
(declare (dynamic-extent terms))
(if (null terms)
0
(reduce #'+ terms)))))
(defun 1+ (number)
(+ 1 number))
(defun 1- (number)
(+ -1 number))
;;; Subtraction
(defun - (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(numargs-case
(1 (x)
(etypecase x
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:negl :eax)
(:jo '(:sub-program (fix-overflow)
(:compile-form (:result-mode :eax)
,(1+ movitz:+movitz-most-positive-fixnum+))
(:jmp 'fix-ok)))
fix-ok)))
(do-it)))
(bignum
(%bignum-negate (copy-bignum x)))
(ratio
(make-ratio (- (ratio-numerator x)) (ratio-denominator x)))))
(2 (minuend subtrahend)
(macrolet
((do-it ()
`(number-double-dispatch (minuend subtrahend)
((number (eql 0))
minuend)
(((eql 0) t)
(- subtrahend))
((fixnum fixnum)
(with-inline-assembly (:returns :eax :labels (done negative-result))
(:compile-two-forms (:eax :ebx) minuend subtrahend)
(:subl :ebx :eax)
(:jno 'done)
(:jnc 'negative-result)
(:movl :eax :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl ,(- movitz:+movitz-most-negative-fixnum+) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'done)
negative-result
(:movl :eax :ecx)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax (:offset movitz-bignum type)))
done))
((positive-bignum fixnum)
(+ (- subtrahend) minuend))
((fixnum positive-bignum)
(%negatef (+ subtrahend (- minuend))
subtrahend minuend))
;;; ((positive-fixnum positive-bignum)
;;; (bignum-canonicalize
;;; (%bignum-negate
;;; (bignum-subf (copy-bignum subtrahend) minuend))))
;;; ((negative-fixnum positive-bignum)
;;; (bignum-canonicalize
;;; (%negatef (bignum-add-fixnum subtrahend minuend)
;;; subtrahend minuend)))
((positive-bignum positive-bignum)
(cond
((= minuend subtrahend)
0)
((< minuend subtrahend)
(let ((x (- subtrahend minuend)))
(%negatef x subtrahend minuend)))
(t (bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum minuend) subtrahend)
(:xorl :edx :edx) ; counter
(:xorl :ecx :ecx) ; carry
sub-loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (carry-overflow)
;; Just propagate carry
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:jmp 'bignum-sub-done)))
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
(:negl :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:jnc 'bignum-sub-done)
propagate-carry
(:addl 4 :edx)
(:subl 1 (:eax :edx (:offset movitz-bignum bigit0)))
(:jc 'propagate-carry)
bignum-sub-done
)))))
(((integer 0 *) (integer * -1))
(+ minuend (- subtrahend)))
(((integer * -1) (integer 0 *))
(%negatef (+ (- minuend) subtrahend) minuend subtrahend))
(((integer * -1) (integer * -1))
(+ minuend (- subtrahend)))
((rational rational)
(/ (- (* (numerator minuend) (denominator subtrahend))
(* (numerator subtrahend) (denominator minuend)))
(* (denominator minuend) (denominator subtrahend))))
)))
(do-it)))
(t (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(if subtrahends
(reduce #'- subtrahends :initial-value minuend)
(- minuend)))))
;;;
(defun zerop (number)
(= 0 number))
(defun plusp (number)
(> number 0))
(defun minusp (number)
(< number 0))
(defun abs (x)
(compiler-macro-call abs x))
(defun signum (x)
(cond
((> x 0) 1)
((< x 0) -1)
(t 0)))
;;;
(defun max (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call max x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((max number1))
(dolist (x numbers max)
(when (> x max)
(setq max x)))))))
(defun min (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call min x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((min number1))
(dolist (x numbers min)
(when (< x min)
(setq min x)))))))
;; shift
(defun ash (integer count)
(cond
((= 0 count)
integer)
((= 0 integer) 0)
((typep count '(integer 0 *))
(let ((result-length (+ (integer-length (if (minusp integer) (1- integer) integer))
count)))
(cond
((<= result-length 29)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:shll :cl :eax)))
((typep integer 'positive-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
integer)
(bignum-shift-leftf result count)))
((typep integer 'positive-bignum)
(let ((result (%make-bignum (ceiling result-length 32))))
(dotimes (i (* 2 (%bignum-bigits result)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(let ((pos (- (* i 16) count)))
(cond
((minusp (+ pos 16)) 0)
((<= 0 pos)
(ldb (byte 16 pos) integer))
(t (ash (ldb (byte (+ pos 16) 0) integer)
(- pos)))))))
(assert (or (plusp (memref result -2
:index (+ -1 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))
(plusp (memref result -2
:index (+ -2 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))))
(bignum-canonicalize result)))
((typep integer 'negative-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
(- integer))
(%bignum-negate (bignum-shift-leftf result count))))
((typep integer 'negative-bignum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(dotimes (i (%bignum-bigits integer))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)
(memref integer (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)))
(%bignum-negate (bignum-shift-leftf result count))))
(t (error 'program-error)))))
(t (let ((count (- count)))
(etypecase integer
(fixnum
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:sarl :cl :eax)
(:andl -4 :eax)
(:cld)))
(positive-bignum
(let ((result-length (- (integer-length integer) count)))
(cond
((<= result-length 1)
1 or 0 .
(t (multiple-value-bind (long short)
(truncate count 16)
(let ((result (%make-bignum (1+ (ceiling result-length 32)))))
(let ((src-max-bigit (* 2 (%bignum-bigits integer))))
(dotimes (i (* 2 (%bignum-bigits result)))
(declare (index i))
(let ((src (+ i long)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(if (< src src-max-bigit)
(memref integer -2 :index src :type :unsigned-byte16)
0)))))
(bignum-canonicalize
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ecx :ebx) short result)
(:xorl :edx :edx) ; counter
We need to use EAX for u32 storage .
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
shift-short-loop
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'end-shift-short-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:eax)
(:shrdl :cl :eax
(:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:jmp 'shift-short-loop)
end-shift-short-loop
(:movl :edx :eax) ; Safe EAX
(:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:cld))))
(do-it))))))))))))))
;;;;
(defun integer-length (integer)
"=> number-of-bits"
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:xorl :eax :eax)
(:compile-form (:result-mode :ecx) integer)
(:testl :ecx :ecx)
(:jns 'not-negative)
(:notl :ecx)
not-negative
(:bsrl :ecx :ecx)
(:jz 'zero)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
,(* -1 movitz:+movitz-fixnum-factor+))
:eax)
zero)))
(do-it)))
(positive-bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:xorl :eax :eax)
bigit-scan-loop
(:subl 4 :edx)
(:jc 'done)
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jz 'bigit-scan-loop)
Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) .
Factor 8
(:bsrl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
Factor 4
(:leal ((:ecx 4) :eax 4) :eax)
done)))
(do-it)))
(negative-bignum
(let ((abs-length (bignum-integer-length integer)))
(if (= 1 (bignum-logcount integer))
(1- abs-length)
abs-length)))))
;;; Multiplication
(defun * (&rest factors)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(let (d0 d1)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) x y)
(:sarl ,movitz::+movitz-fixnum-shift+ :ecx)
(:std)
(:imull :ecx :eax :edx)
(:jno 'fixnum-result) ; most likely/optimized path.
(:cmpl ,movitz::+movitz-fixnum-factor+ :edx)
(:jc 'u32-result)
(:cmpl #xfffffffc :edx)
(:ja 'u32-negative-result)
(:jne 'two-bigits)
(:testl :eax :eax)
(:jnz 'u32-negative-result)
The result requires 2 ..
two-bigits
(:shll ,movitz::+movitz-fixnum-shift+ :edx) ; guaranteed won't overflow.
(:cld)
(:store-lexical (:lexical-binding d0) :eax :type fixnum)
(:store-lexical (:lexical-binding d1) :edx :type fixnum)
(:compile-form (:result-mode :eax) (%make-bignum 2))
(:movl ,(dpb (* 2 movitz:+movitz-fixnum-factor+)
(byte 16 16) (movitz:tag :bignum 0))
(:eax ,movitz:+other-type-offset+))
(:load-lexical (:lexical-binding d0) :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:load-lexical (:lexical-binding d1) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:shrdl ,movitz:+movitz-fixnum-shift+ :ecx
(:eax (:offset movitz-bignum bigit0)))
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0 4)))
(:jns 'fixnum-done)
;; if result was negative, we must negate bignum
(:notl (:eax (:offset movitz-bignum bigit0 4)))
(:negl (:eax (:offset movitz-bignum bigit0)))
(:cmc)
(:adcl 0 (:eax (:offset movitz-bignum bigit0 4)))
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
u32-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:call-local-pf box-u32-ecx)
(:jmp 'fixnum-done)
u32-negative-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:negl :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
fixnum-result
(:movl :edi :edx)
(:cld)
fixnum-done)))
(((eql 0) t) 0)
(((eql 1) t) y)
(((eql -1) t) (- y))
((t fixnum) (* y x))
((fixnum bignum)
(let (r)
(with-inline-assembly (:returns :eax)
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-multiplication))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies:
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-multiplication
(:movl (:esp) :ebp)
(:compile-two-forms (:eax :ebx) (integer-length x) (integer-length y))
Compute ( 1 + ( ceiling ( + ( len x ) ( len y ) ) 32 ) ) ..
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:leal (:eax :ebx ,(* 4 (+ 31 32))) :eax)
(:andl ,(logxor #xffffffff (* 31 4)) :eax)
(:shrl 5 :eax)
New bignum into EAX
(:load-lexical (:lexical-binding y) :ebx) ; bignum
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:store-lexical (:lexical-binding r) :eax :type bignum)
(:movl :eax :ebx) ; r into ebx
(:xorl :esi :esi) ; counter
(:xorl :edx :edx) ; initial carry
Make EAX , EDX , ESI non - GC - roots .
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jns 'multiply-loop)
(:negl :ecx) ; can't overflow
multiply-loop
(:movl :edx (:ebx (:esi 1) ; new
(:offset movitz-bignum bigit0)))
(:compile-form (:result-mode :ebx) y)
(:movl (:ebx (:esi 1) (:offset movitz-bignum bigit0))
:eax)
(:mull :ecx :eax :edx)
(:compile-form (:result-mode :ebx) r)
(:addl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:adcl 0 :edx)
(:addl 4 :esi)
(:cmpw :si (:ebx (:offset movitz-bignum length)))
(:ja 'multiply-loop)
(:testl :edx :edx)
(:jz 'no-carry-expansion)
(:movl :edx (:ebx :esi (:offset movitz-bignum bigit0)))
(:addl 4 :esi)
(:movw :si (:ebx (:offset movitz-bignum length)))
no-carry-expansion
(:leal (:esi ,movitz:+movitz-fixnum-factor+)
Put bignum length into ECX
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edi :edx)
EAX , EDX , and ESI are GC roots again .
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
(:compile-form (:result-mode :ebx) x)
(:testl :ebx :ebx)
(:jns 'positive-result)
;; Negate the resulting bignum
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
positive-result
)))
((positive-bignum positive-bignum)
(if (< x y)
(* y x)
;; X is the biggest factor.
#-movitz-reference-code
(do ((tmp (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32)))
(r (bignum-set-zerof (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32))))
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) (bignum-canonicalize r))
(bignum-set-zerof tmp)
(bignum-addf r (bignum-shift-leftf (bignum-mulf (bignum-addf tmp x)
(ldb (byte 29 i) y))
i)))
#+movitz-reference-code
(do ((r 0)
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) r)
(incf r (ash (* x (ldb (byte 29 i) y)) i)))))
((ratio ratio)
(make-rational (* (ratio-numerator x) (ratio-numerator y))
(* (ratio-denominator x) (ratio-denominator y))))
((ratio t)
(make-rational (* y (ratio-numerator x))
(ratio-denominator x)))
((t ratio)
(make-rational (* x (ratio-numerator y))
(ratio-denominator y)))
((t (integer * -1))
(%negatef (* x (- y)) x y))
(((integer * -1) t)
(%negatef (* (- x) y) x y))
(((integer * -1) (integer * -1))
(* (- x) (- y))))))
(do-it)))
(t (&rest factors)
(declare (dynamic-extent factors))
(if (null factors)
1
(reduce '* factors)))))
Division
(defun truncate (number &optional (divisor 1))
(numargs-case
(1 (number)
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
(t (number divisor)
(number-double-dispatch (number divisor)
((t (eql 1))
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
((fixnum fixnum)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :eax) number)
(:compile-form (:result-mode :ebx) divisor)
(:std)
(:cdq :eax :edx)
(:idivl :ebx :eax :edx)
(:shll #.movitz::+movitz-fixnum-shift+ :eax)
(:cld)
(:movl :edx :ebx)
(:xorl :ecx :ecx)
(:movb 2 :cl) ; return values: qutient, remainder.
(:stc)))
((positive-fixnum positive-bignum)
(values 0 number))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let (r n)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :ebx) number)
(:cmpw ,movitz:+movitz-fixnum-factor+
(:ebx (:offset movitz-bignum length)))
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:movl (:ebx (:offset movitz-bignum bigit0)) :eax)
(:xorl :edx :edx)
(:divl :ecx :eax :edx)
(:movl :eax :ecx)
(:shll ,movitz:+movitz-fixnum-shift+ :edx)
(:movl :edi :eax)
(:cld)
(:pushl :edx)
(:call-local-pf box-u32-ecx)
(:popl :ebx)
(:jmp 'done)
not-size1
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-truncation))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-truncation
(:movl (:esp) :ebp)
(:xorl :eax :eax)
(:compile-form (:result-mode :ebx) number)
(:movw (:ebx (:offset movitz-bignum length)) :ax)
(:addl 4 :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
New bignum into EAX
XXX breaks GC invariant !
(:compile-form (:result-mode :ebx) number)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:testb 3 :cl)
(:jnz '(:sub-program () (:int 63)))
(:movl :ecx :esi)
(:xorl :edx :edx) ; edx=hi-digit=0
; eax=lo-digit=msd(number)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
divide-loop
(:load-lexical (:lexical-binding number) :ebx)
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax)
(:divl :ecx :eax :edx)
(:load-lexical (:lexical-binding r) :ebx)
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4)))
(:subl 4 :esi)
(:jnz 'divide-loop)
(:movl :edi :eax) ; safe value
(:leal ((:edx ,movitz:+movitz-fixnum-factor+)) :edx)
(:cld)
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edx :ebx)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-more-shrinkage)
(:subw 4 (:eax (:offset movitz-bignum length)))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
(:cmpl ,(* 2 movitz:+movitz-fixnum-factor+) :ecx)
(:jne 'no-more-shrinkage)
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:eax (:offset movitz-bignum bigit0)))
(:jnc 'no-more-shrinkage)
(:movl (:eax (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'fixnum-result) ; don't commit the bignum
no-more-shrinkage
(:call-local-pf cons-commit-non-pointer)
fixnum-result
Exit atomically block .
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
done
(:movl 2 :ecx)
(:stc)))))
(do-it)))
((positive-bignum positive-bignum)
(cond
((= number divisor) (values 1 0))
((< number divisor) (values 0 number))
(t
#-movitz-reference-code
(let* ((divisor-length (integer-length divisor))
(guess-pos (- divisor-length 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((tmp (copy-bignum number))
(tmp2 (copy-bignum number))
(q (bignum-set-zerof (%make-bignum (ceiling (1+ (- (integer-length number)
divisor-length))
32))))
(r (copy-bignum number)))
((%bignum< r divisor)
(values (bignum-canonicalize q)
(bignum-canonicalize r)))
(let ((guess (bignum-shift-rightf
(bignum-truncatef (bignum-addf (bignum-set-zerof tmp)
r)
msb)
guess-pos)))
(if (%bignum-zerop guess)
(setf q (bignum-addf-fixnum q 1)
r (bignum-subf r divisor))
(setf q (bignum-addf q guess)
r (do ((i 0 (+ i 29)))
((>= i divisor-length) r)
(bignum-subf r (bignum-shift-leftf
(bignum-mulf (bignum-addf (bignum-set-zerof tmp2) guess)
(ldb (byte 29 i) divisor))
i))))))))
#+movitz-reference-code
(let* ((guess-pos (- (integer-length divisor) 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((shift (- guess-pos))
(q 0)
(r number))
((< r divisor)
(values q r))
(let ((guess (ash (truncate r msb) shift)))
(if (= 0 guess)
(setf q (1+ q)
r (- r divisor))
(setf q (+ q guess)
r (- r (* guess divisor))))))))))
(((integer * -1) (integer 0 *))
(multiple-value-bind (q r)
(truncate (- number) divisor)
(values (%negatef q number divisor)
(%negatef r number divisor))))
(((integer 0 *) (integer * -1))
(multiple-value-bind (q r)
(truncate number (- divisor))
(values (%negatef q number divisor)
r)))
(((integer * -1) (integer * -1))
(multiple-value-bind (q r)
(truncate (- number) (- divisor))
(values q (%negatef r number divisor))))
((rational rational)
(multiple-value-bind (q r)
(truncate (* (numerator number)
(denominator divisor))
(* (denominator number)
(numerator divisor)))
(values q (make-rational r (* (denominator number)
(denominator divisor))))))
))))
(defun / (number &rest denominators)
(numargs-case
(1 (x)
(if (not (typep x 'ratio))
(make-rational 1 x)
(make-rational (%ratio-denominator x)
(%ratio-numerator x))))
(2 (x y)
(multiple-value-bind (q r)
(truncate x y)
(cond
((= 0 r)
q)
(t (make-rational (* (numerator x) (denominator y))
(* (denominator x) (numerator y)))))))
(t (number &rest denominators)
(declare (dynamic-extent denominators))
(cond
((null denominators)
(make-rational 1 number))
((null (cdr denominators))
(multiple-value-bind (q r)
(truncate number (first denominators))
(if (= 0 r)
q
(make-rational number (first denominators)))))
(t (/ number (reduce '* denominators)))))))
(defun round (number &optional (divisor 1))
"Mathematical rounding."
(multiple-value-bind (quotient remainder)
(truncate number divisor)
(let ((rem2 (* 2 remainder)))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b11 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b10 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b01 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1- quotient) (- remainder)))))))))
(defun ceiling (number &optional (divisor 1))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (multiple-value-bind (q r)
(truncate (+ number divisor -1) divisor)
(values q (- r (1- divisor)))))
(t (error "Don't know."))))
(defun rem (dividend divisor)
(nth-value 1 (truncate dividend divisor)))
(defun mod (number divisor)
"Returns second result of FLOOR."
(let ((rem (rem number divisor)))
(if (and (not (zerop rem))
(if (minusp divisor)
(plusp number)
(minusp number)))
(+ rem divisor)
rem)))
;;; bytes
(defun byte (size position)
(check-type size positive-fixnum)
(let ((position (check-the (unsigned-byte 20) position)))
(+ position (ash size 20))))
(defun byte-size (bytespec)
(ash bytespec -20))
(defun byte-position (bytespec)
(ldb (byte 20 0) bytespec))
(defun logbitp (index integer)
(check-type index positive-fixnum)
(macrolet
((do-it ()
`(etypecase integer
(fixnum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:addl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx :ebx)))
(positive-bignum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx (:ebx (:offset movitz-bignum bigit0))))))))
(do-it)))
(define-compiler-macro logbitp (&whole form &environment env index integer)
(if (not (movitz:movitz-constantp index env))
form
(let ((index (movitz:movitz-eval index env)))
(check-type index (integer 0 *))
(typecase index
((integer 0 31)
`(with-inline-assembly (:returns :boolean-cf=1)
(:compile-form (:result-mode :untagged-fixnum-ecx) ,integer)
(:btl ,index :ecx)))
(t form)))))
(defun logand (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:andl :ebx :eax)))
((positive-bignum positive-fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) y)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((positive-fixnum positive-bignum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) y)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) x)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((fixnum positive-bignum)
(let ((result (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result x)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum fixnum)
(let ((result (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result y)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(logand y x)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum x) y)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-and-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:andl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-and-loop)))))
((negative-bignum fixnum)
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :untagged-fixnum-ecx)
(:load-lexical (:lexical-binding y) :eax)
(:leal ((:ecx 4) -4) :ecx)
(:notl :ecx)
(:andl :ecx :eax)))
((negative-bignum positive-bignum)
(cond
((<= (%bignum-bigits y) (%bignum-bigits x))
(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding r) :eax)
(:load-lexical (:lexical-binding x) :ebx)
(:xorl :edx :edx)
(:movl #xffffffff :ecx)
loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:notl :ecx)
(:cmpl -1 :ecx)
(:je 'carry)
(:xorl :ecx :ecx)
carry
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:ja 'loop))))
(t (error "Logand not implemented."))))
)))
(do-it)))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
-1
(reduce #'logand integers)))))
(defun logandc1 (integer1 integer2)
(macrolet
((do-it ()
`(number-double-dispatch (integer1 integer2)
((t positive-fixnum)
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-form (:result-mode :eax) integer1)
(:call-global-pf unbox-u32)
(:shll ,movitz:+movitz-fixnum-shift+ :ecx)
(:compile-form (:result-mode :eax) integer2)
(:notl :ecx)
(:andl :ecx :eax)))
(((eql 0) t) integer2)
(((eql -1) t) 0)
((positive-fixnum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum integer2) integer1)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:notl :ecx)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum integer2) integer1)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-andc1-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-andc1-loop)))))))
(do-it)))
(defun logandc2 (integer1 integer2)
(logandc1 integer2 integer1))
(defun logior (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:orl :ebx :eax)))
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let ((r (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logior y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
or-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:orl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'or-loop))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logior integers)))))
(defun logxor (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:xorl :ebx :eax)))
(((eql 0) t) y)
((t (eql 0)) x)
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum y) x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum x) y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logxor y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1),(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
xor-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:xorl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'xor-loop)
))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logxor integers)))))
(defun lognot (integer)
(- -1 integer))
(defun ldb%byte (size position integer)
"This is LDB with explicit byte-size and position parameters."
(check-type size positive-fixnum)
(check-type position positive-fixnum)
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer position)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:ja '(:sub-program (outside-fixnum)
(:addl #x80000000 :eax) ; sign into carry
(:sbbl :ecx :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'mask-fixnum)))
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std) ; <================= STD
(:sarl :cl :eax) ; shift..
(:andl ,(logxor #xffffffff movitz:+movitz-fixnum-zmask+) :eax)
(:cld) ; =================> CLD
mask-fixnum
(:compile-form (:result-mode :ecx) size)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:jna 'fixnum-result)
(:testl :eax :eax)
(:jns 'fixnum-done)
;; We need to generate a bignum..
.. filling in 1 - bits since the integer is negative .
(:pushl :eax) ; This will become the LSB bigit.
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-ones-expanded-bignum))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ones-expanded-bignum
(:movl (:esp) :ebp)
;;; (:declare-label-set retry-jumper-ones-expanded-bignum (retry-ones-expanded-bignum))
Calculate word - size from bytespec - size .
(:compile-form (:result-mode :ecx) size)
Add 31
Divide by 32
(:andl ,(- movitz:+movitz-fixnum-factor+) :ecx)
Add 1 for header .
:eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-non-pointer)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
add 1 for header .
:ecx)
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
Have fresh bignum in EAX , now fill it with ones .
(:xorl :ecx :ecx) ; counter
fill-ones-loop
(:movl #xffffffff (:eax :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jne 'fill-ones-loop)
(:popl :ecx) ; The LSB bigit.
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:movl :eax :ebx)
Compute MSB bigit mask in EDX
(:compile-form (:result-mode :ecx) size)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std) ; <================= STD
(:xorl :edx :edx)
(:andl 31 :ecx)
(:jz 'fixnum-mask-ok)
(:addl 1 :edx)
(:shll :cl :edx)
fixnum-mask-ok
(:subl 1 :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
And EDX with the MSB bigit .
(:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:movl :edi :edx)
(:movl :edi :eax)
(:cld) ; =================> CLD
(:movl :ebx :eax)
(:jmp 'fixnum-done)
fixnum-result
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
generate fixnum mask in EDX
(:shll :cl :edx)
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:andl :edx :eax)
(:jmp 'fixnum-done)
fixnum-done
)))
(do-it)))
(positive-bignum
(cond
((= size 0) 0)
((<= size 32)
;; The result is likely to be a fixnum (or at least an u32), due to byte-size.
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :eax) position)
(:movl :eax :ecx) ; compute bigit-number in ecx
(:sarl 5 :ecx)
(:andl -4 :ecx)
(:addl 4 :ecx)
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jae 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jc '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:std)
(:movl (:ebx :ecx (:offset movitz-bignum bigit0 -4))
:eax)
(:movl 0 :edx) ; If position was in last bigit.. (don't touch EFLAGS)
.. we must zero - extend rather than read top bigit .
(:movl (:ebx :ecx (:offset movitz-bignum bigit0))
Read top bigit into EDX
no-top-bigit
(:testl #xff00 (:ebx ,movitz:+other-type-offset+))
(:jnz '(:sub-program (negative-bignum)
We must negate the ..
(:break)
))
edx-eax-ok
EDX : EAX now holds the number that must be shifted and masked .
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
Shifted value into EAX
(:compile-form (:result-mode :ecx) size)
Generate a mask in EDX
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:testl 31 :ecx)
(:jz 'mask-ok-u32)
(:addl 1 :edx)
(:shll :cl :edx)
mask-ok-u32
(:subl 1 :edx)
(:andl :edx :eax)
(:movl :eax :ecx) ; For boxing..
(:movl :edi :eax)
(:movl :edi :edx)
(:cld)
;; See if we can return same bignum..
(:cmpl ,(dpb movitz:+movitz-fixnum-factor+
(byte 16 16) (movitz:tag :bignum 0))
(:ebx ,movitz:+other-type-offset+))
(:jne 'cant-return-same)
(:cmpl :ecx (:ebx (:offset movitz-bignum bigit0)))
(:jne 'cant-return-same)
(:movl :ebx :eax)
(:jmp 'done-u32)
cant-return-same
(:call-local-pf box-u32-ecx)
done-u32
)))
(do-it)))
(t (macrolet
((do-it ()
`(let (new-size)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :ecx) position)
(:shrl 5 :ecx) ; compute fixnum bigit-number in ecx
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jnc 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:compile-two-forms (:edx :ecx) position size)
keep size / fixnum in EAX .
(:addl :edx :ecx)
(:into) ; just to make sure
compute msb bigit index / fixnum in ecx
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:je '(:sub-program (equal-size-maybe-return-same)
Can only return same if ( zerop position ) .
(:jnz 'adjust-size)
(:movl :eax :ecx) ; size/fixnum
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'yes-return-same)
(:std) ; <================
we know EDX=0 , now generate mask in EDX
(:addl 1 :edx)
(:shll :cl :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:cmpl :edx (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:movl 0 :edx) ; Safe value, and correct if we need to go to adjust-size.
(:cld) ; =================>
(:jnc 'adjust-size) ; nope, we have to generate a new bignum.
yes-return-same
(:movl :ebx :eax) ; yep, we can return same bignum.
(:jmp 'ldb-done)))
(:jnc 'size-ok)
;; We now know that (+ size position) is beyond the size of the bignum.
So , if ( zerop position ) , we can return the bignum as our result .
(:testl :edx :edx)
(:jz '(:sub-program ()
(:movl :ebx :eax) ; return the source bignum.
(:jmp 'ldb-done)))
adjust-size
The bytespec is ( partially ) outside source - integer , so we make the
;; size smaller before proceeding. new-size = (- source-int-length position)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx) ; length of source-integer
(:shll 5 :ecx) ; fixnum bit-position
In case the new size is zero .
(:subl :edx :ecx) ; subtract position
(:js '(:sub-program (should-not-happen)
;; new size should never be negative.
(:break)))
New size was zero , so the result of ldb is zero .
New size into EAX .
size-ok
(:store-lexical (:lexical-binding new-size) :eax :type fixnum)
;; Set up atomically continuation.
(:declare-label-set restart-ldb-jumper (restart-ldb))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-ldb-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ldb
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding new-size) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
( new ) Size is in EAX .
(:subl ,movitz:+movitz-fixnum-factor+ :eax)
(:andl ,(logxor #xffffffff
(mask-field (byte (+ 5 movitz:+movitz-fixnum-shift+) 0) -1))
:eax)
Divide ( size-1 ) by 32 to get number of bigits-1
Now add 1 for index->size , 1 for header , and 1 for tmp storage before shift .
(:addl ,(* 3 movitz:+movitz-fixnum-factor+) :eax)
(:pushl :eax)
(:call-local-pf cons-non-pointer)
;; (:store-lexical (:lexical-binding r) :eax :type t)
(:popl :ecx)
(:subl ,(* 2 movitz:+movitz-fixnum-factor+) :ecx) ; for tmp storage and header.
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:compile-form (:result-mode :ebx) integer)
(:xchgl :eax :ebx)
now : EAX = old integer , EBX = new result bignum
Edge case : When size(old)=size(new ) , the tail - tmp must be zero .
;; We check here, setting the tail-tmp to a mask for and-ing below.
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx) ; length of source-integer
Initialize tail - tmp to # xffffffff , meaning copy from source - integer .
(:movl #xffffffff (:ebx :ecx (:offset movitz-bignum bigit0)))
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jc '(:sub-program (result-too-big-shouldnt-happen)
(:int 4)))
(:jne 'tail-tmp-ok)
Sizes was equal , so set tail - tmp to zero .
(:movl 0 (:ebx :ecx (:offset movitz-bignum bigit0)))
tail-tmp-ok
;; Now copy the relevant part of the integer
(:std)
(:compile-form (:result-mode :ecx) position)
(:sarl ,(+ 5 movitz:+movitz-fixnum-shift+) :ecx) ; compute bigit-number in ecx
;; We can use primitive pointers because we're both inside atomically and std.
(:leal (:eax (:ecx 4) (:offset movitz-bignum bigit0))
Use EAX as primitive pointer into source
(:xorl :ecx :ecx) ; counter
copy-integer
(:movl (:eax) :edx)
(:addl 4 :eax)
(:movl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jne 'copy-integer)
Copy one more than the length , namely the tmp at the end .
;; Tail-tmp was initialized to a bit-mask above.
(:movl (:eax) :edx)
(:andl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
;; Copy done, now shift
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
if ( zerop ( mod position 32 ) ) , no shift needed .
(:xorl :edx :edx) ; counter
shift-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0 4))
:eax) ; Next bigit into eax
Now shift bigit , with msbs from eax .
(:ebx :edx (:offset movitz-bignum bigit0)))
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'shift-loop)
shift-done
Now we must mask MSB bigit .
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl 5 :ecx)
ECX = index of ( conceptual ) MSB
(:cmpl :ecx :edx)
(:jbe 'mask-done)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'mask-done)
Generate mask in EAX
(:shll :cl :eax)
(:subl 1 :eax)
(:andl :eax (:ebx :edx (:offset movitz-bignum bigit0 -4)))
mask-done
(: : edi : edx ) ; safe EDX
safe EAX
(:cld)
Now we must zero - truncate the result bignum in EBX .
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
zero-truncate-loop
(:cmpl 0 (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:jne 'zero-truncate-done)
(:subl 4 :ecx)
(:jnz 'zero-truncate-loop)
Zero bigits means the entire result collapsed to zero .
(:xorl :eax :eax)
(:jmp 'return-fixnum) ; don't commit the bignum allocation.
zero-truncate-done
If result size is 1 , the result might have ..
(:jne 'complete-bignum-allocation) ; ..collapsed to a fixnum.
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:ebx (:offset movitz-bignum bigit0)))
(:ja 'complete-bignum-allocation)
(:movl (:ebx (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'return-fixnum)
complete-bignum-allocation
(:movw :cx (:ebx (:offset movitz-bignum length)))
(:movl :ebx :eax)
(:leal (:ecx ,movitz:+movitz-fixnum-factor+)
:ecx)
(:call-local-pf cons-commit-non-pointer)
return-fixnum
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
ldb-done))))
(do-it)))))))
(defun ldb (bytespec integer)
(ldb%byte (byte-size bytespec) (byte-position bytespec) integer))
(defun ldb-test (bytespec integer)
(case (byte-size bytespec)
(0 nil)
(1 (logbitp (byte-position bytespec) integer))
(t (/= 0 (ldb bytespec integer)))))
(defun logtest (integer-1 integer-2)
"=> generalized-boolean"
(not (= 0 (logand integer-1 integer-2))))
(defun logcount (integer)
(etypecase integer
(positive-fixnum
(with-inline-assembly (:returns :untagged-fixnum-ecx :type (integer 0 29))
(:load-lexical (:lexical-binding integer) :eax)
(:xorl :ecx :ecx)
count-loop
(:shll 1 :eax)
(:adcl 0 :ecx)
(:testl :eax :eax)
(:jnz 'count-loop)))
(positive-bignum
(bignum-logcount integer))))
(defun dpb (newbyte bytespec integer)
(logior (if (= 0 newbyte)
0
(mask-field bytespec (ash newbyte (byte-position bytespec))))
(if (= 0 integer)
0
(logandc2 integer (mask-field bytespec -1)))))
(defun mask-field (bytespec integer)
(ash (ldb bytespec integer) (byte-position bytespec)))
(defun deposit-field (newbyte bytespec integer)
(logior (mask-field bytespec newbyte)
(logandc2 integer (mask-field bytespec -1))))
;;;
(defun plus-if (x y)
(if (integerp x) (+ x y) x))
(defun minus-if (x y)
(if (integerp x) (- x y) x))
(defun gcd (&rest integers)
(numargs-case
(1 (u) u)
(2 (u v)
Code borrowed from CMUCL .
(cond
((= 0 u) v)
((= 0 v) u)
(t (do ((k 0 (1+ k))
(u (abs u) (truncate u 2))
(v (abs v) (truncate v 2)))
((or (oddp u) (oddp v))
(do ((temp (if (oddp u)
(- v)
(truncate u 2))
(truncate temp 2)))
(nil)
(when (oddp temp)
(if (plusp temp)
(setq u temp)
(setq v (- temp)))
(setq temp (- u v))
(when (zerop temp)
(return (ash u k))))))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(do ((gcd (car integers)
(gcd gcd (car rest)))
(rest (cdr integers) (cdr rest)))
((null rest) gcd)))))
(defun lcm (&rest numbers)
"Returns the least common multiple of one or more integers. LCM of no
arguments is defined to be 1."
(numargs-case
(1 (n)
(abs n))
(2 (n m)
(abs (* (truncate (max n m) (gcd n m)) (min n m))))
(t (&rest numbers)
(declare (dynamic-extent numbers))
(reduce #'lcm numbers
:initial-value 1))))
(defun floor (n &optional (divisor 1))
"This is floor written in terms of truncate."
(numargs-case
(1 (n)
(if (not (typep n 'ratio))
(values n 0)
(multiple-value-bind (r q)
(floor (%ratio-numerator n) (%ratio-denominator n))
(values r (make-rational q (%ratio-denominator n))))))
(2 (n divisor)
(multiple-value-bind (q r)
(truncate n divisor)
(cond
((= 0 r)
(values q r))
((or (and (minusp r) (plusp divisor))
(and (plusp r) (minusp divisor)))
(values (1- q) (+ r divisor)))
(t (values q r)))))
(t (n &optional (divisor 1))
(floor n divisor))))
(defun isqrt (natural)
"=> natural-root"
(check-type natural (integer 0 *))
(if (= 0 natural)
0
(let ((r 1))
(do ((next-r (truncate (+ r (truncate natural r)) 2)
(truncate (+ r (truncate natural r)) 2)))
((typep (- next-r r) '(integer 0 1))
(let ((r+1 (1+ r)))
(if (<= (* r+1 r+1) natural)
r+1
r)))
(setf r next-r)))))
(defun rootn (x root)
(check-type root (integer 2 *))
(let ((root-1 (1- root))
(r (/ x root)))
(dotimes (i 10 r)
(let ((m (min (integer-length (numerator r))
(integer-length (denominator r)))))
(when (>= m 32)
(setf r (/ (ash (numerator r) (- 24 m))
(ash (denominator r) (- 24 m))))))
#+ignore (format t "~&~D: ~X~%~D: ~F [~D ~D]~%" i r i r
(integer-length (numerator r))
(integer-length (denominator r)))
(setf r (/ (+ (* root-1 r)
(/ x (expt r root-1)))
root)))))
(defun sqrt (x)
(rootn x 2))
(defun expt (base-number power-number)
"Take base-number to the power-number."
(etypecase power-number
(positive-fixnum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)
(declare (index i))))
(positive-bignum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)))
((number * -1)
(/ (expt base-number (- power-number))))
(ratio
(expt (rootn base-number (denominator power-number))
(numerator power-number)))))
(defun floatp (x)
(typep x 'real))
(defun realpart (number)
number)
(defun imagpart (number)
(declare (ignore number))
0)
(defun rational (number)
number)
(defun realp (x)
(typep x 'real))
(defconstant boole-clr 'boole-clr)
(defconstant boole-1 'boole-1)
(defconstant boole-2 'boole-2)
(defconstant boole-c1 'boole-c1)
(defconstant boole-c2 'boole-c2)
(defconstant boole-eqv 'logeqv)
(defconstant boole-and 'logand)
(defconstant boole-nand 'lognand)
(defconstant boole-andc1 'logandc1)
(defconstant boole-andc2 'logandc2)
(defconstant boole-ior 'logior)
(defconstant boole-nor 'lognor)
(defconstant boole-orc1 'logorc1)
(defconstant boole-orc2 'logorc2)
(defconstant boole-xor 'logxor)
(defconstant boole-set 'boole-set)
(defun boole (op integer-1 integer-2)
"=> result-integer"
(funcall op integer-1 integer-2))
(defun boole-clr (integer-1 integer-2)
(declare (ignore integer-1 integer-2))
0)
(defun boole-set (integer-1 integer-2)
(declare (ignore integer-1 integer-2))
-1)
(defun boole-1 (integer-1 integer-2)
(declare (ignore integer-2))
integer-1)
(defun boole-2 (integer-1 integer-2)
(declare (ignore integer-1))
integer-2)
(defun boole-c1 (integer-1 integer-2)
(declare (ignore integer-2))
(lognot integer-1))
(defun boole-c2 (integer-1 integer-2)
(declare (ignore integer-1))
(lognot integer-2))
(defun logeqv (integer-1 integer-2)
(lognot (logxor integer-1 integer-2)))
(defun lognand (integer-1 integer-2)
(lognot (logand integer-1 integer-2)))
(defun lognor (integer-1 integer-2)
(lognot (logior integer-1 integer-2)))
(defun logorc1 (integer-1 integer-2)
(logior (lognot integer-1)
integer-2))
(defun logorc2 (integer-1 integer-2)
(logior integer-1
(lognot integer-2)))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/integers.lisp | lisp | ------------------------------------------------------------------
Filename: integers.lisp
Created at: Wed Nov 8 18:44:57 2000
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
unspecified
both were fixnum
but we don't know about n2
n2 is fixnum
Check that both numbers are bignums, and compare them.
Comparing the sign-bytes sets up EFLAGS correctly!
counter
Now we have to make the compare act as unsigned, which is why
Moth n1 and n2 are negative bignums.
counter
Now we have to make the compare act as unsigned, which is why
well..
EQ?
counter
unspecified
compare eax with something bigger
compare ebx with something bigger
unspecified
compare ebx with something bigger
compare ebx with something bigger
The real result is in EFLAGS.
Unsigned
Equality
Addition
..this allows us to detect recursive atomicallies.
Now inside atomically section.
Number of words
bignum
counter
result bignum word-size
Assume x is smallest.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Number of words
Now inside atomically section.
bignum
counter
Carry
Subtraction
((positive-fixnum positive-bignum)
(bignum-canonicalize
(%bignum-negate
(bignum-subf (copy-bignum subtrahend) minuend))))
((negative-fixnum positive-bignum)
(bignum-canonicalize
(%negatef (bignum-add-fixnum subtrahend minuend)
subtrahend minuend)))
counter
carry
Just propagate carry
shift
counter
Safe EAX
Multiplication
most likely/optimized path.
guaranteed won't overflow.
if result was negative, we must negate bignum
Set up atomically continuation.
..this allows us to detect recursive atomicallies:
Now inside atomically section.
bignum
r into ebx
counter
initial carry
can't overflow
new
Negate the resulting bignum
X is the biggest factor.
return values: qutient, remainder.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
edx=hi-digit=0
eax=lo-digit=msd(number)
safe value
don't commit the bignum
bytes
sign into carry
<================= STD
shift..
=================> CLD
We need to generate a bignum..
This will become the LSB bigit.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
(:declare-label-set retry-jumper-ones-expanded-bignum (retry-ones-expanded-bignum))
Now inside atomically section.
counter
The LSB bigit.
<================= STD
=================> CLD
The result is likely to be a fixnum (or at least an u32), due to byte-size.
compute bigit-number in ecx
If position was in last bigit.. (don't touch EFLAGS)
For boxing..
See if we can return same bignum..
compute fixnum bigit-number in ecx
just to make sure
size/fixnum
<================
Safe value, and correct if we need to go to adjust-size.
=================>
nope, we have to generate a new bignum.
yep, we can return same bignum.
We now know that (+ size position) is beyond the size of the bignum.
return the source bignum.
size smaller before proceeding. new-size = (- source-int-length position)
length of source-integer
fixnum bit-position
subtract position
new size should never be negative.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
(:store-lexical (:lexical-binding r) :eax :type t)
for tmp storage and header.
We check here, setting the tail-tmp to a mask for and-ing below.
length of source-integer
Now copy the relevant part of the integer
compute bigit-number in ecx
We can use primitive pointers because we're both inside atomically and std.
counter
Tail-tmp was initialized to a bit-mask above.
Copy done, now shift
counter
Next bigit into eax
safe EDX
don't commit the bignum allocation.
..collapsed to a fixnum.
| Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
Description : Arithmetics .
Author : < >
$ I d : , v 1.128 2008 - 04 - 27 19:41:10 Exp $
(require :muerte/basic-macros)
(require :muerte/typep)
(require :muerte/arithmetic-macros)
(provide :muerte/integers)
(in-package muerte)
(defconstant most-positive-fixnum #.movitz::+movitz-most-positive-fixnum+)
(defconstant most-negative-fixnum #.movitz::+movitz-most-negative-fixnum+)
Comparison
(define-primitive-function fast-compare-two-reals (n1 n2)
"Compare two numbers (i.e. set EFLAGS accordingly)."
(macrolet
((do-it ()
(:testb ,movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'n1-not-fixnum)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum-but-n1-is)
(:ret)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'neither-is-fixnum)
(:locally (:jmp (:edi (:edi-offset fast-compare-real-fixnum))))
n2-not-fixnum-but-n1-is
(:locally (:jmp (:edi (:edi-offset fast-compare-fixnum-real))))
neither-is-fixnum
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
If they are EQ , they are certainly =
(:je '(:sub-program (n1-and-n2-are-eq)
(:ret)))
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz 'go-complicated)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
(:cmpb :ch (:eax (:offset movitz-bignum sign)))
(:jne '(:sub-program (different-signs)
(:ret)))
(:testl #xff00 :ecx)
(:jnz 'compare-negatives)
Both n1 and n2 are positive bignums .
(:shrl 16 :ecx)
(:movzxw (:eax (:offset movitz-bignum length)) :edx)
(: cmpw : cx (: eax (: offset ) ) )
(:cmpl :ecx :edx)
(:jne '(:sub-program (positive-different-sizes)
(:ret)))
Both n1 and n2 are positive bignums of the same size , namely ECX .
positive-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'positive-compare-lsb)
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:je 'positive-compare-loop)
positive-compare-lsb
we compare zero - extended 16 - bit quantities .
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0 2)) :ecx)
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
(:jne 'upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
upper-16-decisive
(:ret)
compare-negatives
(:shrl 16 :ecx)
(:cmpw (:eax (:offset movitz-bignum length)) :cx)
(:jne '(:sub-program (negative-different-sizes)
(:ret)))
Both n1 and n2 are negative bignums of the same size , namely ECX .
negative-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'negative-compare-lsb)
(:movl (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0)))
(:je 'negative-compare-loop)
(:ret)
it 's down to .
we compare zero - extended 16 - bit quantities .
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0 2))
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
(:jne 'negative-upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
negative-upper-16-decisive
(:ret))))
(do-it)))
(defun complicated-eql (x y)
(macrolet
((do-it ()
(:compile-two-forms (:eax :ebx) x y)
(:je 'done)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'not-bignum)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
Ok .. we have two bignums of identical sign and size .
(:shrl 16 :ecx)
compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'done)
(:movl (:eax :edx (:offset movitz-bignum bigit0 -4)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:je 'compare-loop)
(:jmp 'done)
not-bignum
(:cmpb ,(movitz:tag :ratio) :cl)
(:jne 'not-ratio)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
(:movl (:eax (:offset movitz-ratio numerator)) :eax)
(:movl (:ebx (:offset movitz-ratio numerator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jne 'done)
(:compile-two-forms (:eax :ebx) x y)
(:movl (:eax (:offset movitz-ratio denominator)) :eax)
(:movl (:ebx (:offset movitz-ratio denominator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jmp 'done)
not-ratio
done
(:movl :edi :eax)
(:clc)
)))
(do-it)))
(define-primitive-function fast-compare-fixnum-real (n1 n2)
"Compare (known) fixnum <n1> with real <n2>."
(macrolet
((do-it ()
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum)
(:cmpl :ebx :eax)
(:ret)
n2-not-fixnum
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpw ,(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
(:cmpl #x10000000 :edi)
(:ret)
not-plusbignum
(:cmpw ,(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
(:cmpl #x-10000000 :edi)
(:ret))))
(do-it)))
(define-primitive-function fast-compare-real-fixnum (n1 n2)
"Compare real <n1> with fixnum <n2>."
(:testb #.movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'not-fixnum)
(:cmpl :ebx :eax)
(:ret)
not-fixnum
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax #.movitz:+other-type-offset+) :ecx)
(:cmpw #.(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
(:cmpl #x-10000000 :edi)
(:ret)
not-plusbignum
(:cmpw #.(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
(:cmpl #x10000000 :edi)
(:ret)))
(defun complicated-compare (x y)
(let ((ix (* (numerator x) (denominator y)))
(iy (* (numerator y) (denominator x))))
(with-inline-assembly (:returns :multiple-values)
(:compile-two-forms (:eax :ebx) ix iy)
(:call-global-pf fast-compare-two-reals)
(:movl :edi :eax))))
(defun below (x max)
"Is x between 0 and max?"
(compiler-macro-call below x max))
(define-compiler-macro =%2op (n1 n2 &environment env)
(cond
#+ignore
((movitz:movitz-constantp n1 env)
(let ((n1 (movitz:movitz-eval n1 env)))
(etypecase n1
((eql 0)
`(do-result-mode-case ()
(:booleans
(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:testl :eax :eax)))
(t (with-inline-assembly (:returns :boolean-cf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:cmpl 1 :eax)))))
((signed-byte 30)
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-fixnum-real)))
(integer
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-two-reals))))))
#+ignore
((movitz:movitz-constantp n2 env)
`(=%2op ,n2 ,n1))
(t `(eql ,n1 ,n2))))
(define-number-relational = =%2op nil :defun-p nil)
(defun = (first-number &rest numbers)
(declare (dynamic-extent numbers))
(dolist (n numbers t)
(unless (= first-number n)
(return nil))))
(define-compiler-macro /=%2op (n1 n2)
`(not (= ,n1 ,n2)))
(define-number-relational /= /=%2op nil :defun-p nil)
(defun /= (first-number &rest more-numbers)
(numargs-case
(1 (x)
(declare (ignore x))
t)
(2 (x y)
(/=%2op x y))
(t (first-number &rest more-numbers)
(declare (dynamic-extent more-numbers))
(dolist (y more-numbers)
(when (= first-number y)
(return nil)))
(do ((p more-numbers (cdr p)))
((null p) t)
(dolist (q (cdr p))
(when (= (car p) q)
(return nil)))))))
(deftype positive-fixnum ()
'(integer 0 #.movitz:+movitz-most-positive-fixnum+))
(deftype positive-bignum ()
`(integer #.(cl:1+ movitz:+movitz-most-positive-fixnum+) *))
(deftype negative-fixnum ()
`(integer #.movitz:+movitz-most-negative-fixnum+ -1))
(deftype negative-bignum ()
`(integer * #.(cl:1- movitz::+movitz-most-negative-fixnum+)))
(defun fixnump (x)
(typep x 'fixnum))
(defun evenp (x)
(compiler-macro-call evenp x))
(defun oddp (x)
(compiler-macro-call oddp x))
(defun %negatef (x p0 p1)
"Negate x. If x is not eq to p0 or p1, negate x destructively."
(etypecase x
(fixnum (- x))
(bignum
(if (or (eq x p0) (eq x p1))
(- x)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:xorl #xff00 (:eax #.movitz:+other-type-offset+)))))))
(defun + (&rest terms)
(declare (without-check-stack-limit))
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:compile-form (:result-mode :ebx) y)
(:addl :ebx :eax)
(:jo '(:sub-program (fix-fix-overflow)
(:movl :eax :ecx)
(:jns 'fix-fix-negative)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'fix-fix-ok)
fix-fix-negative
(:jz 'fix-double-negative)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:movl ,(dpb 4 (byte 16 16)
(movitz:tag :bignum #xff))
(:eax ,movitz:+other-type-offset+))
(:jmp 'fix-fix-ok)
fix-double-negative
(:compile-form (:result-mode :eax)
,(* 2 movitz:+movitz-most-negative-fixnum+))
(:jmp 'fix-fix-ok)))
fix-fix-ok))
((positive-bignum positive-fixnum)
(+ y x))
((positive-fixnum positive-bignum)
(bignum-add-fixnum y x))
((positive-bignum negative-fixnum)
(+ y x))
((negative-fixnum positive-bignum)
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done))
(:compile-two-forms (:eax :ebx) y x)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl 4 :ecx)
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set retry-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:leal ((:ecx 1) ,(* 1 movitz:+movitz-fixnum-factor+))
(:call-local-pf cons-pointer)
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:negl :ecx)
(:subl :ecx (:eax (:offset movitz-bignum bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :ebx)
(:subl 1 (:eax :ebx (:offset movitz-bignum bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-expansion)
(:subl #x40000 (:eax ,movitz:+other-type-offset+))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(+ y x)
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done
zero-padding-loop))
(:compile-two-forms (:eax :ebx) y x)
(:testl :ebx :ebx)
(:jz 'pfix-pbig-done)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl ,movitz:+movitz-fixnum-factor+ :ecx)
(:jne 'not-size1)
(:movl (:ebx (:offset movitz-bignum bigit0)) :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:jc 'not-size1)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set restart-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+))
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-non-pointer)
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
MSB
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ebx)
add-bignum-loop
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (zero-padding-loop)
(:addl :ecx (:eax :edx (:offset movitz-bignum
bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'zero-padding-loop)
(:jmp 'add-bignum-done)))
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (term1-carry)
The digit + carry carried over , ECX = 0
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
(:jmp 'add-bignum-done)))
(:addl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4)))
(:je 'no-expansion)
(:addl #x40000 (:eax ,movitz:+other-type-offset+))
(:addl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done)
))
(((integer * -1) (integer 0 *))
(- y (- x)))
(((integer 0 *) (integer * -1))
(- x (- y)))
(((integer * -1) (integer * -1))
(%negatef (+ (- x) (- y)) x y))
((rational rational)
(/ (+ (* (numerator x) (denominator y))
(* (numerator y) (denominator x)))
(* (denominator x) (denominator y))))
)))
(do-it)))
(t (&rest terms)
(declare (dynamic-extent terms))
(if (null terms)
0
(reduce #'+ terms)))))
(defun 1+ (number)
(+ 1 number))
(defun 1- (number)
(+ -1 number))
(defun - (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(numargs-case
(1 (x)
(etypecase x
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:negl :eax)
(:jo '(:sub-program (fix-overflow)
(:compile-form (:result-mode :eax)
,(1+ movitz:+movitz-most-positive-fixnum+))
(:jmp 'fix-ok)))
fix-ok)))
(do-it)))
(bignum
(%bignum-negate (copy-bignum x)))
(ratio
(make-ratio (- (ratio-numerator x)) (ratio-denominator x)))))
(2 (minuend subtrahend)
(macrolet
((do-it ()
`(number-double-dispatch (minuend subtrahend)
((number (eql 0))
minuend)
(((eql 0) t)
(- subtrahend))
((fixnum fixnum)
(with-inline-assembly (:returns :eax :labels (done negative-result))
(:compile-two-forms (:eax :ebx) minuend subtrahend)
(:subl :ebx :eax)
(:jno 'done)
(:jnc 'negative-result)
(:movl :eax :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl ,(- movitz:+movitz-most-negative-fixnum+) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'done)
negative-result
(:movl :eax :ecx)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax (:offset movitz-bignum type)))
done))
((positive-bignum fixnum)
(+ (- subtrahend) minuend))
((fixnum positive-bignum)
(%negatef (+ subtrahend (- minuend))
subtrahend minuend))
((positive-bignum positive-bignum)
(cond
((= minuend subtrahend)
0)
((< minuend subtrahend)
(let ((x (- subtrahend minuend)))
(%negatef x subtrahend minuend)))
(t (bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum minuend) subtrahend)
sub-loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (carry-overflow)
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:jmp 'bignum-sub-done)))
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
(:negl :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:jnc 'bignum-sub-done)
propagate-carry
(:addl 4 :edx)
(:subl 1 (:eax :edx (:offset movitz-bignum bigit0)))
(:jc 'propagate-carry)
bignum-sub-done
)))))
(((integer 0 *) (integer * -1))
(+ minuend (- subtrahend)))
(((integer * -1) (integer 0 *))
(%negatef (+ (- minuend) subtrahend) minuend subtrahend))
(((integer * -1) (integer * -1))
(+ minuend (- subtrahend)))
((rational rational)
(/ (- (* (numerator minuend) (denominator subtrahend))
(* (numerator subtrahend) (denominator minuend)))
(* (denominator minuend) (denominator subtrahend))))
)))
(do-it)))
(t (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(if subtrahends
(reduce #'- subtrahends :initial-value minuend)
(- minuend)))))
(defun zerop (number)
(= 0 number))
(defun plusp (number)
(> number 0))
(defun minusp (number)
(< number 0))
(defun abs (x)
(compiler-macro-call abs x))
(defun signum (x)
(cond
((> x 0) 1)
((< x 0) -1)
(t 0)))
(defun max (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call max x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((max number1))
(dolist (x numbers max)
(when (> x max)
(setq max x)))))))
(defun min (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call min x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((min number1))
(dolist (x numbers min)
(when (< x min)
(setq min x)))))))
(defun ash (integer count)
(cond
((= 0 count)
integer)
((= 0 integer) 0)
((typep count '(integer 0 *))
(let ((result-length (+ (integer-length (if (minusp integer) (1- integer) integer))
count)))
(cond
((<= result-length 29)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:shll :cl :eax)))
((typep integer 'positive-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
integer)
(bignum-shift-leftf result count)))
((typep integer 'positive-bignum)
(let ((result (%make-bignum (ceiling result-length 32))))
(dotimes (i (* 2 (%bignum-bigits result)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(let ((pos (- (* i 16) count)))
(cond
((minusp (+ pos 16)) 0)
((<= 0 pos)
(ldb (byte 16 pos) integer))
(t (ash (ldb (byte (+ pos 16) 0) integer)
(- pos)))))))
(assert (or (plusp (memref result -2
:index (+ -1 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))
(plusp (memref result -2
:index (+ -2 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))))
(bignum-canonicalize result)))
((typep integer 'negative-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
(- integer))
(%bignum-negate (bignum-shift-leftf result count))))
((typep integer 'negative-bignum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(dotimes (i (%bignum-bigits integer))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)
(memref integer (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)))
(%bignum-negate (bignum-shift-leftf result count))))
(t (error 'program-error)))))
(t (let ((count (- count)))
(etypecase integer
(fixnum
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:sarl :cl :eax)
(:andl -4 :eax)
(:cld)))
(positive-bignum
(let ((result-length (- (integer-length integer) count)))
(cond
((<= result-length 1)
1 or 0 .
(t (multiple-value-bind (long short)
(truncate count 16)
(let ((result (%make-bignum (1+ (ceiling result-length 32)))))
(let ((src-max-bigit (* 2 (%bignum-bigits integer))))
(dotimes (i (* 2 (%bignum-bigits result)))
(declare (index i))
(let ((src (+ i long)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(if (< src src-max-bigit)
(memref integer -2 :index src :type :unsigned-byte16)
0)))))
(bignum-canonicalize
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ecx :ebx) short result)
We need to use EAX for u32 storage .
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
shift-short-loop
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'end-shift-short-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:eax)
(:shrdl :cl :eax
(:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:jmp 'shift-short-loop)
end-shift-short-loop
(:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:cld))))
(do-it))))))))))))))
(defun integer-length (integer)
"=> number-of-bits"
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:xorl :eax :eax)
(:compile-form (:result-mode :ecx) integer)
(:testl :ecx :ecx)
(:jns 'not-negative)
(:notl :ecx)
not-negative
(:bsrl :ecx :ecx)
(:jz 'zero)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
,(* -1 movitz:+movitz-fixnum-factor+))
:eax)
zero)))
(do-it)))
(positive-bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:xorl :eax :eax)
bigit-scan-loop
(:subl 4 :edx)
(:jc 'done)
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jz 'bigit-scan-loop)
Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) .
Factor 8
(:bsrl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
Factor 4
(:leal ((:ecx 4) :eax 4) :eax)
done)))
(do-it)))
(negative-bignum
(let ((abs-length (bignum-integer-length integer)))
(if (= 1 (bignum-logcount integer))
(1- abs-length)
abs-length)))))
(defun * (&rest factors)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(let (d0 d1)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) x y)
(:sarl ,movitz::+movitz-fixnum-shift+ :ecx)
(:std)
(:imull :ecx :eax :edx)
(:cmpl ,movitz::+movitz-fixnum-factor+ :edx)
(:jc 'u32-result)
(:cmpl #xfffffffc :edx)
(:ja 'u32-negative-result)
(:jne 'two-bigits)
(:testl :eax :eax)
(:jnz 'u32-negative-result)
The result requires 2 ..
two-bigits
(:cld)
(:store-lexical (:lexical-binding d0) :eax :type fixnum)
(:store-lexical (:lexical-binding d1) :edx :type fixnum)
(:compile-form (:result-mode :eax) (%make-bignum 2))
(:movl ,(dpb (* 2 movitz:+movitz-fixnum-factor+)
(byte 16 16) (movitz:tag :bignum 0))
(:eax ,movitz:+other-type-offset+))
(:load-lexical (:lexical-binding d0) :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:load-lexical (:lexical-binding d1) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:shrdl ,movitz:+movitz-fixnum-shift+ :ecx
(:eax (:offset movitz-bignum bigit0)))
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0 4)))
(:jns 'fixnum-done)
(:notl (:eax (:offset movitz-bignum bigit0 4)))
(:negl (:eax (:offset movitz-bignum bigit0)))
(:cmc)
(:adcl 0 (:eax (:offset movitz-bignum bigit0 4)))
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
u32-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:call-local-pf box-u32-ecx)
(:jmp 'fixnum-done)
u32-negative-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:negl :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
fixnum-result
(:movl :edi :edx)
(:cld)
fixnum-done)))
(((eql 0) t) 0)
(((eql 1) t) y)
(((eql -1) t) (- y))
((t fixnum) (* y x))
((fixnum bignum)
(let (r)
(with-inline-assembly (:returns :eax)
(:declare-label-set restart-jumper (restart-multiplication))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-multiplication
(:movl (:esp) :ebp)
(:compile-two-forms (:eax :ebx) (integer-length x) (integer-length y))
Compute ( 1 + ( ceiling ( + ( len x ) ( len y ) ) 32 ) ) ..
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:leal (:eax :ebx ,(* 4 (+ 31 32))) :eax)
(:andl ,(logxor #xffffffff (* 31 4)) :eax)
(:shrl 5 :eax)
New bignum into EAX
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:store-lexical (:lexical-binding r) :eax :type bignum)
Make EAX , EDX , ESI non - GC - roots .
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jns 'multiply-loop)
multiply-loop
(:offset movitz-bignum bigit0)))
(:compile-form (:result-mode :ebx) y)
(:movl (:ebx (:esi 1) (:offset movitz-bignum bigit0))
:eax)
(:mull :ecx :eax :edx)
(:compile-form (:result-mode :ebx) r)
(:addl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:adcl 0 :edx)
(:addl 4 :esi)
(:cmpw :si (:ebx (:offset movitz-bignum length)))
(:ja 'multiply-loop)
(:testl :edx :edx)
(:jz 'no-carry-expansion)
(:movl :edx (:ebx :esi (:offset movitz-bignum bigit0)))
(:addl 4 :esi)
(:movw :si (:ebx (:offset movitz-bignum length)))
no-carry-expansion
(:leal (:esi ,movitz:+movitz-fixnum-factor+)
Put bignum length into ECX
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edi :edx)
EAX , EDX , and ESI are GC roots again .
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
(:compile-form (:result-mode :ebx) x)
(:testl :ebx :ebx)
(:jns 'positive-result)
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
positive-result
)))
((positive-bignum positive-bignum)
(if (< x y)
(* y x)
#-movitz-reference-code
(do ((tmp (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32)))
(r (bignum-set-zerof (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32))))
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) (bignum-canonicalize r))
(bignum-set-zerof tmp)
(bignum-addf r (bignum-shift-leftf (bignum-mulf (bignum-addf tmp x)
(ldb (byte 29 i) y))
i)))
#+movitz-reference-code
(do ((r 0)
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) r)
(incf r (ash (* x (ldb (byte 29 i) y)) i)))))
((ratio ratio)
(make-rational (* (ratio-numerator x) (ratio-numerator y))
(* (ratio-denominator x) (ratio-denominator y))))
((ratio t)
(make-rational (* y (ratio-numerator x))
(ratio-denominator x)))
((t ratio)
(make-rational (* x (ratio-numerator y))
(ratio-denominator y)))
((t (integer * -1))
(%negatef (* x (- y)) x y))
(((integer * -1) t)
(%negatef (* (- x) y) x y))
(((integer * -1) (integer * -1))
(* (- x) (- y))))))
(do-it)))
(t (&rest factors)
(declare (dynamic-extent factors))
(if (null factors)
1
(reduce '* factors)))))
Division
(defun truncate (number &optional (divisor 1))
(numargs-case
(1 (number)
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
(t (number divisor)
(number-double-dispatch (number divisor)
((t (eql 1))
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
((fixnum fixnum)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :eax) number)
(:compile-form (:result-mode :ebx) divisor)
(:std)
(:cdq :eax :edx)
(:idivl :ebx :eax :edx)
(:shll #.movitz::+movitz-fixnum-shift+ :eax)
(:cld)
(:movl :edx :ebx)
(:xorl :ecx :ecx)
(:stc)))
((positive-fixnum positive-bignum)
(values 0 number))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let (r n)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :ebx) number)
(:cmpw ,movitz:+movitz-fixnum-factor+
(:ebx (:offset movitz-bignum length)))
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:movl (:ebx (:offset movitz-bignum bigit0)) :eax)
(:xorl :edx :edx)
(:divl :ecx :eax :edx)
(:movl :eax :ecx)
(:shll ,movitz:+movitz-fixnum-shift+ :edx)
(:movl :edi :eax)
(:cld)
(:pushl :edx)
(:call-local-pf box-u32-ecx)
(:popl :ebx)
(:jmp 'done)
not-size1
(:declare-label-set restart-jumper (restart-truncation))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-truncation
(:movl (:esp) :ebp)
(:xorl :eax :eax)
(:compile-form (:result-mode :ebx) number)
(:movw (:ebx (:offset movitz-bignum length)) :ax)
(:addl 4 :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
New bignum into EAX
XXX breaks GC invariant !
(:compile-form (:result-mode :ebx) number)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:testb 3 :cl)
(:jnz '(:sub-program () (:int 63)))
(:movl :ecx :esi)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
divide-loop
(:load-lexical (:lexical-binding number) :ebx)
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax)
(:divl :ecx :eax :edx)
(:load-lexical (:lexical-binding r) :ebx)
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4)))
(:subl 4 :esi)
(:jnz 'divide-loop)
(:leal ((:edx ,movitz:+movitz-fixnum-factor+)) :edx)
(:cld)
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edx :ebx)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-more-shrinkage)
(:subw 4 (:eax (:offset movitz-bignum length)))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
(:cmpl ,(* 2 movitz:+movitz-fixnum-factor+) :ecx)
(:jne 'no-more-shrinkage)
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:eax (:offset movitz-bignum bigit0)))
(:jnc 'no-more-shrinkage)
(:movl (:eax (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
no-more-shrinkage
(:call-local-pf cons-commit-non-pointer)
fixnum-result
Exit atomically block .
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
done
(:movl 2 :ecx)
(:stc)))))
(do-it)))
((positive-bignum positive-bignum)
(cond
((= number divisor) (values 1 0))
((< number divisor) (values 0 number))
(t
#-movitz-reference-code
(let* ((divisor-length (integer-length divisor))
(guess-pos (- divisor-length 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((tmp (copy-bignum number))
(tmp2 (copy-bignum number))
(q (bignum-set-zerof (%make-bignum (ceiling (1+ (- (integer-length number)
divisor-length))
32))))
(r (copy-bignum number)))
((%bignum< r divisor)
(values (bignum-canonicalize q)
(bignum-canonicalize r)))
(let ((guess (bignum-shift-rightf
(bignum-truncatef (bignum-addf (bignum-set-zerof tmp)
r)
msb)
guess-pos)))
(if (%bignum-zerop guess)
(setf q (bignum-addf-fixnum q 1)
r (bignum-subf r divisor))
(setf q (bignum-addf q guess)
r (do ((i 0 (+ i 29)))
((>= i divisor-length) r)
(bignum-subf r (bignum-shift-leftf
(bignum-mulf (bignum-addf (bignum-set-zerof tmp2) guess)
(ldb (byte 29 i) divisor))
i))))))))
#+movitz-reference-code
(let* ((guess-pos (- (integer-length divisor) 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((shift (- guess-pos))
(q 0)
(r number))
((< r divisor)
(values q r))
(let ((guess (ash (truncate r msb) shift)))
(if (= 0 guess)
(setf q (1+ q)
r (- r divisor))
(setf q (+ q guess)
r (- r (* guess divisor))))))))))
(((integer * -1) (integer 0 *))
(multiple-value-bind (q r)
(truncate (- number) divisor)
(values (%negatef q number divisor)
(%negatef r number divisor))))
(((integer 0 *) (integer * -1))
(multiple-value-bind (q r)
(truncate number (- divisor))
(values (%negatef q number divisor)
r)))
(((integer * -1) (integer * -1))
(multiple-value-bind (q r)
(truncate (- number) (- divisor))
(values q (%negatef r number divisor))))
((rational rational)
(multiple-value-bind (q r)
(truncate (* (numerator number)
(denominator divisor))
(* (denominator number)
(numerator divisor)))
(values q (make-rational r (* (denominator number)
(denominator divisor))))))
))))
(defun / (number &rest denominators)
(numargs-case
(1 (x)
(if (not (typep x 'ratio))
(make-rational 1 x)
(make-rational (%ratio-denominator x)
(%ratio-numerator x))))
(2 (x y)
(multiple-value-bind (q r)
(truncate x y)
(cond
((= 0 r)
q)
(t (make-rational (* (numerator x) (denominator y))
(* (denominator x) (numerator y)))))))
(t (number &rest denominators)
(declare (dynamic-extent denominators))
(cond
((null denominators)
(make-rational 1 number))
((null (cdr denominators))
(multiple-value-bind (q r)
(truncate number (first denominators))
(if (= 0 r)
q
(make-rational number (first denominators)))))
(t (/ number (reduce '* denominators)))))))
(defun round (number &optional (divisor 1))
"Mathematical rounding."
(multiple-value-bind (quotient remainder)
(truncate number divisor)
(let ((rem2 (* 2 remainder)))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b11 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b10 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b01 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1- quotient) (- remainder)))))))))
(defun ceiling (number &optional (divisor 1))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (multiple-value-bind (q r)
(truncate (+ number divisor -1) divisor)
(values q (- r (1- divisor)))))
(t (error "Don't know."))))
(defun rem (dividend divisor)
(nth-value 1 (truncate dividend divisor)))
(defun mod (number divisor)
"Returns second result of FLOOR."
(let ((rem (rem number divisor)))
(if (and (not (zerop rem))
(if (minusp divisor)
(plusp number)
(minusp number)))
(+ rem divisor)
rem)))
(defun byte (size position)
(check-type size positive-fixnum)
(let ((position (check-the (unsigned-byte 20) position)))
(+ position (ash size 20))))
(defun byte-size (bytespec)
(ash bytespec -20))
(defun byte-position (bytespec)
(ldb (byte 20 0) bytespec))
(defun logbitp (index integer)
(check-type index positive-fixnum)
(macrolet
((do-it ()
`(etypecase integer
(fixnum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:addl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx :ebx)))
(positive-bignum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx (:ebx (:offset movitz-bignum bigit0))))))))
(do-it)))
(define-compiler-macro logbitp (&whole form &environment env index integer)
(if (not (movitz:movitz-constantp index env))
form
(let ((index (movitz:movitz-eval index env)))
(check-type index (integer 0 *))
(typecase index
((integer 0 31)
`(with-inline-assembly (:returns :boolean-cf=1)
(:compile-form (:result-mode :untagged-fixnum-ecx) ,integer)
(:btl ,index :ecx)))
(t form)))))
(defun logand (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:andl :ebx :eax)))
((positive-bignum positive-fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) y)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((positive-fixnum positive-bignum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) y)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) x)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((fixnum positive-bignum)
(let ((result (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result x)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum fixnum)
(let ((result (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result y)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(logand y x)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum x) y)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-and-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:andl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-and-loop)))))
((negative-bignum fixnum)
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :untagged-fixnum-ecx)
(:load-lexical (:lexical-binding y) :eax)
(:leal ((:ecx 4) -4) :ecx)
(:notl :ecx)
(:andl :ecx :eax)))
((negative-bignum positive-bignum)
(cond
((<= (%bignum-bigits y) (%bignum-bigits x))
(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding r) :eax)
(:load-lexical (:lexical-binding x) :ebx)
(:xorl :edx :edx)
(:movl #xffffffff :ecx)
loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:notl :ecx)
(:cmpl -1 :ecx)
(:je 'carry)
(:xorl :ecx :ecx)
carry
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:ja 'loop))))
(t (error "Logand not implemented."))))
)))
(do-it)))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
-1
(reduce #'logand integers)))))
(defun logandc1 (integer1 integer2)
(macrolet
((do-it ()
`(number-double-dispatch (integer1 integer2)
((t positive-fixnum)
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-form (:result-mode :eax) integer1)
(:call-global-pf unbox-u32)
(:shll ,movitz:+movitz-fixnum-shift+ :ecx)
(:compile-form (:result-mode :eax) integer2)
(:notl :ecx)
(:andl :ecx :eax)))
(((eql 0) t) integer2)
(((eql -1) t) 0)
((positive-fixnum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum integer2) integer1)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:notl :ecx)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum integer2) integer1)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-andc1-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-andc1-loop)))))))
(do-it)))
(defun logandc2 (integer1 integer2)
(logandc1 integer2 integer1))
(defun logior (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:orl :ebx :eax)))
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let ((r (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logior y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
or-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:orl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'or-loop))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logior integers)))))
(defun logxor (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:xorl :ebx :eax)))
(((eql 0) t) y)
((t (eql 0)) x)
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum y) x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum x) y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logxor y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1),(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
xor-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:xorl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'xor-loop)
))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logxor integers)))))
(defun lognot (integer)
(- -1 integer))
(defun ldb%byte (size position integer)
"This is LDB with explicit byte-size and position parameters."
(check-type size positive-fixnum)
(check-type position positive-fixnum)
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer position)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:ja '(:sub-program (outside-fixnum)
(:sbbl :ecx :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'mask-fixnum)))
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl ,(logxor #xffffffff movitz:+movitz-fixnum-zmask+) :eax)
mask-fixnum
(:compile-form (:result-mode :ecx) size)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:jna 'fixnum-result)
(:testl :eax :eax)
(:jns 'fixnum-done)
.. filling in 1 - bits since the integer is negative .
(:declare-label-set restart-jumper (restart-ones-expanded-bignum))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ones-expanded-bignum
(:movl (:esp) :ebp)
Calculate word - size from bytespec - size .
(:compile-form (:result-mode :ecx) size)
Add 31
Divide by 32
(:andl ,(- movitz:+movitz-fixnum-factor+) :ecx)
Add 1 for header .
:eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-non-pointer)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
add 1 for header .
:ecx)
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
Have fresh bignum in EAX , now fill it with ones .
fill-ones-loop
(:movl #xffffffff (:eax :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jne 'fill-ones-loop)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:movl :eax :ebx)
Compute MSB bigit mask in EDX
(:compile-form (:result-mode :ecx) size)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :edx :edx)
(:andl 31 :ecx)
(:jz 'fixnum-mask-ok)
(:addl 1 :edx)
(:shll :cl :edx)
fixnum-mask-ok
(:subl 1 :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
And EDX with the MSB bigit .
(:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:movl :edi :edx)
(:movl :edi :eax)
(:movl :ebx :eax)
(:jmp 'fixnum-done)
fixnum-result
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
generate fixnum mask in EDX
(:shll :cl :edx)
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:andl :edx :eax)
(:jmp 'fixnum-done)
fixnum-done
)))
(do-it)))
(positive-bignum
(cond
((= size 0) 0)
((<= size 32)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :eax) position)
(:sarl 5 :ecx)
(:andl -4 :ecx)
(:addl 4 :ecx)
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jae 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jc '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:std)
(:movl (:ebx :ecx (:offset movitz-bignum bigit0 -4))
:eax)
.. we must zero - extend rather than read top bigit .
(:movl (:ebx :ecx (:offset movitz-bignum bigit0))
Read top bigit into EDX
no-top-bigit
(:testl #xff00 (:ebx ,movitz:+other-type-offset+))
(:jnz '(:sub-program (negative-bignum)
We must negate the ..
(:break)
))
edx-eax-ok
EDX : EAX now holds the number that must be shifted and masked .
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
Shifted value into EAX
(:compile-form (:result-mode :ecx) size)
Generate a mask in EDX
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:testl 31 :ecx)
(:jz 'mask-ok-u32)
(:addl 1 :edx)
(:shll :cl :edx)
mask-ok-u32
(:subl 1 :edx)
(:andl :edx :eax)
(:movl :edi :eax)
(:movl :edi :edx)
(:cld)
(:cmpl ,(dpb movitz:+movitz-fixnum-factor+
(byte 16 16) (movitz:tag :bignum 0))
(:ebx ,movitz:+other-type-offset+))
(:jne 'cant-return-same)
(:cmpl :ecx (:ebx (:offset movitz-bignum bigit0)))
(:jne 'cant-return-same)
(:movl :ebx :eax)
(:jmp 'done-u32)
cant-return-same
(:call-local-pf box-u32-ecx)
done-u32
)))
(do-it)))
(t (macrolet
((do-it ()
`(let (new-size)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :ecx) position)
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jnc 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:compile-two-forms (:edx :ecx) position size)
keep size / fixnum in EAX .
(:addl :edx :ecx)
compute msb bigit index / fixnum in ecx
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:je '(:sub-program (equal-size-maybe-return-same)
Can only return same if ( zerop position ) .
(:jnz 'adjust-size)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'yes-return-same)
we know EDX=0 , now generate mask in EDX
(:addl 1 :edx)
(:shll :cl :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:cmpl :edx (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
yes-return-same
(:jmp 'ldb-done)))
(:jnc 'size-ok)
So , if ( zerop position ) , we can return the bignum as our result .
(:testl :edx :edx)
(:jz '(:sub-program ()
(:jmp 'ldb-done)))
adjust-size
The bytespec is ( partially ) outside source - integer , so we make the
(:movzxw (:ebx (:offset movitz-bignum length))
In case the new size is zero .
(:js '(:sub-program (should-not-happen)
(:break)))
New size was zero , so the result of ldb is zero .
New size into EAX .
size-ok
(:store-lexical (:lexical-binding new-size) :eax :type fixnum)
(:declare-label-set restart-ldb-jumper (restart-ldb))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-ldb-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ldb
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding new-size) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
( new ) Size is in EAX .
(:subl ,movitz:+movitz-fixnum-factor+ :eax)
(:andl ,(logxor #xffffffff
(mask-field (byte (+ 5 movitz:+movitz-fixnum-shift+) 0) -1))
:eax)
Divide ( size-1 ) by 32 to get number of bigits-1
Now add 1 for index->size , 1 for header , and 1 for tmp storage before shift .
(:addl ,(* 3 movitz:+movitz-fixnum-factor+) :eax)
(:pushl :eax)
(:call-local-pf cons-non-pointer)
(:popl :ecx)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:compile-form (:result-mode :ebx) integer)
(:xchgl :eax :ebx)
now : EAX = old integer , EBX = new result bignum
Edge case : When size(old)=size(new ) , the tail - tmp must be zero .
(:movzxw (:ebx (:offset movitz-bignum length))
Initialize tail - tmp to # xffffffff , meaning copy from source - integer .
(:movl #xffffffff (:ebx :ecx (:offset movitz-bignum bigit0)))
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jc '(:sub-program (result-too-big-shouldnt-happen)
(:int 4)))
(:jne 'tail-tmp-ok)
Sizes was equal , so set tail - tmp to zero .
(:movl 0 (:ebx :ecx (:offset movitz-bignum bigit0)))
tail-tmp-ok
(:std)
(:compile-form (:result-mode :ecx) position)
(:leal (:eax (:ecx 4) (:offset movitz-bignum bigit0))
Use EAX as primitive pointer into source
copy-integer
(:movl (:eax) :edx)
(:addl 4 :eax)
(:movl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jne 'copy-integer)
Copy one more than the length , namely the tmp at the end .
(:movl (:eax) :edx)
(:andl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
if ( zerop ( mod position 32 ) ) , no shift needed .
shift-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0 4))
Now shift bigit , with msbs from eax .
(:ebx :edx (:offset movitz-bignum bigit0)))
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'shift-loop)
shift-done
Now we must mask MSB bigit .
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl 5 :ecx)
ECX = index of ( conceptual ) MSB
(:cmpl :ecx :edx)
(:jbe 'mask-done)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'mask-done)
Generate mask in EAX
(:shll :cl :eax)
(:subl 1 :eax)
(:andl :eax (:ebx :edx (:offset movitz-bignum bigit0 -4)))
mask-done
safe EAX
(:cld)
Now we must zero - truncate the result bignum in EBX .
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
zero-truncate-loop
(:cmpl 0 (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:jne 'zero-truncate-done)
(:subl 4 :ecx)
(:jnz 'zero-truncate-loop)
Zero bigits means the entire result collapsed to zero .
(:xorl :eax :eax)
zero-truncate-done
If result size is 1 , the result might have ..
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:ebx (:offset movitz-bignum bigit0)))
(:ja 'complete-bignum-allocation)
(:movl (:ebx (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'return-fixnum)
complete-bignum-allocation
(:movw :cx (:ebx (:offset movitz-bignum length)))
(:movl :ebx :eax)
(:leal (:ecx ,movitz:+movitz-fixnum-factor+)
:ecx)
(:call-local-pf cons-commit-non-pointer)
return-fixnum
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
ldb-done))))
(do-it)))))))
(defun ldb (bytespec integer)
(ldb%byte (byte-size bytespec) (byte-position bytespec) integer))
(defun ldb-test (bytespec integer)
(case (byte-size bytespec)
(0 nil)
(1 (logbitp (byte-position bytespec) integer))
(t (/= 0 (ldb bytespec integer)))))
(defun logtest (integer-1 integer-2)
"=> generalized-boolean"
(not (= 0 (logand integer-1 integer-2))))
(defun logcount (integer)
(etypecase integer
(positive-fixnum
(with-inline-assembly (:returns :untagged-fixnum-ecx :type (integer 0 29))
(:load-lexical (:lexical-binding integer) :eax)
(:xorl :ecx :ecx)
count-loop
(:shll 1 :eax)
(:adcl 0 :ecx)
(:testl :eax :eax)
(:jnz 'count-loop)))
(positive-bignum
(bignum-logcount integer))))
(defun dpb (newbyte bytespec integer)
(logior (if (= 0 newbyte)
0
(mask-field bytespec (ash newbyte (byte-position bytespec))))
(if (= 0 integer)
0
(logandc2 integer (mask-field bytespec -1)))))
(defun mask-field (bytespec integer)
(ash (ldb bytespec integer) (byte-position bytespec)))
(defun deposit-field (newbyte bytespec integer)
(logior (mask-field bytespec newbyte)
(logandc2 integer (mask-field bytespec -1))))
(defun plus-if (x y)
(if (integerp x) (+ x y) x))
(defun minus-if (x y)
(if (integerp x) (- x y) x))
(defun gcd (&rest integers)
(numargs-case
(1 (u) u)
(2 (u v)
Code borrowed from CMUCL .
(cond
((= 0 u) v)
((= 0 v) u)
(t (do ((k 0 (1+ k))
(u (abs u) (truncate u 2))
(v (abs v) (truncate v 2)))
((or (oddp u) (oddp v))
(do ((temp (if (oddp u)
(- v)
(truncate u 2))
(truncate temp 2)))
(nil)
(when (oddp temp)
(if (plusp temp)
(setq u temp)
(setq v (- temp)))
(setq temp (- u v))
(when (zerop temp)
(return (ash u k))))))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(do ((gcd (car integers)
(gcd gcd (car rest)))
(rest (cdr integers) (cdr rest)))
((null rest) gcd)))))
(defun lcm (&rest numbers)
"Returns the least common multiple of one or more integers. LCM of no
arguments is defined to be 1."
(numargs-case
(1 (n)
(abs n))
(2 (n m)
(abs (* (truncate (max n m) (gcd n m)) (min n m))))
(t (&rest numbers)
(declare (dynamic-extent numbers))
(reduce #'lcm numbers
:initial-value 1))))
(defun floor (n &optional (divisor 1))
"This is floor written in terms of truncate."
(numargs-case
(1 (n)
(if (not (typep n 'ratio))
(values n 0)
(multiple-value-bind (r q)
(floor (%ratio-numerator n) (%ratio-denominator n))
(values r (make-rational q (%ratio-denominator n))))))
(2 (n divisor)
(multiple-value-bind (q r)
(truncate n divisor)
(cond
((= 0 r)
(values q r))
((or (and (minusp r) (plusp divisor))
(and (plusp r) (minusp divisor)))
(values (1- q) (+ r divisor)))
(t (values q r)))))
(t (n &optional (divisor 1))
(floor n divisor))))
(defun isqrt (natural)
"=> natural-root"
(check-type natural (integer 0 *))
(if (= 0 natural)
0
(let ((r 1))
(do ((next-r (truncate (+ r (truncate natural r)) 2)
(truncate (+ r (truncate natural r)) 2)))
((typep (- next-r r) '(integer 0 1))
(let ((r+1 (1+ r)))
(if (<= (* r+1 r+1) natural)
r+1
r)))
(setf r next-r)))))
(defun rootn (x root)
(check-type root (integer 2 *))
(let ((root-1 (1- root))
(r (/ x root)))
(dotimes (i 10 r)
(let ((m (min (integer-length (numerator r))
(integer-length (denominator r)))))
(when (>= m 32)
(setf r (/ (ash (numerator r) (- 24 m))
(ash (denominator r) (- 24 m))))))
#+ignore (format t "~&~D: ~X~%~D: ~F [~D ~D]~%" i r i r
(integer-length (numerator r))
(integer-length (denominator r)))
(setf r (/ (+ (* root-1 r)
(/ x (expt r root-1)))
root)))))
(defun sqrt (x)
(rootn x 2))
(defun expt (base-number power-number)
"Take base-number to the power-number."
(etypecase power-number
(positive-fixnum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)
(declare (index i))))
(positive-bignum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)))
((number * -1)
(/ (expt base-number (- power-number))))
(ratio
(expt (rootn base-number (denominator power-number))
(numerator power-number)))))
(defun floatp (x)
(typep x 'real))
(defun realpart (number)
number)
(defun imagpart (number)
(declare (ignore number))
0)
(defun rational (number)
number)
(defun realp (x)
(typep x 'real))
(defconstant boole-clr 'boole-clr)
(defconstant boole-1 'boole-1)
(defconstant boole-2 'boole-2)
(defconstant boole-c1 'boole-c1)
(defconstant boole-c2 'boole-c2)
(defconstant boole-eqv 'logeqv)
(defconstant boole-and 'logand)
(defconstant boole-nand 'lognand)
(defconstant boole-andc1 'logandc1)
(defconstant boole-andc2 'logandc2)
(defconstant boole-ior 'logior)
(defconstant boole-nor 'lognor)
(defconstant boole-orc1 'logorc1)
(defconstant boole-orc2 'logorc2)
(defconstant boole-xor 'logxor)
(defconstant boole-set 'boole-set)
(defun boole (op integer-1 integer-2)
"=> result-integer"
(funcall op integer-1 integer-2))
(defun boole-clr (integer-1 integer-2)
(declare (ignore integer-1 integer-2))
0)
(defun boole-set (integer-1 integer-2)
(declare (ignore integer-1 integer-2))
-1)
(defun boole-1 (integer-1 integer-2)
(declare (ignore integer-2))
integer-1)
(defun boole-2 (integer-1 integer-2)
(declare (ignore integer-1))
integer-2)
(defun boole-c1 (integer-1 integer-2)
(declare (ignore integer-2))
(lognot integer-1))
(defun boole-c2 (integer-1 integer-2)
(declare (ignore integer-1))
(lognot integer-2))
(defun logeqv (integer-1 integer-2)
(lognot (logxor integer-1 integer-2)))
(defun lognand (integer-1 integer-2)
(lognot (logand integer-1 integer-2)))
(defun lognor (integer-1 integer-2)
(lognot (logior integer-1 integer-2)))
(defun logorc1 (integer-1 integer-2)
(logior (lognot integer-1)
integer-2))
(defun logorc2 (integer-1 integer-2)
(logior integer-1
(lognot integer-2)))
|
0584e662453c3fb2f104176dad5efa10d3af3774ae95c5b4eefd3c757b071751 | Reisen/pixel | UpdatePasswordUser.hs | module API.User.Routes.UpdatePasswordUser
( postUpdatePassword
) where
import Protolude hiding ( hash )
import Servant
import Data.UUID ( fromText )
import Crypto.Random ( getRandomBytes )
import Crypto.Hash ( Digest, SHA3_224(..), hash )
import MonadPixel ( Pixel )
import Pixel ( Error(..), CookieToken(..) )
import Pixel.Model.Token ( _tokenText )
import Pixel.API.UpdatePasswordUser ( Request(..) )
import Pixel.Operations ( UpdatePasswordDetails(..)
, updateUserPassword
)
--------------------------------------------------------------------------------
postUpdatePassword
:: Maybe CookieToken
-> Request
-> Pixel NoContent
postUpdatePassword Nothing _ = throwError UnknownError
postUpdatePassword (Just (CookieToken token)) Request{..} = do
hashSalt :: ByteString <- liftIO $ getRandomBytes 16
let mayUUID = fromText . _tokenText $ token
case mayUUID of
Just uuid -> pure NoContent <* updateUserPassword UpdatePasswordDetails
{ _uuid = uuid
, _currentPassword = _currentPassword
, _newPassword = _newPassword
, _salt = show (hash hashSalt :: Digest SHA3_224)
}
Nothing -> pure NoContent | null | https://raw.githubusercontent.com/Reisen/pixel/9096cc2c5b909049cdca6d14856ffc1fc99d81b5/src/app/API/User/Routes/UpdatePasswordUser.hs | haskell | ------------------------------------------------------------------------------
| module API.User.Routes.UpdatePasswordUser
( postUpdatePassword
) where
import Protolude hiding ( hash )
import Servant
import Data.UUID ( fromText )
import Crypto.Random ( getRandomBytes )
import Crypto.Hash ( Digest, SHA3_224(..), hash )
import MonadPixel ( Pixel )
import Pixel ( Error(..), CookieToken(..) )
import Pixel.Model.Token ( _tokenText )
import Pixel.API.UpdatePasswordUser ( Request(..) )
import Pixel.Operations ( UpdatePasswordDetails(..)
, updateUserPassword
)
postUpdatePassword
:: Maybe CookieToken
-> Request
-> Pixel NoContent
postUpdatePassword Nothing _ = throwError UnknownError
postUpdatePassword (Just (CookieToken token)) Request{..} = do
hashSalt :: ByteString <- liftIO $ getRandomBytes 16
let mayUUID = fromText . _tokenText $ token
case mayUUID of
Just uuid -> pure NoContent <* updateUserPassword UpdatePasswordDetails
{ _uuid = uuid
, _currentPassword = _currentPassword
, _newPassword = _newPassword
, _salt = show (hash hashSalt :: Digest SHA3_224)
}
Nothing -> pure NoContent |
82331cd673091d5ef072d810a16766687c9cd1bb71831f16417c56d354b13fca | marigold-dev/mankavar | main.ml | let () =
let open Ml_main.TBytes.Raw in
let ptr = malloc 50 in
Format.printf "Raw ptr as int:\t%d@;%!" ptr ;
Format.printf "Value int64:\t%Ld@;%!" @@ get_int64 ptr ;
Format.printf "Value int:\t%d@;%!" @@ get_int ptr ;
free ptr ;
()
| null | https://raw.githubusercontent.com/marigold-dev/mankavar/8afac59f0045d096b8eac3184fda805d8177723f/experiments/externals/test/main.ml | ocaml | let () =
let open Ml_main.TBytes.Raw in
let ptr = malloc 50 in
Format.printf "Raw ptr as int:\t%d@;%!" ptr ;
Format.printf "Value int64:\t%Ld@;%!" @@ get_int64 ptr ;
Format.printf "Value int:\t%d@;%!" @@ get_int ptr ;
free ptr ;
()
|
|
8154850944cf25a9814a892b8ad05ebc57d1061986150395da3cda8b88e4af3e | bob-cd/bob | main.clj | ; Copyright 2018- Rahul De
;
Use of this source code is governed by an MIT - style
; license that can be found in the LICENSE file or at
; .
(ns apiserver.main
(:require
[apiserver.system :as system]
[clojure.repl :as repl]
[clojure.tools.logging :as log])
(:gen-class))
(defn shutdown!
[& _]
(log/info "Received SIGINT, Shutting down ...")
(system/stop)
(shutdown-agents)
(log/info "Shutdown complete.")
(System/exit 0))
(defn -main
[& _]
(repl/set-break-handler! shutdown!)
(system/start))
| null | https://raw.githubusercontent.com/bob-cd/bob/72ee2dd1c58fbbeff2c63333732eefa260e5d0cf/apiserver/src/apiserver/main.clj | clojure | Copyright 2018- Rahul De
license that can be found in the LICENSE file or at
. | Use of this source code is governed by an MIT - style
(ns apiserver.main
(:require
[apiserver.system :as system]
[clojure.repl :as repl]
[clojure.tools.logging :as log])
(:gen-class))
(defn shutdown!
[& _]
(log/info "Received SIGINT, Shutting down ...")
(system/stop)
(shutdown-agents)
(log/info "Shutdown complete.")
(System/exit 0))
(defn -main
[& _]
(repl/set-break-handler! shutdown!)
(system/start))
|
e1d07ee148ded5a13e0cb929bcb6e09c72f4108e49abb850ba31a2048d0026e4 | tweag/servant-oauth2 | Hacks.hs | |
A collection of hacky functions needed to work around the fact that
' ' is presently defined in terms of , and , really , we
want something that is defined for Servant .
A collection of hacky functions needed to work around the fact that
'wai-middleware-auth' is presently defined in terms of Wai, and, really, we
want something that is defined for Servant.
-}
# language NamedFieldPuns #
# language TupleSections #
# language ViewPatterns #
module Servant.OAuth2.Hacks where
import "base" Data.Maybe (fromMaybe)
import "text" Data.Text (Text, intercalate)
import "text" Data.Text.Encoding (decodeUtf8, encodeUtf8)
import "hoauth2" Network.OAuth.OAuth2 qualified as OA2
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2
( OAuth2 (..)
)
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2 qualified as Wai
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2.Github
( Github (..)
)
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2.Google
( Google (..)
)
import Servant.OAuth2
import "uri-bytestring" URI.ByteString qualified as U
-- | For some settings specialised to 'Github', return the login url.
--
@since 0.1.0.0
getGithubLoginUrl :: Text -> OAuth2Settings m Github a -> Text
getGithubLoginUrl callbackUrl (provider -> Github { githubOAuth2 })
= getRedirectUrl callbackUrl githubOAuth2 (oa2Scope githubOAuth2)
| For some settings specialised to ' Google ' , return the login url .
--
@since 0.1.0.0
getGoogleLoginUrl :: Text -> OAuth2Settings m Google a -> Text
getGoogleLoginUrl callbackUrl (provider -> Google { googleOAuth2 })
= getRedirectUrl callbackUrl googleOAuth2 (oa2Scope googleOAuth2)
-- | An extremely unfortunate way of getting the redirect URL; stolen from
' Network . Wai . Auth . Internal ' .
--
@since 0.1.0.0
getRedirectUrl :: Text -> Wai.OAuth2 -> Maybe [Text] -> Text
getRedirectUrl callbackUrl waiOa2 oa2Scope = decodeUtf8 redirectUrl
where
scope = encodeUtf8 . intercalate " " <$> oa2Scope
redirectUrl =
getRedirectURI $
OA2.appendQueryParams
(maybe [] ((: []) . ("scope",)) scope)
(OA2.authorizationUrl oa2)
oa2 = fromMaybe (error "Couldn't construct the OAuth2 record.") fromInteralOAuth2
getRedirectURI = U.serializeURIRef'
parseAbsoluteURI urlTxt = do
case U.parseURI U.strictURIParserOptions (encodeUtf8 urlTxt) of
Left _ -> Nothing
Right url -> pure url
fromInteralOAuth2 = do
authEndpointURI <- parseAbsoluteURI $ Wai.oa2AuthorizeEndpoint waiOa2
callbackURI <- parseAbsoluteURI callbackUrl
pure $
OA2.OAuth2
{ OA2.oauth2ClientId = Wai.oa2ClientId waiOa2
, OA2.oauth2ClientSecret = error "Client secret not needed."
, OA2.oauth2AuthorizeEndpoint = authEndpointURI
, OA2.oauth2TokenEndpoint = error "No token endpoint"
, OA2.oauth2RedirectUri = callbackURI
}
| null | https://raw.githubusercontent.com/tweag/servant-oauth2/b8a6e9189986167ef9f4ada1f93e673e9fdd305b/src/Servant/OAuth2/Hacks.hs | haskell | | For some settings specialised to 'Github', return the login url.
| An extremely unfortunate way of getting the redirect URL; stolen from
| |
A collection of hacky functions needed to work around the fact that
' ' is presently defined in terms of , and , really , we
want something that is defined for Servant .
A collection of hacky functions needed to work around the fact that
'wai-middleware-auth' is presently defined in terms of Wai, and, really, we
want something that is defined for Servant.
-}
# language NamedFieldPuns #
# language TupleSections #
# language ViewPatterns #
module Servant.OAuth2.Hacks where
import "base" Data.Maybe (fromMaybe)
import "text" Data.Text (Text, intercalate)
import "text" Data.Text.Encoding (decodeUtf8, encodeUtf8)
import "hoauth2" Network.OAuth.OAuth2 qualified as OA2
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2
( OAuth2 (..)
)
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2 qualified as Wai
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2.Github
( Github (..)
)
import "wai-middleware-auth" Network.Wai.Middleware.Auth.OAuth2.Google
( Google (..)
)
import Servant.OAuth2
import "uri-bytestring" URI.ByteString qualified as U
@since 0.1.0.0
getGithubLoginUrl :: Text -> OAuth2Settings m Github a -> Text
getGithubLoginUrl callbackUrl (provider -> Github { githubOAuth2 })
= getRedirectUrl callbackUrl githubOAuth2 (oa2Scope githubOAuth2)
| For some settings specialised to ' Google ' , return the login url .
@since 0.1.0.0
getGoogleLoginUrl :: Text -> OAuth2Settings m Google a -> Text
getGoogleLoginUrl callbackUrl (provider -> Google { googleOAuth2 })
= getRedirectUrl callbackUrl googleOAuth2 (oa2Scope googleOAuth2)
' Network . Wai . Auth . Internal ' .
@since 0.1.0.0
getRedirectUrl :: Text -> Wai.OAuth2 -> Maybe [Text] -> Text
getRedirectUrl callbackUrl waiOa2 oa2Scope = decodeUtf8 redirectUrl
where
scope = encodeUtf8 . intercalate " " <$> oa2Scope
redirectUrl =
getRedirectURI $
OA2.appendQueryParams
(maybe [] ((: []) . ("scope",)) scope)
(OA2.authorizationUrl oa2)
oa2 = fromMaybe (error "Couldn't construct the OAuth2 record.") fromInteralOAuth2
getRedirectURI = U.serializeURIRef'
parseAbsoluteURI urlTxt = do
case U.parseURI U.strictURIParserOptions (encodeUtf8 urlTxt) of
Left _ -> Nothing
Right url -> pure url
fromInteralOAuth2 = do
authEndpointURI <- parseAbsoluteURI $ Wai.oa2AuthorizeEndpoint waiOa2
callbackURI <- parseAbsoluteURI callbackUrl
pure $
OA2.OAuth2
{ OA2.oauth2ClientId = Wai.oa2ClientId waiOa2
, OA2.oauth2ClientSecret = error "Client secret not needed."
, OA2.oauth2AuthorizeEndpoint = authEndpointURI
, OA2.oauth2TokenEndpoint = error "No token endpoint"
, OA2.oauth2RedirectUri = callbackURI
}
|
08b11922f849bf55834acabb28c668061cdac309728bcfcc95b55297dbaad9ea | alekcz/pcp | includes_test.clj | (ns pcp.includes-test
(:require [clojure.test :refer [deftest is testing]]
[pcp.includes :as includes]))
(deftest extract-namespace-test
(testing "Test extracting namespaces"
(let [result (includes/extract-namespace 'pcp.includes)
ans {'includes #'pcp.includes/includes, 'extract-namespace #'pcp.includes/extract-namespace}]
(is (= ans result))))) | null | https://raw.githubusercontent.com/alekcz/pcp/400844c1f13e3cc51ee6db67d3e2d12e0e776b8f/test/pcp/includes_test.clj | clojure | (ns pcp.includes-test
(:require [clojure.test :refer [deftest is testing]]
[pcp.includes :as includes]))
(deftest extract-namespace-test
(testing "Test extracting namespaces"
(let [result (includes/extract-namespace 'pcp.includes)
ans {'includes #'pcp.includes/includes, 'extract-namespace #'pcp.includes/extract-namespace}]
(is (= ans result))))) |
|
0a1fa367a8402d74f2804d201929aaad6e5ab7a2f33e4da6f1662ec51e6bbf10 | c4-project/c4f | flow_for.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
let prefix_name (rest : Common.Id.t) : Common.Id.t =
(* Shared with Flow_while. *)
Common.Id.("loop" @: rest)
let is_int : Fuzz.Var.Record.t -> bool =
TODO(@MattWindsor91 ): unify with the various ' has_variables_with ' env
stuff , somehow ?
stuff, somehow? *)
Fir.Type.Prim.eq ~to_:Int
Accessor.(
Fuzz.Var.Record.Access.type_of @> Fir.Type.Access.basic_type
@> Fir.Type.Basic.Access.prim)
let kv_var_preds = [Fuzz.Var.Record.has_known_value; is_int]
let kv_live_path_filter_static : Fuzz.Path_filter.t =
Fuzz.Path_filter.(live_loop_surround + forbid_flag In_atomic)
let kv_live_path_filter ({vars; _} : Fuzz.State.t) : Fuzz.Path_filter.t =
Fuzz.Path_filter.(
(* These may induce atomic loads, and so can't be in atomic blocks. *)
in_thread_with_variables ~predicates:kv_var_preds vars
+ kv_live_path_filter_static)
let kv_available (kind : Fuzz.Path_kind.t) : Fuzz.Availability.t =
TODO(@MattWindsor91 ): is the has - variables redundant here ?
Fuzz.Availability.(
has_variables ~predicates:kv_var_preds
+ M.(
lift (fun {state; _} -> kv_live_path_filter state)
>>= is_filter_constructible ~kind))
module Payload = struct
module Counter = struct
type t = {var: Common.Litmus_id.t; ty: Fir.Type.t} [@@deriving sexp]
let can_make : Fuzz.Availability.t =
Fuzz.Availability.in_var_cap ~after_adding:1
let lc_expr ({var; ty} : t) : Fir.Expression.t =
let name = Common.Litmus_id.variable_name var in
let lc_tvar = Common.C_named.make ty ~name in
Fir.Expression.lvalue (Fir.Lvalue.on_value_of_typed_id lc_tvar)
let declare_and_register ({var; ty} : t) (test : Fuzz.Subject.Test.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Fuzz.State.Monad.Let_syntax.(
let value = Fir.Constant.zero_of_type ty in
let init = Fir.{Initialiser.ty; value} in
let%bind test' =
Fuzz.State.Monad.register_and_declare_var var init test
in
(* Note that this sets the known value of the loop counter to 0, so
we have to erase it again; otherwise, the for loop's activity on
the loop counter would be ignored by the rest of the fuzzer and
lead to semantic violations. *)
let%bind () = Fuzz.State.Monad.erase_var_value var in
let%map () = Fuzz.State.Monad.add_dependency var in
test')
let counter_type (prim : Fir.Type.Prim.t) : Fir.Type.t =
Fir.Type.(
make
(Basic.make prim ~is_atomic:false)
~is_pointer:false ~is_volatile:false)
let gen (scope : Common.Scope.t) (prim_type : Fir.Type.Prim.t) :
t Fuzz.Payload_gen.t =
Fuzz.Payload_gen.(
let+ lc_var = fresh_var scope in
{var= lc_var; ty= counter_type prim_type})
end
module Simple = struct
type t = {lc: Counter.t; up_to: Fir.Constant.t} [@@deriving sexp, fields]
let src_exprs (x : t) : Fir.Expression.t list =
[ Fir.Expression.constant x.up_to
; (* The loop counter is effectively being read from as well as written
to each iteration. *)
Counter.lc_expr x.lc ]
module type S_action =
Fuzz.Action_types.S with type Payload.t = t Fuzz.Payload_impl.Pathed.t
end
module Kv = struct
type t =
{lc: Counter.t; kv_val: Fir.Constant.t; kv_expr: Fir.Expression.t}
[@@deriving sexp, fields]
module type S_action =
Fuzz.Action_types.S with type Payload.t = t Fuzz.Payload_impl.Pathed.t
let src_exprs (x : t) : Fir.Expression.t list =
[ x.kv_expr
; (* The loop counter is effectively being read from as well as written
to each iteration. *)
Counter.lc_expr x.lc ]
let direction (i : Fir.Flow_block.For.Simple.Inclusivity.t)
({kv_val; _} : t) : Fir.Flow_block.For.Simple.Direction.t =
(* Try to avoid overflows by only going up if we're negative. *)
match Fir.Constant.as_int kv_val with
| Ok x when x < 0 -> Up i
| _ -> Down i
let control (i : Fir.Flow_block.For.Simple.Inclusivity.t) (payload : t) :
C4f_fir.Flow_block.For.Simple.t =
{ lvalue=
Accessor.construct Fir.Lvalue.variable
(Common.Litmus_id.variable_name payload.lc.var)
; direction= direction i payload
; init_value= Fir.Expression.constant payload.kv_val
; cmp_value= payload.kv_expr }
let gen_lc (scope : Common.Scope.t)
(kv_var : Fir.Env.Record.t Common.C_named.t) :
Counter.t Fuzz.Payload_gen.t =
let prim =
Fir.(
kv_var.@(Common.C_named.value @> Env.Record.type_of
@> Type.Access.basic_type @> Type.Basic.Access.prim))
in
Counter.gen scope prim
let access_of_var (vrec : Fir.Env.Record.t Common.C_named.t) :
Fir.Expression.t Fuzz.Payload_gen.t =
let var =
Common.C_named.map_right
~f:(Accessor_base.get Fir.Env.Record.type_of)
vrec
in
let ty = var.@(Common.C_named.value) in
TODO(@MattWindsor91 ): is this duplicating something ?
Fuzz.Payload_gen.(
if Fir.Type.is_atomic ty then
let+ mo = lift_quickcheck Fir.Mem_order.gen_load in
Fir.Expression.atomic_load
(Fir.Atomic_load.make
~src:(Fir.Address.on_address_of_typed_id var)
~mo )
else
return
(Fir.Expression.lvalue (Fir.Lvalue.on_value_of_typed_id var)))
let known_value_val (vrec : Fir.Env.Record.t Common.C_named.t) :
Fir.Constant.t Fuzz.Payload_gen.t =
vrec.@?(Common.C_named.value @> Fir.Env.Record.known_value)
|> Result.of_option
~error:(Error.of_string "chosen value should have a known value")
|> Fuzz.Payload_gen.Inner.return
let known_value_var (scope : Common.Scope.t) :
Fir.Env.Record.t Common.C_named.t Fuzz.Payload_gen.t =
TODO(@MattWindsor91 ): this shares a lot of DNA with atomic_store
redundant .
redundant. *)
Fuzz.Payload_gen.(
let* vs = vars in
let env =
Fuzz.Var.Map.env_satisfying_all ~scope vs ~predicates:kv_var_preds
in
lift_quickcheck (Fir.Env.gen_random_var_with_record env))
let gen (where : Fuzz.Path.With_meta.t) : t Fuzz.Payload_gen.t =
Fuzz.Payload_gen.(
let scope = Common.Scope.Local (Fuzz.Path.tid where.path) in
let* kv_var = known_value_var scope in
let* lc = gen_lc scope kv_var in
let* kv_val = known_value_val kv_var in
let+ kv_expr = access_of_var kv_var in
{lc; kv_val; kv_expr})
end
end
(* 'Payload' gets shadowed a lot later on. *)
open struct
module Pd = Payload
end
module Insert = struct
let prefix_name (x : Common.Id.t) : Common.Id.t =
prefix_name Common.Id.("insert" @: "for" @: x)
module Kv_never : Payload.Kv.S_action = struct
TODO(@MattWindsor91 ): maybe , if we make the loop counter always store
the KV , we can have that the loop counter persists that KV and can be
reliable used as such .
the KV, we can have that the loop counter persists that KV and can be
reliable used as such. *)
let name = prefix_name Common.Id.("kv-never" @: empty)
let readme : string Lazy.t =
lazy
{| Introduces a loop that initialises its
(fresh) counter to the known value of an existing variable and
compares it in such a way as to be dead-code. |}
let available : Fuzz.Availability.t =
Fuzz.Availability.(Pd.Counter.can_make + kv_available Insert)
let path_filter = kv_live_path_filter
module Payload = struct
type t = Payload.Kv.t Fuzz.Payload_impl.Pathed.t [@@deriving sexp]
let gen =
Fuzz.Payload_impl.Pathed.gen Insert path_filter Payload.Kv.gen
end
let recommendations (_ : Payload.t) : Common.Id.t list =
(* No point introducing dead-code actions if we're introducing dead
code. *)
[]
let make_for (payload : Pd.Kv.t) : Fuzz.Subject.Statement.t =
(* Comparing a var against its known value using < or >. *)
let control = Pd.Kv.control Exclusive payload in
let body = Fuzz.Subject.Block.make_dead_code () in
Fir.(
Accessor.construct Statement.flow
(Flow_block.for_loop_simple ~control body))
TODO(@MattWindsor91 ): unify this with things ?
let run (test : Fuzz.Subject.Test.t)
~(payload : Pd.Kv.t Fuzz.Payload_impl.Pathed.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Fuzz.State.Monad.(
Let_syntax.(
let p = payload.payload in
let%bind test' = Pd.Counter.declare_and_register p.lc test in
let%bind () =
add_expression_dependencies p.kv_expr
~scope:(Local (Fuzz.Path.tid payload.where.path))
in
Fuzz.Payload_impl.Pathed.insert payload
~filter:kv_live_path_filter_static ~test:test' ~f:make_for))
end
end
module Surround = struct
let prefix_name (x : Common.Id.t) : Common.Id.t =
prefix_name Common.Id.("surround" @: "for" @: x)
module Simple : Payload.Simple.S_action = Fuzz.Action.Make_surround (struct
let name = prefix_name Common.Id.("simple" @: empty)
let surround_with : string = "for-loops"
let readme_suffix : string =
{| The for loop initialises its (fresh) counter to zero, then counts
upwards to a random, small, constant value. This action does not
surround non-generated or loop-unsafe statements. |}
let path_filter (_ : Fuzz.State.t) =
(* The restriction on not being in an execute-multiple block isn't for
soundness, it's to prevent the fuzzer from deeply nesting multiple
loops, which can quickly lead to overlong run times. *)
Fuzz.Path_filter.(
live_loop_surround
+ Fuzz.Path_filter.forbid_flag In_execute_multi
+ require_end_check (Stm_no_meta_restriction Once_only))
let available : Fuzz.Availability.t =
Fuzz.Availability.(
Pd.Counter.can_make
+ M.(
lift_state path_filter
>>= is_filter_constructible ~kind:Transform_list))
module Payload = struct
include Payload.Simple
let gen (where : Fuzz.Path.With_meta.t) :
Payload.Simple.t Fuzz.Payload_gen.t =
let scope = Common.Scope.Local (Fuzz.Path.tid where.path) in
Fuzz.Payload_gen.(
let* lc_var = fresh_var scope in
let lc : Pd.Counter.t = {var= lc_var; ty= Fir.Type.int ()} in
let+ up_to =
lift_quickcheck
Base_quickcheck.Generator.small_strictly_positive_int
in
{Payload.Simple.lc; up_to= Int up_to})
end
let recommendations (_ : Payload.t Fuzz.Payload_impl.Pathed.t) :
Common.Id.t list =
[Flow_dead.Insert.Early_out_loop_end.name]
let run_pre (test : Fuzz.Subject.Test.t) ~(payload : Payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Pd.Counter.declare_and_register payload.lc test
let control (payload : Payload.t) : C4f_fir.Flow_block.For.Simple.t =
{ Fir.Flow_block.For.Simple.lvalue=
Accessor.construct Fir.Lvalue.variable
(Common.Litmus_id.variable_name payload.lc.var)
; direction= Up Inclusive
; init_value= Fir.Expression.int_lit 0
; cmp_value= Fir.Expression.constant payload.up_to }
let wrap (statements : Fuzz.Subject.Statement.t list)
~(payload : Payload.t) : Fuzz.Subject.Statement.t =
let control = control payload in
let body = Fuzz.Subject.Block.make_generated ~statements () in
Fir.(
Accessor.construct Statement.flow
(Flow_block.for_loop_simple body ~control))
end)
module Kv_once : Payload.Kv.S_action = Fuzz.Action.Make_surround (struct
let name = prefix_name Common.Id.("kv-once" @: empty)
let surround_with : string = "for-loops"
let readme_suffix : string =
{| The for loop initialises its
(fresh) counter to the known value of an existing variable and
compares it in such a way as to execute only once. |}
let path_filter = kv_live_path_filter
let available : Fuzz.Availability.t =
Fuzz.Availability.(Pd.Counter.can_make + kv_available Transform_list)
module Payload = Payload.Kv
let recommendations (_ : Payload.t Fuzz.Payload_impl.Pathed.t) :
Common.Id.t list =
[Flow_dead.Insert.Early_out_loop_end.name]
let run_pre (test : Fuzz.Subject.Test.t) ~(payload : Payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Pd.Counter.declare_and_register payload.lc test
let wrap (statements : Fuzz.Subject.Statement.t list)
~(payload : Payload.t) : Fuzz.Subject.Statement.t =
let control = Pd.Kv.control Inclusive payload in
let body = Fuzz.Subject.Block.make_generated ~statements () in
Fir.(
Accessor.construct Statement.flow
(Flow_block.for_loop_simple ~control body))
end)
module Dead :
Fuzz.Action_types.S
with type Payload.t = Fir.Flow_block.For.t Fuzz.Payload_impl.Pathed.t =
Fuzz.Action.Make_surround (struct
let name = prefix_name Common.Id.("dead" @: empty)
let surround_with : string = "for-loops"
let readme_suffix : string =
{| This action introduces arbitrary, occasionally nonsensical for loops
into dead code. |}
let path_filter (_ : Fuzz.State.t) : Fuzz.Path_filter.t =
(* We make sure to handle the case where we have no variables available
to us in the generator, so the path filter doesn't have to. *)
Fuzz.Path_filter.require_flag In_dead_code
let available : Fuzz.Availability.t =
Fuzz.Availability.(
Pd.Counter.can_make
+ M.(
lift_state path_filter
>>= is_filter_constructible ~kind:Transform_list))
module Payload = struct
type t = Fir.Flow_block.For.t [@@deriving sexp]
let src_exprs x = x.@*(Fir.Flow_block.For.exprs)
let gen_cmp (env : Fir.Env.t) : Fir.Expression.t Q.Generator.t =
let module CInt = Fir_gen.Expr.Int_values (struct
let env = env
end) in
let module CBool = Fir_gen.Expr.Bool_values (struct
let env = env
end) in
Q.Generator.union
[CInt.quickcheck_generator; CBool.quickcheck_generator]
let gen_assign (env : Fir.Env.t) : Fir.Assign.t option Q.Generator.t =
Option.value_map
(Fir_gen.Assign.any ~src:env ~dst:env)
~default:(Q.Generator.return None) ~f:Q.Generator.option
let gen' (env : Fir.Env.t) : t Q.Generator.t =
Q.Generator.(
Let_syntax.(
let%map init = gen_assign env
and cmp = option (gen_cmp env)
and update = gen_assign env in
Fir.Flow_block.For.make ?init ?cmp ?update ()))
let gen (path : Fuzz.Path.With_meta.t) : t Fuzz.Payload_gen.t =
Fuzz.(
Payload_gen.(
let* env = env_at_path path in
lift_quickcheck (gen' env)))
end
let recommendations (_ : Payload.t Fuzz.Payload_impl.Pathed.t) :
Common.Id.t list =
(* No need to recommend any dead-code introduction actions; this action
already introduces dead code! *)
[]
let run_pre (test : Fuzz.Subject.Test.t) ~(payload : Payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
(* No need to do housekeeping if we're in dead code. *)
ignore payload ;
Fuzz.State.Monad.return test
let wrap (statements : Fuzz.Subject.Statement.t list)
~(payload : Payload.t) : Fuzz.Subject.Statement.t =
let body = Fuzz.Subject.Block.make_dead_code ~statements () in
let loop = Fir.Flow_block.for_loop body ~control:payload in
Fir.(Accessor.construct Statement.flow loop)
end)
end
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fuzz_actions/src/flow_for.ml | ocaml | Shared with Flow_while.
These may induce atomic loads, and so can't be in atomic blocks.
Note that this sets the known value of the loop counter to 0, so
we have to erase it again; otherwise, the for loop's activity on
the loop counter would be ignored by the rest of the fuzzer and
lead to semantic violations.
The loop counter is effectively being read from as well as written
to each iteration.
The loop counter is effectively being read from as well as written
to each iteration.
Try to avoid overflows by only going up if we're negative.
'Payload' gets shadowed a lot later on.
No point introducing dead-code actions if we're introducing dead
code.
Comparing a var against its known value using < or >.
The restriction on not being in an execute-multiple block isn't for
soundness, it's to prevent the fuzzer from deeply nesting multiple
loops, which can quickly lead to overlong run times.
We make sure to handle the case where we have no variables available
to us in the generator, so the path filter doesn't have to.
No need to recommend any dead-code introduction actions; this action
already introduces dead code!
No need to do housekeeping if we're in dead code. | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
let prefix_name (rest : Common.Id.t) : Common.Id.t =
Common.Id.("loop" @: rest)
let is_int : Fuzz.Var.Record.t -> bool =
TODO(@MattWindsor91 ): unify with the various ' has_variables_with ' env
stuff , somehow ?
stuff, somehow? *)
Fir.Type.Prim.eq ~to_:Int
Accessor.(
Fuzz.Var.Record.Access.type_of @> Fir.Type.Access.basic_type
@> Fir.Type.Basic.Access.prim)
let kv_var_preds = [Fuzz.Var.Record.has_known_value; is_int]
let kv_live_path_filter_static : Fuzz.Path_filter.t =
Fuzz.Path_filter.(live_loop_surround + forbid_flag In_atomic)
let kv_live_path_filter ({vars; _} : Fuzz.State.t) : Fuzz.Path_filter.t =
Fuzz.Path_filter.(
in_thread_with_variables ~predicates:kv_var_preds vars
+ kv_live_path_filter_static)
let kv_available (kind : Fuzz.Path_kind.t) : Fuzz.Availability.t =
TODO(@MattWindsor91 ): is the has - variables redundant here ?
Fuzz.Availability.(
has_variables ~predicates:kv_var_preds
+ M.(
lift (fun {state; _} -> kv_live_path_filter state)
>>= is_filter_constructible ~kind))
module Payload = struct
module Counter = struct
type t = {var: Common.Litmus_id.t; ty: Fir.Type.t} [@@deriving sexp]
let can_make : Fuzz.Availability.t =
Fuzz.Availability.in_var_cap ~after_adding:1
let lc_expr ({var; ty} : t) : Fir.Expression.t =
let name = Common.Litmus_id.variable_name var in
let lc_tvar = Common.C_named.make ty ~name in
Fir.Expression.lvalue (Fir.Lvalue.on_value_of_typed_id lc_tvar)
let declare_and_register ({var; ty} : t) (test : Fuzz.Subject.Test.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Fuzz.State.Monad.Let_syntax.(
let value = Fir.Constant.zero_of_type ty in
let init = Fir.{Initialiser.ty; value} in
let%bind test' =
Fuzz.State.Monad.register_and_declare_var var init test
in
let%bind () = Fuzz.State.Monad.erase_var_value var in
let%map () = Fuzz.State.Monad.add_dependency var in
test')
let counter_type (prim : Fir.Type.Prim.t) : Fir.Type.t =
Fir.Type.(
make
(Basic.make prim ~is_atomic:false)
~is_pointer:false ~is_volatile:false)
let gen (scope : Common.Scope.t) (prim_type : Fir.Type.Prim.t) :
t Fuzz.Payload_gen.t =
Fuzz.Payload_gen.(
let+ lc_var = fresh_var scope in
{var= lc_var; ty= counter_type prim_type})
end
module Simple = struct
type t = {lc: Counter.t; up_to: Fir.Constant.t} [@@deriving sexp, fields]
let src_exprs (x : t) : Fir.Expression.t list =
[ Fir.Expression.constant x.up_to
Counter.lc_expr x.lc ]
module type S_action =
Fuzz.Action_types.S with type Payload.t = t Fuzz.Payload_impl.Pathed.t
end
module Kv = struct
type t =
{lc: Counter.t; kv_val: Fir.Constant.t; kv_expr: Fir.Expression.t}
[@@deriving sexp, fields]
module type S_action =
Fuzz.Action_types.S with type Payload.t = t Fuzz.Payload_impl.Pathed.t
let src_exprs (x : t) : Fir.Expression.t list =
[ x.kv_expr
Counter.lc_expr x.lc ]
let direction (i : Fir.Flow_block.For.Simple.Inclusivity.t)
({kv_val; _} : t) : Fir.Flow_block.For.Simple.Direction.t =
match Fir.Constant.as_int kv_val with
| Ok x when x < 0 -> Up i
| _ -> Down i
let control (i : Fir.Flow_block.For.Simple.Inclusivity.t) (payload : t) :
C4f_fir.Flow_block.For.Simple.t =
{ lvalue=
Accessor.construct Fir.Lvalue.variable
(Common.Litmus_id.variable_name payload.lc.var)
; direction= direction i payload
; init_value= Fir.Expression.constant payload.kv_val
; cmp_value= payload.kv_expr }
let gen_lc (scope : Common.Scope.t)
(kv_var : Fir.Env.Record.t Common.C_named.t) :
Counter.t Fuzz.Payload_gen.t =
let prim =
Fir.(
kv_var.@(Common.C_named.value @> Env.Record.type_of
@> Type.Access.basic_type @> Type.Basic.Access.prim))
in
Counter.gen scope prim
let access_of_var (vrec : Fir.Env.Record.t Common.C_named.t) :
Fir.Expression.t Fuzz.Payload_gen.t =
let var =
Common.C_named.map_right
~f:(Accessor_base.get Fir.Env.Record.type_of)
vrec
in
let ty = var.@(Common.C_named.value) in
TODO(@MattWindsor91 ): is this duplicating something ?
Fuzz.Payload_gen.(
if Fir.Type.is_atomic ty then
let+ mo = lift_quickcheck Fir.Mem_order.gen_load in
Fir.Expression.atomic_load
(Fir.Atomic_load.make
~src:(Fir.Address.on_address_of_typed_id var)
~mo )
else
return
(Fir.Expression.lvalue (Fir.Lvalue.on_value_of_typed_id var)))
let known_value_val (vrec : Fir.Env.Record.t Common.C_named.t) :
Fir.Constant.t Fuzz.Payload_gen.t =
vrec.@?(Common.C_named.value @> Fir.Env.Record.known_value)
|> Result.of_option
~error:(Error.of_string "chosen value should have a known value")
|> Fuzz.Payload_gen.Inner.return
let known_value_var (scope : Common.Scope.t) :
Fir.Env.Record.t Common.C_named.t Fuzz.Payload_gen.t =
TODO(@MattWindsor91 ): this shares a lot of DNA with atomic_store
redundant .
redundant. *)
Fuzz.Payload_gen.(
let* vs = vars in
let env =
Fuzz.Var.Map.env_satisfying_all ~scope vs ~predicates:kv_var_preds
in
lift_quickcheck (Fir.Env.gen_random_var_with_record env))
let gen (where : Fuzz.Path.With_meta.t) : t Fuzz.Payload_gen.t =
Fuzz.Payload_gen.(
let scope = Common.Scope.Local (Fuzz.Path.tid where.path) in
let* kv_var = known_value_var scope in
let* lc = gen_lc scope kv_var in
let* kv_val = known_value_val kv_var in
let+ kv_expr = access_of_var kv_var in
{lc; kv_val; kv_expr})
end
end
open struct
module Pd = Payload
end
module Insert = struct
let prefix_name (x : Common.Id.t) : Common.Id.t =
prefix_name Common.Id.("insert" @: "for" @: x)
module Kv_never : Payload.Kv.S_action = struct
TODO(@MattWindsor91 ): maybe , if we make the loop counter always store
the KV , we can have that the loop counter persists that KV and can be
reliable used as such .
the KV, we can have that the loop counter persists that KV and can be
reliable used as such. *)
let name = prefix_name Common.Id.("kv-never" @: empty)
let readme : string Lazy.t =
lazy
{| Introduces a loop that initialises its
(fresh) counter to the known value of an existing variable and
compares it in such a way as to be dead-code. |}
let available : Fuzz.Availability.t =
Fuzz.Availability.(Pd.Counter.can_make + kv_available Insert)
let path_filter = kv_live_path_filter
module Payload = struct
type t = Payload.Kv.t Fuzz.Payload_impl.Pathed.t [@@deriving sexp]
let gen =
Fuzz.Payload_impl.Pathed.gen Insert path_filter Payload.Kv.gen
end
let recommendations (_ : Payload.t) : Common.Id.t list =
[]
let make_for (payload : Pd.Kv.t) : Fuzz.Subject.Statement.t =
let control = Pd.Kv.control Exclusive payload in
let body = Fuzz.Subject.Block.make_dead_code () in
Fir.(
Accessor.construct Statement.flow
(Flow_block.for_loop_simple ~control body))
TODO(@MattWindsor91 ): unify this with things ?
let run (test : Fuzz.Subject.Test.t)
~(payload : Pd.Kv.t Fuzz.Payload_impl.Pathed.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Fuzz.State.Monad.(
Let_syntax.(
let p = payload.payload in
let%bind test' = Pd.Counter.declare_and_register p.lc test in
let%bind () =
add_expression_dependencies p.kv_expr
~scope:(Local (Fuzz.Path.tid payload.where.path))
in
Fuzz.Payload_impl.Pathed.insert payload
~filter:kv_live_path_filter_static ~test:test' ~f:make_for))
end
end
module Surround = struct
let prefix_name (x : Common.Id.t) : Common.Id.t =
prefix_name Common.Id.("surround" @: "for" @: x)
module Simple : Payload.Simple.S_action = Fuzz.Action.Make_surround (struct
let name = prefix_name Common.Id.("simple" @: empty)
let surround_with : string = "for-loops"
let readme_suffix : string =
{| The for loop initialises its (fresh) counter to zero, then counts
upwards to a random, small, constant value. This action does not
surround non-generated or loop-unsafe statements. |}
let path_filter (_ : Fuzz.State.t) =
Fuzz.Path_filter.(
live_loop_surround
+ Fuzz.Path_filter.forbid_flag In_execute_multi
+ require_end_check (Stm_no_meta_restriction Once_only))
let available : Fuzz.Availability.t =
Fuzz.Availability.(
Pd.Counter.can_make
+ M.(
lift_state path_filter
>>= is_filter_constructible ~kind:Transform_list))
module Payload = struct
include Payload.Simple
let gen (where : Fuzz.Path.With_meta.t) :
Payload.Simple.t Fuzz.Payload_gen.t =
let scope = Common.Scope.Local (Fuzz.Path.tid where.path) in
Fuzz.Payload_gen.(
let* lc_var = fresh_var scope in
let lc : Pd.Counter.t = {var= lc_var; ty= Fir.Type.int ()} in
let+ up_to =
lift_quickcheck
Base_quickcheck.Generator.small_strictly_positive_int
in
{Payload.Simple.lc; up_to= Int up_to})
end
let recommendations (_ : Payload.t Fuzz.Payload_impl.Pathed.t) :
Common.Id.t list =
[Flow_dead.Insert.Early_out_loop_end.name]
let run_pre (test : Fuzz.Subject.Test.t) ~(payload : Payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Pd.Counter.declare_and_register payload.lc test
let control (payload : Payload.t) : C4f_fir.Flow_block.For.Simple.t =
{ Fir.Flow_block.For.Simple.lvalue=
Accessor.construct Fir.Lvalue.variable
(Common.Litmus_id.variable_name payload.lc.var)
; direction= Up Inclusive
; init_value= Fir.Expression.int_lit 0
; cmp_value= Fir.Expression.constant payload.up_to }
let wrap (statements : Fuzz.Subject.Statement.t list)
~(payload : Payload.t) : Fuzz.Subject.Statement.t =
let control = control payload in
let body = Fuzz.Subject.Block.make_generated ~statements () in
Fir.(
Accessor.construct Statement.flow
(Flow_block.for_loop_simple body ~control))
end)
module Kv_once : Payload.Kv.S_action = Fuzz.Action.Make_surround (struct
let name = prefix_name Common.Id.("kv-once" @: empty)
let surround_with : string = "for-loops"
let readme_suffix : string =
{| The for loop initialises its
(fresh) counter to the known value of an existing variable and
compares it in such a way as to execute only once. |}
let path_filter = kv_live_path_filter
let available : Fuzz.Availability.t =
Fuzz.Availability.(Pd.Counter.can_make + kv_available Transform_list)
module Payload = Payload.Kv
let recommendations (_ : Payload.t Fuzz.Payload_impl.Pathed.t) :
Common.Id.t list =
[Flow_dead.Insert.Early_out_loop_end.name]
let run_pre (test : Fuzz.Subject.Test.t) ~(payload : Payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
Pd.Counter.declare_and_register payload.lc test
let wrap (statements : Fuzz.Subject.Statement.t list)
~(payload : Payload.t) : Fuzz.Subject.Statement.t =
let control = Pd.Kv.control Inclusive payload in
let body = Fuzz.Subject.Block.make_generated ~statements () in
Fir.(
Accessor.construct Statement.flow
(Flow_block.for_loop_simple ~control body))
end)
module Dead :
Fuzz.Action_types.S
with type Payload.t = Fir.Flow_block.For.t Fuzz.Payload_impl.Pathed.t =
Fuzz.Action.Make_surround (struct
let name = prefix_name Common.Id.("dead" @: empty)
let surround_with : string = "for-loops"
let readme_suffix : string =
{| This action introduces arbitrary, occasionally nonsensical for loops
into dead code. |}
let path_filter (_ : Fuzz.State.t) : Fuzz.Path_filter.t =
Fuzz.Path_filter.require_flag In_dead_code
let available : Fuzz.Availability.t =
Fuzz.Availability.(
Pd.Counter.can_make
+ M.(
lift_state path_filter
>>= is_filter_constructible ~kind:Transform_list))
module Payload = struct
type t = Fir.Flow_block.For.t [@@deriving sexp]
let src_exprs x = x.@*(Fir.Flow_block.For.exprs)
let gen_cmp (env : Fir.Env.t) : Fir.Expression.t Q.Generator.t =
let module CInt = Fir_gen.Expr.Int_values (struct
let env = env
end) in
let module CBool = Fir_gen.Expr.Bool_values (struct
let env = env
end) in
Q.Generator.union
[CInt.quickcheck_generator; CBool.quickcheck_generator]
let gen_assign (env : Fir.Env.t) : Fir.Assign.t option Q.Generator.t =
Option.value_map
(Fir_gen.Assign.any ~src:env ~dst:env)
~default:(Q.Generator.return None) ~f:Q.Generator.option
let gen' (env : Fir.Env.t) : t Q.Generator.t =
Q.Generator.(
Let_syntax.(
let%map init = gen_assign env
and cmp = option (gen_cmp env)
and update = gen_assign env in
Fir.Flow_block.For.make ?init ?cmp ?update ()))
let gen (path : Fuzz.Path.With_meta.t) : t Fuzz.Payload_gen.t =
Fuzz.(
Payload_gen.(
let* env = env_at_path path in
lift_quickcheck (gen' env)))
end
let recommendations (_ : Payload.t Fuzz.Payload_impl.Pathed.t) :
Common.Id.t list =
[]
let run_pre (test : Fuzz.Subject.Test.t) ~(payload : Payload.t) :
Fuzz.Subject.Test.t Fuzz.State.Monad.t =
ignore payload ;
Fuzz.State.Monad.return test
let wrap (statements : Fuzz.Subject.Statement.t list)
~(payload : Payload.t) : Fuzz.Subject.Statement.t =
let body = Fuzz.Subject.Block.make_dead_code ~statements () in
let loop = Fir.Flow_block.for_loop body ~control:payload in
Fir.(Accessor.construct Statement.flow loop)
end)
end
|
564ed9194bfcc83a39d5f417767e6ac6c84edc079185899d57e4978f8d171aac | headwinds/reagent-reframe-material-ui | demo_pickers.cljs | (ns example.demos.demo-pickers
(:require [reagent.core :as r]
[example.utils.js :as utils :refer [moment-parse moment-parse-format moment-parse-d-format reverse-to-yyyy]]
[example.demos.demo-text-field :refer [text-field]]))
State
(def model-default {
:to-date "2018-10-29"
:to-date-display "16 10 2018"
:to-time "13:30"
:to "2018-10-29T11:00"
:from "2018-10-29T11:00"
})
(def model (r/atom model-default))
(defn handle-date-change [e]
(print "date change! " (.. e -target -value)) )
(defn display-date []
(:to-date-display @model)
)
(defn demo-pickers [{:keys [classes] :as props}]
(let [component-state (r/atom {:selected 0})]
(fn []
(let [current-select (get @component-state :selected)]
[:div {:style {:display "flex"
:flexDirection "column"
:position "relative"
:margin 50
:alignItems "left"
}}
[:h2 {:style {:margin "20px 0px"}} "Pickers"]
[:div {:style {:display "flex" :flex-direciton "row"}}
[text-field
{:id "from-datetime-local"
:label "From"
:value (:from @model)
:type "datetime-local"
:variant "outlined"
:InputLabelProps {:shrink true :style {:font-size 14}}
:InputProps {:style {:font-size 12}}
:placeholder "Placeholder"
:class (.-textField classes)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :from %2)) (.. e -target -value)))}]
[text-field
{:id "to-datetime-local"
:label "To"
:value (:to @model)
:type "datetime-local"
:variant "outlined"
:InputLabelProps {:shrink true :style {:font-size 14}}
:InputProps {:style {:font-size 12}}
:placeholder "Placeholder"
:class (.-textField classes)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to %2)) (.. e -target -value)))}]]
[:div {:style {:display "flex" :flex-direciton "row"}}
[:div {:style {:margin "20px 0px" :position "relative" :border-bottom "1px solid #000" :width 160 :margin-right 10 }}
[:div {:style {:position "absolute" :z-index 2 :top -12 }}
[:input {:type "text"
:value (display-date)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to-date-display %2)) (.. e -target -value))
(swap! model #(-> %1 (assoc :to-date %2)) (moment-parse-d-format (.. e -target -value) "YYYY-MM-DD"))
(print "date " (.. e -target -value))
(print "weird " (moment-parse-d-format (.. e -target -value) "YYYY-MM-DD"))
)
:style {:color "#000" :border "none" :font-size 14 :margin-top 12 :width 100}} ]]
[:div {:style {:position "absolute" :z-index 1 }}
[:input {:type "date"
:value (:to-date @model)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to-date %2)) (.. e -target -value))
(swap! model #(-> %1 (assoc :to-date-display %2)) (reverse-to-yyyy (.. e -target -value)))
)
:style {:border "none"
:font-size 14}
} ]]
]
[:div {:style {:margin "20px 0px" :border-bottom "1px solid #000" :width 100 }}
[:input {:type "time"
:value (:to-time @model)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to-time %2)) (.. e -target -value)))
:style {:border "none"
:font-size 14}
} ]
]]
[:h4 {:style {:margin "20px 0px"}} "Results"]
[:div
[:div
[:p "To: " (moment-parse (:to @model))]
]
[:div
[:p "From: " (moment-parse (:to @model))]
]]
;
[:h4 {:style {:margin "20px 0px"}} "About"]
[:div {:style {:width 400}}
[:p "This is an attempt to port "
[:a {:target "_blank" :href "-ui.com/demos/pickers/"}
"Material UI's picker "
] "component."
]]
]
))))
| null | https://raw.githubusercontent.com/headwinds/reagent-reframe-material-ui/8a6fba82a026cfedca38491becac85751be9a9d4/resources/public/js/out/example/demos/demo_pickers.cljs | clojure | (ns example.demos.demo-pickers
(:require [reagent.core :as r]
[example.utils.js :as utils :refer [moment-parse moment-parse-format moment-parse-d-format reverse-to-yyyy]]
[example.demos.demo-text-field :refer [text-field]]))
State
(def model-default {
:to-date "2018-10-29"
:to-date-display "16 10 2018"
:to-time "13:30"
:to "2018-10-29T11:00"
:from "2018-10-29T11:00"
})
(def model (r/atom model-default))
(defn handle-date-change [e]
(print "date change! " (.. e -target -value)) )
(defn display-date []
(:to-date-display @model)
)
(defn demo-pickers [{:keys [classes] :as props}]
(let [component-state (r/atom {:selected 0})]
(fn []
(let [current-select (get @component-state :selected)]
[:div {:style {:display "flex"
:flexDirection "column"
:position "relative"
:margin 50
:alignItems "left"
}}
[:h2 {:style {:margin "20px 0px"}} "Pickers"]
[:div {:style {:display "flex" :flex-direciton "row"}}
[text-field
{:id "from-datetime-local"
:label "From"
:value (:from @model)
:type "datetime-local"
:variant "outlined"
:InputLabelProps {:shrink true :style {:font-size 14}}
:InputProps {:style {:font-size 12}}
:placeholder "Placeholder"
:class (.-textField classes)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :from %2)) (.. e -target -value)))}]
[text-field
{:id "to-datetime-local"
:label "To"
:value (:to @model)
:type "datetime-local"
:variant "outlined"
:InputLabelProps {:shrink true :style {:font-size 14}}
:InputProps {:style {:font-size 12}}
:placeholder "Placeholder"
:class (.-textField classes)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to %2)) (.. e -target -value)))}]]
[:div {:style {:display "flex" :flex-direciton "row"}}
[:div {:style {:margin "20px 0px" :position "relative" :border-bottom "1px solid #000" :width 160 :margin-right 10 }}
[:div {:style {:position "absolute" :z-index 2 :top -12 }}
[:input {:type "text"
:value (display-date)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to-date-display %2)) (.. e -target -value))
(swap! model #(-> %1 (assoc :to-date %2)) (moment-parse-d-format (.. e -target -value) "YYYY-MM-DD"))
(print "date " (.. e -target -value))
(print "weird " (moment-parse-d-format (.. e -target -value) "YYYY-MM-DD"))
)
:style {:color "#000" :border "none" :font-size 14 :margin-top 12 :width 100}} ]]
[:div {:style {:position "absolute" :z-index 1 }}
[:input {:type "date"
:value (:to-date @model)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to-date %2)) (.. e -target -value))
(swap! model #(-> %1 (assoc :to-date-display %2)) (reverse-to-yyyy (.. e -target -value)))
)
:style {:border "none"
:font-size 14}
} ]]
]
[:div {:style {:margin "20px 0px" :border-bottom "1px solid #000" :width 100 }}
[:input {:type "time"
:value (:to-time @model)
:on-change (fn [e]
(swap! model #(-> %1 (assoc :to-time %2)) (.. e -target -value)))
:style {:border "none"
:font-size 14}
} ]
]]
[:h4 {:style {:margin "20px 0px"}} "Results"]
[:div
[:div
[:p "To: " (moment-parse (:to @model))]
]
[:div
[:p "From: " (moment-parse (:to @model))]
]]
[:h4 {:style {:margin "20px 0px"}} "About"]
[:div {:style {:width 400}}
[:p "This is an attempt to port "
[:a {:target "_blank" :href "-ui.com/demos/pickers/"}
"Material UI's picker "
] "component."
]]
]
))))
|
|
5854c273e306c4591deef895434cf3f6e1a95f15ea5a978a6e761bfe044af4de | AshleyYakeley/Truth | Context.hs | module Pinafore.Language.Library.GTK.Element.Context where
import Changes.Core
import Changes.World.GNOME.GTK
import Pinafore.Language.API
import Pinafore.Language.Library.GTK.Context
import Shapes
data SelectionModel =
TextSelectionModel LangTextModel
data ElementContext = MkElementContext
{ ecUnlift :: View --> IO
, ecAccelGroup :: AccelGroup
, ecOtherContext :: OtherContext
, ecSelectNotify :: SelectNotify SelectionModel
}
LangElement
newtype LangElement = MkLangElement
{ unLangElement :: ElementContext -> GView 'Locked Widget
}
elementGroundType :: QGroundType '[] LangElement
elementGroundType = stdSingleGroundType $(iowitness [t|'MkWitKind (SingletonFamily LangElement)|]) "Element.GTK."
instance HasQGroundType '[] LangElement where
qGroundType = elementGroundType
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/f567d19253bb471cbd8c39095fb414229b27706a/Pinafore/pinafore-gnome/lib/Pinafore/Language/Library/GTK/Element/Context.hs | haskell | > IO | module Pinafore.Language.Library.GTK.Element.Context where
import Changes.Core
import Changes.World.GNOME.GTK
import Pinafore.Language.API
import Pinafore.Language.Library.GTK.Context
import Shapes
data SelectionModel =
TextSelectionModel LangTextModel
data ElementContext = MkElementContext
, ecAccelGroup :: AccelGroup
, ecOtherContext :: OtherContext
, ecSelectNotify :: SelectNotify SelectionModel
}
LangElement
newtype LangElement = MkLangElement
{ unLangElement :: ElementContext -> GView 'Locked Widget
}
elementGroundType :: QGroundType '[] LangElement
elementGroundType = stdSingleGroundType $(iowitness [t|'MkWitKind (SingletonFamily LangElement)|]) "Element.GTK."
instance HasQGroundType '[] LangElement where
qGroundType = elementGroundType
|
e49b12ebebfb1cd4048ef07eea8c00f0567f2771f25d14b28e001be08ee51f68 | FranklinChen/learn-you-some-erlang | exceptions.erl | -module(exceptions).
-compile(export_all).
throws(F) ->
try F() of
_ -> ok
catch
Throw -> {throw, caught, Throw}
end.
errors(F) ->
try F() of
_ -> ok
catch
error:Error -> {error, caught, Error}
end.
exits(F) ->
try F() of
_ -> ok
catch
exit:Exit -> {exit, caught, Exit}
end.
sword(1) -> throw(slice);
sword(2) -> erlang:error(cut_arm);
sword(3) -> exit(cut_leg);
sword(4) -> throw(punch);
sword(5) -> exit(cross_bridge).
%%"I must cross this bridge"
black_knight(Attack) when is_function(Attack, 0) ->
try Attack() of
_ -> "None shall pass."
catch
throw:slice -> "It is but a scratch.";
error:cut_arm -> "I've had worse.";
exit:cut_leg -> "Come on you pansy!";
_:_ -> "Just a flesh wound."
end.
%"We'll call it a draw..."
talk() -> "blah blah".
whoa() ->
try
talk(),
_Knight = "None shall Pass!",
_Doubles = [N*2 || N <- lists:seq(1,100)],
throw(up),
_WillReturnThis = tequila
of
tequila -> "hey this worked!"
catch
Exception:Reason -> {caught, Exception, Reason}
end.
im_impressed() ->
try
talk(),
_Knight = "None shall Pass!",
_Doubles = [N*2 || N <- lists:seq(1,100)],
throw(up),
_WillReturnThis = tequila
catch
Exception:Reason -> {caught, Exception, Reason}
end.
catcher(X,Y) ->
case catch X/Y of
{'EXIT', {badarith,_}} -> "uh oh";
N -> N
end.
one_or_two(1) -> return;
one_or_two(2) -> throw(return).
| null | https://raw.githubusercontent.com/FranklinChen/learn-you-some-erlang/878c8bc2011a12862fe72dd7fdc6c921348c79d6/exceptions.erl | erlang | "I must cross this bridge"
"We'll call it a draw..."
| -module(exceptions).
-compile(export_all).
throws(F) ->
try F() of
_ -> ok
catch
Throw -> {throw, caught, Throw}
end.
errors(F) ->
try F() of
_ -> ok
catch
error:Error -> {error, caught, Error}
end.
exits(F) ->
try F() of
_ -> ok
catch
exit:Exit -> {exit, caught, Exit}
end.
sword(1) -> throw(slice);
sword(2) -> erlang:error(cut_arm);
sword(3) -> exit(cut_leg);
sword(4) -> throw(punch);
sword(5) -> exit(cross_bridge).
black_knight(Attack) when is_function(Attack, 0) ->
try Attack() of
_ -> "None shall pass."
catch
throw:slice -> "It is but a scratch.";
error:cut_arm -> "I've had worse.";
exit:cut_leg -> "Come on you pansy!";
_:_ -> "Just a flesh wound."
end.
talk() -> "blah blah".
whoa() ->
try
talk(),
_Knight = "None shall Pass!",
_Doubles = [N*2 || N <- lists:seq(1,100)],
throw(up),
_WillReturnThis = tequila
of
tequila -> "hey this worked!"
catch
Exception:Reason -> {caught, Exception, Reason}
end.
im_impressed() ->
try
talk(),
_Knight = "None shall Pass!",
_Doubles = [N*2 || N <- lists:seq(1,100)],
throw(up),
_WillReturnThis = tequila
catch
Exception:Reason -> {caught, Exception, Reason}
end.
catcher(X,Y) ->
case catch X/Y of
{'EXIT', {badarith,_}} -> "uh oh";
N -> N
end.
one_or_two(1) -> return;
one_or_two(2) -> throw(return).
|
3dcdcb0a5c38a806dd9fe91bcb5dbb59ae96352d4a2d54b29c7adc5a6b8d47d0 | tree-sitter/haskell-tree-sitter | OCaml.hs | module TreeSitter.OCaml
( tree_sitter_ocaml
, getNodeTypesPath
, getTestCorpusDir
) where
import Foreign.Ptr
import TreeSitter.Language
import Paths_tree_sitter_ocaml
foreign import ccall unsafe "vendor/tree-sitter-ocaml/src/parser.c tree_sitter_ocaml" tree_sitter_ocaml :: Ptr Language
getNodeTypesPath :: IO FilePath
getNodeTypesPath = getDataFileName "vendor/tree-sitter-ocaml/src/node-types.json"
getTestCorpusDir :: IO FilePath
getTestCorpusDir = getDataFileName "vendor/tree-sitter-ocaml/corpus"
| null | https://raw.githubusercontent.com/tree-sitter/haskell-tree-sitter/8a5a2b12a3c36a8ca7e117fff04023f1595e04e7/tree-sitter-ocaml/TreeSitter/OCaml.hs | haskell | module TreeSitter.OCaml
( tree_sitter_ocaml
, getNodeTypesPath
, getTestCorpusDir
) where
import Foreign.Ptr
import TreeSitter.Language
import Paths_tree_sitter_ocaml
foreign import ccall unsafe "vendor/tree-sitter-ocaml/src/parser.c tree_sitter_ocaml" tree_sitter_ocaml :: Ptr Language
getNodeTypesPath :: IO FilePath
getNodeTypesPath = getDataFileName "vendor/tree-sitter-ocaml/src/node-types.json"
getTestCorpusDir :: IO FilePath
getTestCorpusDir = getDataFileName "vendor/tree-sitter-ocaml/corpus"
|
|
ff70e45fb261a31e4300f2be784dd8cbfb803b48f5dba65c4af35ed8aa7e1750 | ralphrecto/xic | preTest.ml | open Core.Std
open OUnit2
open TestUtil
open Util
open Pre
open Ir
open ExprSet
module IrCfgEq = struct
let (===) (a: Cfg.IrCfg.t) (b: Cfg.IrCfg.t) : unit =
assert_equal ~cmp:Cfg.IrCfg.equal ~printer:Cfg.IrCfg.to_dot a b
let (=/=) (a: Cfg.IrCfg.t) (b: Cfg.IrCfg.t) : unit =
if Cfg.IrCfg.equal a b then
let a = Cfg.IrCfg.to_dot a in
let b = Cfg.IrCfg.to_dot b in
assert_failure (sprintf "These are equal, but shouldn't be:\n%s\n%s" a b)
end
module EdgeToExprEq = struct
type mapping = (Cfg.IrCfg.E.t * Pre.ExprSet.t) list
let printer (f: mapping) : string =
List.map f ~f:(fun (edge, exprs) ->
sprintf " (%s) -> %s"
(Cfg.IrCfg.string_of_edge edge)
(ExprSet.to_small_string exprs)
)
|> String.concat ~sep:",\n"
|> fun s -> "[\n" ^ s ^ "\n]"
let sort (f: mapping) : mapping =
List.sort ~cmp:(fun (edge, _) (edge', _) -> Cfg.IrCfg.E.compare edge edge') f
let cmp (a: mapping) (b: mapping) : bool =
List.length a = List.length b &&
List.for_all (List.zip_exn a b) ~f:(fun ((edge1, expr1), (edge2, expr2)) ->
Cfg.IrCfg.E.compare edge1 edge2 = 0 &&
Pre.ExprSet.equal expr1 expr2
)
let (===) (a: mapping) (b: mapping) : unit =
assert_equal ~cmp ~printer (sort a) (sort b)
let (=/=) (a: mapping) (b: mapping) : unit =
if cmp a b then
let a = printer a in
let b = printer b in
assert_failure (sprintf "These are equal, but shouldn't be:\n%s\n%s" a b)
end
module StmtsEq = struct
open Ir
let (===) (a: stmt list) (b: stmt list) : unit =
assert_equal ~printer:string_of_stmts a b
end
let make_graph vertexes edges =
let open Cfg.IrCfg in
let g = create () in
List.iter vertexes ~f:(fun i -> add_vertex g (V.create i));
List.iter edges ~f:(fun (i, l, j) -> add_edge_e g (E.create i l j));
g
let get_subexpr_test _ =
let make_binop e1 e2 = BinOp (e1, EQ, e2) in
let binop1 = BinOp (Const 1L, ADD, Const 2L) in
let binop2 = BinOp (Const 1L, SUB, Const 2L) in
let binop3 = BinOp (Const 1L, MUL, Const 2L) in
let binop4 = BinOp (Const 1L, HMUL, Const 2L) in
let binop5 = BinOp (Const 1L, LEQ, Const 2L) in
let binop6 = BinOp (Const 1L, GEQ, Const 2L) in
let binop7 = BinOp (Const 1L, AND, Const 2L) in
let binop8 = BinOp (Const 1L, OR, Const 2L) in
let binop9 = BinOp (Const 1L, EQ, Const 2L) in
let binop10 = make_binop binop1 binop2 in
let binop11 = make_binop binop10 binop3 in
let binop12 = make_binop binop11 binop4 in
let binop13 = make_binop binop12 binop5 in
let binop14 = make_binop binop13 binop6 in
let binop15 = make_binop binop14 binop7 in
let binop16 = make_binop binop15 binop8 in
let binop17 = make_binop binop16 binop9 in
let binop18 = make_binop binop17 binop10 in
let binop19 = make_binop binop18 binop11 in
let subs1 = [binop1] in
let subs2 = [binop10; binop2; binop1] in
let subs3 = [binop11; binop3; binop10; binop2; binop1] in
let subs4 = [binop12; binop4; binop11; binop3; binop10;
binop2; binop1] in
let subs5 = [binop13; binop5; binop12; binop4; binop11;
binop3; binop10; binop2; binop1] in
let subs6 = [binop14; binop6; binop13; binop5; binop12;
binop4; binop11; binop3; binop10; binop2;
binop1] in
let subs7 = [binop15; binop7; binop14; binop6; binop13;
binop5; binop12; binop4; binop11; binop3;
binop10; binop2; binop1] in
let subs8 = [binop16; binop8; binop15; binop7; binop14;
binop6; binop13; binop5; binop12; binop4;
binop11; binop3; binop10; binop2; binop1] in
let subs9 = [binop17; binop9; binop16; binop8; binop15;
binop7; binop14; binop6; binop13; binop5;
binop12; binop4; binop11; binop3; binop10;
binop2; binop1] in
let subs10 = [binop18; binop10; binop17; binop9; binop16;
binop8; binop15; binop7; binop14; binop6;
binop13; binop5; binop12; binop4; binop11;
binop3; binop10; binop2; binop1] in
let subs11 = [binop19; binop11; binop18; binop10; binop17;
binop9; binop16; binop8; binop15; binop7;
binop14; binop6; binop13; binop5; binop12;
binop4; binop11; binop3; binop10; binop2;
binop1] in
let subs_set1 = of_list subs1 in
let subs_set2 = of_list subs2 in
let subs_set3 = of_list subs3 in
let subs_set4 = of_list subs4 in
let subs_set5 = of_list subs5 in
let subs_set6 = of_list subs6 in
let subs_set7 = of_list subs7 in
let subs_set8 = of_list subs8 in
let subs_set9 = of_list subs9 in
let subs_set10 = of_list subs10 in
let subs_set11 = of_list subs11 in
let _ = assert_true (equal (get_subexpr binop1) subs_set1) in
let _ = assert_true (equal (get_subexpr binop10) subs_set2) in
let _ = assert_true (equal (get_subexpr binop11) subs_set3) in
let _ = assert_true (equal (get_subexpr binop12) subs_set4) in
let _ = assert_true (equal (get_subexpr binop13) subs_set5) in
let _ = assert_true (equal (get_subexpr binop14) subs_set6) in
let _ = assert_true (equal (get_subexpr binop15) subs_set7) in
let _ = assert_true (equal (get_subexpr binop16) subs_set8) in
let _ = assert_true (equal (get_subexpr binop17) subs_set9) in
let _ = assert_true (equal (get_subexpr binop18) subs_set10) in
let _ = assert_true (equal (get_subexpr binop19) subs_set11) in
let call1 = Call (Name "dummy", [binop1]) in
let call10 = Call (Name "dummy", [binop10]) in
let call11 = Call (Name "dummy", [binop11]) in
let call12 = Call (Name "dummy", [binop12]) in
let call13 = Call (Name "dummy", [binop13]) in
let call14 = Call (Name "dummy", [binop14]) in
let call15 = Call (Name "dummy", [binop15]) in
let call16 = Call (Name "dummy", [binop16]) in
let call17 = Call (Name "dummy", [binop17]) in
let call18 = Call (Name "dummy", [binop18]) in
let call19 = Call (Name "dummy", [binop19]) in
let _ = assert_true (equal (get_subexpr call1) subs_set1) in
let _ = assert_true (equal (get_subexpr call10) subs_set2) in
let _ = assert_true (equal (get_subexpr call11) subs_set3) in
let _ = assert_true (equal (get_subexpr call12) subs_set4) in
let _ = assert_true (equal (get_subexpr call13) subs_set5) in
let _ = assert_true (equal (get_subexpr call14) subs_set6) in
let _ = assert_true (equal (get_subexpr call15) subs_set7) in
let _ = assert_true (equal (get_subexpr call16) subs_set8) in
let _ = assert_true (equal (get_subexpr call17) subs_set9) in
let _ = assert_true (equal (get_subexpr call18) subs_set10) in
let _ = assert_true (equal (get_subexpr call19) subs_set11) in
let mem1 = Mem (binop1, NORMAL) in
let mem10 = Mem (binop10, NORMAL) in
let mem11 = Mem (binop11, NORMAL) in
let mem12 = Mem (binop12, NORMAL) in
let mem13 = Mem (binop13, NORMAL) in
let mem14 = Mem (binop14, NORMAL) in
let mem15 = Mem (binop15, NORMAL) in
let mem16 = Mem (binop16, NORMAL) in
let mem17 = Mem (binop17, NORMAL) in
let mem18 = Mem (binop18, NORMAL) in
let mem19 = Mem (binop19, NORMAL) in
let mem20 = Mem (call1, NORMAL) in
let mem21 = Mem (call10, NORMAL) in
let mem22 = Mem (call11, NORMAL) in
let mem23 = Mem (call12, NORMAL) in
let mem24 = Mem (call13, NORMAL) in
let mem25 = Mem (call14, NORMAL) in
let mem26 = Mem (call15, NORMAL) in
let mem27 = Mem (call16, NORMAL) in
let mem28 = Mem (call17, NORMAL) in
let mem29 = Mem (call18, NORMAL) in
let mem30 = Mem (call19, NORMAL) in
let mem_subs1 = mem1 :: subs1 in
let mem_subs2 = mem10 :: subs2 in
let mem_subs3 = mem11 :: subs3 in
let mem_subs4 = mem12 :: subs4 in
let mem_subs5 = mem13 :: subs5 in
let mem_subs6 = mem14 :: subs6 in
let mem_subs7 = mem15 :: subs7 in
let mem_subs8 = mem16 :: subs8 in
let mem_subs9 = mem17 :: subs9 in
let mem_subs10 = mem18 :: subs10 in
let mem_subs11 = mem19 :: subs11 in
let mem_subs12 = mem20 :: subs1 in
let mem_subs13 = mem21 :: subs2 in
let mem_subs14 = mem22 :: subs3 in
let mem_subs15 = mem23 :: subs4 in
let mem_subs16 = mem24 :: subs5 in
let mem_subs17 = mem25 :: subs6 in
let mem_subs18 = mem26 :: subs7 in
let mem_subs19 = mem27 :: subs8 in
let mem_subs20 = mem28 :: subs9 in
let mem_subs21 = mem29 :: subs10 in
let mem_subs22 = mem30 :: subs11 in
let mem_subs_set1 = of_list mem_subs1 in
let mem_subs_set10 = of_list mem_subs2 in
let mem_subs_set11 = of_list mem_subs3 in
let mem_subs_set12 = of_list mem_subs4 in
let mem_subs_set13 = of_list mem_subs5 in
let mem_subs_set14 = of_list mem_subs6 in
let mem_subs_set15 = of_list mem_subs7 in
let mem_subs_set16 = of_list mem_subs8 in
let mem_subs_set17 = of_list mem_subs9 in
let mem_subs_set18 = of_list mem_subs10 in
let mem_subs_set19 = of_list mem_subs11 in
let mem_subs_set20 = of_list mem_subs12 in
let mem_subs_set21 = of_list mem_subs13 in
let mem_subs_set22 = of_list mem_subs14 in
let mem_subs_set23 = of_list mem_subs15 in
let mem_subs_set24 = of_list mem_subs16 in
let mem_subs_set25 = of_list mem_subs17 in
let mem_subs_set26 = of_list mem_subs18 in
let mem_subs_set27 = of_list mem_subs19 in
let mem_subs_set28 = of_list mem_subs20 in
let mem_subs_set29 = of_list mem_subs21 in
let mem_subs_set30 = of_list mem_subs22 in
let _ = assert_true (equal (get_subexpr mem1) mem_subs_set1) in
let _ = assert_true (equal (get_subexpr mem10) mem_subs_set10) in
let _ = assert_true (equal (get_subexpr mem11) mem_subs_set11) in
let _ = assert_true (equal (get_subexpr mem12) mem_subs_set12) in
let _ = assert_true (equal (get_subexpr mem13) mem_subs_set13) in
let _ = assert_true (equal (get_subexpr mem14) mem_subs_set14) in
let _ = assert_true (equal (get_subexpr mem15) mem_subs_set15) in
let _ = assert_true (equal (get_subexpr mem16) mem_subs_set16) in
let _ = assert_true (equal (get_subexpr mem17) mem_subs_set17) in
let _ = assert_true (equal (get_subexpr mem18) mem_subs_set18) in
let _ = assert_true (equal (get_subexpr mem19) mem_subs_set19) in
let _ = assert_true (equal (get_subexpr mem20) mem_subs_set20) in
let _ = assert_true (equal (get_subexpr mem21) mem_subs_set21) in
let _ = assert_true (equal (get_subexpr mem22) mem_subs_set22) in
let _ = assert_true (equal (get_subexpr mem23) mem_subs_set23) in
let _ = assert_true (equal (get_subexpr mem24) mem_subs_set24) in
let _ = assert_true (equal (get_subexpr mem25) mem_subs_set25) in
let _ = assert_true (equal (get_subexpr mem26) mem_subs_set26) in
let _ = assert_true (equal (get_subexpr mem27) mem_subs_set27) in
let _ = assert_true (equal (get_subexpr mem28) mem_subs_set28) in
let _ = assert_true (equal (get_subexpr mem29) mem_subs_set29) in
let _ = assert_true (equal (get_subexpr mem30) mem_subs_set30) in
let mem_binop1 = make_binop mem1 mem20 in
let mem_binop2 = make_binop mem10 mem21 in
let mem_binop3 = make_binop mem11 mem22 in
let mem_binop4 = make_binop mem12 mem23 in
let mem_binop5 = make_binop mem13 mem24 in
let mem_binop6 = make_binop mem14 mem25 in
let mem_binop7 = make_binop mem15 mem26 in
let mem_binop8 = make_binop mem16 mem27 in
let mem_binop9 = make_binop mem17 mem28 in
let mem_binop10 = make_binop mem18 mem29 in
let mem_binop11 = make_binop mem19 mem30 in
let mem_binop_subs1 = mem_binop1 :: (mem_subs1 @ mem_subs12) in
let mem_binop_subs2 = mem_binop2 :: (mem_subs2 @ mem_subs13) in
let mem_binop_subs3 = mem_binop3 :: (mem_subs3 @ mem_subs14) in
let mem_binop_subs4 = mem_binop4 :: (mem_subs4 @ mem_subs15) in
let mem_binop_subs5 = mem_binop5 :: (mem_subs5 @ mem_subs16) in
let mem_binop_subs6 = mem_binop6 :: (mem_subs6 @ mem_subs17) in
let mem_binop_subs7 = mem_binop7 :: (mem_subs7 @ mem_subs18) in
let mem_binop_subs8 = mem_binop8 :: (mem_subs8 @ mem_subs19) in
let mem_binop_subs9 = mem_binop9 :: (mem_subs9 @ mem_subs20) in
let mem_binop_subs10 = mem_binop10 :: (mem_subs10 @ mem_subs21) in
let mem_binop_subs11 = mem_binop11 :: (mem_subs11 @ mem_subs22) in
let mem_binop_subs_set1 = of_list mem_binop_subs1 in
let mem_binop_subs_set10 = of_list mem_binop_subs2 in
let mem_binop_subs_set11 = of_list mem_binop_subs3 in
let mem_binop_subs_set12 = of_list mem_binop_subs4 in
let mem_binop_subs_set13 = of_list mem_binop_subs5 in
let mem_binop_subs_set14 = of_list mem_binop_subs6 in
let mem_binop_subs_set15 = of_list mem_binop_subs7 in
let mem_binop_subs_set16 = of_list mem_binop_subs8 in
let mem_binop_subs_set17 = of_list mem_binop_subs9 in
let mem_binop_subs_set18 = of_list mem_binop_subs10 in
let mem_binop_subs_set19 = of_list mem_binop_subs11 in
let _ = assert_true (equal (get_subexpr mem_binop1) mem_binop_subs_set1) in
let _ = assert_true (equal (get_subexpr mem_binop2) mem_binop_subs_set10) in
let _ = assert_true (equal (get_subexpr mem_binop3) mem_binop_subs_set11) in
let _ = assert_true (equal (get_subexpr mem_binop4) mem_binop_subs_set12) in
let _ = assert_true (equal (get_subexpr mem_binop5) mem_binop_subs_set13) in
let _ = assert_true (equal (get_subexpr mem_binop6) mem_binop_subs_set14) in
let _ = assert_true (equal (get_subexpr mem_binop7) mem_binop_subs_set15) in
let _ = assert_true (equal (get_subexpr mem_binop8) mem_binop_subs_set16) in
let _ = assert_true (equal (get_subexpr mem_binop9) mem_binop_subs_set17) in
let _ = assert_true (equal (get_subexpr mem_binop10) mem_binop_subs_set18) in
let _ = assert_true (equal (get_subexpr mem_binop11) mem_binop_subs_set19) in
let temp1 = Temp "x" in
let _ = assert_true (equal (get_subexpr temp1) empty) in
let cjump1 = CJumpOne (binop1, "dummy") in
let cjump2 = CJumpOne (binop10, "dummy") in
let cjump3 = CJumpOne (binop11, "dummy") in
let cjump4 = CJumpOne (binop12, "dummy") in
let cjump5 = CJumpOne (binop13, "dummy") in
let cjump6 = CJumpOne (binop14, "dummy") in
let cjump7 = CJumpOne (binop15, "dummy") in
let cjump8 = CJumpOne (binop16, "dummy") in
let cjump9 = CJumpOne (binop17, "dummy") in
let cjump10 = CJumpOne (binop18, "dummy") in
let cjump11 = CJumpOne (binop19, "dummy") in
let cjump12 = CJumpOne (call1, "dummy") in
let cjump13 = CJumpOne (call10, "dummy") in
let cjump14 = CJumpOne (call11, "dummy") in
let cjump15 = CJumpOne (call12, "dummy") in
let cjump16 = CJumpOne (call13, "dummy") in
let cjump17 = CJumpOne (call14, "dummy") in
let cjump18 = CJumpOne (call15, "dummy") in
let cjump19 = CJumpOne (call16, "dummy") in
let cjump20 = CJumpOne (call17, "dummy") in
let cjump21 = CJumpOne (call18, "dummy") in
let cjump22 = CJumpOne (call19, "dummy") in
let cjump23 = CJumpOne (mem1, "dummy") in
let cjump24 = CJumpOne (mem10, "dummy") in
let cjump25 = CJumpOne (mem11, "dummy") in
let cjump26 = CJumpOne (mem12, "dummy") in
let cjump27 = CJumpOne (mem13, "dummy") in
let cjump28 = CJumpOne (mem14, "dummy") in
let cjump29 = CJumpOne (mem15, "dummy") in
let cjump30 = CJumpOne (mem16, "dummy") in
let cjump31 = CJumpOne (mem17, "dummy") in
let cjump32 = CJumpOne (mem18, "dummy") in
let cjump33 = CJumpOne (mem19, "dummy") in
let cjump34 = CJumpOne (mem20, "dummy") in
let cjump35 = CJumpOne (mem21, "dummy") in
let cjump36 = CJumpOne (mem22, "dummy") in
let cjump37 = CJumpOne (mem23, "dummy") in
let cjump38 = CJumpOne (mem24, "dummy") in
let cjump39 = CJumpOne (mem25, "dummy") in
let cjump40 = CJumpOne (mem26, "dummy") in
let cjump41 = CJumpOne (mem27, "dummy") in
let cjump42 = CJumpOne (mem28, "dummy") in
let cjump43 = CJumpOne (mem29, "dummy") in
let cjump44 = CJumpOne (mem30, "dummy") in
let cjump45 = CJumpOne (mem_binop1, "dummy") in
let cjump46 = CJumpOne (mem_binop2, "dummy") in
let cjump47 = CJumpOne (mem_binop3, "dummy") in
let cjump48 = CJumpOne (mem_binop4, "dummy") in
let cjump49 = CJumpOne (mem_binop5, "dummy") in
let cjump50 = CJumpOne (mem_binop6, "dummy") in
let cjump51 = CJumpOne (mem_binop7, "dummy") in
let cjump52 = CJumpOne (mem_binop8, "dummy") in
let cjump53 = CJumpOne (mem_binop9, "dummy") in
let cjump54 = CJumpOne (mem_binop10, "dummy") in
let cjump55 = CJumpOne (mem_binop11, "dummy") in
let _ = assert_true (equal (get_subexpr_stmt cjump1) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump2) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt cjump3) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt cjump4) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt cjump5) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt cjump6) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt cjump7) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt cjump8) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt cjump9) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt cjump10) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump11) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump12) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump13) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt cjump14) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt cjump15) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt cjump16) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt cjump17) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt cjump18) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt cjump19) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt cjump20) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt cjump21) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump22) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump23) mem_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump24) mem_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump25) mem_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump26) mem_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt cjump27) mem_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt cjump28) mem_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt cjump29) mem_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt cjump30) mem_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt cjump31) mem_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt cjump32) mem_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt cjump33) mem_subs_set19) in
let _ = assert_true (equal (get_subexpr_stmt cjump34) mem_subs_set20) in
let _ = assert_true (equal (get_subexpr_stmt cjump35) mem_subs_set21) in
let _ = assert_true (equal (get_subexpr_stmt cjump36) mem_subs_set22) in
let _ = assert_true (equal (get_subexpr_stmt cjump37) mem_subs_set23) in
let _ = assert_true (equal (get_subexpr_stmt cjump38) mem_subs_set24) in
let _ = assert_true (equal (get_subexpr_stmt cjump39) mem_subs_set25) in
let _ = assert_true (equal (get_subexpr_stmt cjump40) mem_subs_set26) in
let _ = assert_true (equal (get_subexpr_stmt cjump41) mem_subs_set27) in
let _ = assert_true (equal (get_subexpr_stmt cjump42) mem_subs_set28) in
let _ = assert_true (equal (get_subexpr_stmt cjump43) mem_subs_set29) in
let _ = assert_true (equal (get_subexpr_stmt cjump44) mem_subs_set30) in
let _ = assert_true (equal (get_subexpr_stmt cjump45) mem_binop_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump46) mem_binop_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump47) mem_binop_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump48) mem_binop_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt cjump49) mem_binop_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt cjump50) mem_binop_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt cjump51) mem_binop_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt cjump52) mem_binop_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt cjump53) mem_binop_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt cjump54) mem_binop_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt cjump55) mem_binop_subs_set19) in
let move1 = Move (Temp "dummy", binop1) in
let move2 = Move (Temp "dummy", binop10) in
let move3 = Move (Temp "dummy", binop11) in
let move4 = Move (Temp "dummy", binop12) in
let move5 = Move (Temp "dummy", binop13) in
let move6 = Move (Temp "dummy", binop14) in
let move7 = Move (Temp "dummy", binop15) in
let move8 = Move (Temp "dummy", binop16) in
let move9 = Move (Temp "dummy", binop17) in
let move10 = Move (Temp "dummy", binop18) in
let move11 = Move (Temp "dummy", binop19) in
let move12 = Move (Temp "dummy", call1) in
let move13 = Move (Temp "dummy", call10) in
let move14 = Move (Temp "dummy", call11) in
let move15 = Move (Temp "dummy", call12) in
let move16 = Move (Temp "dummy", call13) in
let move17 = Move (Temp "dummy", call14) in
let move18 = Move (Temp "dummy", call15) in
let move19 = Move (Temp "dummy", call16) in
let move20 = Move (Temp "dummy", call17) in
let move21 = Move (Temp "dummy", call18) in
let move22 = Move (Temp "dummy", call19) in
let move23 = Move (Temp "dummy", mem1) in
let move24 = Move (Temp "dummy", mem10) in
let move25 = Move (Temp "dummy", mem11) in
let move26 = Move (Temp "dummy", mem12) in
let move27 = Move (Temp "dummy", mem13) in
let move28 = Move (Temp "dummy", mem14) in
let move29 = Move (Temp "dummy", mem15) in
let move30 = Move (Temp "dummy", mem16) in
let move31 = Move (Temp "dummy", mem17) in
let move32 = Move (Temp "dummy", mem18) in
let move33 = Move (Temp "dummy", mem19) in
let move34 = Move (Temp "dummy", mem20) in
let move35 = Move (Temp "dummy", mem21) in
let move36 = Move (Temp "dummy", mem22) in
let move37 = Move (Temp "dummy", mem23) in
let move38 = Move (Temp "dummy", mem24) in
let move39 = Move (Temp "dummy", mem25) in
let move40 = Move (Temp "dummy", mem26) in
let move41 = Move (Temp "dummy", mem27) in
let move42 = Move (Temp "dummy", mem28) in
let move43 = Move (Temp "dummy", mem29) in
let move44 = Move (Temp "dummy", mem30) in
let move45 = Move (Temp "dummy", mem_binop1) in
let move46 = Move (Temp "dummy", mem_binop2) in
let move47 = Move (Temp "dummy", mem_binop3) in
let move48 = Move (Temp "dummy", mem_binop4) in
let move49 = Move (Temp "dummy", mem_binop5) in
let move50 = Move (Temp "dummy", mem_binop6) in
let move51 = Move (Temp "dummy", mem_binop7) in
let move52 = Move (Temp "dummy", mem_binop8) in
let move53 = Move (Temp "dummy", mem_binop9) in
let move54 = Move (Temp "dummy", mem_binop10) in
let move55 = Move (Temp "dummy", mem_binop11) in
let move56 = Move (mem1, binop1) in
let move57 = Move (mem1, binop10) in
let move58 = Move (mem1, binop11) in
let move59 = Move (mem1, binop12) in
let move60 = Move (mem1, binop13) in
let move61 = Move (mem1, binop14) in
let move62 = Move (mem1, binop15) in
let move63 = Move (mem1, binop16) in
let move64 = Move (mem1, binop17) in
let move65 = Move (mem1, binop18) in
let move66 = Move (mem1, binop19) in
let move67 = Move (mem1, call1) in
let move68 = Move (mem1, call10) in
let move69 = Move (mem1, call11) in
let move70 = Move (mem1, call12) in
let move71 = Move (mem1, call13) in
let move72 = Move (mem1, call14) in
let move73 = Move (mem1, call15) in
let move74 = Move (mem1, call16) in
let move75 = Move (mem1, call17) in
let move76 = Move (mem1, call18) in
let move77 = Move (mem1, call19) in
let move78 = Move (mem1, mem1) in
let move79 = Move (mem1, mem10) in
let move80 = Move (mem1, mem11) in
let move81 = Move (mem1, mem12) in
let move82 = Move (mem1, mem13) in
let move83 = Move (mem1, mem14) in
let move84 = Move (mem1, mem15) in
let move85 = Move (mem1, mem16) in
let move86 = Move (mem1, mem17) in
let move87 = Move (mem1, mem18) in
let move88 = Move (mem1, mem19) in
let move89 = Move (mem1, mem20) in
let move90 = Move (mem1, mem21) in
let move91 = Move (mem1, mem22) in
let move92 = Move (mem1, mem23) in
let move93 = Move (mem1, mem24) in
let move94 = Move (mem1, mem25) in
let move95 = Move (mem1, mem26) in
let move96 = Move (mem1, mem27) in
let move97 = Move (mem1, mem28) in
let move98 = Move (mem1, mem29) in
let move99 = Move (mem1, mem30) in
let move100 = Move (mem1, mem_binop1) in
let move101 = Move (mem1, mem_binop2) in
let move102 = Move (mem1, mem_binop3) in
let move103 = Move (mem1, mem_binop4) in
let move104 = Move (mem1, mem_binop5) in
let move105 = Move (mem1, mem_binop6) in
let move106 = Move (mem1, mem_binop7) in
let move107 = Move (mem1, mem_binop8) in
let move108 = Move (mem1, mem_binop9) in
let move109 = Move (mem1, mem_binop10) in
let move110 = Move (mem1, mem_binop11) in
let move_mem1 = mem1 :: subs1 in
let move_mem2 = mem1 :: subs2 in
let move_mem3 = mem1 :: subs3 in
let move_mem4 = mem1 :: subs4 in
let move_mem5 = mem1 :: subs5 in
let move_mem6 = mem1 :: subs6 in
let move_mem7 = mem1 :: subs7 in
let move_mem8 = mem1 :: subs8 in
let move_mem9 = mem1 :: subs9 in
let move_mem10 = mem1 :: subs10 in
let move_mem11 = mem1 :: subs11 in
let move_mem12 = mem1 :: subs1 in
let move_mem13 = mem1 :: subs2 in
let move_mem14 = mem1 :: subs3 in
let move_mem15 = mem1 :: subs4 in
let move_mem16 = mem1 :: subs5 in
let move_mem17 = mem1 :: subs6 in
let move_mem18 = mem1 :: subs7 in
let move_mem19 = mem1 :: subs8 in
let move_mem20 = mem1 :: subs9 in
let move_mem21 = mem1 :: subs10 in
let move_mem22 = mem1 :: subs11 in
let move_mem23 = mem1 :: mem_subs1 in
let move_mem24 = mem1 :: mem_subs2 in
let move_mem25 = mem1 :: mem_subs3 in
let move_mem26 = mem1 :: mem_subs4 in
let move_mem27 = mem1 :: mem_subs5 in
let move_mem28 = mem1 :: mem_subs6 in
let move_mem29 = mem1 :: mem_subs7 in
let move_mem30 = mem1 :: mem_subs8 in
let move_mem31 = mem1 :: mem_subs9 in
let move_mem32 = mem1 :: mem_subs10 in
let move_mem33 = mem1 :: mem_subs11 in
let move_mem34 = mem1 :: mem_subs12 in
let move_mem35 = mem1 :: mem_subs13 in
let move_mem36 = mem1 :: mem_subs14 in
let move_mem37 = mem1 :: mem_subs15 in
let move_mem38 = mem1 :: mem_subs16 in
let move_mem39 = mem1 :: mem_subs17 in
let move_mem40 = mem1 :: mem_subs18 in
let move_mem41 = mem1 :: mem_subs19 in
let move_mem42 = mem1 :: mem_subs20 in
let move_mem43 = mem1 :: mem_subs21 in
let move_mem44 = mem1 :: mem_subs22 in
let move_mem45 = mem1 :: mem_binop_subs1 in
let move_mem46 = mem1 :: mem_binop_subs2 in
let move_mem47 = mem1 :: mem_binop_subs3 in
let move_mem48 = mem1 :: mem_binop_subs4 in
let move_mem49 = mem1 :: mem_binop_subs5 in
let move_mem50 = mem1 :: mem_binop_subs6 in
let move_mem51 = mem1 :: mem_binop_subs7 in
let move_mem52 = mem1 :: mem_binop_subs8 in
let move_mem53 = mem1 :: mem_binop_subs9 in
let move_mem54 = mem1 :: mem_binop_subs10 in
let move_mem55 = mem1 :: mem_binop_subs11 in
let move_mem_subs1 = of_list move_mem1 in
let move_mem_subs2 = of_list move_mem2 in
let move_mem_subs3 = of_list move_mem3 in
let move_mem_subs4 = of_list move_mem4 in
let move_mem_subs5 = of_list move_mem5 in
let move_mem_subs6 = of_list move_mem6 in
let move_mem_subs7 = of_list move_mem7 in
let move_mem_subs8 = of_list move_mem8 in
let move_mem_subs9 = of_list move_mem9 in
let move_mem_subs10 = of_list move_mem10 in
let move_mem_subs11 = of_list move_mem11 in
let move_mem_subs12 = of_list move_mem12 in
let move_mem_subs13 = of_list move_mem13 in
let move_mem_subs14 = of_list move_mem14 in
let move_mem_subs15 = of_list move_mem15 in
let move_mem_subs16 = of_list move_mem16 in
let move_mem_subs17 = of_list move_mem17 in
let move_mem_subs18 = of_list move_mem18 in
let move_mem_subs19 = of_list move_mem19 in
let move_mem_subs20 = of_list move_mem20 in
let move_mem_subs21 = of_list move_mem21 in
let move_mem_subs22 = of_list move_mem22 in
let move_mem_subs23 = of_list move_mem23 in
let move_mem_subs24 = of_list move_mem24 in
let move_mem_subs25 = of_list move_mem25 in
let move_mem_subs26 = of_list move_mem26 in
let move_mem_subs27 = of_list move_mem27 in
let move_mem_subs28 = of_list move_mem28 in
let move_mem_subs29 = of_list move_mem29 in
let move_mem_subs30 = of_list move_mem30 in
let move_mem_subs31 = of_list move_mem31 in
let move_mem_subs32 = of_list move_mem32 in
let move_mem_subs33 = of_list move_mem33 in
let move_mem_subs34 = of_list move_mem34 in
let move_mem_subs35 = of_list move_mem35 in
let move_mem_subs36 = of_list move_mem36 in
let move_mem_subs37 = of_list move_mem37 in
let move_mem_subs38 = of_list move_mem38 in
let move_mem_subs39 = of_list move_mem39 in
let move_mem_subs40 = of_list move_mem40 in
let move_mem_subs41 = of_list move_mem41 in
let move_mem_subs42 = of_list move_mem42 in
let move_mem_subs43 = of_list move_mem43 in
let move_mem_subs44 = of_list move_mem44 in
let move_mem_subs45 = of_list move_mem45 in
let move_mem_subs46 = of_list move_mem46 in
let move_mem_subs47 = of_list move_mem47 in
let move_mem_subs48 = of_list move_mem48 in
let move_mem_subs49 = of_list move_mem49 in
let move_mem_subs50 = of_list move_mem50 in
let move_mem_subs51 = of_list move_mem51 in
let move_mem_subs52 = of_list move_mem52 in
let move_mem_subs53 = of_list move_mem53 in
let move_mem_subs54 = of_list move_mem54 in
let move_mem_subs55 = of_list move_mem55 in
let _ = assert_true (equal (get_subexpr_stmt move1) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move2) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt move3) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt move4) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt move5) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt move6) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt move7) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt move8) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt move9) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt move10) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move11) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move12) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move13) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt move14) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt move15) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt move16) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt move17) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt move18) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt move19) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt move20) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt move21) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move22) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move23) mem_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move24) mem_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move25) mem_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move26) mem_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt move27) mem_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt move28) mem_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt move29) mem_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt move30) mem_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt move31) mem_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt move32) mem_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt move33) mem_subs_set19) in
let _ = assert_true (equal (get_subexpr_stmt move34) mem_subs_set20) in
let _ = assert_true (equal (get_subexpr_stmt move35) mem_subs_set21) in
let _ = assert_true (equal (get_subexpr_stmt move36) mem_subs_set22) in
let _ = assert_true (equal (get_subexpr_stmt move37) mem_subs_set23) in
let _ = assert_true (equal (get_subexpr_stmt move38) mem_subs_set24) in
let _ = assert_true (equal (get_subexpr_stmt move39) mem_subs_set25) in
let _ = assert_true (equal (get_subexpr_stmt move40) mem_subs_set26) in
let _ = assert_true (equal (get_subexpr_stmt move41) mem_subs_set27) in
let _ = assert_true (equal (get_subexpr_stmt move42) mem_subs_set28) in
let _ = assert_true (equal (get_subexpr_stmt move43) mem_subs_set29) in
let _ = assert_true (equal (get_subexpr_stmt move44) mem_subs_set30) in
let _ = assert_true (equal (get_subexpr_stmt move45) mem_binop_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move46) mem_binop_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move47) mem_binop_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move48) mem_binop_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt move49) mem_binop_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt move50) mem_binop_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt move51) mem_binop_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt move52) mem_binop_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt move53) mem_binop_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt move54) mem_binop_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt move55) mem_binop_subs_set19) in
let _ = assert_true (equal (get_subexpr_stmt move56) move_mem_subs1) in
let _ = assert_true (equal (get_subexpr_stmt move57) move_mem_subs2) in
let _ = assert_true (equal (get_subexpr_stmt move58) move_mem_subs3) in
let _ = assert_true (equal (get_subexpr_stmt move59) move_mem_subs4) in
let _ = assert_true (equal (get_subexpr_stmt move60) move_mem_subs5) in
let _ = assert_true (equal (get_subexpr_stmt move61) move_mem_subs6) in
let _ = assert_true (equal (get_subexpr_stmt move62) move_mem_subs7) in
let _ = assert_true (equal (get_subexpr_stmt move63) move_mem_subs8) in
let _ = assert_true (equal (get_subexpr_stmt move64) move_mem_subs9) in
let _ = assert_true (equal (get_subexpr_stmt move65) move_mem_subs10) in
let _ = assert_true (equal (get_subexpr_stmt move66) move_mem_subs11) in
let _ = assert_true (equal (get_subexpr_stmt move67) move_mem_subs12) in
let _ = assert_true (equal (get_subexpr_stmt move68) move_mem_subs13) in
let _ = assert_true (equal (get_subexpr_stmt move69) move_mem_subs14) in
let _ = assert_true (equal (get_subexpr_stmt move70) move_mem_subs15) in
let _ = assert_true (equal (get_subexpr_stmt move71) move_mem_subs16) in
let _ = assert_true (equal (get_subexpr_stmt move72) move_mem_subs17) in
let _ = assert_true (equal (get_subexpr_stmt move73) move_mem_subs18) in
let _ = assert_true (equal (get_subexpr_stmt move74) move_mem_subs19) in
let _ = assert_true (equal (get_subexpr_stmt move75) move_mem_subs20) in
let _ = assert_true (equal (get_subexpr_stmt move76) move_mem_subs21) in
let _ = assert_true (equal (get_subexpr_stmt move77) move_mem_subs22) in
let _ = assert_true (equal (get_subexpr_stmt move78) move_mem_subs23) in
let _ = assert_true (equal (get_subexpr_stmt move79) move_mem_subs24) in
let _ = assert_true (equal (get_subexpr_stmt move80) move_mem_subs25) in
let _ = assert_true (equal (get_subexpr_stmt move81) move_mem_subs26) in
let _ = assert_true (equal (get_subexpr_stmt move82) move_mem_subs27) in
let _ = assert_true (equal (get_subexpr_stmt move83) move_mem_subs28) in
let _ = assert_true (equal (get_subexpr_stmt move84) move_mem_subs29) in
let _ = assert_true (equal (get_subexpr_stmt move85) move_mem_subs30) in
let _ = assert_true (equal (get_subexpr_stmt move86) move_mem_subs31) in
let _ = assert_true (equal (get_subexpr_stmt move87) move_mem_subs32) in
let _ = assert_true (equal (get_subexpr_stmt move88) move_mem_subs33) in
let _ = assert_true (equal (get_subexpr_stmt move89) move_mem_subs34) in
let _ = assert_true (equal (get_subexpr_stmt move90) move_mem_subs35) in
let _ = assert_true (equal (get_subexpr_stmt move91) move_mem_subs36) in
let _ = assert_true (equal (get_subexpr_stmt move92) move_mem_subs37) in
let _ = assert_true (equal (get_subexpr_stmt move93) move_mem_subs38) in
let _ = assert_true (equal (get_subexpr_stmt move94) move_mem_subs39) in
let _ = assert_true (equal (get_subexpr_stmt move95) move_mem_subs40) in
let _ = assert_true (equal (get_subexpr_stmt move96) move_mem_subs41) in
let _ = assert_true (equal (get_subexpr_stmt move97) move_mem_subs42) in
let _ = assert_true (equal (get_subexpr_stmt move98) move_mem_subs43) in
let _ = assert_true (equal (get_subexpr_stmt move99) move_mem_subs44) in
let _ = assert_true (equal (get_subexpr_stmt move100) move_mem_subs45) in
let _ = assert_true (equal (get_subexpr_stmt move101) move_mem_subs46) in
let _ = assert_true (equal (get_subexpr_stmt move102) move_mem_subs47) in
let _ = assert_true (equal (get_subexpr_stmt move103) move_mem_subs48) in
let _ = assert_true (equal (get_subexpr_stmt move104) move_mem_subs49) in
let _ = assert_true (equal (get_subexpr_stmt move105) move_mem_subs50) in
let _ = assert_true (equal (get_subexpr_stmt move106) move_mem_subs51) in
let _ = assert_true (equal (get_subexpr_stmt move107) move_mem_subs52) in
let _ = assert_true (equal (get_subexpr_stmt move108) move_mem_subs53) in
let _ = assert_true (equal (get_subexpr_stmt move109) move_mem_subs54) in
let _ = assert_true (equal (get_subexpr_stmt move110) move_mem_subs55) in
let jump1 = Jump (Name "dummy") in
let label1 = Label "dummy" in
let return1 = Return in
let _ = assert_true (equal (get_subexpr_stmt jump1) empty) in
let _ = assert_true (equal (get_subexpr_stmt label1) empty) in
let _ = assert_true (equal (get_subexpr_stmt return1) empty) in
()
let preprocess_test _ =
let open Ir.Abbreviations in
let open Cfg.IrData in
let open Cfg.IrDataStartExit in
let open IrCfgEq in
let test input_vs input_es expected_vs expected_es =
let input = make_graph input_vs input_es in
let expected = make_graph expected_vs expected_es in
Pre.preprocess input;
expected === input
in
let norm = Cfg.EdgeData.Normal in
let ir0 = move (temp "ir0") (zero) in
let ir1 = move (temp "ir1") (one) in
let ir2 = move (temp "ir2") (two) in
let ir3 = move (temp "ir3") (three) in
let ir4 = move (temp "ir4") (four) in
let ir5 = move (temp "ir5") (five) in
let ir6 = move (temp "ir6") (six) in
let n0 = Cfg.IrCfg.V.create (Node {num=0; ir=ir0}) in
let n1 = Cfg.IrCfg.V.create (Node {num=1; ir=ir1}) in
let n2 = Cfg.IrCfg.V.create (Node {num=2; ir=ir2}) in
let n3 = Cfg.IrCfg.V.create (Node {num=3; ir=ir3}) in
let n4 = Cfg.IrCfg.V.create (Node {num=4; ir=ir4}) in
let n5 = Cfg.IrCfg.V.create (Node {num=5; ir=ir5}) in
let n6 = Cfg.IrCfg.V.create (Node {num=6; ir=ir6}) in
let d3 = Cfg.IrCfg.V.create (Node {num=3; ir=Pre.dummy_ir}) in
let d4 = Cfg.IrCfg.V.create (Node {num=4; ir=Pre.dummy_ir}) in
let d5 = Cfg.IrCfg.V.create (Node {num=5; ir=Pre.dummy_ir}) in
let d6 = Cfg.IrCfg.V.create (Node {num=6; ir=Pre.dummy_ir}) in
let d7 = Cfg.IrCfg.V.create (Node {num=7; ir=Pre.dummy_ir}) in
let d8 = Cfg.IrCfg.V.create (Node {num=8; ir=Pre.dummy_ir}) in
let d9 = Cfg.IrCfg.V.create (Node {num=9; ir=Pre.dummy_ir}) in
let d10 = Cfg.IrCfg.V.create (Node {num=10; ir=Pre.dummy_ir}) in
let ivs = [n0; n1] in
let ies = [(n0, norm, n1)] in
let evs = ivs in
let ees = ies in
test ivs ies evs ees;
let ivs = [n0; n1; n2] in
let ies = [(n0, norm, n2); (n1, norm, n2)] in
let evs = ivs @ [d3; d4] in
let ees = [
(n0, norm, d3); (d3, norm, n2);
(n1, norm, d4); (d4, norm, n2);
] in
test ivs ies evs ees;
let ivs = [n0; n1; n2] in
let ies = [(n0, norm, n1); (n0, norm, n2)] in
let evs = ivs in
let ees = ies in
test ivs ies evs ees;
let ivs = [n0; n1; n2; n3] in
let ies = [(n0, norm, n3); (n1, norm, n3); (n2, norm, n3)] in
let evs = ivs @ [d4; d5; d6] in
let ees = [
(n0, norm, d4); (d4, norm, n3);
(n1, norm, d5); (d5, norm, n3);
(n2, norm, d6); (d6, norm, n3);
] in
test ivs ies evs ees;
let ivs = [n0; n1; n2; n3; n4; n5; n6] in
let ies = [
(n0, norm, n1);
(n0, norm, n2);
(n1, norm, n3);
(n2, norm, n3);
(n3, norm, n4);
(n3, norm, n5);
(n4, norm, n6);
(n5, norm, n6);
] in
let evs = ivs @ [d7; d8; d9; d10] in
let ees = [
(n0, norm, n1);
(n0, norm, n2);
(n1, norm, d7); (d7, norm, n3);
(n2, norm, d8); (d8, norm, n3);
(n3, norm, n4);
(n3, norm, n5);
(n4, norm, d9); (d9, norm, n6);
(n5, norm, d10); (d10, norm, n6);
] in
test ivs ies evs ees;
()
module BookExample = struct
open Ir.Abbreviations
open Ir.Infix
module C = Cfg.IrCfg
module D = Cfg.IrData
module SE = Cfg.IrDataStartExit
module E = Pre.ExprSet
let tru = Cfg.EdgeData.True
let fls = Cfg.EdgeData.False
let start = C.V.create SE.Start
let exit = C.V.create SE.Exit
let norm = Cfg.EdgeData.Normal
let node num ir = C.V.create (SE.Node D.{num; ir})
(* vertexes *)
let n1 = node 1 (label "node1")
let n2 = node 2 (move (temp "c") two)
let n3 = node 3 (label "node3")
let n4 = node 4 (label "node4")
let n5 = node 5 (move (temp "a") (temp "b" + temp "c"))
let n6 = node 6 (label "node6")
let n7 = node 7 (move (temp "d") (temp "b" + temp "c"))
let n8 = node 8 (label "node8")
let n9 = node 9 (move (temp "e") (temp "b" + temp "c"))
let n10 = node 10 (label "node10")
let n11 = node 11 (label "node11")
let vs = [start; n1; n2; n3; n4; n5; n6; n7; n8; n9; n10; n11; exit]
(* edges *)
let es_1 = (start, norm, n1)
let e1_2 = (n1, fls, n2)
let e2_3 = (n2, norm, n3)
let e3_4 = (n3, norm, n4)
let e4_7 = (n4, norm, n7)
let e1_5 = (n1, tru, n5)
let e5_6 = (n5, norm, n6)
let e6_7 = (n6, norm, n7)
let e7_8 = (n7, norm, n8)
let e8_9 = (n8, fls, n9)
let e9_10 = (n9, norm, n10)
let e10_11 = (n10, tru, n11)
let e11_e = (n11, norm, exit)
let e8_11 = (n8, tru, n11)
let e10_9 = (n10, fls, n9)
let es = [
es_1; e1_2; e2_3; e3_4; e4_7; e1_5; e5_6; e6_7; e7_8; e8_9; e9_10; e10_11;
e11_e; e8_11; e10_9;
]
(* graph *)
let g = make_graph vs es
let univ = E.of_list [temp "b" + temp "c"]
let uses = fun v ->
match v with
| SE.Start
| SE.Exit -> E.empty
| SE.Node _ when List.mem ~equal:C.V.equal [n5; n7; n9] v ->
E.of_list [temp "b" + temp "c"]
| SE.Node _ -> E.empty
let kills = fun v ->
if List.mem ~equal:C.V.equal [n2] v
then E.singleton (temp "b" + temp "c")
else E.empty
let busy = fun v ->
if List.mem ~equal:C.V.equal [n5; n6; n3; n4; n7; n9] v
then E.singleton (temp "b" + temp "c")
else E.empty
let earliest = fun v ->
if List.mem ~equal:C.V.equal [n3; n5] v
then E.singleton (temp "b" + temp "c")
else E.empty
let latest = fun v ->
if List.mem ~equal:C.V.equal [n4; n5] v
then E.singleton (temp "b" + temp "c")
else E.empty
end
let busy_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
(* testing helper *)
let test expected edges g univ uses kills =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.BusyExpr.worklist BusyExprCFG.{g; univ; uses; kills} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
(* helpers *)
let start = C.V.create SE.Start in
let exit = C.V.create SE.Exit in
let norm = Cfg.EdgeData.Normal in
(* (start) -> (x = 1 + 2) -> (exit) *)
let n0 = C.V.create (SE.Node D.{num=0; ir=(move (temp "x") (one + two))}) in
let vs = [start; n0; exit] in
let e0 = (start, norm, n0) in
let e1 = (n0, norm, exit) in
let es = [(start, norm, n0); (n0, norm, exit)] in
let g = make_graph vs es in
let univ = E.of_list [one + two] in
let uses = function
| SE.Start | SE.Exit -> E.empty
| SE.Node _ -> E.of_list [one + two]
in
let kills = fun _ -> E.empty in
let expected = [
(e0, E.of_list [one + two]);
(e1, E.empty);
] in
test expected es g univ uses kills;
(* book example *)
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, bc);
(e3_4, bc);
(e4_7, bc);
(e1_5, bc);
(e5_6, bc);
(e6_7, bc);
(e7_8, E.empty);
(e8_9, bc);
(e9_10, E.empty);
(e10_11, E.empty);
(e11_e, E.empty);
(e8_11, E.empty);
(e10_9, bc);
] in
test expected es g univ uses kills;
()
let avail_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
(* testing helper *)
let test expected edges g univ busy kills =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.AvailExpr.worklist AvailExprCFG.{g; univ; busy; kills} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
(* book example *)
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, E.empty);
(e3_4, bc);
(e4_7, bc);
(e1_5, E.empty);
(e5_6, bc);
(e6_7, bc);
(e7_8, bc);
(e8_9, bc);
(e9_10, bc);
(e10_11, bc);
(e11_e, bc);
(e8_11, bc);
(e10_9, bc);
] in
test expected es g univ busy kills;
()
let post_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
(* testing helper *)
let test expected edges g univ uses earliest =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.PostponeExpr.worklist PostponeExprCFG.{g; univ; uses; earliest} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
(* book example *)
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, E.empty);
(e3_4, bc);
(e4_7, bc);
(e1_5, E.empty);
(e5_6, E.empty);
(e6_7, E.empty);
(e7_8, E.empty);
(e8_9, E.empty);
(e9_10, E.empty);
(e10_11, E.empty);
(e11_e, E.empty);
(e8_11, E.empty);
(e10_9, E.empty);
] in
test expected es g univ uses earliest;
()
let used_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
(* testing helper *)
let test expected edges g uses latest =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.UsedExpr.worklist UsedExprCFG.{uses; latest} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
(* book example *)
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, E.empty);
(e3_4, E.empty);
(e4_7, bc);
(e1_5, E.empty);
(e5_6, bc);
(e6_7, bc);
(e7_8, bc);
(e8_9, bc);
(e9_10, bc);
(e10_11, E.empty);
(e11_e, E.empty);
(e8_11, E.empty);
(e10_9, bc);
] in
test expected es g uses latest;
()
let enchilada_test _ =
let open StmtsEq in
let open Ir.Abbreviations in
let open Ir.Infix in
let a = temp "a" in
let b = temp "b" in
let c = temp "c" in
let d = temp "d" in
let e = temp "e" in
(* book example *)
let irs = [
cjumpone one "n5"; (* B1 *)
move c two; (* B2 *)
jump (name "n7"); (* B3 *)
B5
B5
label "n7"; (* B7 *)
move d (b + c); (* B7 *)
B8
B9
B9
B10
B11
] in
Ir_generation.FreshTemp.reset();
Fresh.FreshLabel.reset();
let t = Ir.Temp (Ir_generation.FreshTemp.gen 0) in
let expected = [
label (Fresh.FreshLabel.gen 0); (* start *)
cjumpone one "n5"; (* B1 *)
move c two; (* B2 *)
move t (b + c); (* B3 *)
jump (name "n7"); (* B3 *)
B5
B5
B5
label "n7"; (* B7 *)
move d t; (* B7 *)
B8
B9
B9
B10
B11
] in
expected === Pre.pre irs;
()
(* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *)
(* ! DON'T FORGET TO ADD YOUR TESTS HERE ! *)
(* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *)
let main () =
"suite" >::: [
"get_subexpr_test" >:: get_subexpr_test;
"preprocess_test" >:: preprocess_test;
"busy_test" >:: busy_test;
"avail_test" >:: avail_test;
"post_test" >:: post_test;
"used_test" >:: used_test;
"enchilada_test" >:: enchilada_test;
] |> run_test_tt_main
let _ = main ()
| null | https://raw.githubusercontent.com/ralphrecto/xic/7dddfc855775467244a7949ee6d311dd8150f748/test/ocaml/preTest.ml | ocaml | vertexes
edges
graph
testing helper
helpers
(start) -> (x = 1 + 2) -> (exit)
book example
testing helper
book example
testing helper
book example
testing helper
book example
book example
B1
B2
B3
B7
B7
start
B1
B2
B3
B3
B7
B7
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! DON'T FORGET TO ADD YOUR TESTS HERE !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | open Core.Std
open OUnit2
open TestUtil
open Util
open Pre
open Ir
open ExprSet
module IrCfgEq = struct
let (===) (a: Cfg.IrCfg.t) (b: Cfg.IrCfg.t) : unit =
assert_equal ~cmp:Cfg.IrCfg.equal ~printer:Cfg.IrCfg.to_dot a b
let (=/=) (a: Cfg.IrCfg.t) (b: Cfg.IrCfg.t) : unit =
if Cfg.IrCfg.equal a b then
let a = Cfg.IrCfg.to_dot a in
let b = Cfg.IrCfg.to_dot b in
assert_failure (sprintf "These are equal, but shouldn't be:\n%s\n%s" a b)
end
module EdgeToExprEq = struct
type mapping = (Cfg.IrCfg.E.t * Pre.ExprSet.t) list
let printer (f: mapping) : string =
List.map f ~f:(fun (edge, exprs) ->
sprintf " (%s) -> %s"
(Cfg.IrCfg.string_of_edge edge)
(ExprSet.to_small_string exprs)
)
|> String.concat ~sep:",\n"
|> fun s -> "[\n" ^ s ^ "\n]"
let sort (f: mapping) : mapping =
List.sort ~cmp:(fun (edge, _) (edge', _) -> Cfg.IrCfg.E.compare edge edge') f
let cmp (a: mapping) (b: mapping) : bool =
List.length a = List.length b &&
List.for_all (List.zip_exn a b) ~f:(fun ((edge1, expr1), (edge2, expr2)) ->
Cfg.IrCfg.E.compare edge1 edge2 = 0 &&
Pre.ExprSet.equal expr1 expr2
)
let (===) (a: mapping) (b: mapping) : unit =
assert_equal ~cmp ~printer (sort a) (sort b)
let (=/=) (a: mapping) (b: mapping) : unit =
if cmp a b then
let a = printer a in
let b = printer b in
assert_failure (sprintf "These are equal, but shouldn't be:\n%s\n%s" a b)
end
module StmtsEq = struct
open Ir
let (===) (a: stmt list) (b: stmt list) : unit =
assert_equal ~printer:string_of_stmts a b
end
let make_graph vertexes edges =
let open Cfg.IrCfg in
let g = create () in
List.iter vertexes ~f:(fun i -> add_vertex g (V.create i));
List.iter edges ~f:(fun (i, l, j) -> add_edge_e g (E.create i l j));
g
let get_subexpr_test _ =
let make_binop e1 e2 = BinOp (e1, EQ, e2) in
let binop1 = BinOp (Const 1L, ADD, Const 2L) in
let binop2 = BinOp (Const 1L, SUB, Const 2L) in
let binop3 = BinOp (Const 1L, MUL, Const 2L) in
let binop4 = BinOp (Const 1L, HMUL, Const 2L) in
let binop5 = BinOp (Const 1L, LEQ, Const 2L) in
let binop6 = BinOp (Const 1L, GEQ, Const 2L) in
let binop7 = BinOp (Const 1L, AND, Const 2L) in
let binop8 = BinOp (Const 1L, OR, Const 2L) in
let binop9 = BinOp (Const 1L, EQ, Const 2L) in
let binop10 = make_binop binop1 binop2 in
let binop11 = make_binop binop10 binop3 in
let binop12 = make_binop binop11 binop4 in
let binop13 = make_binop binop12 binop5 in
let binop14 = make_binop binop13 binop6 in
let binop15 = make_binop binop14 binop7 in
let binop16 = make_binop binop15 binop8 in
let binop17 = make_binop binop16 binop9 in
let binop18 = make_binop binop17 binop10 in
let binop19 = make_binop binop18 binop11 in
let subs1 = [binop1] in
let subs2 = [binop10; binop2; binop1] in
let subs3 = [binop11; binop3; binop10; binop2; binop1] in
let subs4 = [binop12; binop4; binop11; binop3; binop10;
binop2; binop1] in
let subs5 = [binop13; binop5; binop12; binop4; binop11;
binop3; binop10; binop2; binop1] in
let subs6 = [binop14; binop6; binop13; binop5; binop12;
binop4; binop11; binop3; binop10; binop2;
binop1] in
let subs7 = [binop15; binop7; binop14; binop6; binop13;
binop5; binop12; binop4; binop11; binop3;
binop10; binop2; binop1] in
let subs8 = [binop16; binop8; binop15; binop7; binop14;
binop6; binop13; binop5; binop12; binop4;
binop11; binop3; binop10; binop2; binop1] in
let subs9 = [binop17; binop9; binop16; binop8; binop15;
binop7; binop14; binop6; binop13; binop5;
binop12; binop4; binop11; binop3; binop10;
binop2; binop1] in
let subs10 = [binop18; binop10; binop17; binop9; binop16;
binop8; binop15; binop7; binop14; binop6;
binop13; binop5; binop12; binop4; binop11;
binop3; binop10; binop2; binop1] in
let subs11 = [binop19; binop11; binop18; binop10; binop17;
binop9; binop16; binop8; binop15; binop7;
binop14; binop6; binop13; binop5; binop12;
binop4; binop11; binop3; binop10; binop2;
binop1] in
let subs_set1 = of_list subs1 in
let subs_set2 = of_list subs2 in
let subs_set3 = of_list subs3 in
let subs_set4 = of_list subs4 in
let subs_set5 = of_list subs5 in
let subs_set6 = of_list subs6 in
let subs_set7 = of_list subs7 in
let subs_set8 = of_list subs8 in
let subs_set9 = of_list subs9 in
let subs_set10 = of_list subs10 in
let subs_set11 = of_list subs11 in
let _ = assert_true (equal (get_subexpr binop1) subs_set1) in
let _ = assert_true (equal (get_subexpr binop10) subs_set2) in
let _ = assert_true (equal (get_subexpr binop11) subs_set3) in
let _ = assert_true (equal (get_subexpr binop12) subs_set4) in
let _ = assert_true (equal (get_subexpr binop13) subs_set5) in
let _ = assert_true (equal (get_subexpr binop14) subs_set6) in
let _ = assert_true (equal (get_subexpr binop15) subs_set7) in
let _ = assert_true (equal (get_subexpr binop16) subs_set8) in
let _ = assert_true (equal (get_subexpr binop17) subs_set9) in
let _ = assert_true (equal (get_subexpr binop18) subs_set10) in
let _ = assert_true (equal (get_subexpr binop19) subs_set11) in
let call1 = Call (Name "dummy", [binop1]) in
let call10 = Call (Name "dummy", [binop10]) in
let call11 = Call (Name "dummy", [binop11]) in
let call12 = Call (Name "dummy", [binop12]) in
let call13 = Call (Name "dummy", [binop13]) in
let call14 = Call (Name "dummy", [binop14]) in
let call15 = Call (Name "dummy", [binop15]) in
let call16 = Call (Name "dummy", [binop16]) in
let call17 = Call (Name "dummy", [binop17]) in
let call18 = Call (Name "dummy", [binop18]) in
let call19 = Call (Name "dummy", [binop19]) in
let _ = assert_true (equal (get_subexpr call1) subs_set1) in
let _ = assert_true (equal (get_subexpr call10) subs_set2) in
let _ = assert_true (equal (get_subexpr call11) subs_set3) in
let _ = assert_true (equal (get_subexpr call12) subs_set4) in
let _ = assert_true (equal (get_subexpr call13) subs_set5) in
let _ = assert_true (equal (get_subexpr call14) subs_set6) in
let _ = assert_true (equal (get_subexpr call15) subs_set7) in
let _ = assert_true (equal (get_subexpr call16) subs_set8) in
let _ = assert_true (equal (get_subexpr call17) subs_set9) in
let _ = assert_true (equal (get_subexpr call18) subs_set10) in
let _ = assert_true (equal (get_subexpr call19) subs_set11) in
let mem1 = Mem (binop1, NORMAL) in
let mem10 = Mem (binop10, NORMAL) in
let mem11 = Mem (binop11, NORMAL) in
let mem12 = Mem (binop12, NORMAL) in
let mem13 = Mem (binop13, NORMAL) in
let mem14 = Mem (binop14, NORMAL) in
let mem15 = Mem (binop15, NORMAL) in
let mem16 = Mem (binop16, NORMAL) in
let mem17 = Mem (binop17, NORMAL) in
let mem18 = Mem (binop18, NORMAL) in
let mem19 = Mem (binop19, NORMAL) in
let mem20 = Mem (call1, NORMAL) in
let mem21 = Mem (call10, NORMAL) in
let mem22 = Mem (call11, NORMAL) in
let mem23 = Mem (call12, NORMAL) in
let mem24 = Mem (call13, NORMAL) in
let mem25 = Mem (call14, NORMAL) in
let mem26 = Mem (call15, NORMAL) in
let mem27 = Mem (call16, NORMAL) in
let mem28 = Mem (call17, NORMAL) in
let mem29 = Mem (call18, NORMAL) in
let mem30 = Mem (call19, NORMAL) in
let mem_subs1 = mem1 :: subs1 in
let mem_subs2 = mem10 :: subs2 in
let mem_subs3 = mem11 :: subs3 in
let mem_subs4 = mem12 :: subs4 in
let mem_subs5 = mem13 :: subs5 in
let mem_subs6 = mem14 :: subs6 in
let mem_subs7 = mem15 :: subs7 in
let mem_subs8 = mem16 :: subs8 in
let mem_subs9 = mem17 :: subs9 in
let mem_subs10 = mem18 :: subs10 in
let mem_subs11 = mem19 :: subs11 in
let mem_subs12 = mem20 :: subs1 in
let mem_subs13 = mem21 :: subs2 in
let mem_subs14 = mem22 :: subs3 in
let mem_subs15 = mem23 :: subs4 in
let mem_subs16 = mem24 :: subs5 in
let mem_subs17 = mem25 :: subs6 in
let mem_subs18 = mem26 :: subs7 in
let mem_subs19 = mem27 :: subs8 in
let mem_subs20 = mem28 :: subs9 in
let mem_subs21 = mem29 :: subs10 in
let mem_subs22 = mem30 :: subs11 in
let mem_subs_set1 = of_list mem_subs1 in
let mem_subs_set10 = of_list mem_subs2 in
let mem_subs_set11 = of_list mem_subs3 in
let mem_subs_set12 = of_list mem_subs4 in
let mem_subs_set13 = of_list mem_subs5 in
let mem_subs_set14 = of_list mem_subs6 in
let mem_subs_set15 = of_list mem_subs7 in
let mem_subs_set16 = of_list mem_subs8 in
let mem_subs_set17 = of_list mem_subs9 in
let mem_subs_set18 = of_list mem_subs10 in
let mem_subs_set19 = of_list mem_subs11 in
let mem_subs_set20 = of_list mem_subs12 in
let mem_subs_set21 = of_list mem_subs13 in
let mem_subs_set22 = of_list mem_subs14 in
let mem_subs_set23 = of_list mem_subs15 in
let mem_subs_set24 = of_list mem_subs16 in
let mem_subs_set25 = of_list mem_subs17 in
let mem_subs_set26 = of_list mem_subs18 in
let mem_subs_set27 = of_list mem_subs19 in
let mem_subs_set28 = of_list mem_subs20 in
let mem_subs_set29 = of_list mem_subs21 in
let mem_subs_set30 = of_list mem_subs22 in
let _ = assert_true (equal (get_subexpr mem1) mem_subs_set1) in
let _ = assert_true (equal (get_subexpr mem10) mem_subs_set10) in
let _ = assert_true (equal (get_subexpr mem11) mem_subs_set11) in
let _ = assert_true (equal (get_subexpr mem12) mem_subs_set12) in
let _ = assert_true (equal (get_subexpr mem13) mem_subs_set13) in
let _ = assert_true (equal (get_subexpr mem14) mem_subs_set14) in
let _ = assert_true (equal (get_subexpr mem15) mem_subs_set15) in
let _ = assert_true (equal (get_subexpr mem16) mem_subs_set16) in
let _ = assert_true (equal (get_subexpr mem17) mem_subs_set17) in
let _ = assert_true (equal (get_subexpr mem18) mem_subs_set18) in
let _ = assert_true (equal (get_subexpr mem19) mem_subs_set19) in
let _ = assert_true (equal (get_subexpr mem20) mem_subs_set20) in
let _ = assert_true (equal (get_subexpr mem21) mem_subs_set21) in
let _ = assert_true (equal (get_subexpr mem22) mem_subs_set22) in
let _ = assert_true (equal (get_subexpr mem23) mem_subs_set23) in
let _ = assert_true (equal (get_subexpr mem24) mem_subs_set24) in
let _ = assert_true (equal (get_subexpr mem25) mem_subs_set25) in
let _ = assert_true (equal (get_subexpr mem26) mem_subs_set26) in
let _ = assert_true (equal (get_subexpr mem27) mem_subs_set27) in
let _ = assert_true (equal (get_subexpr mem28) mem_subs_set28) in
let _ = assert_true (equal (get_subexpr mem29) mem_subs_set29) in
let _ = assert_true (equal (get_subexpr mem30) mem_subs_set30) in
let mem_binop1 = make_binop mem1 mem20 in
let mem_binop2 = make_binop mem10 mem21 in
let mem_binop3 = make_binop mem11 mem22 in
let mem_binop4 = make_binop mem12 mem23 in
let mem_binop5 = make_binop mem13 mem24 in
let mem_binop6 = make_binop mem14 mem25 in
let mem_binop7 = make_binop mem15 mem26 in
let mem_binop8 = make_binop mem16 mem27 in
let mem_binop9 = make_binop mem17 mem28 in
let mem_binop10 = make_binop mem18 mem29 in
let mem_binop11 = make_binop mem19 mem30 in
let mem_binop_subs1 = mem_binop1 :: (mem_subs1 @ mem_subs12) in
let mem_binop_subs2 = mem_binop2 :: (mem_subs2 @ mem_subs13) in
let mem_binop_subs3 = mem_binop3 :: (mem_subs3 @ mem_subs14) in
let mem_binop_subs4 = mem_binop4 :: (mem_subs4 @ mem_subs15) in
let mem_binop_subs5 = mem_binop5 :: (mem_subs5 @ mem_subs16) in
let mem_binop_subs6 = mem_binop6 :: (mem_subs6 @ mem_subs17) in
let mem_binop_subs7 = mem_binop7 :: (mem_subs7 @ mem_subs18) in
let mem_binop_subs8 = mem_binop8 :: (mem_subs8 @ mem_subs19) in
let mem_binop_subs9 = mem_binop9 :: (mem_subs9 @ mem_subs20) in
let mem_binop_subs10 = mem_binop10 :: (mem_subs10 @ mem_subs21) in
let mem_binop_subs11 = mem_binop11 :: (mem_subs11 @ mem_subs22) in
let mem_binop_subs_set1 = of_list mem_binop_subs1 in
let mem_binop_subs_set10 = of_list mem_binop_subs2 in
let mem_binop_subs_set11 = of_list mem_binop_subs3 in
let mem_binop_subs_set12 = of_list mem_binop_subs4 in
let mem_binop_subs_set13 = of_list mem_binop_subs5 in
let mem_binop_subs_set14 = of_list mem_binop_subs6 in
let mem_binop_subs_set15 = of_list mem_binop_subs7 in
let mem_binop_subs_set16 = of_list mem_binop_subs8 in
let mem_binop_subs_set17 = of_list mem_binop_subs9 in
let mem_binop_subs_set18 = of_list mem_binop_subs10 in
let mem_binop_subs_set19 = of_list mem_binop_subs11 in
let _ = assert_true (equal (get_subexpr mem_binop1) mem_binop_subs_set1) in
let _ = assert_true (equal (get_subexpr mem_binop2) mem_binop_subs_set10) in
let _ = assert_true (equal (get_subexpr mem_binop3) mem_binop_subs_set11) in
let _ = assert_true (equal (get_subexpr mem_binop4) mem_binop_subs_set12) in
let _ = assert_true (equal (get_subexpr mem_binop5) mem_binop_subs_set13) in
let _ = assert_true (equal (get_subexpr mem_binop6) mem_binop_subs_set14) in
let _ = assert_true (equal (get_subexpr mem_binop7) mem_binop_subs_set15) in
let _ = assert_true (equal (get_subexpr mem_binop8) mem_binop_subs_set16) in
let _ = assert_true (equal (get_subexpr mem_binop9) mem_binop_subs_set17) in
let _ = assert_true (equal (get_subexpr mem_binop10) mem_binop_subs_set18) in
let _ = assert_true (equal (get_subexpr mem_binop11) mem_binop_subs_set19) in
let temp1 = Temp "x" in
let _ = assert_true (equal (get_subexpr temp1) empty) in
let cjump1 = CJumpOne (binop1, "dummy") in
let cjump2 = CJumpOne (binop10, "dummy") in
let cjump3 = CJumpOne (binop11, "dummy") in
let cjump4 = CJumpOne (binop12, "dummy") in
let cjump5 = CJumpOne (binop13, "dummy") in
let cjump6 = CJumpOne (binop14, "dummy") in
let cjump7 = CJumpOne (binop15, "dummy") in
let cjump8 = CJumpOne (binop16, "dummy") in
let cjump9 = CJumpOne (binop17, "dummy") in
let cjump10 = CJumpOne (binop18, "dummy") in
let cjump11 = CJumpOne (binop19, "dummy") in
let cjump12 = CJumpOne (call1, "dummy") in
let cjump13 = CJumpOne (call10, "dummy") in
let cjump14 = CJumpOne (call11, "dummy") in
let cjump15 = CJumpOne (call12, "dummy") in
let cjump16 = CJumpOne (call13, "dummy") in
let cjump17 = CJumpOne (call14, "dummy") in
let cjump18 = CJumpOne (call15, "dummy") in
let cjump19 = CJumpOne (call16, "dummy") in
let cjump20 = CJumpOne (call17, "dummy") in
let cjump21 = CJumpOne (call18, "dummy") in
let cjump22 = CJumpOne (call19, "dummy") in
let cjump23 = CJumpOne (mem1, "dummy") in
let cjump24 = CJumpOne (mem10, "dummy") in
let cjump25 = CJumpOne (mem11, "dummy") in
let cjump26 = CJumpOne (mem12, "dummy") in
let cjump27 = CJumpOne (mem13, "dummy") in
let cjump28 = CJumpOne (mem14, "dummy") in
let cjump29 = CJumpOne (mem15, "dummy") in
let cjump30 = CJumpOne (mem16, "dummy") in
let cjump31 = CJumpOne (mem17, "dummy") in
let cjump32 = CJumpOne (mem18, "dummy") in
let cjump33 = CJumpOne (mem19, "dummy") in
let cjump34 = CJumpOne (mem20, "dummy") in
let cjump35 = CJumpOne (mem21, "dummy") in
let cjump36 = CJumpOne (mem22, "dummy") in
let cjump37 = CJumpOne (mem23, "dummy") in
let cjump38 = CJumpOne (mem24, "dummy") in
let cjump39 = CJumpOne (mem25, "dummy") in
let cjump40 = CJumpOne (mem26, "dummy") in
let cjump41 = CJumpOne (mem27, "dummy") in
let cjump42 = CJumpOne (mem28, "dummy") in
let cjump43 = CJumpOne (mem29, "dummy") in
let cjump44 = CJumpOne (mem30, "dummy") in
let cjump45 = CJumpOne (mem_binop1, "dummy") in
let cjump46 = CJumpOne (mem_binop2, "dummy") in
let cjump47 = CJumpOne (mem_binop3, "dummy") in
let cjump48 = CJumpOne (mem_binop4, "dummy") in
let cjump49 = CJumpOne (mem_binop5, "dummy") in
let cjump50 = CJumpOne (mem_binop6, "dummy") in
let cjump51 = CJumpOne (mem_binop7, "dummy") in
let cjump52 = CJumpOne (mem_binop8, "dummy") in
let cjump53 = CJumpOne (mem_binop9, "dummy") in
let cjump54 = CJumpOne (mem_binop10, "dummy") in
let cjump55 = CJumpOne (mem_binop11, "dummy") in
let _ = assert_true (equal (get_subexpr_stmt cjump1) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump2) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt cjump3) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt cjump4) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt cjump5) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt cjump6) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt cjump7) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt cjump8) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt cjump9) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt cjump10) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump11) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump12) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump13) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt cjump14) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt cjump15) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt cjump16) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt cjump17) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt cjump18) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt cjump19) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt cjump20) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt cjump21) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump22) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump23) mem_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump24) mem_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump25) mem_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump26) mem_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt cjump27) mem_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt cjump28) mem_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt cjump29) mem_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt cjump30) mem_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt cjump31) mem_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt cjump32) mem_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt cjump33) mem_subs_set19) in
let _ = assert_true (equal (get_subexpr_stmt cjump34) mem_subs_set20) in
let _ = assert_true (equal (get_subexpr_stmt cjump35) mem_subs_set21) in
let _ = assert_true (equal (get_subexpr_stmt cjump36) mem_subs_set22) in
let _ = assert_true (equal (get_subexpr_stmt cjump37) mem_subs_set23) in
let _ = assert_true (equal (get_subexpr_stmt cjump38) mem_subs_set24) in
let _ = assert_true (equal (get_subexpr_stmt cjump39) mem_subs_set25) in
let _ = assert_true (equal (get_subexpr_stmt cjump40) mem_subs_set26) in
let _ = assert_true (equal (get_subexpr_stmt cjump41) mem_subs_set27) in
let _ = assert_true (equal (get_subexpr_stmt cjump42) mem_subs_set28) in
let _ = assert_true (equal (get_subexpr_stmt cjump43) mem_subs_set29) in
let _ = assert_true (equal (get_subexpr_stmt cjump44) mem_subs_set30) in
let _ = assert_true (equal (get_subexpr_stmt cjump45) mem_binop_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt cjump46) mem_binop_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt cjump47) mem_binop_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt cjump48) mem_binop_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt cjump49) mem_binop_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt cjump50) mem_binop_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt cjump51) mem_binop_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt cjump52) mem_binop_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt cjump53) mem_binop_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt cjump54) mem_binop_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt cjump55) mem_binop_subs_set19) in
let move1 = Move (Temp "dummy", binop1) in
let move2 = Move (Temp "dummy", binop10) in
let move3 = Move (Temp "dummy", binop11) in
let move4 = Move (Temp "dummy", binop12) in
let move5 = Move (Temp "dummy", binop13) in
let move6 = Move (Temp "dummy", binop14) in
let move7 = Move (Temp "dummy", binop15) in
let move8 = Move (Temp "dummy", binop16) in
let move9 = Move (Temp "dummy", binop17) in
let move10 = Move (Temp "dummy", binop18) in
let move11 = Move (Temp "dummy", binop19) in
let move12 = Move (Temp "dummy", call1) in
let move13 = Move (Temp "dummy", call10) in
let move14 = Move (Temp "dummy", call11) in
let move15 = Move (Temp "dummy", call12) in
let move16 = Move (Temp "dummy", call13) in
let move17 = Move (Temp "dummy", call14) in
let move18 = Move (Temp "dummy", call15) in
let move19 = Move (Temp "dummy", call16) in
let move20 = Move (Temp "dummy", call17) in
let move21 = Move (Temp "dummy", call18) in
let move22 = Move (Temp "dummy", call19) in
let move23 = Move (Temp "dummy", mem1) in
let move24 = Move (Temp "dummy", mem10) in
let move25 = Move (Temp "dummy", mem11) in
let move26 = Move (Temp "dummy", mem12) in
let move27 = Move (Temp "dummy", mem13) in
let move28 = Move (Temp "dummy", mem14) in
let move29 = Move (Temp "dummy", mem15) in
let move30 = Move (Temp "dummy", mem16) in
let move31 = Move (Temp "dummy", mem17) in
let move32 = Move (Temp "dummy", mem18) in
let move33 = Move (Temp "dummy", mem19) in
let move34 = Move (Temp "dummy", mem20) in
let move35 = Move (Temp "dummy", mem21) in
let move36 = Move (Temp "dummy", mem22) in
let move37 = Move (Temp "dummy", mem23) in
let move38 = Move (Temp "dummy", mem24) in
let move39 = Move (Temp "dummy", mem25) in
let move40 = Move (Temp "dummy", mem26) in
let move41 = Move (Temp "dummy", mem27) in
let move42 = Move (Temp "dummy", mem28) in
let move43 = Move (Temp "dummy", mem29) in
let move44 = Move (Temp "dummy", mem30) in
let move45 = Move (Temp "dummy", mem_binop1) in
let move46 = Move (Temp "dummy", mem_binop2) in
let move47 = Move (Temp "dummy", mem_binop3) in
let move48 = Move (Temp "dummy", mem_binop4) in
let move49 = Move (Temp "dummy", mem_binop5) in
let move50 = Move (Temp "dummy", mem_binop6) in
let move51 = Move (Temp "dummy", mem_binop7) in
let move52 = Move (Temp "dummy", mem_binop8) in
let move53 = Move (Temp "dummy", mem_binop9) in
let move54 = Move (Temp "dummy", mem_binop10) in
let move55 = Move (Temp "dummy", mem_binop11) in
let move56 = Move (mem1, binop1) in
let move57 = Move (mem1, binop10) in
let move58 = Move (mem1, binop11) in
let move59 = Move (mem1, binop12) in
let move60 = Move (mem1, binop13) in
let move61 = Move (mem1, binop14) in
let move62 = Move (mem1, binop15) in
let move63 = Move (mem1, binop16) in
let move64 = Move (mem1, binop17) in
let move65 = Move (mem1, binop18) in
let move66 = Move (mem1, binop19) in
let move67 = Move (mem1, call1) in
let move68 = Move (mem1, call10) in
let move69 = Move (mem1, call11) in
let move70 = Move (mem1, call12) in
let move71 = Move (mem1, call13) in
let move72 = Move (mem1, call14) in
let move73 = Move (mem1, call15) in
let move74 = Move (mem1, call16) in
let move75 = Move (mem1, call17) in
let move76 = Move (mem1, call18) in
let move77 = Move (mem1, call19) in
let move78 = Move (mem1, mem1) in
let move79 = Move (mem1, mem10) in
let move80 = Move (mem1, mem11) in
let move81 = Move (mem1, mem12) in
let move82 = Move (mem1, mem13) in
let move83 = Move (mem1, mem14) in
let move84 = Move (mem1, mem15) in
let move85 = Move (mem1, mem16) in
let move86 = Move (mem1, mem17) in
let move87 = Move (mem1, mem18) in
let move88 = Move (mem1, mem19) in
let move89 = Move (mem1, mem20) in
let move90 = Move (mem1, mem21) in
let move91 = Move (mem1, mem22) in
let move92 = Move (mem1, mem23) in
let move93 = Move (mem1, mem24) in
let move94 = Move (mem1, mem25) in
let move95 = Move (mem1, mem26) in
let move96 = Move (mem1, mem27) in
let move97 = Move (mem1, mem28) in
let move98 = Move (mem1, mem29) in
let move99 = Move (mem1, mem30) in
let move100 = Move (mem1, mem_binop1) in
let move101 = Move (mem1, mem_binop2) in
let move102 = Move (mem1, mem_binop3) in
let move103 = Move (mem1, mem_binop4) in
let move104 = Move (mem1, mem_binop5) in
let move105 = Move (mem1, mem_binop6) in
let move106 = Move (mem1, mem_binop7) in
let move107 = Move (mem1, mem_binop8) in
let move108 = Move (mem1, mem_binop9) in
let move109 = Move (mem1, mem_binop10) in
let move110 = Move (mem1, mem_binop11) in
let move_mem1 = mem1 :: subs1 in
let move_mem2 = mem1 :: subs2 in
let move_mem3 = mem1 :: subs3 in
let move_mem4 = mem1 :: subs4 in
let move_mem5 = mem1 :: subs5 in
let move_mem6 = mem1 :: subs6 in
let move_mem7 = mem1 :: subs7 in
let move_mem8 = mem1 :: subs8 in
let move_mem9 = mem1 :: subs9 in
let move_mem10 = mem1 :: subs10 in
let move_mem11 = mem1 :: subs11 in
let move_mem12 = mem1 :: subs1 in
let move_mem13 = mem1 :: subs2 in
let move_mem14 = mem1 :: subs3 in
let move_mem15 = mem1 :: subs4 in
let move_mem16 = mem1 :: subs5 in
let move_mem17 = mem1 :: subs6 in
let move_mem18 = mem1 :: subs7 in
let move_mem19 = mem1 :: subs8 in
let move_mem20 = mem1 :: subs9 in
let move_mem21 = mem1 :: subs10 in
let move_mem22 = mem1 :: subs11 in
let move_mem23 = mem1 :: mem_subs1 in
let move_mem24 = mem1 :: mem_subs2 in
let move_mem25 = mem1 :: mem_subs3 in
let move_mem26 = mem1 :: mem_subs4 in
let move_mem27 = mem1 :: mem_subs5 in
let move_mem28 = mem1 :: mem_subs6 in
let move_mem29 = mem1 :: mem_subs7 in
let move_mem30 = mem1 :: mem_subs8 in
let move_mem31 = mem1 :: mem_subs9 in
let move_mem32 = mem1 :: mem_subs10 in
let move_mem33 = mem1 :: mem_subs11 in
let move_mem34 = mem1 :: mem_subs12 in
let move_mem35 = mem1 :: mem_subs13 in
let move_mem36 = mem1 :: mem_subs14 in
let move_mem37 = mem1 :: mem_subs15 in
let move_mem38 = mem1 :: mem_subs16 in
let move_mem39 = mem1 :: mem_subs17 in
let move_mem40 = mem1 :: mem_subs18 in
let move_mem41 = mem1 :: mem_subs19 in
let move_mem42 = mem1 :: mem_subs20 in
let move_mem43 = mem1 :: mem_subs21 in
let move_mem44 = mem1 :: mem_subs22 in
let move_mem45 = mem1 :: mem_binop_subs1 in
let move_mem46 = mem1 :: mem_binop_subs2 in
let move_mem47 = mem1 :: mem_binop_subs3 in
let move_mem48 = mem1 :: mem_binop_subs4 in
let move_mem49 = mem1 :: mem_binop_subs5 in
let move_mem50 = mem1 :: mem_binop_subs6 in
let move_mem51 = mem1 :: mem_binop_subs7 in
let move_mem52 = mem1 :: mem_binop_subs8 in
let move_mem53 = mem1 :: mem_binop_subs9 in
let move_mem54 = mem1 :: mem_binop_subs10 in
let move_mem55 = mem1 :: mem_binop_subs11 in
let move_mem_subs1 = of_list move_mem1 in
let move_mem_subs2 = of_list move_mem2 in
let move_mem_subs3 = of_list move_mem3 in
let move_mem_subs4 = of_list move_mem4 in
let move_mem_subs5 = of_list move_mem5 in
let move_mem_subs6 = of_list move_mem6 in
let move_mem_subs7 = of_list move_mem7 in
let move_mem_subs8 = of_list move_mem8 in
let move_mem_subs9 = of_list move_mem9 in
let move_mem_subs10 = of_list move_mem10 in
let move_mem_subs11 = of_list move_mem11 in
let move_mem_subs12 = of_list move_mem12 in
let move_mem_subs13 = of_list move_mem13 in
let move_mem_subs14 = of_list move_mem14 in
let move_mem_subs15 = of_list move_mem15 in
let move_mem_subs16 = of_list move_mem16 in
let move_mem_subs17 = of_list move_mem17 in
let move_mem_subs18 = of_list move_mem18 in
let move_mem_subs19 = of_list move_mem19 in
let move_mem_subs20 = of_list move_mem20 in
let move_mem_subs21 = of_list move_mem21 in
let move_mem_subs22 = of_list move_mem22 in
let move_mem_subs23 = of_list move_mem23 in
let move_mem_subs24 = of_list move_mem24 in
let move_mem_subs25 = of_list move_mem25 in
let move_mem_subs26 = of_list move_mem26 in
let move_mem_subs27 = of_list move_mem27 in
let move_mem_subs28 = of_list move_mem28 in
let move_mem_subs29 = of_list move_mem29 in
let move_mem_subs30 = of_list move_mem30 in
let move_mem_subs31 = of_list move_mem31 in
let move_mem_subs32 = of_list move_mem32 in
let move_mem_subs33 = of_list move_mem33 in
let move_mem_subs34 = of_list move_mem34 in
let move_mem_subs35 = of_list move_mem35 in
let move_mem_subs36 = of_list move_mem36 in
let move_mem_subs37 = of_list move_mem37 in
let move_mem_subs38 = of_list move_mem38 in
let move_mem_subs39 = of_list move_mem39 in
let move_mem_subs40 = of_list move_mem40 in
let move_mem_subs41 = of_list move_mem41 in
let move_mem_subs42 = of_list move_mem42 in
let move_mem_subs43 = of_list move_mem43 in
let move_mem_subs44 = of_list move_mem44 in
let move_mem_subs45 = of_list move_mem45 in
let move_mem_subs46 = of_list move_mem46 in
let move_mem_subs47 = of_list move_mem47 in
let move_mem_subs48 = of_list move_mem48 in
let move_mem_subs49 = of_list move_mem49 in
let move_mem_subs50 = of_list move_mem50 in
let move_mem_subs51 = of_list move_mem51 in
let move_mem_subs52 = of_list move_mem52 in
let move_mem_subs53 = of_list move_mem53 in
let move_mem_subs54 = of_list move_mem54 in
let move_mem_subs55 = of_list move_mem55 in
let _ = assert_true (equal (get_subexpr_stmt move1) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move2) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt move3) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt move4) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt move5) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt move6) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt move7) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt move8) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt move9) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt move10) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move11) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move12) subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move13) subs_set2) in
let _ = assert_true (equal (get_subexpr_stmt move14) subs_set3) in
let _ = assert_true (equal (get_subexpr_stmt move15) subs_set4) in
let _ = assert_true (equal (get_subexpr_stmt move16) subs_set5) in
let _ = assert_true (equal (get_subexpr_stmt move17) subs_set6) in
let _ = assert_true (equal (get_subexpr_stmt move18) subs_set7) in
let _ = assert_true (equal (get_subexpr_stmt move19) subs_set8) in
let _ = assert_true (equal (get_subexpr_stmt move20) subs_set9) in
let _ = assert_true (equal (get_subexpr_stmt move21) subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move22) subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move23) mem_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move24) mem_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move25) mem_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move26) mem_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt move27) mem_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt move28) mem_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt move29) mem_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt move30) mem_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt move31) mem_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt move32) mem_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt move33) mem_subs_set19) in
let _ = assert_true (equal (get_subexpr_stmt move34) mem_subs_set20) in
let _ = assert_true (equal (get_subexpr_stmt move35) mem_subs_set21) in
let _ = assert_true (equal (get_subexpr_stmt move36) mem_subs_set22) in
let _ = assert_true (equal (get_subexpr_stmt move37) mem_subs_set23) in
let _ = assert_true (equal (get_subexpr_stmt move38) mem_subs_set24) in
let _ = assert_true (equal (get_subexpr_stmt move39) mem_subs_set25) in
let _ = assert_true (equal (get_subexpr_stmt move40) mem_subs_set26) in
let _ = assert_true (equal (get_subexpr_stmt move41) mem_subs_set27) in
let _ = assert_true (equal (get_subexpr_stmt move42) mem_subs_set28) in
let _ = assert_true (equal (get_subexpr_stmt move43) mem_subs_set29) in
let _ = assert_true (equal (get_subexpr_stmt move44) mem_subs_set30) in
let _ = assert_true (equal (get_subexpr_stmt move45) mem_binop_subs_set1) in
let _ = assert_true (equal (get_subexpr_stmt move46) mem_binop_subs_set10) in
let _ = assert_true (equal (get_subexpr_stmt move47) mem_binop_subs_set11) in
let _ = assert_true (equal (get_subexpr_stmt move48) mem_binop_subs_set12) in
let _ = assert_true (equal (get_subexpr_stmt move49) mem_binop_subs_set13) in
let _ = assert_true (equal (get_subexpr_stmt move50) mem_binop_subs_set14) in
let _ = assert_true (equal (get_subexpr_stmt move51) mem_binop_subs_set15) in
let _ = assert_true (equal (get_subexpr_stmt move52) mem_binop_subs_set16) in
let _ = assert_true (equal (get_subexpr_stmt move53) mem_binop_subs_set17) in
let _ = assert_true (equal (get_subexpr_stmt move54) mem_binop_subs_set18) in
let _ = assert_true (equal (get_subexpr_stmt move55) mem_binop_subs_set19) in
let _ = assert_true (equal (get_subexpr_stmt move56) move_mem_subs1) in
let _ = assert_true (equal (get_subexpr_stmt move57) move_mem_subs2) in
let _ = assert_true (equal (get_subexpr_stmt move58) move_mem_subs3) in
let _ = assert_true (equal (get_subexpr_stmt move59) move_mem_subs4) in
let _ = assert_true (equal (get_subexpr_stmt move60) move_mem_subs5) in
let _ = assert_true (equal (get_subexpr_stmt move61) move_mem_subs6) in
let _ = assert_true (equal (get_subexpr_stmt move62) move_mem_subs7) in
let _ = assert_true (equal (get_subexpr_stmt move63) move_mem_subs8) in
let _ = assert_true (equal (get_subexpr_stmt move64) move_mem_subs9) in
let _ = assert_true (equal (get_subexpr_stmt move65) move_mem_subs10) in
let _ = assert_true (equal (get_subexpr_stmt move66) move_mem_subs11) in
let _ = assert_true (equal (get_subexpr_stmt move67) move_mem_subs12) in
let _ = assert_true (equal (get_subexpr_stmt move68) move_mem_subs13) in
let _ = assert_true (equal (get_subexpr_stmt move69) move_mem_subs14) in
let _ = assert_true (equal (get_subexpr_stmt move70) move_mem_subs15) in
let _ = assert_true (equal (get_subexpr_stmt move71) move_mem_subs16) in
let _ = assert_true (equal (get_subexpr_stmt move72) move_mem_subs17) in
let _ = assert_true (equal (get_subexpr_stmt move73) move_mem_subs18) in
let _ = assert_true (equal (get_subexpr_stmt move74) move_mem_subs19) in
let _ = assert_true (equal (get_subexpr_stmt move75) move_mem_subs20) in
let _ = assert_true (equal (get_subexpr_stmt move76) move_mem_subs21) in
let _ = assert_true (equal (get_subexpr_stmt move77) move_mem_subs22) in
let _ = assert_true (equal (get_subexpr_stmt move78) move_mem_subs23) in
let _ = assert_true (equal (get_subexpr_stmt move79) move_mem_subs24) in
let _ = assert_true (equal (get_subexpr_stmt move80) move_mem_subs25) in
let _ = assert_true (equal (get_subexpr_stmt move81) move_mem_subs26) in
let _ = assert_true (equal (get_subexpr_stmt move82) move_mem_subs27) in
let _ = assert_true (equal (get_subexpr_stmt move83) move_mem_subs28) in
let _ = assert_true (equal (get_subexpr_stmt move84) move_mem_subs29) in
let _ = assert_true (equal (get_subexpr_stmt move85) move_mem_subs30) in
let _ = assert_true (equal (get_subexpr_stmt move86) move_mem_subs31) in
let _ = assert_true (equal (get_subexpr_stmt move87) move_mem_subs32) in
let _ = assert_true (equal (get_subexpr_stmt move88) move_mem_subs33) in
let _ = assert_true (equal (get_subexpr_stmt move89) move_mem_subs34) in
let _ = assert_true (equal (get_subexpr_stmt move90) move_mem_subs35) in
let _ = assert_true (equal (get_subexpr_stmt move91) move_mem_subs36) in
let _ = assert_true (equal (get_subexpr_stmt move92) move_mem_subs37) in
let _ = assert_true (equal (get_subexpr_stmt move93) move_mem_subs38) in
let _ = assert_true (equal (get_subexpr_stmt move94) move_mem_subs39) in
let _ = assert_true (equal (get_subexpr_stmt move95) move_mem_subs40) in
let _ = assert_true (equal (get_subexpr_stmt move96) move_mem_subs41) in
let _ = assert_true (equal (get_subexpr_stmt move97) move_mem_subs42) in
let _ = assert_true (equal (get_subexpr_stmt move98) move_mem_subs43) in
let _ = assert_true (equal (get_subexpr_stmt move99) move_mem_subs44) in
let _ = assert_true (equal (get_subexpr_stmt move100) move_mem_subs45) in
let _ = assert_true (equal (get_subexpr_stmt move101) move_mem_subs46) in
let _ = assert_true (equal (get_subexpr_stmt move102) move_mem_subs47) in
let _ = assert_true (equal (get_subexpr_stmt move103) move_mem_subs48) in
let _ = assert_true (equal (get_subexpr_stmt move104) move_mem_subs49) in
let _ = assert_true (equal (get_subexpr_stmt move105) move_mem_subs50) in
let _ = assert_true (equal (get_subexpr_stmt move106) move_mem_subs51) in
let _ = assert_true (equal (get_subexpr_stmt move107) move_mem_subs52) in
let _ = assert_true (equal (get_subexpr_stmt move108) move_mem_subs53) in
let _ = assert_true (equal (get_subexpr_stmt move109) move_mem_subs54) in
let _ = assert_true (equal (get_subexpr_stmt move110) move_mem_subs55) in
let jump1 = Jump (Name "dummy") in
let label1 = Label "dummy" in
let return1 = Return in
let _ = assert_true (equal (get_subexpr_stmt jump1) empty) in
let _ = assert_true (equal (get_subexpr_stmt label1) empty) in
let _ = assert_true (equal (get_subexpr_stmt return1) empty) in
()
let preprocess_test _ =
let open Ir.Abbreviations in
let open Cfg.IrData in
let open Cfg.IrDataStartExit in
let open IrCfgEq in
let test input_vs input_es expected_vs expected_es =
let input = make_graph input_vs input_es in
let expected = make_graph expected_vs expected_es in
Pre.preprocess input;
expected === input
in
let norm = Cfg.EdgeData.Normal in
let ir0 = move (temp "ir0") (zero) in
let ir1 = move (temp "ir1") (one) in
let ir2 = move (temp "ir2") (two) in
let ir3 = move (temp "ir3") (three) in
let ir4 = move (temp "ir4") (four) in
let ir5 = move (temp "ir5") (five) in
let ir6 = move (temp "ir6") (six) in
let n0 = Cfg.IrCfg.V.create (Node {num=0; ir=ir0}) in
let n1 = Cfg.IrCfg.V.create (Node {num=1; ir=ir1}) in
let n2 = Cfg.IrCfg.V.create (Node {num=2; ir=ir2}) in
let n3 = Cfg.IrCfg.V.create (Node {num=3; ir=ir3}) in
let n4 = Cfg.IrCfg.V.create (Node {num=4; ir=ir4}) in
let n5 = Cfg.IrCfg.V.create (Node {num=5; ir=ir5}) in
let n6 = Cfg.IrCfg.V.create (Node {num=6; ir=ir6}) in
let d3 = Cfg.IrCfg.V.create (Node {num=3; ir=Pre.dummy_ir}) in
let d4 = Cfg.IrCfg.V.create (Node {num=4; ir=Pre.dummy_ir}) in
let d5 = Cfg.IrCfg.V.create (Node {num=5; ir=Pre.dummy_ir}) in
let d6 = Cfg.IrCfg.V.create (Node {num=6; ir=Pre.dummy_ir}) in
let d7 = Cfg.IrCfg.V.create (Node {num=7; ir=Pre.dummy_ir}) in
let d8 = Cfg.IrCfg.V.create (Node {num=8; ir=Pre.dummy_ir}) in
let d9 = Cfg.IrCfg.V.create (Node {num=9; ir=Pre.dummy_ir}) in
let d10 = Cfg.IrCfg.V.create (Node {num=10; ir=Pre.dummy_ir}) in
let ivs = [n0; n1] in
let ies = [(n0, norm, n1)] in
let evs = ivs in
let ees = ies in
test ivs ies evs ees;
let ivs = [n0; n1; n2] in
let ies = [(n0, norm, n2); (n1, norm, n2)] in
let evs = ivs @ [d3; d4] in
let ees = [
(n0, norm, d3); (d3, norm, n2);
(n1, norm, d4); (d4, norm, n2);
] in
test ivs ies evs ees;
let ivs = [n0; n1; n2] in
let ies = [(n0, norm, n1); (n0, norm, n2)] in
let evs = ivs in
let ees = ies in
test ivs ies evs ees;
let ivs = [n0; n1; n2; n3] in
let ies = [(n0, norm, n3); (n1, norm, n3); (n2, norm, n3)] in
let evs = ivs @ [d4; d5; d6] in
let ees = [
(n0, norm, d4); (d4, norm, n3);
(n1, norm, d5); (d5, norm, n3);
(n2, norm, d6); (d6, norm, n3);
] in
test ivs ies evs ees;
let ivs = [n0; n1; n2; n3; n4; n5; n6] in
let ies = [
(n0, norm, n1);
(n0, norm, n2);
(n1, norm, n3);
(n2, norm, n3);
(n3, norm, n4);
(n3, norm, n5);
(n4, norm, n6);
(n5, norm, n6);
] in
let evs = ivs @ [d7; d8; d9; d10] in
let ees = [
(n0, norm, n1);
(n0, norm, n2);
(n1, norm, d7); (d7, norm, n3);
(n2, norm, d8); (d8, norm, n3);
(n3, norm, n4);
(n3, norm, n5);
(n4, norm, d9); (d9, norm, n6);
(n5, norm, d10); (d10, norm, n6);
] in
test ivs ies evs ees;
()
module BookExample = struct
open Ir.Abbreviations
open Ir.Infix
module C = Cfg.IrCfg
module D = Cfg.IrData
module SE = Cfg.IrDataStartExit
module E = Pre.ExprSet
let tru = Cfg.EdgeData.True
let fls = Cfg.EdgeData.False
let start = C.V.create SE.Start
let exit = C.V.create SE.Exit
let norm = Cfg.EdgeData.Normal
let node num ir = C.V.create (SE.Node D.{num; ir})
let n1 = node 1 (label "node1")
let n2 = node 2 (move (temp "c") two)
let n3 = node 3 (label "node3")
let n4 = node 4 (label "node4")
let n5 = node 5 (move (temp "a") (temp "b" + temp "c"))
let n6 = node 6 (label "node6")
let n7 = node 7 (move (temp "d") (temp "b" + temp "c"))
let n8 = node 8 (label "node8")
let n9 = node 9 (move (temp "e") (temp "b" + temp "c"))
let n10 = node 10 (label "node10")
let n11 = node 11 (label "node11")
let vs = [start; n1; n2; n3; n4; n5; n6; n7; n8; n9; n10; n11; exit]
let es_1 = (start, norm, n1)
let e1_2 = (n1, fls, n2)
let e2_3 = (n2, norm, n3)
let e3_4 = (n3, norm, n4)
let e4_7 = (n4, norm, n7)
let e1_5 = (n1, tru, n5)
let e5_6 = (n5, norm, n6)
let e6_7 = (n6, norm, n7)
let e7_8 = (n7, norm, n8)
let e8_9 = (n8, fls, n9)
let e9_10 = (n9, norm, n10)
let e10_11 = (n10, tru, n11)
let e11_e = (n11, norm, exit)
let e8_11 = (n8, tru, n11)
let e10_9 = (n10, fls, n9)
let es = [
es_1; e1_2; e2_3; e3_4; e4_7; e1_5; e5_6; e6_7; e7_8; e8_9; e9_10; e10_11;
e11_e; e8_11; e10_9;
]
let g = make_graph vs es
let univ = E.of_list [temp "b" + temp "c"]
let uses = fun v ->
match v with
| SE.Start
| SE.Exit -> E.empty
| SE.Node _ when List.mem ~equal:C.V.equal [n5; n7; n9] v ->
E.of_list [temp "b" + temp "c"]
| SE.Node _ -> E.empty
let kills = fun v ->
if List.mem ~equal:C.V.equal [n2] v
then E.singleton (temp "b" + temp "c")
else E.empty
let busy = fun v ->
if List.mem ~equal:C.V.equal [n5; n6; n3; n4; n7; n9] v
then E.singleton (temp "b" + temp "c")
else E.empty
let earliest = fun v ->
if List.mem ~equal:C.V.equal [n3; n5] v
then E.singleton (temp "b" + temp "c")
else E.empty
let latest = fun v ->
if List.mem ~equal:C.V.equal [n4; n5] v
then E.singleton (temp "b" + temp "c")
else E.empty
end
let busy_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
let test expected edges g univ uses kills =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.BusyExpr.worklist BusyExprCFG.{g; univ; uses; kills} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
let start = C.V.create SE.Start in
let exit = C.V.create SE.Exit in
let norm = Cfg.EdgeData.Normal in
let n0 = C.V.create (SE.Node D.{num=0; ir=(move (temp "x") (one + two))}) in
let vs = [start; n0; exit] in
let e0 = (start, norm, n0) in
let e1 = (n0, norm, exit) in
let es = [(start, norm, n0); (n0, norm, exit)] in
let g = make_graph vs es in
let univ = E.of_list [one + two] in
let uses = function
| SE.Start | SE.Exit -> E.empty
| SE.Node _ -> E.of_list [one + two]
in
let kills = fun _ -> E.empty in
let expected = [
(e0, E.of_list [one + two]);
(e1, E.empty);
] in
test expected es g univ uses kills;
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, bc);
(e3_4, bc);
(e4_7, bc);
(e1_5, bc);
(e5_6, bc);
(e6_7, bc);
(e7_8, E.empty);
(e8_9, bc);
(e9_10, E.empty);
(e10_11, E.empty);
(e11_e, E.empty);
(e8_11, E.empty);
(e10_9, bc);
] in
test expected es g univ uses kills;
()
let avail_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
let test expected edges g univ busy kills =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.AvailExpr.worklist AvailExprCFG.{g; univ; busy; kills} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, E.empty);
(e3_4, bc);
(e4_7, bc);
(e1_5, E.empty);
(e5_6, bc);
(e6_7, bc);
(e7_8, bc);
(e8_9, bc);
(e9_10, bc);
(e10_11, bc);
(e11_e, bc);
(e8_11, bc);
(e10_9, bc);
] in
test expected es g univ busy kills;
()
let post_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
let test expected edges g univ uses earliest =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.PostponeExpr.worklist PostponeExprCFG.{g; univ; uses; earliest} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, E.empty);
(e3_4, bc);
(e4_7, bc);
(e1_5, E.empty);
(e5_6, E.empty);
(e6_7, E.empty);
(e7_8, E.empty);
(e8_9, E.empty);
(e9_10, E.empty);
(e10_11, E.empty);
(e11_e, E.empty);
(e8_11, E.empty);
(e10_9, E.empty);
] in
test expected es g univ uses earliest;
()
let used_test _ =
let open Ir.Abbreviations in
let open Ir.Infix in
let module C = Cfg.IrCfg in
let module D = Cfg.IrData in
let module SE = Cfg.IrDataStartExit in
let module E = Pre.ExprSet in
let test expected edges g uses latest =
let open EdgeToExprEq in
let make_edge (src, l, dst) = C.E.create src l dst in
let edges = List.map edges ~f:make_edge in
let expected = List.map expected ~f:(fun (edge, expr) -> (make_edge edge, expr)) in
let actual = Pre.UsedExpr.worklist UsedExprCFG.{uses; latest} g in
expected === List.map edges ~f:(fun edge -> (edge, actual edge))
in
let open BookExample in
let bc = E.singleton (temp "b" + temp "c") in
let expected = [
(es_1, E.empty);
(e1_2, E.empty);
(e2_3, E.empty);
(e3_4, E.empty);
(e4_7, bc);
(e1_5, E.empty);
(e5_6, bc);
(e6_7, bc);
(e7_8, bc);
(e8_9, bc);
(e9_10, bc);
(e10_11, E.empty);
(e11_e, E.empty);
(e8_11, E.empty);
(e10_9, bc);
] in
test expected es g uses latest;
()
let enchilada_test _ =
let open StmtsEq in
let open Ir.Abbreviations in
let open Ir.Infix in
let a = temp "a" in
let b = temp "b" in
let c = temp "c" in
let d = temp "d" in
let e = temp "e" in
let irs = [
B5
B5
B8
B9
B9
B10
B11
] in
Ir_generation.FreshTemp.reset();
Fresh.FreshLabel.reset();
let t = Ir.Temp (Ir_generation.FreshTemp.gen 0) in
let expected = [
B5
B5
B5
B8
B9
B9
B10
B11
] in
expected === Pre.pre irs;
()
let main () =
"suite" >::: [
"get_subexpr_test" >:: get_subexpr_test;
"preprocess_test" >:: preprocess_test;
"busy_test" >:: busy_test;
"avail_test" >:: avail_test;
"post_test" >:: post_test;
"used_test" >:: used_test;
"enchilada_test" >:: enchilada_test;
] |> run_test_tt_main
let _ = main ()
|
21d50d05299c24f6c87ce10c2b3258b8e8d7cba93d6559f1b39eac62b7b7ccf6 | clojure-dus/chess | moves.clj | (ns chess.movelogic.bitboard.moves
(:use [chess.movelogic.bitboard bitoperations file-rank chessboard piece-attacks])
(:use [clojure.pprint]))
(require '[clojure.core.reducers :as r])
(comment (set! *warn-on-reflection* true))
(defn attacked-by-black? [mask-sq game-state]
"looks at squares set in mask-sq and returns true if black attacks any of these squares"
(some-bitmap (fn [sq]
(or (bit-and? (:p game-state) (aget ^longs pawn-white-attack-array sq))
(bit-and? (:k game-state) (aget ^longs king-attack-array sq))
(bit-and? (:n game-state) (aget ^longs knight-attack-array sq))
(bit-and? (bit-or (:r game-state) (:q game-state))
(get-attack-rank game-state sq))
(bit-and? (bit-or (:r game-state) (:q game-state))
(get-attack-file game-state sq))
(bit-and? (bit-or (:b game-state) (:q game-state))
(get-attack-diagonal-a1h8 game-state sq))
(bit-and? (bit-or (:b game-state) (:q game-state))
(get-attack-diagonal-a8h1 game-state sq)))) mask-sq))
(defn attacked-by-white? [mask-sq game-state]
"looks at squares set in mask-sq and returns true if white attacks any of these squares"
(some-bitmap (fn [sq]
(or (bit-and? (:P game-state) (aget ^longs pawn-black-attack-array sq))
(bit-and? (:K game-state) (aget ^longs king-attack-array sq))
(bit-and? (:N game-state) (aget ^longs knight-attack-array sq))
(bit-and? (bit-or (:R game-state) (:Q game-state))
(get-attack-rank game-state sq))
(bit-and? (bit-or (:R game-state) (:Q game-state))
(get-attack-file game-state sq))
(bit-and? (bit-or (:B game-state) (:Q game-state))
(get-attack-diagonal-a1h8 game-state sq))
(bit-and? (bit-or (:B game-state) (:Q game-state))
(get-attack-diagonal-a8h1 game-state sq)))) mask-sq))
(defn check? [game-state]
(if (= :w (:turn game-state))
(attacked-by-black? (:K game-state) game-state)
(attacked-by-white? (:k game-state) game-state)))
(defmulti find-piece-moves (fn[piece _ _]
(case piece
(:N :n) :Knight
(:R :r) :Rook
(:B :b) :Bishop
(:Q :q) :Queen
:K :WhiteKing
:k :BlackKing
:P :WhitePawn
:p :BlackPawn)))
(defmethod find-piece-moves :Knight [piece game-state from-sq]
(let [piece-move-bitset (aget ^longs knight-attack-array from-sq)
not-occupied-squares (bit-not (pieces-by-turn game-state))]
(bit-and piece-move-bitset not-occupied-squares)))
(defmethod find-piece-moves :WhitePawn [piece game-state from-sq]
(let [moves (aget ^longs pawn-white-move-array from-sq)
all-pieces (:allpieces game-state)
occupied (bit-and all-pieces moves)
moves (bit-xor moves occupied)
double-moves (aget ^longs pawn-white-double-move-array from-sq)
occupied-4-row (bit-and all-pieces double-moves)
occupied-3-row (bit-and (bit-shift-left all-pieces 8) double-moves)
double-moves (bit-xor double-moves (bit-or occupied-3-row occupied-4-row))
attacks (bit-and (:blackpieces game-state)
(aget ^longs pawn-white-attack-array from-sq))]
(bit-or moves double-moves attacks)))
(defmethod find-piece-moves :BlackPawn [piece game-state from-sq]
(let [moves (aget ^longs pawn-black-move-array from-sq)
all-pieces (:allpieces game-state)
occupied (bit-and all-pieces moves)
moves (bit-xor moves occupied)
double-moves (aget ^longs pawn-black-double-move-array from-sq)
occupied-5-row (bit-and all-pieces double-moves)
occupied-6-row (bit-and (bit-shift-right all-pieces 8) double-moves)
double-moves (bit-xor double-moves (bit-or occupied-5-row occupied-6-row))
attacks (bit-and (:whitepieces game-state)
(aget ^longs pawn-black-attack-array from-sq))]
(bit-or moves double-moves attacks)))
(defn ^Long get-rochade-moves [game-state kind]
(let [rochade (:rochade game-state )
occupied (pieces-by-turn game-state)]
(condp = kind
:K (if (and (:K rochade)
(not (bit-and? mask-rochade-white-king occupied))
(not (attacked-by-black? mask-rochade-white-king game-state)))
move-rochade-white-king 0)
:Q (if (and (:Q rochade)
(not (bit-and? mask-rochade-white-queen occupied))
(not (attacked-by-black? mask-rochade-white-queen game-state)))
move-rochade-white-queen 0)
:k (if (and (:k rochade)
(not (bit-and? mask-rochade-black-king occupied))
(not (attacked-by-white? mask-rochade-black-king game-state)))
move-rochade-black-king 0)
:q (if (and (:q rochade)
(not (bit-and? mask-rochade-black-queen occupied))
(not (attacked-by-white? mask-rochade-black-queen game-state)))
move-rochade-black-queen 0))))
(defmethod find-piece-moves :WhiteKing [piece game-state from-sq]
(let [moves (aget ^longs king-attack-array from-sq)
occupied (pieces-by-turn game-state)
not-occupied (bit-not occupied)
moves (bit-and moves not-occupied)]
(bit-or moves
(get-rochade-moves game-state :K)
(get-rochade-moves game-state :Q))))
(defmethod find-piece-moves :BlackKing [piece game-state from-sq]
(let [moves (aget ^longs king-attack-array from-sq)
^long occupied (pieces-by-turn game-state)
not-occupied (bit-not occupied)
moves (bit-and moves not-occupied)]
(bit-or moves
(get-rochade-moves game-state :k)
(get-rochade-moves game-state :q))))
(defmethod find-piece-moves :Rook [piece game-state from-sq]
(let [not-occupied (bit-not (pieces-by-turn game-state))
slide-moves-rank (bit-and (get-attack-rank game-state from-sq) not-occupied)
slide-moves-file (bit-and (get-attack-file game-state from-sq) not-occupied)
slide-moves (bit-or slide-moves-rank slide-moves-file)]
slide-moves))
(defmethod find-piece-moves :Bishop [piece game-state from-sq]
(let [not-occupied (bit-not (pieces-by-turn game-state))
slide-diagonal-a1 (bit-and (get-attack-diagonal-a1h8 game-state from-sq) not-occupied)
slide-diagonal-a8 (bit-and (get-attack-diagonal-a8h1 game-state from-sq) not-occupied)]
(bit-or slide-diagonal-a1 slide-diagonal-a8)))
(defmethod find-piece-moves :Queen [piece game-state from-sq]
(let [not-occupied (bit-not (pieces-by-turn game-state))
slide-moves-rank (bit-and (get-attack-rank game-state from-sq) not-occupied)
slide-moves-file (bit-and (get-attack-file game-state from-sq) not-occupied)
slide-moves-rook (bit-or slide-moves-rank slide-moves-file)
slide-diagonal-a1 (bit-and (get-attack-diagonal-a1h8 game-state from-sq) not-occupied)
slide-diagonal-a8 (bit-and (get-attack-diagonal-a8h1 game-state from-sq) not-occupied)]
(bit-or slide-diagonal-a1 slide-diagonal-a8 slide-moves-rook)))
(defn create-move [piece from-sq dest-pos]
(condp = piece
:P (if (< dest-pos 56)
[piece from-sq dest-pos]
[[piece from-sq dest-pos :Q] ; means last row so pawn gets promoted
[piece from-sq dest-pos :R]
[piece from-sq dest-pos :B]
[piece from-sq dest-pos :N]])
:p (if (> dest-pos 7)
[piece from-sq dest-pos]
[[piece from-sq dest-pos :q] ; means last row so pawn gets promoted
[piece from-sq dest-pos :r]
[piece from-sq dest-pos :b]
[piece from-sq dest-pos :n]])
[piece from-sq dest-pos]))
(defn move-parser [piece from-square]
(fn[bitboard] (r/map (partial create-move piece from-square) bitboard)))
(defn find-moves[game-state]
(fn[square]
(let [piece (get (:board game-state) square)
get-piece-moves (partial find-piece-moves piece game-state)
create-move (move-parser piece square)
transform (comp create-move get-piece-moves)]
(transform square))))
(defn possible-moves [game-state pieces]
(into [] (r/mapcat (find-moves game-state) pieces)))
(defn generate-moves [game-state]
(possible-moves game-state (pieces-by-turn game-state)))
(defn print-generate-moves [game-state]
(print-board
(create-board-fn
(map (fn [[p x y]] [p y])
(generate-moves game-state) ))))
| null | https://raw.githubusercontent.com/clojure-dus/chess/7eb0e5bf15290f520f31e7eb3f2b7742c7f27729/src/chess/movelogic/bitboard/moves.clj | clojure | means last row so pawn gets promoted
means last row so pawn gets promoted
| (ns chess.movelogic.bitboard.moves
(:use [chess.movelogic.bitboard bitoperations file-rank chessboard piece-attacks])
(:use [clojure.pprint]))
(require '[clojure.core.reducers :as r])
(comment (set! *warn-on-reflection* true))
(defn attacked-by-black? [mask-sq game-state]
"looks at squares set in mask-sq and returns true if black attacks any of these squares"
(some-bitmap (fn [sq]
(or (bit-and? (:p game-state) (aget ^longs pawn-white-attack-array sq))
(bit-and? (:k game-state) (aget ^longs king-attack-array sq))
(bit-and? (:n game-state) (aget ^longs knight-attack-array sq))
(bit-and? (bit-or (:r game-state) (:q game-state))
(get-attack-rank game-state sq))
(bit-and? (bit-or (:r game-state) (:q game-state))
(get-attack-file game-state sq))
(bit-and? (bit-or (:b game-state) (:q game-state))
(get-attack-diagonal-a1h8 game-state sq))
(bit-and? (bit-or (:b game-state) (:q game-state))
(get-attack-diagonal-a8h1 game-state sq)))) mask-sq))
(defn attacked-by-white? [mask-sq game-state]
"looks at squares set in mask-sq and returns true if white attacks any of these squares"
(some-bitmap (fn [sq]
(or (bit-and? (:P game-state) (aget ^longs pawn-black-attack-array sq))
(bit-and? (:K game-state) (aget ^longs king-attack-array sq))
(bit-and? (:N game-state) (aget ^longs knight-attack-array sq))
(bit-and? (bit-or (:R game-state) (:Q game-state))
(get-attack-rank game-state sq))
(bit-and? (bit-or (:R game-state) (:Q game-state))
(get-attack-file game-state sq))
(bit-and? (bit-or (:B game-state) (:Q game-state))
(get-attack-diagonal-a1h8 game-state sq))
(bit-and? (bit-or (:B game-state) (:Q game-state))
(get-attack-diagonal-a8h1 game-state sq)))) mask-sq))
(defn check? [game-state]
(if (= :w (:turn game-state))
(attacked-by-black? (:K game-state) game-state)
(attacked-by-white? (:k game-state) game-state)))
(defmulti find-piece-moves (fn[piece _ _]
(case piece
(:N :n) :Knight
(:R :r) :Rook
(:B :b) :Bishop
(:Q :q) :Queen
:K :WhiteKing
:k :BlackKing
:P :WhitePawn
:p :BlackPawn)))
(defmethod find-piece-moves :Knight [piece game-state from-sq]
(let [piece-move-bitset (aget ^longs knight-attack-array from-sq)
not-occupied-squares (bit-not (pieces-by-turn game-state))]
(bit-and piece-move-bitset not-occupied-squares)))
(defmethod find-piece-moves :WhitePawn [piece game-state from-sq]
(let [moves (aget ^longs pawn-white-move-array from-sq)
all-pieces (:allpieces game-state)
occupied (bit-and all-pieces moves)
moves (bit-xor moves occupied)
double-moves (aget ^longs pawn-white-double-move-array from-sq)
occupied-4-row (bit-and all-pieces double-moves)
occupied-3-row (bit-and (bit-shift-left all-pieces 8) double-moves)
double-moves (bit-xor double-moves (bit-or occupied-3-row occupied-4-row))
attacks (bit-and (:blackpieces game-state)
(aget ^longs pawn-white-attack-array from-sq))]
(bit-or moves double-moves attacks)))
(defmethod find-piece-moves :BlackPawn [piece game-state from-sq]
(let [moves (aget ^longs pawn-black-move-array from-sq)
all-pieces (:allpieces game-state)
occupied (bit-and all-pieces moves)
moves (bit-xor moves occupied)
double-moves (aget ^longs pawn-black-double-move-array from-sq)
occupied-5-row (bit-and all-pieces double-moves)
occupied-6-row (bit-and (bit-shift-right all-pieces 8) double-moves)
double-moves (bit-xor double-moves (bit-or occupied-5-row occupied-6-row))
attacks (bit-and (:whitepieces game-state)
(aget ^longs pawn-black-attack-array from-sq))]
(bit-or moves double-moves attacks)))
(defn ^Long get-rochade-moves [game-state kind]
(let [rochade (:rochade game-state )
occupied (pieces-by-turn game-state)]
(condp = kind
:K (if (and (:K rochade)
(not (bit-and? mask-rochade-white-king occupied))
(not (attacked-by-black? mask-rochade-white-king game-state)))
move-rochade-white-king 0)
:Q (if (and (:Q rochade)
(not (bit-and? mask-rochade-white-queen occupied))
(not (attacked-by-black? mask-rochade-white-queen game-state)))
move-rochade-white-queen 0)
:k (if (and (:k rochade)
(not (bit-and? mask-rochade-black-king occupied))
(not (attacked-by-white? mask-rochade-black-king game-state)))
move-rochade-black-king 0)
:q (if (and (:q rochade)
(not (bit-and? mask-rochade-black-queen occupied))
(not (attacked-by-white? mask-rochade-black-queen game-state)))
move-rochade-black-queen 0))))
(defmethod find-piece-moves :WhiteKing [piece game-state from-sq]
(let [moves (aget ^longs king-attack-array from-sq)
occupied (pieces-by-turn game-state)
not-occupied (bit-not occupied)
moves (bit-and moves not-occupied)]
(bit-or moves
(get-rochade-moves game-state :K)
(get-rochade-moves game-state :Q))))
(defmethod find-piece-moves :BlackKing [piece game-state from-sq]
(let [moves (aget ^longs king-attack-array from-sq)
^long occupied (pieces-by-turn game-state)
not-occupied (bit-not occupied)
moves (bit-and moves not-occupied)]
(bit-or moves
(get-rochade-moves game-state :k)
(get-rochade-moves game-state :q))))
(defmethod find-piece-moves :Rook [piece game-state from-sq]
(let [not-occupied (bit-not (pieces-by-turn game-state))
slide-moves-rank (bit-and (get-attack-rank game-state from-sq) not-occupied)
slide-moves-file (bit-and (get-attack-file game-state from-sq) not-occupied)
slide-moves (bit-or slide-moves-rank slide-moves-file)]
slide-moves))
(defmethod find-piece-moves :Bishop [piece game-state from-sq]
(let [not-occupied (bit-not (pieces-by-turn game-state))
slide-diagonal-a1 (bit-and (get-attack-diagonal-a1h8 game-state from-sq) not-occupied)
slide-diagonal-a8 (bit-and (get-attack-diagonal-a8h1 game-state from-sq) not-occupied)]
(bit-or slide-diagonal-a1 slide-diagonal-a8)))
(defmethod find-piece-moves :Queen [piece game-state from-sq]
(let [not-occupied (bit-not (pieces-by-turn game-state))
slide-moves-rank (bit-and (get-attack-rank game-state from-sq) not-occupied)
slide-moves-file (bit-and (get-attack-file game-state from-sq) not-occupied)
slide-moves-rook (bit-or slide-moves-rank slide-moves-file)
slide-diagonal-a1 (bit-and (get-attack-diagonal-a1h8 game-state from-sq) not-occupied)
slide-diagonal-a8 (bit-and (get-attack-diagonal-a8h1 game-state from-sq) not-occupied)]
(bit-or slide-diagonal-a1 slide-diagonal-a8 slide-moves-rook)))
(defn create-move [piece from-sq dest-pos]
(condp = piece
:P (if (< dest-pos 56)
[piece from-sq dest-pos]
[piece from-sq dest-pos :R]
[piece from-sq dest-pos :B]
[piece from-sq dest-pos :N]])
:p (if (> dest-pos 7)
[piece from-sq dest-pos]
[piece from-sq dest-pos :r]
[piece from-sq dest-pos :b]
[piece from-sq dest-pos :n]])
[piece from-sq dest-pos]))
(defn move-parser [piece from-square]
(fn[bitboard] (r/map (partial create-move piece from-square) bitboard)))
(defn find-moves[game-state]
(fn[square]
(let [piece (get (:board game-state) square)
get-piece-moves (partial find-piece-moves piece game-state)
create-move (move-parser piece square)
transform (comp create-move get-piece-moves)]
(transform square))))
(defn possible-moves [game-state pieces]
(into [] (r/mapcat (find-moves game-state) pieces)))
(defn generate-moves [game-state]
(possible-moves game-state (pieces-by-turn game-state)))
(defn print-generate-moves [game-state]
(print-board
(create-board-fn
(map (fn [[p x y]] [p y])
(generate-moves game-state) ))))
|
26440d340b63b0c66389a49ddd6d08e4e3502c942c2f4325a607faf3d5902b73 | futurice/haskell-mega-repo | HourKinds.hs | {-# LANGUAGE ApplicativeDo #-}
# LANGUAGE DerivingVia #
# LANGUAGE DataKinds #
# LANGUAGE InstanceSigs #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Futuqu.Ggrr.HourKinds where
import Data.Fixed (Centi)
import Data.Set.Lens (setOf)
import Futurice.Generics
import Futurice.Integrations
import Futurice.Integrations.TimereportKind
import Futurice.Prelude
import Futurice.Time
import Prelude ()
import qualified Data.Map.Strict as Map
import qualified PlanMill as PM
import Futuqu.Rada.People
import Futuqu.Rada.Timereports
-------------------------------------------------------------------------------
-- Data
-------------------------------------------------------------------------------
data HourKind = HourKind
-- identifiers
{ hkUserId :: PM.UserId
-- data
, hkBillableHours :: !(NDT 'Hours Centi)
, hkNonBillableHours :: !(NDT 'Hours Centi)
, hkInternalHours :: !(NDT 'Hours Centi)
, hkAbsenceHours :: !(NDT 'Hours Centi)
-- additional data
, hkUtz :: !Double
, hkUtzTarget :: !(Maybe Double) -- we could default to 0. we don't.
-- TODO: add value creation?
}
deriving (Eq, Ord, Show, GhcGeneric)
deriving anyclass (NFData, SopGeneric, HasDatatypeInfo)
deriving via Sopica HourKind instance ToJSON HourKind
deriving via Sopica HourKind instance FromJSON HourKind
deriving via Sopica HourKind instance DefaultOrdered HourKind
deriving via Sopica HourKind instance ToRecord HourKind
deriving via Sopica HourKind instance ToNamedRecord HourKind
instance ToSchema HourKind where declareNamedSchema = sopDeclareNamedSchema
-------------------------------------------------------------------------------
Endpoint
-------------------------------------------------------------------------------
hourKindsData
:: forall m. (MonadTime m, MonadPlanMillQuery m, MonadPersonio m, MonadPower m, MonadMemoize m)
=> Month
-> m [HourKind]
hourKindsData month = do
people <- peopleData
let pUtz :: Map PM.UserId Int
pUtz = Map.fromList
[ (uid, utzTarget)
| p <- people
, uid <- toList (pPlanmill p)
, utzTarget <- toList (pUtzTarget p)
]
trs <- timereportsData month
let uids = setOf (folded . getter trUserId) trs
let trs' :: Map (PM.UserId, TimereportKind) (NDT 'Hours Centi)
trs' = Map.filter (> 0) $ Map.fromListWith (+)
[ ((trUserId tr, trKind tr), trHours tr)
| tr <- trs
]
return
[ HourKind
{ hkUserId = uid
, hkBillableHours = billable
, hkNonBillableHours = nonBillable
, hkInternalHours = internal
, hkAbsenceHours = absence
, hkUtz =
if total == 0
then 0
else 100 * realToFrac (unNDT billable) / realToFrac (unNDT total)
, hkUtzTarget = pUtz ^? ix uid . getter fromIntegral
}
| uid <- toList uids
, let billable = trs' ^. ix (uid, KindBillable)
, let nonBillable = trs' ^. ix (uid, KindNonBillable)
, let internal = trs' ^. ix (uid, KindInternal)
, let absence = trs' ^. ix (uid, KindAbsence)
+ trs' ^. ix (uid, KindSickLeave)
, let total = billable + nonBillable + internal -- note: doesn't include absences.
]
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/95fe8e33ad6426eb6e52a9c23db4aeffd443b3e5/futuqu/src/Futuqu/Ggrr/HourKinds.hs | haskell | # LANGUAGE ApplicativeDo #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
-----------------------------------------------------------------------------
Data
-----------------------------------------------------------------------------
identifiers
data
additional data
we could default to 0. we don't.
TODO: add value creation?
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
note: doesn't include absences. | # LANGUAGE DerivingVia #
# LANGUAGE DataKinds #
# LANGUAGE InstanceSigs #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
module Futuqu.Ggrr.HourKinds where
import Data.Fixed (Centi)
import Data.Set.Lens (setOf)
import Futurice.Generics
import Futurice.Integrations
import Futurice.Integrations.TimereportKind
import Futurice.Prelude
import Futurice.Time
import Prelude ()
import qualified Data.Map.Strict as Map
import qualified PlanMill as PM
import Futuqu.Rada.People
import Futuqu.Rada.Timereports
data HourKind = HourKind
{ hkUserId :: PM.UserId
, hkBillableHours :: !(NDT 'Hours Centi)
, hkNonBillableHours :: !(NDT 'Hours Centi)
, hkInternalHours :: !(NDT 'Hours Centi)
, hkAbsenceHours :: !(NDT 'Hours Centi)
, hkUtz :: !Double
}
deriving (Eq, Ord, Show, GhcGeneric)
deriving anyclass (NFData, SopGeneric, HasDatatypeInfo)
deriving via Sopica HourKind instance ToJSON HourKind
deriving via Sopica HourKind instance FromJSON HourKind
deriving via Sopica HourKind instance DefaultOrdered HourKind
deriving via Sopica HourKind instance ToRecord HourKind
deriving via Sopica HourKind instance ToNamedRecord HourKind
instance ToSchema HourKind where declareNamedSchema = sopDeclareNamedSchema
Endpoint
hourKindsData
:: forall m. (MonadTime m, MonadPlanMillQuery m, MonadPersonio m, MonadPower m, MonadMemoize m)
=> Month
-> m [HourKind]
hourKindsData month = do
people <- peopleData
let pUtz :: Map PM.UserId Int
pUtz = Map.fromList
[ (uid, utzTarget)
| p <- people
, uid <- toList (pPlanmill p)
, utzTarget <- toList (pUtzTarget p)
]
trs <- timereportsData month
let uids = setOf (folded . getter trUserId) trs
let trs' :: Map (PM.UserId, TimereportKind) (NDT 'Hours Centi)
trs' = Map.filter (> 0) $ Map.fromListWith (+)
[ ((trUserId tr, trKind tr), trHours tr)
| tr <- trs
]
return
[ HourKind
{ hkUserId = uid
, hkBillableHours = billable
, hkNonBillableHours = nonBillable
, hkInternalHours = internal
, hkAbsenceHours = absence
, hkUtz =
if total == 0
then 0
else 100 * realToFrac (unNDT billable) / realToFrac (unNDT total)
, hkUtzTarget = pUtz ^? ix uid . getter fromIntegral
}
| uid <- toList uids
, let billable = trs' ^. ix (uid, KindBillable)
, let nonBillable = trs' ^. ix (uid, KindNonBillable)
, let internal = trs' ^. ix (uid, KindInternal)
, let absence = trs' ^. ix (uid, KindAbsence)
+ trs' ^. ix (uid, KindSickLeave)
]
|
b38abc460643e870a51f9d09152d9e25f3a88940014bc4b0547e130aafeba2e8 | JacquesCarette/Drasil | Body.hs | -- | Defines lesson plan notebook section constructors.
module Drasil.NBSections.Body (
-- * Constructors
reviewSec, mainIdeaSec, mthdAndanls, exampleSec) where
import Language.Drasil
import qualified Drasil.DocLang.Notebook as NB (review, mainIdea, methAndAnls, example)
-- Leave blank for now
: : Contents
= foldlSP [ S " " ]
-- | Review Section.
reviewSec :: [Contents] -> Section
reviewSec cs = NB.review cs []
-- | Main Idea Section.
mainIdeaSec :: [Contents] -> [Section] -> Section
mainIdeaSec = NB.mainIdea
-- | Method and Analysis Section.
mthdAndanls :: [Contents] -> [Section] -> Section
mthdAndanls = NB.methAndAnls
-- | Example Section.
exampleSec :: [Contents] -> [Section] -> Section
exampleSec = NB.example | null | https://raw.githubusercontent.com/JacquesCarette/Drasil/92dddf7a545ba5029f99ad5c5eddcd8dad56a2d8/code/drasil-docLang/lib/Drasil/NBSections/Body.hs | haskell | | Defines lesson plan notebook section constructors.
* Constructors
Leave blank for now
| Review Section.
| Main Idea Section.
| Method and Analysis Section.
| Example Section. | module Drasil.NBSections.Body (
reviewSec, mainIdeaSec, mthdAndanls, exampleSec) where
import Language.Drasil
import qualified Drasil.DocLang.Notebook as NB (review, mainIdea, methAndAnls, example)
: : Contents
= foldlSP [ S " " ]
reviewSec :: [Contents] -> Section
reviewSec cs = NB.review cs []
mainIdeaSec :: [Contents] -> [Section] -> Section
mainIdeaSec = NB.mainIdea
mthdAndanls :: [Contents] -> [Section] -> Section
mthdAndanls = NB.methAndAnls
exampleSec :: [Contents] -> [Section] -> Section
exampleSec = NB.example |
a1f0d9e95405e0ead558c648cd8f5bca82e0f876b3bca3023e007047f070af3e | hasktorch/hasktorch | Recurrent.hs | module Torch.Typed.NN.Recurrent
( module Torch.Typed.NN.Recurrent,
module Torch.Typed.NN.Recurrent.Auxiliary,
module Torch.Typed.NN.Recurrent.GRU,
module Torch.Typed.NN.Recurrent.LSTM,
module Torch.Typed.NN.Recurrent.Cell.GRU,
module Torch.Typed.NN.Recurrent.Cell.LSTM,
)
where
import Torch.Typed.NN.Recurrent.Auxiliary
import Torch.Typed.NN.Recurrent.Cell.GRU
import Torch.Typed.NN.Recurrent.Cell.LSTM
import Torch.Typed.NN.Recurrent.GRU
import Torch.Typed.NN.Recurrent.LSTM
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/9560d149b06af17e2d4e73d1e116afd2b0baff86/hasktorch/src/Torch/Typed/NN/Recurrent.hs | haskell | module Torch.Typed.NN.Recurrent
( module Torch.Typed.NN.Recurrent,
module Torch.Typed.NN.Recurrent.Auxiliary,
module Torch.Typed.NN.Recurrent.GRU,
module Torch.Typed.NN.Recurrent.LSTM,
module Torch.Typed.NN.Recurrent.Cell.GRU,
module Torch.Typed.NN.Recurrent.Cell.LSTM,
)
where
import Torch.Typed.NN.Recurrent.Auxiliary
import Torch.Typed.NN.Recurrent.Cell.GRU
import Torch.Typed.NN.Recurrent.Cell.LSTM
import Torch.Typed.NN.Recurrent.GRU
import Torch.Typed.NN.Recurrent.LSTM
|
|
de3c27ac7959bfc785fb727e7ffe76a99c1383d0c50cae6b3d54266a81158e6b | dannypsnl/k | def.rkt | #lang racket/base
(provide def)
(require syntax/parse/define
(for-syntax racket/base
racket/list
racket/dict
syntax/parse
syntax/transformer
syntax/stx
"bindings.rkt"
"core.rkt"
"helper/stx-util.rkt"
"helper/id-hash.rkt"))
(begin-for-syntax
(define (syntax->compute-pattern pattern-stx)
(syntax-parse pattern-stx
[x:id #:when (constructor? #'x)
#'(~literal x)]
[(x ...)
(stx-map syntax->compute-pattern #'(x ...))]
[x #'x]))
(define-syntax-class def-clause
(pattern [pat* ... => expr]
#:attr pat #`(_ #,@(stx-map syntax->compute-pattern #'(pat* ...)))))
(define (on-pattern pat exp-ty locals subst-map)
(syntax-parse pat
[x:id #:when (constructor? #'x)
(check-type #'x exp-ty
subst-map
locals)]
; typeof x should be a Pi type here, then here are going to unify p*... with telescope of the Pi type
; we should use telescope to bind type to free variable
[(x:id p* ...) #:when (constructor? #'x)
(syntax-parse (typeof #'x)
[(Pi ([x* : typ*] ...) _)
(for ([p (syntax->list #'(p* ...))]
[ty (syntax->list #'(typ* ...))])
(on-pattern p ty locals subst-map))]
[_ (raise-syntax-error 'bad-pattern
"not an expandable constructor"
#'x)])]
; bind pattern type to the free variable here
; and brings the binding to the end for return type unification
[x:id (dict-set! locals #'x exp-ty)]
[_ (raise-syntax-error 'bad-pattern
(format "pattern only allows to destruct on constructor")
pat)])))
(define-syntax-parser def
#:datum-literals (:)
[(_ name:id : ty #:postulate props ...) #'(define-syntax-parser name [_:id (syntax-property* #''name 'type #'ty props ...)])]
[(_ name:id : ty #:constructor) #'(def name : ty #:postulate 'constructor #t)]
[(_ name:id : ty expr)
(check-type #'expr (normalize #'ty))
#'(begin
(void ty)
(define-syntax name (make-variable-like-transformer #'expr)))]
[(_ (name:id p*:bindings) : ty #:postulate props ...)
(with-syntax ([id-case #'[_:id
(syntax-property*
#''name
'type
#'(Pi ([p*.name : p*.ty] ...) ty)
props ...)]]
; implicit form
[implicit-case #'[(_:id p*.name ...)
(define (normalize-implicit-form ty-stx)
((compose last syntax->list local-expand-expr)
ty-stx))
(define binds (make-hash))
; store implicit arguments
(stx-map (lambda (implicit-argument implicit-argument-ty)
(hash-set! binds
(syntax->datum implicit-argument)
(syntax-property implicit-argument 'type implicit-argument-ty)))
#'(p*.full-name ...) #'(p*.full-ty ...))
(define expanded (normalize-implicit-form #''(name p*.full-name ...)))
(println (subst expanded binds))
(subst expanded binds)]]
; full case: users provide implicit arguments
; application with implicit must provides all implicits
; NOTE: maybe this is not required, but need some researching
[full-apply-case #'[(_:id p*.full-name ...)
(define locals (make-mutable-id-hash))
(when (syntax-property #'p*.full-name 'type)
(dict-set! locals #'p*.full-name (syntax-property #'p*.full-name 'type)))
...
(define subst-map (make-hash))
(check-type #'p*.full-name (subst #'p*.full-ty subst-map)
subst-map locals)
...
(syntax-property* #'`(name ,p*.full-name ...)
'type (subst #'ty subst-map)
props ...)]])
(if (stx-length=? #'(p*.name ...) #'(p*.full-name ...))
#'(define-syntax-parser name
id-case
full-apply-case)
#'(define-syntax-parser name
id-case
implicit-case
full-apply-case)))]
[(_ (name:id p*:bindings) : ty #:constructor) #'(def (name [p*.name : p*.ty] ...) : ty #:postulate 'constructor #t)]
[(_ (name:id p*:bindings) : ret-ty
clause*:def-clause ...)
(for ([pat* (syntax->list #'((clause*.pat* ...) ...))]
[expr (syntax->list #'(clause*.expr ...))])
; locals stores local identifiers to it's type
(define locals (make-mutable-id-hash))
; itself type need to be stored for later pattern check
(dict-set! locals #'name #`(Pi ([p*.name : p*.ty] ...) ret-ty))
(define subst-map (make-hash))
(for ([pat (syntax->list pat*)]
[exp-ty (syntax->list #'(p*.ty ...))])
(on-pattern pat exp-ty locals subst-map))
; check pattern's body has correct type
(check-type expr #'ret-ty subst-map
locals))
(with-syntax (; FIXME: these should be implicit bindings
[(free-p-ty* ...)
(filter free-identifier? (syntax->list #'(p*.full-ty ...)))])
#'(begin
(void (let* ([free-p-ty* 'free-p-ty*] ...
[p*.name 'p*.name] ...)
ret-ty))
;;; computation definition
(define-syntax-parser name
[_:id (syntax-property*
#''name
'type
#'(Pi ([p*.name : p*.ty] ...) ret-ty))]
[clause*.pat #'clause*.expr] ...)))])
| null | https://raw.githubusercontent.com/dannypsnl/k/2b5f5066806a5bbd0733b781a2ed5fce6956a4f5/k-core/k/def.rkt | racket | typeof x should be a Pi type here, then here are going to unify p*... with telescope of the Pi type
we should use telescope to bind type to free variable
bind pattern type to the free variable here
and brings the binding to the end for return type unification
implicit form
store implicit arguments
full case: users provide implicit arguments
application with implicit must provides all implicits
NOTE: maybe this is not required, but need some researching
locals stores local identifiers to it's type
itself type need to be stored for later pattern check
check pattern's body has correct type
FIXME: these should be implicit bindings
computation definition | #lang racket/base
(provide def)
(require syntax/parse/define
(for-syntax racket/base
racket/list
racket/dict
syntax/parse
syntax/transformer
syntax/stx
"bindings.rkt"
"core.rkt"
"helper/stx-util.rkt"
"helper/id-hash.rkt"))
(begin-for-syntax
(define (syntax->compute-pattern pattern-stx)
(syntax-parse pattern-stx
[x:id #:when (constructor? #'x)
#'(~literal x)]
[(x ...)
(stx-map syntax->compute-pattern #'(x ...))]
[x #'x]))
(define-syntax-class def-clause
(pattern [pat* ... => expr]
#:attr pat #`(_ #,@(stx-map syntax->compute-pattern #'(pat* ...)))))
(define (on-pattern pat exp-ty locals subst-map)
(syntax-parse pat
[x:id #:when (constructor? #'x)
(check-type #'x exp-ty
subst-map
locals)]
[(x:id p* ...) #:when (constructor? #'x)
(syntax-parse (typeof #'x)
[(Pi ([x* : typ*] ...) _)
(for ([p (syntax->list #'(p* ...))]
[ty (syntax->list #'(typ* ...))])
(on-pattern p ty locals subst-map))]
[_ (raise-syntax-error 'bad-pattern
"not an expandable constructor"
#'x)])]
[x:id (dict-set! locals #'x exp-ty)]
[_ (raise-syntax-error 'bad-pattern
(format "pattern only allows to destruct on constructor")
pat)])))
(define-syntax-parser def
#:datum-literals (:)
[(_ name:id : ty #:postulate props ...) #'(define-syntax-parser name [_:id (syntax-property* #''name 'type #'ty props ...)])]
[(_ name:id : ty #:constructor) #'(def name : ty #:postulate 'constructor #t)]
[(_ name:id : ty expr)
(check-type #'expr (normalize #'ty))
#'(begin
(void ty)
(define-syntax name (make-variable-like-transformer #'expr)))]
[(_ (name:id p*:bindings) : ty #:postulate props ...)
(with-syntax ([id-case #'[_:id
(syntax-property*
#''name
'type
#'(Pi ([p*.name : p*.ty] ...) ty)
props ...)]]
[implicit-case #'[(_:id p*.name ...)
(define (normalize-implicit-form ty-stx)
((compose last syntax->list local-expand-expr)
ty-stx))
(define binds (make-hash))
(stx-map (lambda (implicit-argument implicit-argument-ty)
(hash-set! binds
(syntax->datum implicit-argument)
(syntax-property implicit-argument 'type implicit-argument-ty)))
#'(p*.full-name ...) #'(p*.full-ty ...))
(define expanded (normalize-implicit-form #''(name p*.full-name ...)))
(println (subst expanded binds))
(subst expanded binds)]]
[full-apply-case #'[(_:id p*.full-name ...)
(define locals (make-mutable-id-hash))
(when (syntax-property #'p*.full-name 'type)
(dict-set! locals #'p*.full-name (syntax-property #'p*.full-name 'type)))
...
(define subst-map (make-hash))
(check-type #'p*.full-name (subst #'p*.full-ty subst-map)
subst-map locals)
...
(syntax-property* #'`(name ,p*.full-name ...)
'type (subst #'ty subst-map)
props ...)]])
(if (stx-length=? #'(p*.name ...) #'(p*.full-name ...))
#'(define-syntax-parser name
id-case
full-apply-case)
#'(define-syntax-parser name
id-case
implicit-case
full-apply-case)))]
[(_ (name:id p*:bindings) : ty #:constructor) #'(def (name [p*.name : p*.ty] ...) : ty #:postulate 'constructor #t)]
[(_ (name:id p*:bindings) : ret-ty
clause*:def-clause ...)
(for ([pat* (syntax->list #'((clause*.pat* ...) ...))]
[expr (syntax->list #'(clause*.expr ...))])
(define locals (make-mutable-id-hash))
(dict-set! locals #'name #`(Pi ([p*.name : p*.ty] ...) ret-ty))
(define subst-map (make-hash))
(for ([pat (syntax->list pat*)]
[exp-ty (syntax->list #'(p*.ty ...))])
(on-pattern pat exp-ty locals subst-map))
(check-type expr #'ret-ty subst-map
locals))
[(free-p-ty* ...)
(filter free-identifier? (syntax->list #'(p*.full-ty ...)))])
#'(begin
(void (let* ([free-p-ty* 'free-p-ty*] ...
[p*.name 'p*.name] ...)
ret-ty))
(define-syntax-parser name
[_:id (syntax-property*
#''name
'type
#'(Pi ([p*.name : p*.ty] ...) ret-ty))]
[clause*.pat #'clause*.expr] ...)))])
|
5a00b4bf7e1fc2d14fc15a5338da2855bd013056dbc6fd86b862a9ea50eca58a | fulcro-legacy/semantic-ui-wrapper | ui_divider.cljs | (ns fulcrologic.semantic-ui.elements.divider.ui-divider
(:require
[fulcrologic.semantic-ui.factory-helpers :as h]
["semantic-ui-react/dist/commonjs/elements/Divider/Divider" :default Divider]))
(def ui-divider
"A divider visually segments content into groups.
Props:
- as (custom): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- clearing (bool): Divider can clear the content above it.
- content (custom): Shorthand for primary content.
- fitted (bool): Divider can be fitted without any space above or below it.
- hidden (bool): Divider can divide content without creating a dividing line.
- horizontal (bool): Divider can segment content horizontally.
- inverted (bool): Divider can have its colours inverted.
- section (bool): Divider can provide greater margins to divide sections of content.
- vertical (bool): Divider can segment content vertically."
(h/factory-apply Divider))
| null | https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/elements/divider/ui_divider.cljs | clojure | (ns fulcrologic.semantic-ui.elements.divider.ui-divider
(:require
[fulcrologic.semantic-ui.factory-helpers :as h]
["semantic-ui-react/dist/commonjs/elements/Divider/Divider" :default Divider]))
(def ui-divider
"A divider visually segments content into groups.
Props:
- as (custom): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- clearing (bool): Divider can clear the content above it.
- content (custom): Shorthand for primary content.
- fitted (bool): Divider can be fitted without any space above or below it.
- hidden (bool): Divider can divide content without creating a dividing line.
- horizontal (bool): Divider can segment content horizontally.
- inverted (bool): Divider can have its colours inverted.
- section (bool): Divider can provide greater margins to divide sections of content.
- vertical (bool): Divider can segment content vertically."
(h/factory-apply Divider))
|
|
76fe96d568d8fba06338ff32808790fc40f158fa4767d5486f6caee9453a2929 | vonzhou/LearnYouHaskellForGreatGood | foldM.hs |
binSmalls :: Int -> Int -> Maybe Int
binSmalls acc x
| x > 9 = Nothing
| otherwise = Just (acc + x)
| null | https://raw.githubusercontent.com/vonzhou/LearnYouHaskellForGreatGood/439d848deac53ef6da6df433078b7f1dcf54d18d/chapter14/foldM.hs | haskell |
binSmalls :: Int -> Int -> Maybe Int
binSmalls acc x
| x > 9 = Nothing
| otherwise = Just (acc + x)
|
|
523c691b55b1870ed90b0bb925d3d3a046b48c809f3c82a740c2069a921df7ec | gja/pwa-clojure | main.cljs | (ns pwa-clojure.main
(:require [pwa-clojure.app-state :as app-state]
[pwa-clojure.pages :as pages]
[pwa-clojure.navigation :as navigation]
[rum.core :as rum]
[pwa-clojure.components :as components]))
(defn- get-current-path []
js/window.location.pathname)
(defn- get-container [name]
(.getElementById js/window.document name))
(rum/defc reactive-component < rum/reactive []
(pages/pwa-component (:handler (rum/react app-state/app-state))
(:data (rum/react app-state/app-state))))
(defn- make-progressive! []
(when js/navigator.serviceWorker
(.register js/navigator.serviceWorker "/service-worker.js")))
(defonce app-loaded (atom false))
(defn load-app []
(when-not @app-loaded
(reset! app-loaded true)
(rum/mount (reactive-component) (get-container "container"))
(rum/mount (components/main-navigation) (get-container "header-container"))))
(defn ^:export start-cljs-app []
(navigation/move-to-page (get-current-path) load-app)
(make-progressive!))
(start-cljs-app)
| null | https://raw.githubusercontent.com/gja/pwa-clojure/a06450747c6ead439d1a74653a34afe415d8ef02/src-cljs/pwa_clojure/main.cljs | clojure | (ns pwa-clojure.main
(:require [pwa-clojure.app-state :as app-state]
[pwa-clojure.pages :as pages]
[pwa-clojure.navigation :as navigation]
[rum.core :as rum]
[pwa-clojure.components :as components]))
(defn- get-current-path []
js/window.location.pathname)
(defn- get-container [name]
(.getElementById js/window.document name))
(rum/defc reactive-component < rum/reactive []
(pages/pwa-component (:handler (rum/react app-state/app-state))
(:data (rum/react app-state/app-state))))
(defn- make-progressive! []
(when js/navigator.serviceWorker
(.register js/navigator.serviceWorker "/service-worker.js")))
(defonce app-loaded (atom false))
(defn load-app []
(when-not @app-loaded
(reset! app-loaded true)
(rum/mount (reactive-component) (get-container "container"))
(rum/mount (components/main-navigation) (get-container "header-container"))))
(defn ^:export start-cljs-app []
(navigation/move-to-page (get-current-path) load-app)
(make-progressive!))
(start-cljs-app)
|
|
f32fbaf67fd930f700b96979f1aeef48d0a527fcd2de0b768c4bbc032ab8b32c | comby-tools/comby | test_string_literals_alpha.ml | open Core
open Rewriter
open Test_helpers
include Test_alpha
let all ?(configuration = configuration) template source =
C.all ~configuration ~template ~source ()
let%expect_test "comments_in_string_literals_should_not_be_treated_as_comments_by_fuzzy" =
let source = {|"/*"(x)|} in
let template = {|(:[1])|} in
let rewrite_template = {|:[1]|} in
all template source
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|"/*"x|}]
let%expect_test "comments_in_string_literals_should_not_be_treated_as_comments_by_fuzzy_go_raw" =
let source = {|`//`(x)|} in
let template = {|(:[1])|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|`//`x|}]
let%expect_test "tolerate_unbalanced_stuff_in_string_literals" =
let template = {|"("|} in
let source = {|"("|} in
let matches = all ~configuration template source in
print_matches matches;
[%expect_exact {|[
{
"range": {
"start": { "offset": 0, "line": 1, "column": 1 },
"end": { "offset": 3, "line": 1, "column": 4 }
},
"environment": [],
"matched": "\"(\""
}
]|}]
let%expect_test "base_literal_matching" =
let source = {|"hello"|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|hello|}]
let%expect_test "base_literal_matching" =
let source = {|rewrite ("hello") this string|} in
let match_template = {|rewrite (":[1]") this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|hello|}]
let%expect_test "match_string_literals" =
let source = {|rewrite (".") this string|} in
let match_template = {|rewrite (":[1]") this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|.|}]
let%expect_test "match_string_literals" =
let source = {|rewrite ("") this string|} in
let match_template = {|rewrite (":[1]") this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {||}]
let%expect_test "match_string_literals" =
let source = {|"(" match "a""a" this "(" |} in
let match_template = {|match :[1] this|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"(" "a""a" "(" |}]
(* this tests special functionality in non-literal hole parser
but which must still ignore unbalanced delims within strings *)
let%expect_test "match_string_literals" =
let source = {|"(" match "(""(" this "(" |} in
let match_template = {|match :[1] this|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"(" "(""(" "(" |}]
let%expect_test "match_string_literals" =
let source = {|rewrite ("") this string|} in
let match_template = {|rewrite (:[1]) this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|""|}]
let%expect_test "base_literal_matching" =
let source = {|"("|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|(|}]
let%expect_test "base_literal_matching" =
let source = {|"(""("|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|((|}]
let%expect_test "base_literal_matching" =
let source = {|"(""("|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|((|}]
let%expect_test "base_literal_matching" =
let source = {|"hello world"|} in
let match_template = {|":[x] :[y]"|} in
let rewrite_template = {|:[x] :[y]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|hello world|}]
complex test : basically , we are checking that the inside of this literal is only matched by the b part
let%expect_test "base_literal_matching" =
let source = {|val a = "class = ${String::class}" val b = "not $a"|} in
let match_template = {|":[x]$:[[y]]"|} in
let rewrite_template = {|(rewritten part: (:[x]) ([y]))|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|val a = "class = ${String::class}" val b = (rewritten part: (not ) ([y]))|}]
let%expect_test "base_literal_matching" =
let source = {|get("type") rekt ("enabled", True)|} in
let match_template = {|(":[1]", :[[3]])|} in
let rewrite_template = {|(rewritten part: (:[1]) (:[3]))|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|get("type") rekt (rewritten part: (enabled) (True))|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"" this|} in
let match_template = {|match "\"" this|} in
let rewrite_template = "" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {||}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"" this|} in
let match_template = {|match :[1] this|} in
let rewrite_template = ":[1]" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"\""|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"\"" this|} in
let match_template = {|match :[1] this|} in
let rewrite_template = ":[1]" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"\"\""|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"(\"" "(\"" this|} in
let match_template = {|match :[1] this|} in
let rewrite_template = ":[1]" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"\"(\"" "(\""|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"(\"" "(\"" this|} in
let match_template = {|match ":[1]" ":[2]" this|} in
let rewrite_template = {|:[1] :[2]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|\"(\" (\"|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match 'sin(gle' 'quo(tes' this|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match 'sin(gle' 'quo(tes' this|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match '\''|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match '\''|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match 'asdf'|} in
let match_template = {|':[1]'|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match asdf|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match '\''|} in
let match_template = {|':[1]'|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match \'|}]
let%expect_test "go_raw_string_literals" =
let source =
{|
x = x
y = `multi-line
raw str(ing literal`
z = `other multi-line
raw stri(ng literal`
|}
in
let match_template = {|`:[1]`|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~source ~template:match_template ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|
x = x
y = multi-line
raw str(ing literal
z = other multi-line
raw stri(ng literal
|}]
let%expect_test "go_raw_string_literals" =
let source = {|blah `(` quux|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~source ~template:match_template ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|blah `(` quux|}]
let%expect_test "match_string_literals" =
let source = {|`(` match `(``(` this `(` |} in
let match_template = {|match :[1] this|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template:match_template ~source ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|`(` `(``(` `(` |}]
let%expect_test "go_raw_string_literals" =
let source =
{|
x = x
y = `multi-line
raw "str"(ing literal`
z = `other multi-line
raw '"'\"\\s\\\\\tr\ni(ng literal`
|}
in
let match_template = {|`:[1]`|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~source ~template:match_template ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|
x = x
y = multi-line
raw "str"(ing literal
z = other multi-line
raw '"'\"\\s\\\\\tr\ni(ng literal
|}]
let%expect_test "regression_matching_kubernetes" =
let source = {|"\n" y = 5|} in
let template = {|y = :[1]|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|"\n" 5|}]
let%expect_test "match_escaped_any_char" =
let source = {|printf("hello world\n");|} in
let template = {|printf(":[1]");|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|hello world\n|}]
let%expect_test "match_escaped_escaped" =
let source = {|printf("hello world\n\\");|} in
let template = {|printf(":[1]");|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|hello world\n\\|}]
let%expect_test "match_escaped_escaped" =
let source = {|printf("hello world\n\");|} in
let template = {|printf(":[1]");|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "EXPECT SUCCESS");
[%expect_exact {|EXPECT SUCCESS|}]
let%expect_test "holes_in_raw_literals" =
let source = {|
return expect(
extensionsController.executeCommand({
command: 'queryGraphQL',
arguments: [
`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`,
{ repoName: 'foo' },
],
})
)
|} in
let template = {|`:[1]`|} in
begin
Typescript.all ~configuration ~template ~source ()
|> function
| [] -> print_string "No matches."
| hd :: _ ->
print_string hd.matched
end;
[%expect_exact {|`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`|}]
let%expect_test "holes_in_raw_literals_partial" =
let source = {|
return expect(
extensionsController.executeCommand({
command: 'queryGraphQL',
arguments: [
`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`,
{ repoName: 'foo' },
],
})
)
|} in
let template = {|` query ResolveRepo(:[1]) {:[2]} `|} in
begin
Typescript.all ~configuration ~template ~source ()
|> function
| [] -> print_string "No matches."
| hd :: _ ->
print_string hd.matched
end;
[%expect_exact {|`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`|}]
let%expect_test "dont_detect_comments_in_strings_with_hole_matcher" =
let source = {|"// not a comment"|} in
let template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|// not a comment|}]
Deactivated : this will conflict with division syntax
let%expect_test " match_regex_delimiters " =
let source = { |/f\/oo/ " /bar/"| } in
let template = { } in
let rewrite_template = { |:[1]| } in
~configuration ~template ~source ( )
| > Rewrite.all ~source ~rewrite_template
| > ( function
| Some { rewritten_source ; _ } - > print_string rewritten_source
| None - > print_string " EXPECT SUCCESS " ) ;
[ % expect_exact { |f\/oo " /bar/"| } ]
let%expect_test "match_regex_delimiters" =
let source = {|/f\/oo/ "/bar/"|} in
let template = {|/:[1]/|} in
let rewrite_template = {|:[1]|} in
Typescript.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "EXPECT SUCCESS");
[%expect_exact {|f\/oo "/bar/"|}]
*)
| null | https://raw.githubusercontent.com/comby-tools/comby/7b401063024da9ddc94446ade27a24806398d838/test/common/test_string_literals_alpha.ml | ocaml | this tests special functionality in non-literal hole parser
but which must still ignore unbalanced delims within strings | open Core
open Rewriter
open Test_helpers
include Test_alpha
let all ?(configuration = configuration) template source =
C.all ~configuration ~template ~source ()
let%expect_test "comments_in_string_literals_should_not_be_treated_as_comments_by_fuzzy" =
let source = {|"/*"(x)|} in
let template = {|(:[1])|} in
let rewrite_template = {|:[1]|} in
all template source
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|"/*"x|}]
let%expect_test "comments_in_string_literals_should_not_be_treated_as_comments_by_fuzzy_go_raw" =
let source = {|`//`(x)|} in
let template = {|(:[1])|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|`//`x|}]
let%expect_test "tolerate_unbalanced_stuff_in_string_literals" =
let template = {|"("|} in
let source = {|"("|} in
let matches = all ~configuration template source in
print_matches matches;
[%expect_exact {|[
{
"range": {
"start": { "offset": 0, "line": 1, "column": 1 },
"end": { "offset": 3, "line": 1, "column": 4 }
},
"environment": [],
"matched": "\"(\""
}
]|}]
let%expect_test "base_literal_matching" =
let source = {|"hello"|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|hello|}]
let%expect_test "base_literal_matching" =
let source = {|rewrite ("hello") this string|} in
let match_template = {|rewrite (":[1]") this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|hello|}]
let%expect_test "match_string_literals" =
let source = {|rewrite (".") this string|} in
let match_template = {|rewrite (":[1]") this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|.|}]
let%expect_test "match_string_literals" =
let source = {|rewrite ("") this string|} in
let match_template = {|rewrite (":[1]") this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {||}]
let%expect_test "match_string_literals" =
let source = {|"(" match "a""a" this "(" |} in
let match_template = {|match :[1] this|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"(" "a""a" "(" |}]
let%expect_test "match_string_literals" =
let source = {|"(" match "(""(" this "(" |} in
let match_template = {|match :[1] this|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"(" "(""(" "(" |}]
let%expect_test "match_string_literals" =
let source = {|rewrite ("") this string|} in
let match_template = {|rewrite (:[1]) this string|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|""|}]
let%expect_test "base_literal_matching" =
let source = {|"("|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|(|}]
let%expect_test "base_literal_matching" =
let source = {|"(""("|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|((|}]
let%expect_test "base_literal_matching" =
let source = {|"(""("|} in
let match_template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|((|}]
let%expect_test "base_literal_matching" =
let source = {|"hello world"|} in
let match_template = {|":[x] :[y]"|} in
let rewrite_template = {|:[x] :[y]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|hello world|}]
complex test : basically , we are checking that the inside of this literal is only matched by the b part
let%expect_test "base_literal_matching" =
let source = {|val a = "class = ${String::class}" val b = "not $a"|} in
let match_template = {|":[x]$:[[y]]"|} in
let rewrite_template = {|(rewritten part: (:[x]) ([y]))|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|val a = "class = ${String::class}" val b = (rewritten part: (not ) ([y]))|}]
let%expect_test "base_literal_matching" =
let source = {|get("type") rekt ("enabled", True)|} in
let match_template = {|(":[1]", :[[3]])|} in
let rewrite_template = {|(rewritten part: (:[1]) (:[3]))|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|get("type") rekt (rewritten part: (enabled) (True))|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"" this|} in
let match_template = {|match "\"" this|} in
let rewrite_template = "" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {||}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"" this|} in
let match_template = {|match :[1] this|} in
let rewrite_template = ":[1]" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"\""|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"\"" this|} in
let match_template = {|match :[1] this|} in
let rewrite_template = ":[1]" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"\"\""|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"(\"" "(\"" this|} in
let match_template = {|match :[1] this|} in
let rewrite_template = ":[1]" in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|"\"(\"" "(\""|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match "\"(\"" "(\"" this|} in
let match_template = {|match ":[1]" ":[2]" this|} in
let rewrite_template = {|:[1] :[2]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|\"(\" (\"|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match 'sin(gle' 'quo(tes' this|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match 'sin(gle' 'quo(tes' this|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match '\''|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match '\''|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match 'asdf'|} in
let match_template = {|':[1]'|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match asdf|}]
let%expect_test "rewrite_string_literals_8" =
let source = {|match '\''|} in
let match_template = {|':[1]'|} in
let rewrite_template = {|:[1]|} in
all match_template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|match \'|}]
let%expect_test "go_raw_string_literals" =
let source =
{|
x = x
y = `multi-line
raw str(ing literal`
z = `other multi-line
raw stri(ng literal`
|}
in
let match_template = {|`:[1]`|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~source ~template:match_template ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|
x = x
y = multi-line
raw str(ing literal
z = other multi-line
raw stri(ng literal
|}]
let%expect_test "go_raw_string_literals" =
let source = {|blah `(` quux|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~source ~template:match_template ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|blah `(` quux|}]
let%expect_test "match_string_literals" =
let source = {|`(` match `(``(` this `(` |} in
let match_template = {|match :[1] this|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template:match_template ~source ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|`(` `(``(` `(` |}]
let%expect_test "go_raw_string_literals" =
let source =
{|
x = x
y = `multi-line
raw "str"(ing literal`
z = `other multi-line
raw '"'\"\\s\\\\\tr\ni(ng literal`
|}
in
let match_template = {|`:[1]`|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~source ~template:match_template ()
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact {|
x = x
y = multi-line
raw "str"(ing literal
z = other multi-line
raw '"'\"\\s\\\\\tr\ni(ng literal
|}]
let%expect_test "regression_matching_kubernetes" =
let source = {|"\n" y = 5|} in
let template = {|y = :[1]|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|"\n" 5|}]
let%expect_test "match_escaped_any_char" =
let source = {|printf("hello world\n");|} in
let template = {|printf(":[1]");|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|hello world\n|}]
let%expect_test "match_escaped_escaped" =
let source = {|printf("hello world\n\\");|} in
let template = {|printf(":[1]");|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|hello world\n\\|}]
let%expect_test "match_escaped_escaped" =
let source = {|printf("hello world\n\");|} in
let template = {|printf(":[1]");|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "EXPECT SUCCESS");
[%expect_exact {|EXPECT SUCCESS|}]
let%expect_test "holes_in_raw_literals" =
let source = {|
return expect(
extensionsController.executeCommand({
command: 'queryGraphQL',
arguments: [
`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`,
{ repoName: 'foo' },
],
})
)
|} in
let template = {|`:[1]`|} in
begin
Typescript.all ~configuration ~template ~source ()
|> function
| [] -> print_string "No matches."
| hd :: _ ->
print_string hd.matched
end;
[%expect_exact {|`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`|}]
let%expect_test "holes_in_raw_literals_partial" =
let source = {|
return expect(
extensionsController.executeCommand({
command: 'queryGraphQL',
arguments: [
`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`,
{ repoName: 'foo' },
],
})
)
|} in
let template = {|` query ResolveRepo(:[1]) {:[2]} `|} in
begin
Typescript.all ~configuration ~template ~source ()
|> function
| [] -> print_string "No matches."
| hd :: _ ->
print_string hd.matched
end;
[%expect_exact {|`
query ResolveRepo($repoName: String!) {
repository(name: $repoName) {
url
}
}
`|}]
let%expect_test "dont_detect_comments_in_strings_with_hole_matcher" =
let source = {|"// not a comment"|} in
let template = {|":[1]"|} in
let rewrite_template = {|:[1]|} in
Go.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "BROKEN EXPECT");
[%expect_exact {|// not a comment|}]
Deactivated : this will conflict with division syntax
let%expect_test " match_regex_delimiters " =
let source = { |/f\/oo/ " /bar/"| } in
let template = { } in
let rewrite_template = { |:[1]| } in
~configuration ~template ~source ( )
| > Rewrite.all ~source ~rewrite_template
| > ( function
| Some { rewritten_source ; _ } - > print_string rewritten_source
| None - > print_string " EXPECT SUCCESS " ) ;
[ % expect_exact { |f\/oo " /bar/"| } ]
let%expect_test "match_regex_delimiters" =
let source = {|/f\/oo/ "/bar/"|} in
let template = {|/:[1]/|} in
let rewrite_template = {|:[1]|} in
Typescript.all ~configuration ~template ~source ()
|> Rewrite.all ~source ~rewrite_template
|> (function
| Some { rewritten_source; _ } -> print_string rewritten_source
| None -> print_string "EXPECT SUCCESS");
[%expect_exact {|f\/oo "/bar/"|}]
*)
|
f6570fae5c92063fb36edd7706c4927d6835c3219e05e91a441a2af100aa3030 | camlp4/camlp4 | pr_scheme.ml | (* pa_r.cmo q_MLast.cmo pa_extfun.cmo pr_dump.cmo *)
(***********************************************************************)
(* *)
(* Camlp4 *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file *)
(* ../../../LICENSE. *)
(* *)
(***********************************************************************)
open Pcaml;
open Format;
type printer_t 'a =
{ pr_fun : mutable string -> next 'a;
pr_levels : mutable list (pr_level 'a) }
and pr_level 'a =
{ pr_label : string;
pr_box : formatter -> (formatter -> unit) -> 'a -> unit;
pr_rules : mutable pr_rule 'a }
and pr_rule 'a =
Extfun.t 'a (formatter -> curr 'a -> next 'a -> string -> kont -> unit)
and curr 'a = formatter -> ('a * string * kont) -> unit
and next 'a = formatter -> ('a * string * kont) -> unit
and kont = formatter -> unit;
value not_impl name x ppf k =
let desc =
if Obj.is_block (Obj.repr x) then
"tag = " ^ string_of_int (Obj.tag (Obj.repr x))
else "int_val = " ^ string_of_int (Obj.magic x)
in
fprintf ppf "<pr_scheme: not impl: %s; %s>%t" name desc k
;
value pr_fun name pr lab =
loop False pr.pr_levels where rec loop app =
fun
[ [] -> fun ppf (x, dg, k) -> failwith ("unable to print " ^ name)
| [lev :: levl] ->
if app || lev.pr_label = lab then
let next = loop True levl in
let rec curr ppf (x, dg, k) =
Extfun.apply lev.pr_rules x ppf curr next dg k
in
fun ppf ((x, _, _) as n) -> lev.pr_box ppf (fun ppf -> curr ppf n) x
else loop app levl ]
;
value rec find_pr_level lab =
fun
[ [] -> failwith ("level " ^ lab ^ " not found")
| [lev :: levl] ->
if lev.pr_label = lab then lev else find_pr_level lab levl ]
;
value pr_constr_decl = {pr_fun = fun []; pr_levels = []};
value constr_decl ppf (x, k) = pr_constr_decl.pr_fun "top" ppf (x, "", k);
pr_constr_decl.pr_fun := pr_fun "constr_decl" pr_constr_decl;
value pr_ctyp = {pr_fun = fun []; pr_levels = []};
pr_ctyp.pr_fun := pr_fun "ctyp" pr_ctyp;
value ctyp ppf (x, k) = pr_ctyp.pr_fun "top" ppf (x, "", k);
value pr_expr = {pr_fun = fun []; pr_levels = []};
pr_expr.pr_fun := pr_fun "expr" pr_expr;
value expr ppf (x, k) = pr_expr.pr_fun "top" ppf (x, "", k);
value pr_label_decl = {pr_fun = fun []; pr_levels = []};
value label_decl ppf (x, k) = pr_label_decl.pr_fun "top" ppf (x, "", k);
pr_label_decl.pr_fun := pr_fun "label_decl" pr_label_decl;
value pr_let_binding = {pr_fun = fun []; pr_levels = []};
pr_let_binding.pr_fun := pr_fun "let_binding" pr_let_binding;
value let_binding ppf (x, k) = pr_let_binding.pr_fun "top" ppf (x, "", k);
value pr_match_assoc = {pr_fun = fun []; pr_levels = []};
pr_match_assoc.pr_fun := pr_fun "match_assoc" pr_match_assoc;
value match_assoc ppf (x, k) = pr_match_assoc.pr_fun "top" ppf (x, "", k);
value pr_mod_ident = {pr_fun = fun []; pr_levels = []};
pr_mod_ident.pr_fun := pr_fun "mod_ident" pr_mod_ident;
value mod_ident ppf (x, k) = pr_mod_ident.pr_fun "top" ppf (x, "", k);
value pr_module_binding = {pr_fun = fun []; pr_levels = []};
pr_module_binding.pr_fun := pr_fun "module_binding" pr_module_binding;
value module_binding ppf (x, k) =
pr_module_binding.pr_fun "top" ppf (x, "", k);
value pr_module_expr = {pr_fun = fun []; pr_levels = []};
pr_module_expr.pr_fun := pr_fun "module_expr" pr_module_expr;
value module_expr ppf (x, k) = pr_module_expr.pr_fun "top" ppf (x, "", k);
value pr_module_type = {pr_fun = fun []; pr_levels = []};
pr_module_type.pr_fun := pr_fun "module_type" pr_module_type;
value module_type ppf (x, k) = pr_module_type.pr_fun "top" ppf (x, "", k);
value pr_patt = {pr_fun = fun []; pr_levels = []};
pr_patt.pr_fun := pr_fun "patt" pr_patt;
value patt ppf (x, k) = pr_patt.pr_fun "top" ppf (x, "", k);
value pr_sig_item = {pr_fun = fun []; pr_levels = []};
pr_sig_item.pr_fun := pr_fun "sig_item" pr_sig_item;
value sig_item ppf (x, k) = pr_sig_item.pr_fun "top" ppf (x, "", k);
value pr_str_item = {pr_fun = fun []; pr_levels = []};
pr_str_item.pr_fun := pr_fun "str_item" pr_str_item;
value str_item ppf (x, k) = pr_str_item.pr_fun "top" ppf (x, "", k);
value pr_type_decl = {pr_fun = fun []; pr_levels = []};
value type_decl ppf (x, k) = pr_type_decl.pr_fun "top" ppf (x, "", k);
pr_type_decl.pr_fun := pr_fun "type_decl" pr_type_decl;
value pr_type_params = {pr_fun = fun []; pr_levels = []};
value type_params ppf (x, k) = pr_type_params.pr_fun "top" ppf (x, "", k);
pr_type_params.pr_fun := pr_fun "type_params" pr_type_params;
value pr_with_constr = {pr_fun = fun []; pr_levels = []};
value with_constr ppf (x, k) = pr_with_constr.pr_fun "top" ppf (x, "", k);
pr_with_constr.pr_fun := pr_fun "with_constr" pr_with_constr;
(* general functions *)
value nok ppf = ();
value ks s k ppf = fprintf ppf "%s%t" s k;
value rec list f ppf (l, k) =
match l with
[ [] -> k ppf
| [x] -> f ppf (x, k)
| [x :: l] -> fprintf ppf "%a@ %a" f (x, nok) (list f) (l, k) ]
;
value rec listwb b f ppf (l, k) =
match l with
[ [] -> k ppf
| [x] -> f ppf ((b, x), k)
| [x :: l] -> fprintf ppf "%a@ %a" f ((b, x), nok) (listwb "" f) (l, k) ]
;
(* specific functions *)
value rec is_irrefut_patt =
fun
[ <:patt< $lid:_$ >> -> True
| <:patt< () >> -> True
| <:patt< _ >> -> True
| <:patt< ($x$ as $y$) >> -> is_irrefut_patt x && is_irrefut_patt y
| <:patt< { $list:fpl$ } >> ->
List.for_all (fun (_, p) -> is_irrefut_patt p) fpl
| <:patt< ($p$ : $_$) >> -> is_irrefut_patt p
| <:patt< ($list:pl$) >> -> List.for_all is_irrefut_patt pl
| <:patt< ? $_$ : ( $p$ ) >> -> is_irrefut_patt p
| <:patt< ? $_$ : ($p$ = $_$) >> -> is_irrefut_patt p
| <:patt< ~ $_$ >> -> True
| <:patt< ~ $_$ : $p$ >> -> is_irrefut_patt p
| _ -> False ]
;
value expr_fun_args ge = Extfun.apply pr_expr_fun_args.val ge;
pr_expr_fun_args.val :=
extfun Extfun.empty with
[ <:expr< fun [$p$ -> $e$] >> as ge ->
if is_irrefut_patt p then
let (pl, e) = expr_fun_args e in
([p :: pl], e)
else ([], ge)
| ge -> ([], ge) ];
value sequence ppf (e, k) =
match e with
[ <:expr< do { $list:el$ } >> ->
fprintf ppf "@[<hv>%a@]" (list expr) (el, k)
| _ -> expr ppf (e, k) ]
;
value string ppf (s, k) = fprintf ppf "\"%s\"%t" s k;
value int_repr s =
if String.length s > 2 && s.[0] = '0' then
match s.[1] with
[ 'b' | 'o' | 'x' | 'B' | 'O' | 'X' ->
"#" ^ String.sub s 1 (String.length s - 1)
| _ -> s ]
else s
;
value assoc_left_parsed_op_list = ["+"; "*"; "land"; "lor"; "lxor"];
value assoc_right_parsed_op_list = ["and"; "or"; "^"; "@"];
value and_by_couple_op_list = ["="; "<>"; "<"; ">"; "<="; ">="; "=="; "!="];
(* extensible pretty print functions *)
pr_constr_decl.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (loc, c, []) ->
fun ppf curr next dg k -> fprintf ppf "(@[<hv>%s%t@]" c (ks ")" k)
| (loc, c, tl) ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>%s@ %a@]" c (list ctyp) (tl, ks ")" k) ]}];
pr_ctyp.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:ctyp< [ $list:cdl$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>sum@ %a@]" (list constr_decl) (cdl, ks ")" k)
| <:ctyp< { $list:cdl$ } >> ->
fun ppf curr next dg k ->
fprintf ppf "{@[<hv>%a@]" (list label_decl) (cdl, ks "}" k)
| <:ctyp< ( $list:tl$ ) >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[* @[<hv>%a@]@]" (list ctyp) (tl, ks ")" k)
| <:ctyp< $t1$ -> $t2$ >> ->
fun ppf curr next dg k ->
let tl =
loop t2 where rec loop =
fun
[ <:ctyp< $t1$ -> $t2$ >> -> [t1 :: loop t2]
| t -> [t] ]
in
fprintf ppf "(@[-> @[<hv>%a@]@]" (list ctyp)
([t1 :: tl], ks ")" k)
| <:ctyp< $t1$ $t2$ >> ->
fun ppf curr next dg k ->
let (t, tl) =
loop [t2] t1 where rec loop tl =
fun
[ <:ctyp< $t1$ $t2$ >> -> loop [t2 :: tl] t1
| t1 -> (t1, tl) ]
in
fprintf ppf "(@[%a@ %a@]" ctyp (t, nok) (list ctyp) (tl, ks ")" k)
| <:ctyp< $t1$ . $t2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.%a" ctyp (t1, nok) ctyp (t2, k)
| <:ctyp< $lid:s$ >> | <:ctyp< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:ctyp< ' $s$ >> ->
fun ppf curr next dg k -> fprintf ppf "'%s%t" s k
| <:ctyp< _ >> ->
fun ppf curr next dg k -> fprintf ppf "_%t" k
| x ->
fun ppf curr next dg k -> not_impl "ctyp" x ppf k ]}];
pr_expr.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:expr< fun [] >> ->
fun ppf curr next dg k ->
fprintf ppf "(lambda%t" (ks ")" k)
| <:expr< fun $lid:s$ -> $e$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(lambda@ %s@;<1 1>%a" s expr (e, ks ")" k)
| <:expr< fun [ $list:pwel$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>lambda_match@ %a@]" (list match_assoc)
(pwel, ks ")" k)
| <:expr< match $e$ with [ $list:pwel$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>@[<b 2>match@ %a@]@ %a@]" expr (e, nok)
(list match_assoc) (pwel, ks ")" k)
| <:expr< try $e$ with [ $list:pwel$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>@[<b 2>try@ %a@]@ %a@]" expr (e, nok)
(list match_assoc) (pwel, ks ")" k)
| <:expr< let $p1$ = $e1$ in $e2$ >> ->
fun ppf curr next dg k ->
let (pel, e) =
loop [(p1, e1)] e2 where rec loop pel =
fun
[ <:expr< let $p1$ = $e1$ in $e2$ >> ->
loop [(p1, e1) :: pel] e2
| e -> (List.rev pel, e) ]
in
let b =
match pel with
[ [_] -> "let"
| _ -> "let*" ]
in
fprintf ppf "(@[@[%s (@[<v>%a@]@]@;<1 2>%a@]" b
(listwb "" let_binding) (pel, ks ")" nok)
sequence (e, ks ")" k)
| <:expr< let $opt:rf$ $list:pel$ in $e$ >> ->
fun ppf curr next dg k ->
let b = if rf then "letrec" else "let" in
fprintf ppf "(@[<hv>%s@ (@[<hv>%a@]@ %a@]" b
(listwb "" let_binding) (pel, ks ")" nok) expr (e, ks ")" k)
| <:expr< if $e1$ then $e2$ else () >> ->
fun ppf curr next dg k ->
fprintf ppf "(if @[%a@;<1 0>%a@]" expr (e1, nok)
expr (e2, ks ")" k)
| <:expr< if $e1$ then $e2$ else $e3$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(if @[%a@ %a@ %a@]" expr (e1, nok)
expr (e2, nok) expr (e3, ks ")" k)
| <:expr< do { $list:el$ } >> ->
fun ppf curr next dg k ->
fprintf ppf "(begin@;<1 1>@[<hv>%a@]" (list expr) (el, ks ")" k)
| <:expr< for $i$ = $e1$ to $e2$ do { $list:el$ } >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[for %s@ %a@ %a %a@]" i expr (e1, nok)
expr (e2, nok) (list expr) (el, ks ")" k)
| <:expr< ($e$ : $t$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(:@ %a@ %a" expr (e, nok) ctyp (t, ks ")" k)
| <:expr< ($list:el$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(values @[%a@]" (list expr) (el, ks ")" k)
| <:expr< { $list:fel$ } >> ->
fun ppf curr next dg k ->
let record_binding ppf ((p, e), k) =
fprintf ppf "(@[%a@ %a@]" patt (p, nok) expr (e, ks ")" k)
in
fprintf ppf "{@[<hv>%a@]" (list record_binding) (fel, ks "}" k)
| <:expr< { ($e$) with $list:fel$ } >> ->
fun ppf curr next dg k ->
let record_binding ppf ((p, e), k) =
fprintf ppf "(@[%a@ %a@]" patt (p, nok) expr (e, ks ")" k)
in
fprintf ppf "{@[@[with@ %a@]@ @[%a@]@]" expr (e, nok)
(list record_binding) (fel, ks "}" k)
| <:expr< $e1$ := $e2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(:=@;<1 1>%a@;<1 1>%a" expr (e1, nok)
expr (e2, ks ")" k)
| <:expr< [$_$ :: $_$] >> as e ->
fun ppf curr next dg k ->
let (el, c) =
make_list e where rec make_list e =
match e with
[ <:expr< [$e$ :: $y$] >> ->
let (el, c) = make_list y in
([e :: el], c)
| <:expr< [] >> -> ([], None)
| x -> ([], Some e) ]
in
match c with
[ None ->
fprintf ppf "[%a" (list expr) (el, ks "]" k)
| Some x ->
fprintf ppf "[%a@ %a" (list expr) (el, ks " ." nok)
expr (x, ks "]" k) ]
| <:expr< lazy ($x$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[lazy@ %a@]" expr (x, ks ")" k)
| <:expr< $lid:s$ $e1$ $e2$ >>
when List.mem s assoc_right_parsed_op_list ->
fun ppf curr next dg k ->
let el =
loop [e1] e2 where rec loop el =
fun
[ <:expr< $lid:s1$ $e1$ $e2$ >> when s1 = s ->
loop [e1 :: el] e2
| e -> List.rev [e :: el] ]
in
fprintf ppf "(@[%s %a@]" s (list expr) (el, ks ")" k)
| <:expr< $e1$ $e2$ >> ->
fun ppf curr next dg k ->
let (f, el) =
loop [e2] e1 where rec loop el =
fun
[ <:expr< $e1$ $e2$ >> -> loop [e2 :: el] e1
| e1 -> (e1, el) ]
in
fprintf ppf "(@[%a@ %a@]" expr (f, nok) (list expr) (el, ks ")" k)
| <:expr< ~ $s$ : ($e$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(~%s@ %a" s expr (e, ks ")" k)
| <:expr< $e1$ .[ $e2$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.[%a" expr (e1, nok) expr (e2, ks "]" k)
| <:expr< $e1$ .( $e2$ ) >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.(%a" expr (e1, nok) expr (e2, ks ")" k)
| <:expr< $e1$ . $e2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.%a" expr (e1, nok) expr (e2, k)
| <:expr< $int:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" (int_repr s) k
| <:expr< $lid:s$ >> | <:expr< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:expr< ` $s$ >> ->
fun ppf curr next dg k -> fprintf ppf "`%s%t" s k
| <:expr< $str:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "\"%s\"%t" s k
| <:expr< $chr:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "'%s'%t" s k
| x ->
fun ppf curr next dg k -> not_impl "expr" x ppf k ]}];
pr_label_decl.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (loc, f, m, t) ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>%s%t@ %a@]" f
(fun ppf -> if m then fprintf ppf "@ mutable" else ())
ctyp (t, ks ")" k) ]}];
pr_let_binding.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (b, (p, e)) ->
fun ppf curr next dg k ->
let (pl, e) = expr_fun_args e in
match pl with
[ [] ->
fprintf ppf "(@[<b 1>%s%s%a@ %a@]" b
(if b = "" then "" else " ") patt (p, nok)
sequence (e, ks ")" k)
| _ ->
fprintf ppf "(@[<b 1>%s%s(%a)@ %a@]" b
(if b = "" then "" else " ") (list patt) ([p :: pl], nok)
sequence (e, ks ")" k) ] ]}];
pr_match_assoc.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (p, we, e) ->
fun ppf curr next dg k ->
fprintf ppf "(@[%t@ %a@]"
(fun ppf ->
match we with
[ Some e ->
fprintf ppf "(when@ %a@ %a" patt (p, nok)
expr (e, ks ")" nok)
| None -> patt ppf (p, nok) ])
sequence (e, ks ")" k) ]}];
pr_mod_ident.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ [s] ->
fun ppf curr next dg k ->
fprintf ppf "%s%t" s k
| [s :: sl] ->
fun ppf curr next dg k ->
fprintf ppf "%s.%a" s curr (sl, "", k)
| x ->
fun ppf curr next dg k -> not_impl "mod_ident" x ppf k ]}];
pr_module_binding.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (b, s, me) ->
fun ppf curr next dg k ->
fprintf ppf "%s@ %s@ %a" b s module_expr (me, k) ]}];
pr_module_expr.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:module_expr< functor ($i$ : $mt$) -> $me$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[@[functor@ %s@]@ %a@]@ %a@]"
i module_type (mt, nok) module_expr (me, ks ")" k)
| <:module_expr< struct $list:sil$ end >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[struct@ @[<hv>%a@]@]" (list str_item)
(sil, ks ")" k)
| <:module_expr< $me1$ $me2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[%a@ %a@]" module_expr (me1, nok)
module_expr (me2, ks ")" k)
| <:module_expr< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| x ->
fun ppf curr next dg k -> not_impl "module_expr" x ppf k ]}];
pr_module_type.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:module_type< functor ($i$ : $mt1$) -> $mt2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[@[functor@ %s@]@ %a@]@ %a@]"
i module_type (mt1, nok) module_type (mt2, ks ")" k)
| <:module_type< sig $list:sil$ end >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[sig@ @[<hv>%a@]@]" (list sig_item) (sil, ks ")" k)
| <:module_type< $mt$ with $list:wcl$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[with@;<1 2>@[%a@ (%a@]@]" module_type (mt, nok)
(list with_constr) (wcl, ks "))" k)
| <:module_type< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| x ->
fun ppf curr next dg k -> not_impl "module_type" x ppf k ]}];
pr_patt.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:patt< $p1$ | $p2$ >> ->
fun ppf curr next dg k ->
let (f, pl) =
loop [p2] p1 where rec loop pl =
fun
[ <:patt< $p1$ | $p2$ >> -> loop [p2 :: pl] p1
| p1 -> (p1, pl) ]
in
fprintf ppf "(@[or@ %a@ %a@]" patt (f, nok) (list patt)
(pl, ks ")" k)
| <:patt< ($p1$ as $p2$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[as@ %a@ %a@]" patt (p1, nok) patt (p2, ks ")" k)
| <:patt< $p1$ .. $p2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[range@ %a@ %a@]" patt (p1, nok) patt (p2, ks ")" k)
| <:patt< [$_$ :: $_$] >> as p ->
fun ppf curr next dg k ->
let (pl, c) =
make_list p where rec make_list p =
match p with
[ <:patt< [$p$ :: $y$] >> ->
let (pl, c) = make_list y in
([p :: pl], c)
| <:patt< [] >> -> ([], None)
| x -> ([], Some p) ]
in
match c with
[ None ->
fprintf ppf "[%a" (list patt) (pl, ks "]" k)
| Some x ->
fprintf ppf "[%a@ %a" (list patt) (pl, ks " ." nok)
patt (x, ks "]" k) ]
| <:patt< $p1$ $p2$ >> ->
fun ppf curr next dg k ->
let pl =
loop [p2] p1 where rec loop pl =
fun
[ <:patt< $p1$ $p2$ >> -> loop [p2 :: pl] p1
| p1 -> [p1 :: pl] ]
in
fprintf ppf "(@[%a@]" (list patt) (pl, ks ")" k)
| <:patt< ($p$ : $t$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(:@ %a@ %a" patt (p, nok) ctyp (t, ks ")" k)
| <:patt< ($list:pl$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(values @[%a@]" (list patt) (pl, ks ")" k)
| <:patt< { $list:fpl$ } >> ->
fun ppf curr next dg k ->
let record_binding ppf ((p1, p2), k) =
fprintf ppf "(@[%a@ %a@]" patt (p1, nok) patt (p2, ks ")" k)
in
fprintf ppf "(@[<hv>{}@ %a@]" (list record_binding) (fpl, ks ")" k)
| <:patt< ? $x$ >> ->
fun ppf curr next dg k -> fprintf ppf "?%s%t" x k
| <:patt< ? ($lid:x$ = $e$) >> ->
fun ppf curr next dg k -> fprintf ppf "(?%s@ %a" x expr (e, ks ")" k)
| <:patt< $p1$ . $p2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.%a" patt (p1, nok) patt (p2, k)
| <:patt< $lid:s$ >> | <:patt< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:patt< $str:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "\"%s\"%t" s k
| <:patt< $chr:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "'%s'%t" s k
| <:patt< $int:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" (int_repr s) k
| <:patt< $flo:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:patt< _ >> ->
fun ppf curr next dg k -> fprintf ppf "_%t" k
| x ->
fun ppf curr next dg k -> not_impl "patt" x ppf k ]}];
pr_sig_item.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:sig_item< type $list:tdl$ >> ->
fun ppf curr next dg k ->
match tdl with
[ [td] -> fprintf ppf "(%a" type_decl (("type", td), ks ")" k)
| tdl ->
fprintf ppf "(@[<hv>type@ %a@]" (listwb "" type_decl)
(tdl, ks ")" k) ]
| <:sig_item< exception $c$ of $list:tl$ >> ->
fun ppf curr next dg k ->
match tl with
[ [] -> fprintf ppf "(@[exception@ %s%t@]" c (ks ")" k)
| tl ->
fprintf ppf "(@[@[exception@ %s@]@ %a@]" c
(list ctyp) (tl, ks ")" k) ]
| <:sig_item< value $i$ : $t$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[value %s@]@ %a@]" i ctyp (t, ks ")" k)
| <:sig_item< external $i$ : $t$ = $list:pd$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[external@ %s@]@ %a@ %a@]" i ctyp (t, nok)
(list string) (pd, ks ")" k)
| <:sig_item< module $s$ : $mt$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[module@ %s@]@ %a@]" s
module_type (mt, ks ")" k)
| <:sig_item< module type $s$ = $mt$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[moduletype@ %s@]@ %a@]" s
module_type (mt, ks ")" k)
| <:sig_item< declare $list:s$ end >> ->
fun ppf curr next dg k ->
if s = [] then fprintf ppf "; ..."
else fprintf ppf "%a" (list sig_item) (s, k)
| MLast.SgUse _ _ _ ->
fun ppf curr next dg k -> ()
| x ->
fun ppf curr next dg k -> not_impl "sig_item" x ppf k ]}];
pr_str_item.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:str_item< open $i$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(open@ %a" mod_ident (i, ks ")" k)
| <:str_item< type $list:tdl$ >> ->
fun ppf curr next dg k ->
match tdl with
[ [td] -> fprintf ppf "(%a" type_decl (("type", td), ks ")" k)
| tdl ->
fprintf ppf "(@[<hv>type@ %a@]" (listwb "" type_decl)
(tdl, ks ")" k) ]
| <:str_item< exception $c$ of $list:tl$ >> ->
fun ppf curr next dg k ->
match tl with
[ [] -> fprintf ppf "(@[exception@ %s%t@]" c (ks ")" k)
| tl ->
fprintf ppf "(@[@[exception@ %s@]@ %a@]" c
(list ctyp) (tl, ks ")" k) ]
| <:str_item< value $opt:rf$ $list:pel$ >> ->
fun ppf curr next dg k ->
let b = if rf then "definerec" else "define" in
match pel with
[ [(p, e)] ->
fprintf ppf "%a" let_binding ((b, (p, e)), k)
| pel ->
fprintf ppf "(@[<hv 1>%s*@ %a@]" b (listwb "" let_binding)
(pel, ks ")" k) ]
| <:str_item< module $s$ = $me$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(%a" module_binding (("module", s, me), ks ")" k)
| <:str_item< module type $s$ = $mt$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[moduletype@ %s@]@ %a@]" s
module_type (mt, ks ")" k)
| <:str_item< external $i$ : $t$ = $list:pd$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[external@ %s@ %a@ %a@]" i ctyp (t, nok)
(list string) (pd, ks ")" k)
| <:str_item< $exp:e$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a" expr (e, k)
| <:str_item< # $s$ $opt:x$ >> ->
fun ppf curr next dg k ->
match x with
[ Some e -> fprintf ppf "; # (%s %a" s expr (e, ks ")" k)
| None -> fprintf ppf "; # (%s%t" s (ks ")" k) ]
| <:str_item< declare $list:s$ end >> ->
fun ppf curr next dg k ->
if s = [] then fprintf ppf "; ..."
else fprintf ppf "%a" (list str_item) (s, k)
| MLast.StUse _ _ _ ->
fun ppf curr next dg k -> ()
| x ->
fun ppf curr next dg k -> not_impl "str_item" x ppf k ]}];
pr_type_decl.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (b, ((_, tn), tp, te, cl)) ->
fun ppf curr next dg k ->
fprintf ppf "%t%t@;<1 1>%a"
(fun ppf ->
if b <> "" then fprintf ppf "%s@ " b
else ())
(fun ppf ->
match tp with
[ [] -> fprintf ppf "%s" tn
| tp -> fprintf ppf "(%s%a)" tn type_params (tp, nok) ])
ctyp (te, k) ]}];
pr_type_params.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ [(s, vari) :: tpl] ->
fun ppf curr next dg k ->
fprintf ppf "@ '%s%a" s type_params (tpl, k)
| [] ->
fun ppf curr next dg k -> () ]}];
pr_with_constr.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ MLast.WcTyp _ m tp te ->
fun ppf curr next dg k ->
fprintf ppf "(type@ %t@;<1 1>%a"
(fun ppf ->
match tp with
[ [] -> fprintf ppf "%a" mod_ident (m, nok)
| tp ->
fprintf ppf "(%a@ %a)" mod_ident (m, nok)
type_params (tp, nok) ])
ctyp (te, ks ")" k)
| x ->
fun ppf curr next dg k -> not_impl "with_constr" x ppf k ]}];
(* main *)
value output_string_eval ppf s =
loop 0 where rec loop i =
if i == String.length s then ()
else if i == String.length s - 1 then pp_print_char ppf s.[i]
else
match (s.[i], s.[i + 1]) with
[ ('\\', 'n') -> do { pp_print_char ppf '\n'; loop (i + 2) }
| (c, _) -> do { pp_print_char ppf c; loop (i + 1) } ]
;
value sep = Pcaml.inter_phrases;
value input_source ic len =
let buff = Buffer.create 20 in
try
let rec loop i =
if i >= len then Buffer.contents buff
else do { let c = input_char ic in Buffer.add_char buff c; loop (i + 1) }
in
loop 0
with
[ End_of_file ->
let s = Buffer.contents buff in
if s = "" then
match sep.val with
[ Some s -> s
| None -> "\n" ]
else s ]
;
value copy_source ppf (ic, first, bp, ep) =
match sep.val with
[ Some str ->
if first then ()
else if ep == in_channel_length ic then pp_print_string ppf "\n"
else output_string_eval ppf str
| None ->
do {
seek_in ic bp;
let s = input_source ic (ep - bp) in pp_print_string ppf s
} ]
;
value copy_to_end ppf (ic, first, bp) =
let ilen = in_channel_length ic in
if bp < ilen then copy_source ppf (ic, first, bp, ilen)
else pp_print_string ppf "\n"
;
value apply_printer printer ast =
let ppf = std_formatter in
if Pcaml.input_file.val <> "-" && Pcaml.input_file.val <> "" then do {
let ic = open_in_bin Pcaml.input_file.val in
try
let (first, last_pos) =
List.fold_left
(fun (first, last_pos) (si, (bp, ep)) ->
do {
fprintf ppf "@[%a@]@?" copy_source (ic, first, last_pos.Lexing.pos_cnum, bp.Lexing.pos_cnum);
fprintf ppf "@[%a@]@?" printer (si, nok);
(False, ep)
})
(True, Token.nowhere) ast
in
fprintf ppf "@[%a@]@?" copy_to_end (ic, first, last_pos.Lexing.pos_cnum)
with x ->
do { fprintf ppf "@."; close_in ic; raise x };
close_in ic;
}
else failwith "not implemented"
;
Pcaml.print_interf.val := apply_printer sig_item;
Pcaml.print_implem.val := apply_printer str_item;
Pcaml.add_option "-l" (Arg.Int (fun x -> set_margin x))
"<length> Maximum line length for pretty printing.";
Pcaml.add_option "-sep" (Arg.String (fun x -> sep.val := Some x))
"<string> Use this string between phrases instead of reading source.";
| null | https://raw.githubusercontent.com/camlp4/camlp4/9b3314ea63288decb857239bd94f0c3342136844/camlp4/unmaintained/scheme/pr_scheme.ml | ocaml | pa_r.cmo q_MLast.cmo pa_extfun.cmo pr_dump.cmo
*********************************************************************
Camlp4
the special exception on linking described in file
../../../LICENSE.
*********************************************************************
general functions
specific functions
extensible pretty print functions
main | , projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
open Pcaml;
open Format;
type printer_t 'a =
{ pr_fun : mutable string -> next 'a;
pr_levels : mutable list (pr_level 'a) }
and pr_level 'a =
{ pr_label : string;
pr_box : formatter -> (formatter -> unit) -> 'a -> unit;
pr_rules : mutable pr_rule 'a }
and pr_rule 'a =
Extfun.t 'a (formatter -> curr 'a -> next 'a -> string -> kont -> unit)
and curr 'a = formatter -> ('a * string * kont) -> unit
and next 'a = formatter -> ('a * string * kont) -> unit
and kont = formatter -> unit;
value not_impl name x ppf k =
let desc =
if Obj.is_block (Obj.repr x) then
"tag = " ^ string_of_int (Obj.tag (Obj.repr x))
else "int_val = " ^ string_of_int (Obj.magic x)
in
fprintf ppf "<pr_scheme: not impl: %s; %s>%t" name desc k
;
value pr_fun name pr lab =
loop False pr.pr_levels where rec loop app =
fun
[ [] -> fun ppf (x, dg, k) -> failwith ("unable to print " ^ name)
| [lev :: levl] ->
if app || lev.pr_label = lab then
let next = loop True levl in
let rec curr ppf (x, dg, k) =
Extfun.apply lev.pr_rules x ppf curr next dg k
in
fun ppf ((x, _, _) as n) -> lev.pr_box ppf (fun ppf -> curr ppf n) x
else loop app levl ]
;
value rec find_pr_level lab =
fun
[ [] -> failwith ("level " ^ lab ^ " not found")
| [lev :: levl] ->
if lev.pr_label = lab then lev else find_pr_level lab levl ]
;
value pr_constr_decl = {pr_fun = fun []; pr_levels = []};
value constr_decl ppf (x, k) = pr_constr_decl.pr_fun "top" ppf (x, "", k);
pr_constr_decl.pr_fun := pr_fun "constr_decl" pr_constr_decl;
value pr_ctyp = {pr_fun = fun []; pr_levels = []};
pr_ctyp.pr_fun := pr_fun "ctyp" pr_ctyp;
value ctyp ppf (x, k) = pr_ctyp.pr_fun "top" ppf (x, "", k);
value pr_expr = {pr_fun = fun []; pr_levels = []};
pr_expr.pr_fun := pr_fun "expr" pr_expr;
value expr ppf (x, k) = pr_expr.pr_fun "top" ppf (x, "", k);
value pr_label_decl = {pr_fun = fun []; pr_levels = []};
value label_decl ppf (x, k) = pr_label_decl.pr_fun "top" ppf (x, "", k);
pr_label_decl.pr_fun := pr_fun "label_decl" pr_label_decl;
value pr_let_binding = {pr_fun = fun []; pr_levels = []};
pr_let_binding.pr_fun := pr_fun "let_binding" pr_let_binding;
value let_binding ppf (x, k) = pr_let_binding.pr_fun "top" ppf (x, "", k);
value pr_match_assoc = {pr_fun = fun []; pr_levels = []};
pr_match_assoc.pr_fun := pr_fun "match_assoc" pr_match_assoc;
value match_assoc ppf (x, k) = pr_match_assoc.pr_fun "top" ppf (x, "", k);
value pr_mod_ident = {pr_fun = fun []; pr_levels = []};
pr_mod_ident.pr_fun := pr_fun "mod_ident" pr_mod_ident;
value mod_ident ppf (x, k) = pr_mod_ident.pr_fun "top" ppf (x, "", k);
value pr_module_binding = {pr_fun = fun []; pr_levels = []};
pr_module_binding.pr_fun := pr_fun "module_binding" pr_module_binding;
value module_binding ppf (x, k) =
pr_module_binding.pr_fun "top" ppf (x, "", k);
value pr_module_expr = {pr_fun = fun []; pr_levels = []};
pr_module_expr.pr_fun := pr_fun "module_expr" pr_module_expr;
value module_expr ppf (x, k) = pr_module_expr.pr_fun "top" ppf (x, "", k);
value pr_module_type = {pr_fun = fun []; pr_levels = []};
pr_module_type.pr_fun := pr_fun "module_type" pr_module_type;
value module_type ppf (x, k) = pr_module_type.pr_fun "top" ppf (x, "", k);
value pr_patt = {pr_fun = fun []; pr_levels = []};
pr_patt.pr_fun := pr_fun "patt" pr_patt;
value patt ppf (x, k) = pr_patt.pr_fun "top" ppf (x, "", k);
value pr_sig_item = {pr_fun = fun []; pr_levels = []};
pr_sig_item.pr_fun := pr_fun "sig_item" pr_sig_item;
value sig_item ppf (x, k) = pr_sig_item.pr_fun "top" ppf (x, "", k);
value pr_str_item = {pr_fun = fun []; pr_levels = []};
pr_str_item.pr_fun := pr_fun "str_item" pr_str_item;
value str_item ppf (x, k) = pr_str_item.pr_fun "top" ppf (x, "", k);
value pr_type_decl = {pr_fun = fun []; pr_levels = []};
value type_decl ppf (x, k) = pr_type_decl.pr_fun "top" ppf (x, "", k);
pr_type_decl.pr_fun := pr_fun "type_decl" pr_type_decl;
value pr_type_params = {pr_fun = fun []; pr_levels = []};
value type_params ppf (x, k) = pr_type_params.pr_fun "top" ppf (x, "", k);
pr_type_params.pr_fun := pr_fun "type_params" pr_type_params;
value pr_with_constr = {pr_fun = fun []; pr_levels = []};
value with_constr ppf (x, k) = pr_with_constr.pr_fun "top" ppf (x, "", k);
pr_with_constr.pr_fun := pr_fun "with_constr" pr_with_constr;
value nok ppf = ();
value ks s k ppf = fprintf ppf "%s%t" s k;
value rec list f ppf (l, k) =
match l with
[ [] -> k ppf
| [x] -> f ppf (x, k)
| [x :: l] -> fprintf ppf "%a@ %a" f (x, nok) (list f) (l, k) ]
;
value rec listwb b f ppf (l, k) =
match l with
[ [] -> k ppf
| [x] -> f ppf ((b, x), k)
| [x :: l] -> fprintf ppf "%a@ %a" f ((b, x), nok) (listwb "" f) (l, k) ]
;
value rec is_irrefut_patt =
fun
[ <:patt< $lid:_$ >> -> True
| <:patt< () >> -> True
| <:patt< _ >> -> True
| <:patt< ($x$ as $y$) >> -> is_irrefut_patt x && is_irrefut_patt y
| <:patt< { $list:fpl$ } >> ->
List.for_all (fun (_, p) -> is_irrefut_patt p) fpl
| <:patt< ($p$ : $_$) >> -> is_irrefut_patt p
| <:patt< ($list:pl$) >> -> List.for_all is_irrefut_patt pl
| <:patt< ? $_$ : ( $p$ ) >> -> is_irrefut_patt p
| <:patt< ? $_$ : ($p$ = $_$) >> -> is_irrefut_patt p
| <:patt< ~ $_$ >> -> True
| <:patt< ~ $_$ : $p$ >> -> is_irrefut_patt p
| _ -> False ]
;
value expr_fun_args ge = Extfun.apply pr_expr_fun_args.val ge;
pr_expr_fun_args.val :=
extfun Extfun.empty with
[ <:expr< fun [$p$ -> $e$] >> as ge ->
if is_irrefut_patt p then
let (pl, e) = expr_fun_args e in
([p :: pl], e)
else ([], ge)
| ge -> ([], ge) ];
value sequence ppf (e, k) =
match e with
[ <:expr< do { $list:el$ } >> ->
fprintf ppf "@[<hv>%a@]" (list expr) (el, k)
| _ -> expr ppf (e, k) ]
;
value string ppf (s, k) = fprintf ppf "\"%s\"%t" s k;
value int_repr s =
if String.length s > 2 && s.[0] = '0' then
match s.[1] with
[ 'b' | 'o' | 'x' | 'B' | 'O' | 'X' ->
"#" ^ String.sub s 1 (String.length s - 1)
| _ -> s ]
else s
;
value assoc_left_parsed_op_list = ["+"; "*"; "land"; "lor"; "lxor"];
value assoc_right_parsed_op_list = ["and"; "or"; "^"; "@"];
value and_by_couple_op_list = ["="; "<>"; "<"; ">"; "<="; ">="; "=="; "!="];
pr_constr_decl.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (loc, c, []) ->
fun ppf curr next dg k -> fprintf ppf "(@[<hv>%s%t@]" c (ks ")" k)
| (loc, c, tl) ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>%s@ %a@]" c (list ctyp) (tl, ks ")" k) ]}];
pr_ctyp.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:ctyp< [ $list:cdl$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>sum@ %a@]" (list constr_decl) (cdl, ks ")" k)
| <:ctyp< { $list:cdl$ } >> ->
fun ppf curr next dg k ->
fprintf ppf "{@[<hv>%a@]" (list label_decl) (cdl, ks "}" k)
| <:ctyp< ( $list:tl$ ) >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[* @[<hv>%a@]@]" (list ctyp) (tl, ks ")" k)
| <:ctyp< $t1$ -> $t2$ >> ->
fun ppf curr next dg k ->
let tl =
loop t2 where rec loop =
fun
[ <:ctyp< $t1$ -> $t2$ >> -> [t1 :: loop t2]
| t -> [t] ]
in
fprintf ppf "(@[-> @[<hv>%a@]@]" (list ctyp)
([t1 :: tl], ks ")" k)
| <:ctyp< $t1$ $t2$ >> ->
fun ppf curr next dg k ->
let (t, tl) =
loop [t2] t1 where rec loop tl =
fun
[ <:ctyp< $t1$ $t2$ >> -> loop [t2 :: tl] t1
| t1 -> (t1, tl) ]
in
fprintf ppf "(@[%a@ %a@]" ctyp (t, nok) (list ctyp) (tl, ks ")" k)
| <:ctyp< $t1$ . $t2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.%a" ctyp (t1, nok) ctyp (t2, k)
| <:ctyp< $lid:s$ >> | <:ctyp< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:ctyp< ' $s$ >> ->
fun ppf curr next dg k -> fprintf ppf "'%s%t" s k
| <:ctyp< _ >> ->
fun ppf curr next dg k -> fprintf ppf "_%t" k
| x ->
fun ppf curr next dg k -> not_impl "ctyp" x ppf k ]}];
pr_expr.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:expr< fun [] >> ->
fun ppf curr next dg k ->
fprintf ppf "(lambda%t" (ks ")" k)
| <:expr< fun $lid:s$ -> $e$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(lambda@ %s@;<1 1>%a" s expr (e, ks ")" k)
| <:expr< fun [ $list:pwel$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>lambda_match@ %a@]" (list match_assoc)
(pwel, ks ")" k)
| <:expr< match $e$ with [ $list:pwel$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>@[<b 2>match@ %a@]@ %a@]" expr (e, nok)
(list match_assoc) (pwel, ks ")" k)
| <:expr< try $e$ with [ $list:pwel$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>@[<b 2>try@ %a@]@ %a@]" expr (e, nok)
(list match_assoc) (pwel, ks ")" k)
| <:expr< let $p1$ = $e1$ in $e2$ >> ->
fun ppf curr next dg k ->
let (pel, e) =
loop [(p1, e1)] e2 where rec loop pel =
fun
[ <:expr< let $p1$ = $e1$ in $e2$ >> ->
loop [(p1, e1) :: pel] e2
| e -> (List.rev pel, e) ]
in
let b =
match pel with
[ [_] -> "let"
| _ -> "let*" ]
in
fprintf ppf "(@[@[%s (@[<v>%a@]@]@;<1 2>%a@]" b
(listwb "" let_binding) (pel, ks ")" nok)
sequence (e, ks ")" k)
| <:expr< let $opt:rf$ $list:pel$ in $e$ >> ->
fun ppf curr next dg k ->
let b = if rf then "letrec" else "let" in
fprintf ppf "(@[<hv>%s@ (@[<hv>%a@]@ %a@]" b
(listwb "" let_binding) (pel, ks ")" nok) expr (e, ks ")" k)
| <:expr< if $e1$ then $e2$ else () >> ->
fun ppf curr next dg k ->
fprintf ppf "(if @[%a@;<1 0>%a@]" expr (e1, nok)
expr (e2, ks ")" k)
| <:expr< if $e1$ then $e2$ else $e3$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(if @[%a@ %a@ %a@]" expr (e1, nok)
expr (e2, nok) expr (e3, ks ")" k)
| <:expr< do { $list:el$ } >> ->
fun ppf curr next dg k ->
fprintf ppf "(begin@;<1 1>@[<hv>%a@]" (list expr) (el, ks ")" k)
| <:expr< for $i$ = $e1$ to $e2$ do { $list:el$ } >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[for %s@ %a@ %a %a@]" i expr (e1, nok)
expr (e2, nok) (list expr) (el, ks ")" k)
| <:expr< ($e$ : $t$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(:@ %a@ %a" expr (e, nok) ctyp (t, ks ")" k)
| <:expr< ($list:el$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(values @[%a@]" (list expr) (el, ks ")" k)
| <:expr< { $list:fel$ } >> ->
fun ppf curr next dg k ->
let record_binding ppf ((p, e), k) =
fprintf ppf "(@[%a@ %a@]" patt (p, nok) expr (e, ks ")" k)
in
fprintf ppf "{@[<hv>%a@]" (list record_binding) (fel, ks "}" k)
| <:expr< { ($e$) with $list:fel$ } >> ->
fun ppf curr next dg k ->
let record_binding ppf ((p, e), k) =
fprintf ppf "(@[%a@ %a@]" patt (p, nok) expr (e, ks ")" k)
in
fprintf ppf "{@[@[with@ %a@]@ @[%a@]@]" expr (e, nok)
(list record_binding) (fel, ks "}" k)
| <:expr< $e1$ := $e2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(:=@;<1 1>%a@;<1 1>%a" expr (e1, nok)
expr (e2, ks ")" k)
| <:expr< [$_$ :: $_$] >> as e ->
fun ppf curr next dg k ->
let (el, c) =
make_list e where rec make_list e =
match e with
[ <:expr< [$e$ :: $y$] >> ->
let (el, c) = make_list y in
([e :: el], c)
| <:expr< [] >> -> ([], None)
| x -> ([], Some e) ]
in
match c with
[ None ->
fprintf ppf "[%a" (list expr) (el, ks "]" k)
| Some x ->
fprintf ppf "[%a@ %a" (list expr) (el, ks " ." nok)
expr (x, ks "]" k) ]
| <:expr< lazy ($x$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[lazy@ %a@]" expr (x, ks ")" k)
| <:expr< $lid:s$ $e1$ $e2$ >>
when List.mem s assoc_right_parsed_op_list ->
fun ppf curr next dg k ->
let el =
loop [e1] e2 where rec loop el =
fun
[ <:expr< $lid:s1$ $e1$ $e2$ >> when s1 = s ->
loop [e1 :: el] e2
| e -> List.rev [e :: el] ]
in
fprintf ppf "(@[%s %a@]" s (list expr) (el, ks ")" k)
| <:expr< $e1$ $e2$ >> ->
fun ppf curr next dg k ->
let (f, el) =
loop [e2] e1 where rec loop el =
fun
[ <:expr< $e1$ $e2$ >> -> loop [e2 :: el] e1
| e1 -> (e1, el) ]
in
fprintf ppf "(@[%a@ %a@]" expr (f, nok) (list expr) (el, ks ")" k)
| <:expr< ~ $s$ : ($e$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(~%s@ %a" s expr (e, ks ")" k)
| <:expr< $e1$ .[ $e2$ ] >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.[%a" expr (e1, nok) expr (e2, ks "]" k)
| <:expr< $e1$ .( $e2$ ) >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.(%a" expr (e1, nok) expr (e2, ks ")" k)
| <:expr< $e1$ . $e2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.%a" expr (e1, nok) expr (e2, k)
| <:expr< $int:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" (int_repr s) k
| <:expr< $lid:s$ >> | <:expr< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:expr< ` $s$ >> ->
fun ppf curr next dg k -> fprintf ppf "`%s%t" s k
| <:expr< $str:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "\"%s\"%t" s k
| <:expr< $chr:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "'%s'%t" s k
| x ->
fun ppf curr next dg k -> not_impl "expr" x ppf k ]}];
pr_label_decl.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (loc, f, m, t) ->
fun ppf curr next dg k ->
fprintf ppf "(@[<hv>%s%t@ %a@]" f
(fun ppf -> if m then fprintf ppf "@ mutable" else ())
ctyp (t, ks ")" k) ]}];
pr_let_binding.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (b, (p, e)) ->
fun ppf curr next dg k ->
let (pl, e) = expr_fun_args e in
match pl with
[ [] ->
fprintf ppf "(@[<b 1>%s%s%a@ %a@]" b
(if b = "" then "" else " ") patt (p, nok)
sequence (e, ks ")" k)
| _ ->
fprintf ppf "(@[<b 1>%s%s(%a)@ %a@]" b
(if b = "" then "" else " ") (list patt) ([p :: pl], nok)
sequence (e, ks ")" k) ] ]}];
pr_match_assoc.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (p, we, e) ->
fun ppf curr next dg k ->
fprintf ppf "(@[%t@ %a@]"
(fun ppf ->
match we with
[ Some e ->
fprintf ppf "(when@ %a@ %a" patt (p, nok)
expr (e, ks ")" nok)
| None -> patt ppf (p, nok) ])
sequence (e, ks ")" k) ]}];
pr_mod_ident.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ [s] ->
fun ppf curr next dg k ->
fprintf ppf "%s%t" s k
| [s :: sl] ->
fun ppf curr next dg k ->
fprintf ppf "%s.%a" s curr (sl, "", k)
| x ->
fun ppf curr next dg k -> not_impl "mod_ident" x ppf k ]}];
pr_module_binding.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (b, s, me) ->
fun ppf curr next dg k ->
fprintf ppf "%s@ %s@ %a" b s module_expr (me, k) ]}];
pr_module_expr.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:module_expr< functor ($i$ : $mt$) -> $me$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[@[functor@ %s@]@ %a@]@ %a@]"
i module_type (mt, nok) module_expr (me, ks ")" k)
| <:module_expr< struct $list:sil$ end >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[struct@ @[<hv>%a@]@]" (list str_item)
(sil, ks ")" k)
| <:module_expr< $me1$ $me2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[%a@ %a@]" module_expr (me1, nok)
module_expr (me2, ks ")" k)
| <:module_expr< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| x ->
fun ppf curr next dg k -> not_impl "module_expr" x ppf k ]}];
pr_module_type.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:module_type< functor ($i$ : $mt1$) -> $mt2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[@[functor@ %s@]@ %a@]@ %a@]"
i module_type (mt1, nok) module_type (mt2, ks ")" k)
| <:module_type< sig $list:sil$ end >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[sig@ @[<hv>%a@]@]" (list sig_item) (sil, ks ")" k)
| <:module_type< $mt$ with $list:wcl$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[with@;<1 2>@[%a@ (%a@]@]" module_type (mt, nok)
(list with_constr) (wcl, ks "))" k)
| <:module_type< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| x ->
fun ppf curr next dg k -> not_impl "module_type" x ppf k ]}];
pr_patt.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:patt< $p1$ | $p2$ >> ->
fun ppf curr next dg k ->
let (f, pl) =
loop [p2] p1 where rec loop pl =
fun
[ <:patt< $p1$ | $p2$ >> -> loop [p2 :: pl] p1
| p1 -> (p1, pl) ]
in
fprintf ppf "(@[or@ %a@ %a@]" patt (f, nok) (list patt)
(pl, ks ")" k)
| <:patt< ($p1$ as $p2$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[as@ %a@ %a@]" patt (p1, nok) patt (p2, ks ")" k)
| <:patt< $p1$ .. $p2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[range@ %a@ %a@]" patt (p1, nok) patt (p2, ks ")" k)
| <:patt< [$_$ :: $_$] >> as p ->
fun ppf curr next dg k ->
let (pl, c) =
make_list p where rec make_list p =
match p with
[ <:patt< [$p$ :: $y$] >> ->
let (pl, c) = make_list y in
([p :: pl], c)
| <:patt< [] >> -> ([], None)
| x -> ([], Some p) ]
in
match c with
[ None ->
fprintf ppf "[%a" (list patt) (pl, ks "]" k)
| Some x ->
fprintf ppf "[%a@ %a" (list patt) (pl, ks " ." nok)
patt (x, ks "]" k) ]
| <:patt< $p1$ $p2$ >> ->
fun ppf curr next dg k ->
let pl =
loop [p2] p1 where rec loop pl =
fun
[ <:patt< $p1$ $p2$ >> -> loop [p2 :: pl] p1
| p1 -> [p1 :: pl] ]
in
fprintf ppf "(@[%a@]" (list patt) (pl, ks ")" k)
| <:patt< ($p$ : $t$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(:@ %a@ %a" patt (p, nok) ctyp (t, ks ")" k)
| <:patt< ($list:pl$) >> ->
fun ppf curr next dg k ->
fprintf ppf "(values @[%a@]" (list patt) (pl, ks ")" k)
| <:patt< { $list:fpl$ } >> ->
fun ppf curr next dg k ->
let record_binding ppf ((p1, p2), k) =
fprintf ppf "(@[%a@ %a@]" patt (p1, nok) patt (p2, ks ")" k)
in
fprintf ppf "(@[<hv>{}@ %a@]" (list record_binding) (fpl, ks ")" k)
| <:patt< ? $x$ >> ->
fun ppf curr next dg k -> fprintf ppf "?%s%t" x k
| <:patt< ? ($lid:x$ = $e$) >> ->
fun ppf curr next dg k -> fprintf ppf "(?%s@ %a" x expr (e, ks ")" k)
| <:patt< $p1$ . $p2$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a.%a" patt (p1, nok) patt (p2, k)
| <:patt< $lid:s$ >> | <:patt< $uid:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:patt< $str:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "\"%s\"%t" s k
| <:patt< $chr:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "'%s'%t" s k
| <:patt< $int:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" (int_repr s) k
| <:patt< $flo:s$ >> ->
fun ppf curr next dg k -> fprintf ppf "%s%t" s k
| <:patt< _ >> ->
fun ppf curr next dg k -> fprintf ppf "_%t" k
| x ->
fun ppf curr next dg k -> not_impl "patt" x ppf k ]}];
pr_sig_item.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:sig_item< type $list:tdl$ >> ->
fun ppf curr next dg k ->
match tdl with
[ [td] -> fprintf ppf "(%a" type_decl (("type", td), ks ")" k)
| tdl ->
fprintf ppf "(@[<hv>type@ %a@]" (listwb "" type_decl)
(tdl, ks ")" k) ]
| <:sig_item< exception $c$ of $list:tl$ >> ->
fun ppf curr next dg k ->
match tl with
[ [] -> fprintf ppf "(@[exception@ %s%t@]" c (ks ")" k)
| tl ->
fprintf ppf "(@[@[exception@ %s@]@ %a@]" c
(list ctyp) (tl, ks ")" k) ]
| <:sig_item< value $i$ : $t$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[value %s@]@ %a@]" i ctyp (t, ks ")" k)
| <:sig_item< external $i$ : $t$ = $list:pd$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[external@ %s@]@ %a@ %a@]" i ctyp (t, nok)
(list string) (pd, ks ")" k)
| <:sig_item< module $s$ : $mt$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[module@ %s@]@ %a@]" s
module_type (mt, ks ")" k)
| <:sig_item< module type $s$ = $mt$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[moduletype@ %s@]@ %a@]" s
module_type (mt, ks ")" k)
| <:sig_item< declare $list:s$ end >> ->
fun ppf curr next dg k ->
if s = [] then fprintf ppf "; ..."
else fprintf ppf "%a" (list sig_item) (s, k)
| MLast.SgUse _ _ _ ->
fun ppf curr next dg k -> ()
| x ->
fun ppf curr next dg k -> not_impl "sig_item" x ppf k ]}];
pr_str_item.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ <:str_item< open $i$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(open@ %a" mod_ident (i, ks ")" k)
| <:str_item< type $list:tdl$ >> ->
fun ppf curr next dg k ->
match tdl with
[ [td] -> fprintf ppf "(%a" type_decl (("type", td), ks ")" k)
| tdl ->
fprintf ppf "(@[<hv>type@ %a@]" (listwb "" type_decl)
(tdl, ks ")" k) ]
| <:str_item< exception $c$ of $list:tl$ >> ->
fun ppf curr next dg k ->
match tl with
[ [] -> fprintf ppf "(@[exception@ %s%t@]" c (ks ")" k)
| tl ->
fprintf ppf "(@[@[exception@ %s@]@ %a@]" c
(list ctyp) (tl, ks ")" k) ]
| <:str_item< value $opt:rf$ $list:pel$ >> ->
fun ppf curr next dg k ->
let b = if rf then "definerec" else "define" in
match pel with
[ [(p, e)] ->
fprintf ppf "%a" let_binding ((b, (p, e)), k)
| pel ->
fprintf ppf "(@[<hv 1>%s*@ %a@]" b (listwb "" let_binding)
(pel, ks ")" k) ]
| <:str_item< module $s$ = $me$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(%a" module_binding (("module", s, me), ks ")" k)
| <:str_item< module type $s$ = $mt$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[@[moduletype@ %s@]@ %a@]" s
module_type (mt, ks ")" k)
| <:str_item< external $i$ : $t$ = $list:pd$ >> ->
fun ppf curr next dg k ->
fprintf ppf "(@[external@ %s@ %a@ %a@]" i ctyp (t, nok)
(list string) (pd, ks ")" k)
| <:str_item< $exp:e$ >> ->
fun ppf curr next dg k ->
fprintf ppf "%a" expr (e, k)
| <:str_item< # $s$ $opt:x$ >> ->
fun ppf curr next dg k ->
match x with
[ Some e -> fprintf ppf "; # (%s %a" s expr (e, ks ")" k)
| None -> fprintf ppf "; # (%s%t" s (ks ")" k) ]
| <:str_item< declare $list:s$ end >> ->
fun ppf curr next dg k ->
if s = [] then fprintf ppf "; ..."
else fprintf ppf "%a" (list str_item) (s, k)
| MLast.StUse _ _ _ ->
fun ppf curr next dg k -> ()
| x ->
fun ppf curr next dg k -> not_impl "str_item" x ppf k ]}];
pr_type_decl.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ (b, ((_, tn), tp, te, cl)) ->
fun ppf curr next dg k ->
fprintf ppf "%t%t@;<1 1>%a"
(fun ppf ->
if b <> "" then fprintf ppf "%s@ " b
else ())
(fun ppf ->
match tp with
[ [] -> fprintf ppf "%s" tn
| tp -> fprintf ppf "(%s%a)" tn type_params (tp, nok) ])
ctyp (te, k) ]}];
pr_type_params.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ [(s, vari) :: tpl] ->
fun ppf curr next dg k ->
fprintf ppf "@ '%s%a" s type_params (tpl, k)
| [] ->
fun ppf curr next dg k -> () ]}];
pr_with_constr.pr_levels :=
[{pr_label = "top";
pr_box ppf f x = fprintf ppf "@[%t@]" f;
pr_rules =
extfun Extfun.empty with
[ MLast.WcTyp _ m tp te ->
fun ppf curr next dg k ->
fprintf ppf "(type@ %t@;<1 1>%a"
(fun ppf ->
match tp with
[ [] -> fprintf ppf "%a" mod_ident (m, nok)
| tp ->
fprintf ppf "(%a@ %a)" mod_ident (m, nok)
type_params (tp, nok) ])
ctyp (te, ks ")" k)
| x ->
fun ppf curr next dg k -> not_impl "with_constr" x ppf k ]}];
value output_string_eval ppf s =
loop 0 where rec loop i =
if i == String.length s then ()
else if i == String.length s - 1 then pp_print_char ppf s.[i]
else
match (s.[i], s.[i + 1]) with
[ ('\\', 'n') -> do { pp_print_char ppf '\n'; loop (i + 2) }
| (c, _) -> do { pp_print_char ppf c; loop (i + 1) } ]
;
value sep = Pcaml.inter_phrases;
value input_source ic len =
let buff = Buffer.create 20 in
try
let rec loop i =
if i >= len then Buffer.contents buff
else do { let c = input_char ic in Buffer.add_char buff c; loop (i + 1) }
in
loop 0
with
[ End_of_file ->
let s = Buffer.contents buff in
if s = "" then
match sep.val with
[ Some s -> s
| None -> "\n" ]
else s ]
;
value copy_source ppf (ic, first, bp, ep) =
match sep.val with
[ Some str ->
if first then ()
else if ep == in_channel_length ic then pp_print_string ppf "\n"
else output_string_eval ppf str
| None ->
do {
seek_in ic bp;
let s = input_source ic (ep - bp) in pp_print_string ppf s
} ]
;
value copy_to_end ppf (ic, first, bp) =
let ilen = in_channel_length ic in
if bp < ilen then copy_source ppf (ic, first, bp, ilen)
else pp_print_string ppf "\n"
;
value apply_printer printer ast =
let ppf = std_formatter in
if Pcaml.input_file.val <> "-" && Pcaml.input_file.val <> "" then do {
let ic = open_in_bin Pcaml.input_file.val in
try
let (first, last_pos) =
List.fold_left
(fun (first, last_pos) (si, (bp, ep)) ->
do {
fprintf ppf "@[%a@]@?" copy_source (ic, first, last_pos.Lexing.pos_cnum, bp.Lexing.pos_cnum);
fprintf ppf "@[%a@]@?" printer (si, nok);
(False, ep)
})
(True, Token.nowhere) ast
in
fprintf ppf "@[%a@]@?" copy_to_end (ic, first, last_pos.Lexing.pos_cnum)
with x ->
do { fprintf ppf "@."; close_in ic; raise x };
close_in ic;
}
else failwith "not implemented"
;
Pcaml.print_interf.val := apply_printer sig_item;
Pcaml.print_implem.val := apply_printer str_item;
Pcaml.add_option "-l" (Arg.Int (fun x -> set_margin x))
"<length> Maximum line length for pretty printing.";
Pcaml.add_option "-sep" (Arg.String (fun x -> sep.val := Some x))
"<string> Use this string between phrases instead of reading source.";
|
b264a93f2a9ddf23b517f3c3619cf6698784c416a147a4691983de2efafd6273 | drjdn/p5scm | test_p5scm.ml |
The MIT License
Copyright ( c ) 2021 < >
The MIT License
Copyright (c) 2021 Jason D. Nielsen <>
*)
open P5scm
let tscm = "
(define pass (ref True))
(define (passed bool)
(match bool
(True (print_endline \"[Pass]\"))
(False (print_endline \"[Fail]\"))))
(print_newline)
(print_string \"Simple test: \")
(passed True)
(print_newline)
(define lst [1 2 3])
(definerec (sum x)
(match x
([] 0)
([hd . tl] (+ hd (sum tl)))))
(print_string \"Recursive function test: \")
(passed (= (sum lst) 6))
(print_newline)
(define ()
(let ((a #(0 1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.exists (lambda a (< a 10)) a))
(assert (Array.exists (lambda a (> a 0)) a))
(assert (Array.exists (lambda a (= a 0)) a))
(assert (Array.exists (lambda a (= a 1)) a))
(assert (Array.exists (lambda a (= a 2)) a))
(assert (Array.exists (lambda a (= a 3)) a))
(assert (Array.exists (lambda a (= a 4)) a))
(assert (Array.exists (lambda a (= a 5)) a))
(assert (Array.exists (lambda a (= a 6)) a))
(assert (Array.exists (lambda a (= a 7)) a))
(assert (Array.exists (lambda a (= a 8)) a))
(assert (Array.exists (lambda a (= a 9)) a))
(assert (not (Array.exists (lambda a (< a 0)) a)))
(assert (not (Array.exists (lambda a (> a 9)) a)))
(assert (Array.exists (lambda _ True) a)))))
(define ()
(let ((a #(1 2 3)))
(begin
(assert (Array.exists (lambda a (< a 3)) a))
(assert (Array.exists (lambda a (< a 2)) a))
(assert (not (Array.exists (lambda a (< a 1)) a)))
(assert (Array.exists (lambda a (= (mod a 2) 0)) #(1 4 5)))
(assert (not (Array.exists (lambda a (= (mod a 2) 0)) #(1 3 5))))
(assert (not (Array.exists (lambda _ True) #())))
(assert (Array.exists (lambda a (= a.(9) 1)) (Array.make_matrix 10 10 1)))
(let ((f (Array.create_float 10)))
(begin
(Array.fill f 0 10 1.0)
(assert (Array.exists (lambda a (= a 1.0)) f)))))))
(define ()
(let (((: a (array int)) #()))
(begin
(assert (not (Array.exists (lambda a (= a 0)) a)))
(assert (not (Array.exists (lambda a (= a 1)) a)))
(assert (not (Array.exists (lambda a (= a 2)) a)))
(assert (not (Array.exists (lambda a (= a 3)) a)))
(assert (not (Array.exists (lambda a (= a 4)) a)))
(assert (not (Array.exists (lambda a (= a 5)) a)))
(assert (not (Array.exists (lambda a (= a 6)) a)))
(assert (not (Array.exists (lambda a (= a 7)) a)))
(assert (not (Array.exists (lambda a (= a 8)) a)))
(assert (not (Array.exists (lambda a (= a 9)) a)))
(assert (not (Array.exists (lambda a (<> a 0)) a)))
(assert (not (Array.exists (lambda a (<> a 1)) a)))
(assert (not (Array.exists (lambda a (<> a 2)) a)))
(assert (not (Array.exists (lambda a (<> a 3)) a)))
(assert (not (Array.exists (lambda a (<> a 4)) a)))
(assert (not (Array.exists (lambda a (<> a 5)) a)))
(assert (not (Array.exists (lambda a (<> a 6)) a)))
(assert (not (Array.exists (lambda a (<> a 7)) a)))
(assert (not (Array.exists (lambda a (<> a 8)) a)))
(assert (not (Array.exists (lambda a (<> a 9)) a)))
(assert (not (Array.exists (lambda a (< a 0)) a)))
(assert (not (Array.exists (lambda a (< a 1)) a)))
(assert (not (Array.exists (lambda a (< a 2)) a)))
(assert (not (Array.exists (lambda a (< a 3)) a)))
(assert (not (Array.exists (lambda a (< a 4)) a)))
(assert (not (Array.exists (lambda a (< a 5)) a)))
(assert (not (Array.exists (lambda a (< a 6)) a)))
(assert (not (Array.exists (lambda a (< a 7)) a)))
(assert (not (Array.exists (lambda a (< a 8)) a)))
(assert (not (Array.exists (lambda a (< a 9)) a)))
(assert (not (Array.exists (lambda a (> a 0)) a)))
(assert (not (Array.exists (lambda a (> a 1)) a)))
(assert (not (Array.exists (lambda a (> a 2)) a)))
(assert (not (Array.exists (lambda a (> a 3)) a)))
(assert (not (Array.exists (lambda a (> a 4)) a)))
(assert (not (Array.exists (lambda a (> a 5)) a)))
(assert (not (Array.exists (lambda a (> a 6)) a)))
(assert (not (Array.exists (lambda a (> a 7)) a)))
(assert (not (Array.exists (lambda a (> a 8)) a)))
(assert (not (Array.exists (lambda a (> a 9)) a))))))
(define ()
(let ((a #(0 1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.for_all (lambda a (< a 10)) a))
(assert (Array.for_all (lambda a (>= a 0)) a))
(assert (not (Array.for_all (lambda a (= a 0)) a)))
(assert (not (Array.for_all (lambda a (= a 1)) a)))
(assert (not (Array.for_all (lambda a (= a 2)) a)))
(assert (not (Array.for_all (lambda a (= a 3)) a)))
(assert (not (Array.for_all (lambda a (= a 4)) a)))
(assert (not (Array.for_all (lambda a (= a 5)) a)))
(assert (not (Array.for_all (lambda a (= a 6)) a)))
(assert (not (Array.for_all (lambda a (= a 7)) a)))
(assert (not (Array.for_all (lambda a (= a 8)) a)))
(assert (not (Array.for_all (lambda a (= a 9)) a)))
(assert (Array.for_all (lambda a (<> a 10)) a))
(assert (Array.for_all (lambda a (<> a (- 1))) a))
(assert (Array.for_all (lambda _ True) a)))))
(define ()
(begin
(assert (Array.for_all (lambda x (= (mod x 2) 0)) #(2 4 6)))
(assert (not (Array.for_all (lambda x (= (mod x 2) 0)) #(2 3 6))))
(assert (Array.for_all (lambda _ False) #()))
(assert (Array.for_all (lambda a (= a.(9) 1)) (Array.make_matrix 10 10 1)))
(let ((f (Array.create_float 10)))
(begin
(Array.fill f 0 10 1.0)
(assert (Array.for_all (lambda a (= a 1.0)) f))))))
(define ()
(let ((a #()))
(begin
(assert (Array.for_all (lambda a (< a 10)) a))
(assert (Array.for_all (lambda a (>= a 0)) a))
(assert (Array.for_all (lambda a (= a 0)) a))
(assert (Array.for_all (lambda a (= a 1)) a))
(assert (Array.for_all (lambda a (= a 2)) a))
(assert (Array.for_all (lambda a (= a 3)) a))
(assert (Array.for_all (lambda a (= a 4)) a))
(assert (Array.for_all (lambda a (= a 5)) a))
(assert (Array.for_all (lambda a (= a 6)) a))
(assert (Array.for_all (lambda a (= a 7)) a))
(assert (Array.for_all (lambda a (= a 8)) a))
(assert (Array.for_all (lambda a (= a 9)) a))
(assert (Array.for_all (lambda a (<> a 10)) a))
(assert (Array.for_all (lambda a (<> a (- 1))) a))
(assert (Array.for_all (lambda _ True) a)))))
(define (does_raise3 f a b c) (try (begin (ignore (f a b c)) False) (_ True)))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)) (b #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.exists2 (lambda (a b) (= a b)) a b))
(assert (Array.exists2 (lambda (a b) (= (- a b) 0)) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 1) (= b 1))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 2) (= b 2))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 3) (= b 3))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 4) (= b 4))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 5) (= b 5))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 6) (= b 6))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 7) (= b 7))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 8) (= b 8))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 9) (= b 9))) a b))
(assert (not (Array.exists2 (lambda (a b) (<> a b)) a b))))))
(define ()
(let ((a #(1)) (b #(1 2)))
(begin
(assert (does_raise3 Array.exists2 (lambda (a b) (= a b)) a b))
(assert (does_raise3 Array.exists2 (lambda (_ _) True) a b))
(assert (does_raise3 Array.exists2 (lambda (_ _) False) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 1) (= b 1))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 2) (= b 2))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 3) (= b 3))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 4) (= b 4))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 5) (= b 5))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 6) (= b 6))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 7) (= b 7))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 8) (= b 8))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 9) (= b 9))) a b)))))
(define ()
(begin
(assert (Array.exists2 = #(1 2 3) #(3 2 1)))
(assert (not (Array.exists2 <> #(1 2 3) #(1 2 3))))
(assert (does_raise3 Array.exists2 = #(1 2) #(3)))
(let* ((f (Array.create_float 10)) (g (Array.create_float 10)))
(begin
(Array.fill f 0 10 1.0)
(Array.fill g 0 10 1.0)
(assert (Array.exists2 (lambda (a b) (&& (= a 1.0) (= b 1.0))) f g))))))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)) (b #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.for_all2 (lambda (a b) (= a b)) a b))
(assert (Array.for_all2 (lambda (a b) (= (- a b) 0)) a b))
(assert (Array.for_all2 (lambda (a b) (&& (> a 0) (> b 0))) a b))
(assert (Array.for_all2 (lambda (a b) (&& (< a 10) (< b 10))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 1) (= b 1) (<> b 1))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 2) (= b 2) (<> b 2))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 3) (= b 3) (<> b 3))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 4) (= b 4) (<> b 4))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 5) (= b 5) (<> b 5))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 6) (= b 6) (<> b 6))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 7) (= b 7) (<> b 7))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 8) (= b 8) (<> b 8))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 9) (= b 9) (<> b 9))) a b))
(assert (not (Array.for_all2 (lambda (a b) (<> a b)) a b))))))
(define ()
(let ((a #(1)) (b #(1 2)))
(begin
(assert (does_raise3 Array.for_all2 (lambda (a b) (= a b)) a b))
(assert (does_raise3 Array.for_all2 (lambda (_ _) True) a b))
(assert (does_raise3 Array.for_all2 (lambda (_ _) False) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 1) (= b 1))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 2) (= b 2))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 3) (= b 3))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 4) (= b 4))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 5) (= b 5))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 6) (= b 6))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 7) (= b 7))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 8) (= b 8))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 9) (= b 9))) a b)))))
(define ()
(begin
(assert (not (Array.for_all2 = #(1 2 3) #(3 2 1))))
(assert (Array.for_all2 = #(1 2 3) #(1 2 3)))
(assert (not (Array.for_all2 <> #(1 2 3) #(3 2 1))))
(assert (does_raise3 Array.for_all2 = #(1 2 3) #(1 2 3 4)))
(assert (does_raise3 Array.for_all2 = #(1 2) #()))))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.mem 1 a))
(assert (Array.mem 2 a))
(assert (Array.mem 3 a))
(assert (Array.mem 4 a))
(assert (Array.mem 5 a))
(assert (Array.mem 6 a))
(assert (Array.mem 7 a))
(assert (Array.mem 8 a))
(assert (Array.mem 9 a))
(assert (not (Array.mem 0 a)))
(assert (not (Array.mem 10 a))))))
(define ()
(begin
(assert (Array.mem 2 #(1 2 3)))
(assert (not (Array.mem 2 #())))
(assert (Array.mem (ref 3) #((ref 1) (ref 2) (ref 3))))
(assert (Array.mem #(1 2 3) #(#(1 2 3) #(2 3 4) #(0))))
(assert (Array.mem 1 (Array.make 100 1)))
(assert (Array.mem (ref 1) (Array.make 100 (ref 1))))
(let ((f (Array.create_float 10)))
(begin (Array.fill f 0 10 1.0) (assert (Array.mem 1.0 f))))))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.memq 1 a))
(assert (Array.memq 2 a))
(assert (Array.memq 3 a))
(assert (Array.memq 4 a))
(assert (Array.memq 5 a))
(assert (Array.memq 6 a))
(assert (Array.memq 7 a))
(assert (Array.memq 8 a))
(assert (Array.memq 9 a))
(assert (not (Array.memq 0 a)))
(assert (not (Array.memq 10 a))))))
(define ()
(begin
(assert (Array.memq 2 #(1 2 3)))
(assert (not (Array.memq 2 #())))
(assert (not (Array.memq (ref 3) #((ref 1) (ref 2) (ref 3)))))
(assert (not (Array.memq #(1 2 3) #(#(1 2 3) #(2 3 4) #(0)))))
(assert (Array.memq 1 (Array.make 100 1)))
(assert (not (Array.memq (ref 1) (Array.make 100 (ref 1)))))
(let ((f (Array.create_float 10))) (Array.fill f 0 10 1.0))))
(print_string \"Array tests: \")
(passed True)
(print_newline)
(print_string \"Structure test: \")
(type pt {(x int) (y int)})
(define xy {(x 1) (y 2)})
(:= pass.val (== xy.x 1))
(passed pass.val)
(print_newline)
(print_string \"List test: \")
(define lst [1 2 3])
(:= pass.val (== (List.fold_left + 0 lst) 6))
(passed pass.val)
(print_newline)
(print_string \"Vector test: \")
(define vec #(1 2 3))
(:= pass.val (== (Array.fold_left + 0 vec) 6))
(passed pass.val)
(print_newline)
"
let pwd = Sys.getcwd ();;
let ast = Parse.parse_from_string tscm in
let p5str = Pp_ast.ast_to_p5scm ast in
Trans.scm_to_bin_file p5str "test.ml";;
let _ = Sys.command("ocamlopt test.ml -o run");;
let _ = Sys.command("./run");;
| null | https://raw.githubusercontent.com/drjdn/p5scm/b12ccf2b5d34ae338c91ecd0ecc0d3ebd22009b3/src/test/test_p5scm.ml | ocaml |
The MIT License
Copyright ( c ) 2021 < >
The MIT License
Copyright (c) 2021 Jason D. Nielsen <>
*)
open P5scm
let tscm = "
(define pass (ref True))
(define (passed bool)
(match bool
(True (print_endline \"[Pass]\"))
(False (print_endline \"[Fail]\"))))
(print_newline)
(print_string \"Simple test: \")
(passed True)
(print_newline)
(define lst [1 2 3])
(definerec (sum x)
(match x
([] 0)
([hd . tl] (+ hd (sum tl)))))
(print_string \"Recursive function test: \")
(passed (= (sum lst) 6))
(print_newline)
(define ()
(let ((a #(0 1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.exists (lambda a (< a 10)) a))
(assert (Array.exists (lambda a (> a 0)) a))
(assert (Array.exists (lambda a (= a 0)) a))
(assert (Array.exists (lambda a (= a 1)) a))
(assert (Array.exists (lambda a (= a 2)) a))
(assert (Array.exists (lambda a (= a 3)) a))
(assert (Array.exists (lambda a (= a 4)) a))
(assert (Array.exists (lambda a (= a 5)) a))
(assert (Array.exists (lambda a (= a 6)) a))
(assert (Array.exists (lambda a (= a 7)) a))
(assert (Array.exists (lambda a (= a 8)) a))
(assert (Array.exists (lambda a (= a 9)) a))
(assert (not (Array.exists (lambda a (< a 0)) a)))
(assert (not (Array.exists (lambda a (> a 9)) a)))
(assert (Array.exists (lambda _ True) a)))))
(define ()
(let ((a #(1 2 3)))
(begin
(assert (Array.exists (lambda a (< a 3)) a))
(assert (Array.exists (lambda a (< a 2)) a))
(assert (not (Array.exists (lambda a (< a 1)) a)))
(assert (Array.exists (lambda a (= (mod a 2) 0)) #(1 4 5)))
(assert (not (Array.exists (lambda a (= (mod a 2) 0)) #(1 3 5))))
(assert (not (Array.exists (lambda _ True) #())))
(assert (Array.exists (lambda a (= a.(9) 1)) (Array.make_matrix 10 10 1)))
(let ((f (Array.create_float 10)))
(begin
(Array.fill f 0 10 1.0)
(assert (Array.exists (lambda a (= a 1.0)) f)))))))
(define ()
(let (((: a (array int)) #()))
(begin
(assert (not (Array.exists (lambda a (= a 0)) a)))
(assert (not (Array.exists (lambda a (= a 1)) a)))
(assert (not (Array.exists (lambda a (= a 2)) a)))
(assert (not (Array.exists (lambda a (= a 3)) a)))
(assert (not (Array.exists (lambda a (= a 4)) a)))
(assert (not (Array.exists (lambda a (= a 5)) a)))
(assert (not (Array.exists (lambda a (= a 6)) a)))
(assert (not (Array.exists (lambda a (= a 7)) a)))
(assert (not (Array.exists (lambda a (= a 8)) a)))
(assert (not (Array.exists (lambda a (= a 9)) a)))
(assert (not (Array.exists (lambda a (<> a 0)) a)))
(assert (not (Array.exists (lambda a (<> a 1)) a)))
(assert (not (Array.exists (lambda a (<> a 2)) a)))
(assert (not (Array.exists (lambda a (<> a 3)) a)))
(assert (not (Array.exists (lambda a (<> a 4)) a)))
(assert (not (Array.exists (lambda a (<> a 5)) a)))
(assert (not (Array.exists (lambda a (<> a 6)) a)))
(assert (not (Array.exists (lambda a (<> a 7)) a)))
(assert (not (Array.exists (lambda a (<> a 8)) a)))
(assert (not (Array.exists (lambda a (<> a 9)) a)))
(assert (not (Array.exists (lambda a (< a 0)) a)))
(assert (not (Array.exists (lambda a (< a 1)) a)))
(assert (not (Array.exists (lambda a (< a 2)) a)))
(assert (not (Array.exists (lambda a (< a 3)) a)))
(assert (not (Array.exists (lambda a (< a 4)) a)))
(assert (not (Array.exists (lambda a (< a 5)) a)))
(assert (not (Array.exists (lambda a (< a 6)) a)))
(assert (not (Array.exists (lambda a (< a 7)) a)))
(assert (not (Array.exists (lambda a (< a 8)) a)))
(assert (not (Array.exists (lambda a (< a 9)) a)))
(assert (not (Array.exists (lambda a (> a 0)) a)))
(assert (not (Array.exists (lambda a (> a 1)) a)))
(assert (not (Array.exists (lambda a (> a 2)) a)))
(assert (not (Array.exists (lambda a (> a 3)) a)))
(assert (not (Array.exists (lambda a (> a 4)) a)))
(assert (not (Array.exists (lambda a (> a 5)) a)))
(assert (not (Array.exists (lambda a (> a 6)) a)))
(assert (not (Array.exists (lambda a (> a 7)) a)))
(assert (not (Array.exists (lambda a (> a 8)) a)))
(assert (not (Array.exists (lambda a (> a 9)) a))))))
(define ()
(let ((a #(0 1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.for_all (lambda a (< a 10)) a))
(assert (Array.for_all (lambda a (>= a 0)) a))
(assert (not (Array.for_all (lambda a (= a 0)) a)))
(assert (not (Array.for_all (lambda a (= a 1)) a)))
(assert (not (Array.for_all (lambda a (= a 2)) a)))
(assert (not (Array.for_all (lambda a (= a 3)) a)))
(assert (not (Array.for_all (lambda a (= a 4)) a)))
(assert (not (Array.for_all (lambda a (= a 5)) a)))
(assert (not (Array.for_all (lambda a (= a 6)) a)))
(assert (not (Array.for_all (lambda a (= a 7)) a)))
(assert (not (Array.for_all (lambda a (= a 8)) a)))
(assert (not (Array.for_all (lambda a (= a 9)) a)))
(assert (Array.for_all (lambda a (<> a 10)) a))
(assert (Array.for_all (lambda a (<> a (- 1))) a))
(assert (Array.for_all (lambda _ True) a)))))
(define ()
(begin
(assert (Array.for_all (lambda x (= (mod x 2) 0)) #(2 4 6)))
(assert (not (Array.for_all (lambda x (= (mod x 2) 0)) #(2 3 6))))
(assert (Array.for_all (lambda _ False) #()))
(assert (Array.for_all (lambda a (= a.(9) 1)) (Array.make_matrix 10 10 1)))
(let ((f (Array.create_float 10)))
(begin
(Array.fill f 0 10 1.0)
(assert (Array.for_all (lambda a (= a 1.0)) f))))))
(define ()
(let ((a #()))
(begin
(assert (Array.for_all (lambda a (< a 10)) a))
(assert (Array.for_all (lambda a (>= a 0)) a))
(assert (Array.for_all (lambda a (= a 0)) a))
(assert (Array.for_all (lambda a (= a 1)) a))
(assert (Array.for_all (lambda a (= a 2)) a))
(assert (Array.for_all (lambda a (= a 3)) a))
(assert (Array.for_all (lambda a (= a 4)) a))
(assert (Array.for_all (lambda a (= a 5)) a))
(assert (Array.for_all (lambda a (= a 6)) a))
(assert (Array.for_all (lambda a (= a 7)) a))
(assert (Array.for_all (lambda a (= a 8)) a))
(assert (Array.for_all (lambda a (= a 9)) a))
(assert (Array.for_all (lambda a (<> a 10)) a))
(assert (Array.for_all (lambda a (<> a (- 1))) a))
(assert (Array.for_all (lambda _ True) a)))))
(define (does_raise3 f a b c) (try (begin (ignore (f a b c)) False) (_ True)))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)) (b #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.exists2 (lambda (a b) (= a b)) a b))
(assert (Array.exists2 (lambda (a b) (= (- a b) 0)) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 1) (= b 1))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 2) (= b 2))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 3) (= b 3))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 4) (= b 4))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 5) (= b 5))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 6) (= b 6))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 7) (= b 7))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 8) (= b 8))) a b))
(assert (Array.exists2 (lambda (a b) (&& (= a 9) (= b 9))) a b))
(assert (not (Array.exists2 (lambda (a b) (<> a b)) a b))))))
(define ()
(let ((a #(1)) (b #(1 2)))
(begin
(assert (does_raise3 Array.exists2 (lambda (a b) (= a b)) a b))
(assert (does_raise3 Array.exists2 (lambda (_ _) True) a b))
(assert (does_raise3 Array.exists2 (lambda (_ _) False) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 1) (= b 1))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 2) (= b 2))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 3) (= b 3))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 4) (= b 4))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 5) (= b 5))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 6) (= b 6))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 7) (= b 7))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 8) (= b 8))) a b))
(assert
(does_raise3 Array.exists2 (lambda (a b) (&& (= a 9) (= b 9))) a b)))))
(define ()
(begin
(assert (Array.exists2 = #(1 2 3) #(3 2 1)))
(assert (not (Array.exists2 <> #(1 2 3) #(1 2 3))))
(assert (does_raise3 Array.exists2 = #(1 2) #(3)))
(let* ((f (Array.create_float 10)) (g (Array.create_float 10)))
(begin
(Array.fill f 0 10 1.0)
(Array.fill g 0 10 1.0)
(assert (Array.exists2 (lambda (a b) (&& (= a 1.0) (= b 1.0))) f g))))))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)) (b #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.for_all2 (lambda (a b) (= a b)) a b))
(assert (Array.for_all2 (lambda (a b) (= (- a b) 0)) a b))
(assert (Array.for_all2 (lambda (a b) (&& (> a 0) (> b 0))) a b))
(assert (Array.for_all2 (lambda (a b) (&& (< a 10) (< b 10))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 1) (= b 1) (<> b 1))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 2) (= b 2) (<> b 2))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 3) (= b 3) (<> b 3))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 4) (= b 4) (<> b 4))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 5) (= b 5) (<> b 5))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 6) (= b 6) (<> b 6))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 7) (= b 7) (<> b 7))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 8) (= b 8) (<> b 8))) a b))
(assert (Array.for_all2 (lambda (a b) (if (= a 9) (= b 9) (<> b 9))) a b))
(assert (not (Array.for_all2 (lambda (a b) (<> a b)) a b))))))
(define ()
(let ((a #(1)) (b #(1 2)))
(begin
(assert (does_raise3 Array.for_all2 (lambda (a b) (= a b)) a b))
(assert (does_raise3 Array.for_all2 (lambda (_ _) True) a b))
(assert (does_raise3 Array.for_all2 (lambda (_ _) False) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 1) (= b 1))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 2) (= b 2))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 3) (= b 3))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 4) (= b 4))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 5) (= b 5))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 6) (= b 6))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 7) (= b 7))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 8) (= b 8))) a b))
(assert
(does_raise3 Array.for_all2 (lambda (a b) (&& (= a 9) (= b 9))) a b)))))
(define ()
(begin
(assert (not (Array.for_all2 = #(1 2 3) #(3 2 1))))
(assert (Array.for_all2 = #(1 2 3) #(1 2 3)))
(assert (not (Array.for_all2 <> #(1 2 3) #(3 2 1))))
(assert (does_raise3 Array.for_all2 = #(1 2 3) #(1 2 3 4)))
(assert (does_raise3 Array.for_all2 = #(1 2) #()))))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.mem 1 a))
(assert (Array.mem 2 a))
(assert (Array.mem 3 a))
(assert (Array.mem 4 a))
(assert (Array.mem 5 a))
(assert (Array.mem 6 a))
(assert (Array.mem 7 a))
(assert (Array.mem 8 a))
(assert (Array.mem 9 a))
(assert (not (Array.mem 0 a)))
(assert (not (Array.mem 10 a))))))
(define ()
(begin
(assert (Array.mem 2 #(1 2 3)))
(assert (not (Array.mem 2 #())))
(assert (Array.mem (ref 3) #((ref 1) (ref 2) (ref 3))))
(assert (Array.mem #(1 2 3) #(#(1 2 3) #(2 3 4) #(0))))
(assert (Array.mem 1 (Array.make 100 1)))
(assert (Array.mem (ref 1) (Array.make 100 (ref 1))))
(let ((f (Array.create_float 10)))
(begin (Array.fill f 0 10 1.0) (assert (Array.mem 1.0 f))))))
(define ()
(let ((a #(1 2 3 4 5 6 7 8 9)))
(begin
(assert (Array.memq 1 a))
(assert (Array.memq 2 a))
(assert (Array.memq 3 a))
(assert (Array.memq 4 a))
(assert (Array.memq 5 a))
(assert (Array.memq 6 a))
(assert (Array.memq 7 a))
(assert (Array.memq 8 a))
(assert (Array.memq 9 a))
(assert (not (Array.memq 0 a)))
(assert (not (Array.memq 10 a))))))
(define ()
(begin
(assert (Array.memq 2 #(1 2 3)))
(assert (not (Array.memq 2 #())))
(assert (not (Array.memq (ref 3) #((ref 1) (ref 2) (ref 3)))))
(assert (not (Array.memq #(1 2 3) #(#(1 2 3) #(2 3 4) #(0)))))
(assert (Array.memq 1 (Array.make 100 1)))
(assert (not (Array.memq (ref 1) (Array.make 100 (ref 1)))))
(let ((f (Array.create_float 10))) (Array.fill f 0 10 1.0))))
(print_string \"Array tests: \")
(passed True)
(print_newline)
(print_string \"Structure test: \")
(type pt {(x int) (y int)})
(define xy {(x 1) (y 2)})
(:= pass.val (== xy.x 1))
(passed pass.val)
(print_newline)
(print_string \"List test: \")
(define lst [1 2 3])
(:= pass.val (== (List.fold_left + 0 lst) 6))
(passed pass.val)
(print_newline)
(print_string \"Vector test: \")
(define vec #(1 2 3))
(:= pass.val (== (Array.fold_left + 0 vec) 6))
(passed pass.val)
(print_newline)
"
let pwd = Sys.getcwd ();;
let ast = Parse.parse_from_string tscm in
let p5str = Pp_ast.ast_to_p5scm ast in
Trans.scm_to_bin_file p5str "test.ml";;
let _ = Sys.command("ocamlopt test.ml -o run");;
let _ = Sys.command("./run");;
|
|
c6e7af18e52a750fcbaf7f1dfef0bfe454fc4bc54d2c4d0966074a6ea9c77a73 | samply/blaze | chained.clj | (ns blaze.db.impl.search-param.chained
(:require
[blaze.anomaly :as ba :refer [when-ok]]
[blaze.coll.core :as coll]
[blaze.db.impl.codec :as codec]
[blaze.db.impl.index :as index]
[blaze.db.impl.index.resource-handle :as rh]
[blaze.db.impl.macros :refer [with-open-coll]]
[blaze.db.impl.protocols :as p]
[blaze.db.kv :as kv]
[blaze.db.node.resource-indexer.spec]
[blaze.db.node.spec]
[blaze.db.search-param-registry :as sr]
[blaze.db.search-param-registry.spec]
[clojure.string :as str]))
(defn- search-param-not-found-msg [code type]
(format "The search-param with code `%s` and type `%s` was not found."
code type))
(defn- resolve-search-param [registry type code]
(if-let [search-param (sr/get registry code type)]
search-param
(ba/not-found (search-param-not-found-msg code type) :http/status 400)))
(defrecord ChainedSearchParam [search-param ref-search-param ref-tid ref-modifier code]
p/SearchParam
(-compile-value [_ modifier value]
(p/-compile-value search-param modifier value))
(-resource-handles [_ context tid modifier compiled-value]
(coll/eduction
(comp (map #(p/-compile-value ref-search-param ref-modifier (rh/reference %)))
(mapcat #(p/-resource-handles ref-search-param context tid modifier %))
(distinct))
;; TODO: improve
(with-open-coll [svri (kv/new-iterator (:snapshot context) :search-param-value-index)]
(p/-resource-handles search-param (assoc context :svri svri) ref-tid
modifier compiled-value))))
(-resource-handles [this context tid modifier compiled-value start-id]
(let [start-id (codec/id-string start-id)]
(coll/eduction
(drop-while #(not= start-id (rh/id %)))
(p/-resource-handles this context tid modifier compiled-value))))
(-matches? [_ context resource-handle modifier compiled-values]
(some
#(p/-matches? search-param context % modifier compiled-values)
(index/targets! context resource-handle
(codec/c-hash (:code ref-search-param)) ref-tid))))
(defn- chained-search-param
[registry ref-search-param ref-type ref-modifier original-code [code modifier]]
(when-ok [search-param (resolve-search-param registry ref-type code)]
[(->ChainedSearchParam search-param ref-search-param (codec/tid ref-type)
ref-modifier original-code)
modifier]))
(defn- reference-type-msg [ref-code s type]
(format "The search parameter with code `%s` in the chain `%s` must be of type reference but has type `%s`."
ref-code s type))
(defn- ambiguous-target-type-msg [types s]
(format "Ambiguous target types `%s` in the chain `%s`. Please use a modifier to constrain the type."
types s))
(defn parse-search-param [registry type s]
(let [chain (str/split s #"\.")]
(case (count chain)
1
(let [[code :as ret] (str/split (first chain) #":" 2)]
(when-ok [search-param (resolve-search-param registry type code)]
(assoc ret 0 search-param)))
2
(let [[[ref-code ref-modifier] code-modifier] (mapv #(str/split % #":" 2) chain)]
(when-ok [{:keys [type target] :as ref-search-param} (resolve-search-param registry type ref-code)]
(cond
(not= "reference" type)
(ba/incorrect (reference-type-msg ref-code s type))
(= 1 (count target))
(chained-search-param registry ref-search-param (first target)
ref-modifier s code-modifier)
ref-modifier
(chained-search-param registry ref-search-param ref-modifier
ref-modifier s code-modifier)
:else
(ba/incorrect (ambiguous-target-type-msg (str/join ", " target) s)))))
(ba/unsupported "Search parameter chains longer than 2 are currently not supported. Please file an issue."))))
| null | https://raw.githubusercontent.com/samply/blaze/6ef8eff7687513554131819d080fed9aaf531a34/modules/db/src/blaze/db/impl/search_param/chained.clj | clojure | TODO: improve | (ns blaze.db.impl.search-param.chained
(:require
[blaze.anomaly :as ba :refer [when-ok]]
[blaze.coll.core :as coll]
[blaze.db.impl.codec :as codec]
[blaze.db.impl.index :as index]
[blaze.db.impl.index.resource-handle :as rh]
[blaze.db.impl.macros :refer [with-open-coll]]
[blaze.db.impl.protocols :as p]
[blaze.db.kv :as kv]
[blaze.db.node.resource-indexer.spec]
[blaze.db.node.spec]
[blaze.db.search-param-registry :as sr]
[blaze.db.search-param-registry.spec]
[clojure.string :as str]))
(defn- search-param-not-found-msg [code type]
(format "The search-param with code `%s` and type `%s` was not found."
code type))
(defn- resolve-search-param [registry type code]
(if-let [search-param (sr/get registry code type)]
search-param
(ba/not-found (search-param-not-found-msg code type) :http/status 400)))
(defrecord ChainedSearchParam [search-param ref-search-param ref-tid ref-modifier code]
p/SearchParam
(-compile-value [_ modifier value]
(p/-compile-value search-param modifier value))
(-resource-handles [_ context tid modifier compiled-value]
(coll/eduction
(comp (map #(p/-compile-value ref-search-param ref-modifier (rh/reference %)))
(mapcat #(p/-resource-handles ref-search-param context tid modifier %))
(distinct))
(with-open-coll [svri (kv/new-iterator (:snapshot context) :search-param-value-index)]
(p/-resource-handles search-param (assoc context :svri svri) ref-tid
modifier compiled-value))))
(-resource-handles [this context tid modifier compiled-value start-id]
(let [start-id (codec/id-string start-id)]
(coll/eduction
(drop-while #(not= start-id (rh/id %)))
(p/-resource-handles this context tid modifier compiled-value))))
(-matches? [_ context resource-handle modifier compiled-values]
(some
#(p/-matches? search-param context % modifier compiled-values)
(index/targets! context resource-handle
(codec/c-hash (:code ref-search-param)) ref-tid))))
(defn- chained-search-param
[registry ref-search-param ref-type ref-modifier original-code [code modifier]]
(when-ok [search-param (resolve-search-param registry ref-type code)]
[(->ChainedSearchParam search-param ref-search-param (codec/tid ref-type)
ref-modifier original-code)
modifier]))
(defn- reference-type-msg [ref-code s type]
(format "The search parameter with code `%s` in the chain `%s` must be of type reference but has type `%s`."
ref-code s type))
(defn- ambiguous-target-type-msg [types s]
(format "Ambiguous target types `%s` in the chain `%s`. Please use a modifier to constrain the type."
types s))
(defn parse-search-param [registry type s]
(let [chain (str/split s #"\.")]
(case (count chain)
1
(let [[code :as ret] (str/split (first chain) #":" 2)]
(when-ok [search-param (resolve-search-param registry type code)]
(assoc ret 0 search-param)))
2
(let [[[ref-code ref-modifier] code-modifier] (mapv #(str/split % #":" 2) chain)]
(when-ok [{:keys [type target] :as ref-search-param} (resolve-search-param registry type ref-code)]
(cond
(not= "reference" type)
(ba/incorrect (reference-type-msg ref-code s type))
(= 1 (count target))
(chained-search-param registry ref-search-param (first target)
ref-modifier s code-modifier)
ref-modifier
(chained-search-param registry ref-search-param ref-modifier
ref-modifier s code-modifier)
:else
(ba/incorrect (ambiguous-target-type-msg (str/join ", " target) s)))))
(ba/unsupported "Search parameter chains longer than 2 are currently not supported. Please file an issue."))))
|
72fa91b487fc81bd5b387fce2d425a18c4aee6597d0973ef423c944139ac6e7b | Decentralized-Pictures/T4L3NT | environment_protocol_T.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2018 Nomadic Labs . < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Environment_context
This module contains the real module signature of an economic
protocol that the Shell sees . There is actually only one signature
to avoid [ if]-[then]-[else ] expressions inside the Shell .
When we change the module signature output of the environment , we
need to implement a forward - compatible interface . This is done by
upgrading the old interface to the new one .
The first change in this signature was introduced by the [ V3 ]
environment . This is why we implement a functor from the initial
environment [ V0 ] to [ V3 ] directly because neither [ V1 ] nor [ V2 ]
change the module signature output of the environment .
All the equalities constraints are here for typing only . We use a
destructive substitution ( [: =] ) for types that are defined by the
shell , or that are common to all the economic protocol
environments , and an equality constraint ( [ =] ) for the types that
are abstracted from the economic protocol .
[ module type T ] defines the same signature as the last [ Vx ]
environment ( [ module type Vx_T ] ) .
If you want to mock this module type , see { ! Environment_protocol_T_test } .
protocol that the Shell sees. There is actually only one signature
to avoid [if]-[then]-[else] expressions inside the Shell.
When we change the module signature output of the environment, we
need to implement a forward-compatible interface. This is done by
upgrading the old interface to the new one.
The first change in this signature was introduced by the [V3]
environment. This is why we implement a functor from the initial
environment [V0] to [V3] directly because neither [V1] nor [V2]
change the module signature output of the environment.
All the equalities constraints are here for typing only. We use a
destructive substitution ([:=]) for types that are defined by the
shell, or that are common to all the economic protocol
environments, and an equality constraint ([=]) for the types that
are abstracted from the economic protocol.
[module type T] defines the same signature as the last [Vx]
environment ([module type Vx_T]).
If you want to mock this module type, see {!Environment_protocol_T_test}. *)
module type T = sig
(* Documentation for this interface may be found in
module type [PROTOCOL] of [sigs/v3/updater.mli]. *)
include Environment_protocol_T_V3.T
val set_log_message_consumer :
(Internal_event.level -> string -> unit) -> unit
val environment_version : Protocol.env_version
end
module V0toV3
(E : Environment_protocol_T_V0.T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult) :
Environment_protocol_T_V3.T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult
and type block_header_data = E.block_header_data
and type block_header = E.block_header
and type block_header_metadata = E.block_header_metadata
and type operation_data = E.operation_data
and type operation = E.operation
and type operation_receipt = E.operation_receipt
and type validation_state = E.validation_state
and type cache_key = Context.Cache.key
and type cache_value = Context.Cache.value = struct
include E
let finalize_block vs _ = E.finalize_block vs
(* Add backwards compatibility shadowing here *)
let relative_position_within_block = compare_operations
let value_of_key ~chain_id:_ ~predecessor_context:_ ~predecessor_timestamp:_
~predecessor_level:_ ~predecessor_fitness:_ ~predecessor:_ ~timestamp:_ =
return (fun _ ->
Lwt.return
(Error_monad.error_with
"element_of_key called on environment protocol < V3"))
type cache_key = Context.Cache.key
type cache_value = Context.Cache.value
end
[ module type PROTOCOL ] is protocol signature that the shell can use .
A module of this signature is typically obtained through an adapter
( see Lift functors in environment definitions ) of the Main module
( which complies with the [ Updater ] signature ) .
A module of this signature is typically obtained through an adapter
(see Lift functors in environment definitions) of the Main module
(which complies with the [Updater] signature).
*)
module type PROTOCOL = sig
include
T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult
and type cache_key := Context.Cache.key
and type cache_value := Context.Cache.value
val environment_version : Protocol.env_version
val begin_partial_application :
chain_id:Chain_id.t ->
ancestor_context:Context.t ->
predecessor:Block_header.t ->
predecessor_hash:Block_hash.t ->
cache:Context.source_of_cache ->
block_header ->
(validation_state, tztrace) result Lwt.t
val begin_application :
chain_id:Chain_id.t ->
predecessor_context:Context.t ->
predecessor_timestamp:Time.Protocol.t ->
predecessor_fitness:Fitness.t ->
cache:Context.source_of_cache ->
block_header ->
validation_state Error_monad.tzresult Lwt.t
val begin_construction :
chain_id:Chain_id.t ->
predecessor_context:Context.t ->
predecessor_timestamp:Time.Protocol.t ->
predecessor_level:Int32.t ->
predecessor_fitness:Fitness.t ->
predecessor:Block_hash.t ->
timestamp:Time.Protocol.t ->
?protocol_data:block_header_data ->
cache:Context.source_of_cache ->
unit ->
validation_state Error_monad.tzresult Lwt.t
val finalize_block :
validation_state ->
Block_header.shell_header option ->
(validation_result * block_header_metadata) tzresult Lwt.t
end
(*
For environment V where V < V3, the caching mechanism is ignored.
The following functor provides a protocol adapter to implement
this.
*)
module IgnoreCaches
(P : T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult) =
struct
include P
let init context header =
Context.Cache.set_cache_layout context [] >>= fun context ->
init context header
let begin_partial_application ~chain_id ~ancestor_context
~predecessor_timestamp ~predecessor_fitness raw_block =
begin_partial_application
~chain_id
~ancestor_context
~predecessor_timestamp
~predecessor_fitness
raw_block
let begin_application ~chain_id ~predecessor_context ~predecessor_timestamp
~predecessor_fitness ~cache:_ raw_block =
begin_application
~chain_id
~predecessor_context
~predecessor_timestamp
~predecessor_fitness
raw_block
let begin_construction ~chain_id ~predecessor_context ~predecessor_timestamp
~predecessor_level ~predecessor_fitness ~predecessor ~timestamp
?protocol_data ~cache:_ () =
begin_construction
~chain_id
~predecessor_context
~predecessor_timestamp
~predecessor_level
~predecessor_fitness
~predecessor
~timestamp
?protocol_data
()
let finalize_block c shell_header = P.finalize_block c shell_header
end
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/lib_protocol_environment/environment_protocol_T.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
Documentation for this interface may be found in
module type [PROTOCOL] of [sigs/v3/updater.mli].
Add backwards compatibility shadowing here
For environment V where V < V3, the caching mechanism is ignored.
The following functor provides a protocol adapter to implement
this.
| Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2018 Nomadic Labs . < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Environment_context
This module contains the real module signature of an economic
protocol that the Shell sees . There is actually only one signature
to avoid [ if]-[then]-[else ] expressions inside the Shell .
When we change the module signature output of the environment , we
need to implement a forward - compatible interface . This is done by
upgrading the old interface to the new one .
The first change in this signature was introduced by the [ V3 ]
environment . This is why we implement a functor from the initial
environment [ V0 ] to [ V3 ] directly because neither [ V1 ] nor [ V2 ]
change the module signature output of the environment .
All the equalities constraints are here for typing only . We use a
destructive substitution ( [: =] ) for types that are defined by the
shell , or that are common to all the economic protocol
environments , and an equality constraint ( [ =] ) for the types that
are abstracted from the economic protocol .
[ module type T ] defines the same signature as the last [ Vx ]
environment ( [ module type Vx_T ] ) .
If you want to mock this module type , see { ! Environment_protocol_T_test } .
protocol that the Shell sees. There is actually only one signature
to avoid [if]-[then]-[else] expressions inside the Shell.
When we change the module signature output of the environment, we
need to implement a forward-compatible interface. This is done by
upgrading the old interface to the new one.
The first change in this signature was introduced by the [V3]
environment. This is why we implement a functor from the initial
environment [V0] to [V3] directly because neither [V1] nor [V2]
change the module signature output of the environment.
All the equalities constraints are here for typing only. We use a
destructive substitution ([:=]) for types that are defined by the
shell, or that are common to all the economic protocol
environments, and an equality constraint ([=]) for the types that
are abstracted from the economic protocol.
[module type T] defines the same signature as the last [Vx]
environment ([module type Vx_T]).
If you want to mock this module type, see {!Environment_protocol_T_test}. *)
module type T = sig
include Environment_protocol_T_V3.T
val set_log_message_consumer :
(Internal_event.level -> string -> unit) -> unit
val environment_version : Protocol.env_version
end
module V0toV3
(E : Environment_protocol_T_V0.T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult) :
Environment_protocol_T_V3.T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult
and type block_header_data = E.block_header_data
and type block_header = E.block_header
and type block_header_metadata = E.block_header_metadata
and type operation_data = E.operation_data
and type operation = E.operation
and type operation_receipt = E.operation_receipt
and type validation_state = E.validation_state
and type cache_key = Context.Cache.key
and type cache_value = Context.Cache.value = struct
include E
let finalize_block vs _ = E.finalize_block vs
let relative_position_within_block = compare_operations
let value_of_key ~chain_id:_ ~predecessor_context:_ ~predecessor_timestamp:_
~predecessor_level:_ ~predecessor_fitness:_ ~predecessor:_ ~timestamp:_ =
return (fun _ ->
Lwt.return
(Error_monad.error_with
"element_of_key called on environment protocol < V3"))
type cache_key = Context.Cache.key
type cache_value = Context.Cache.value
end
[ module type PROTOCOL ] is protocol signature that the shell can use .
A module of this signature is typically obtained through an adapter
( see Lift functors in environment definitions ) of the Main module
( which complies with the [ Updater ] signature ) .
A module of this signature is typically obtained through an adapter
(see Lift functors in environment definitions) of the Main module
(which complies with the [Updater] signature).
*)
module type PROTOCOL = sig
include
T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult
and type cache_key := Context.Cache.key
and type cache_value := Context.Cache.value
val environment_version : Protocol.env_version
val begin_partial_application :
chain_id:Chain_id.t ->
ancestor_context:Context.t ->
predecessor:Block_header.t ->
predecessor_hash:Block_hash.t ->
cache:Context.source_of_cache ->
block_header ->
(validation_state, tztrace) result Lwt.t
val begin_application :
chain_id:Chain_id.t ->
predecessor_context:Context.t ->
predecessor_timestamp:Time.Protocol.t ->
predecessor_fitness:Fitness.t ->
cache:Context.source_of_cache ->
block_header ->
validation_state Error_monad.tzresult Lwt.t
val begin_construction :
chain_id:Chain_id.t ->
predecessor_context:Context.t ->
predecessor_timestamp:Time.Protocol.t ->
predecessor_level:Int32.t ->
predecessor_fitness:Fitness.t ->
predecessor:Block_hash.t ->
timestamp:Time.Protocol.t ->
?protocol_data:block_header_data ->
cache:Context.source_of_cache ->
unit ->
validation_state Error_monad.tzresult Lwt.t
val finalize_block :
validation_state ->
Block_header.shell_header option ->
(validation_result * block_header_metadata) tzresult Lwt.t
end
module IgnoreCaches
(P : T
with type context := Context.t
and type quota := quota
and type validation_result := validation_result
and type rpc_context := rpc_context
and type 'a tzresult := 'a Error_monad.tzresult) =
struct
include P
let init context header =
Context.Cache.set_cache_layout context [] >>= fun context ->
init context header
let begin_partial_application ~chain_id ~ancestor_context
~predecessor_timestamp ~predecessor_fitness raw_block =
begin_partial_application
~chain_id
~ancestor_context
~predecessor_timestamp
~predecessor_fitness
raw_block
let begin_application ~chain_id ~predecessor_context ~predecessor_timestamp
~predecessor_fitness ~cache:_ raw_block =
begin_application
~chain_id
~predecessor_context
~predecessor_timestamp
~predecessor_fitness
raw_block
let begin_construction ~chain_id ~predecessor_context ~predecessor_timestamp
~predecessor_level ~predecessor_fitness ~predecessor ~timestamp
?protocol_data ~cache:_ () =
begin_construction
~chain_id
~predecessor_context
~predecessor_timestamp
~predecessor_level
~predecessor_fitness
~predecessor
~timestamp
?protocol_data
()
let finalize_block c shell_header = P.finalize_block c shell_header
end
|
8d2bf6987f5eb10f21225c6a2b8c9e3aa0bfd53a9579c8b52ac5fb93076afaae | pfdietz/ansi-test | macro-function.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Fri Jun 3 22:17:34 2005
;;;; Contains: Tests of MACRO-FUNCTION
(deftest macro-function.1
(loop for n in *cl-macro-symbols*
unless (macro-function n)
collect n)
nil)
(deftest macro-function.2
(loop for n in *cl-macro-symbols*
unless (macro-function n nil)
collect n)
nil)
(deftest macro-function.3
(loop for n in *cl-macro-symbols*
unless (eval `(macrolet ((%m (s &environment env)
(list 'quote
(macro-function s env))))
(%m ,n)))
collect n)
nil)
(deftest macro-function.4
(macro-function (gensym))
nil)
(deftest macro-function.5
(remove-if-not #'macro-function *cl-function-symbols*)
nil)
(deftest macro-function.6
(remove-if-not #'macro-function *cl-accessor-symbols*)
nil)
(deftest macro-function.7
(let ((fn
(macrolet ((%m () 16))
(macrolet ((%n (&environment env)
(list 'quote (macro-function '%m env))))
(%n)))))
(values
(notnot (functionp fn))
(funcall fn '(%m) nil)))
t 16)
(deftest macro-function.8
(let ((sym (gensym)))
(setf (macro-function sym) (macro-function 'pop))
(eval `(let ((x '(a b c)))
(values
(,sym x)
x))))
a (b c))
(deftest macro-function.9
(let ((sym (gensym)))
(setf (macro-function sym nil) (macro-function 'pop))
(eval `(let ((x '(a b c)))
(values
(,sym x)
x))))
a (b c))
(deftest macro-function.10
(let ((sym (gensym)))
(eval `(defun ,sym (x) :bad))
(setf (macro-function sym) (macro-function 'pop))
(eval `(let ((x '(a b c)))
(values
(,sym x)
x))))
a (b c))
(deftest macro-function.11
(let ((fn
(flet ((%m () 16))
(macrolet ((%n (&environment env)
(list 'quote (macro-function '%m env))))
(%n)))))
fn)
nil)
(deftest macro-function.12
(let ((sym (gensym)))
(eval `(defmacro ,sym () t))
(let ((i 0))
(values
(funcall (macro-function (progn (incf i) sym)) (list sym) nil)
i)))
t 1)
(deftest macro-function.13
(let ((sym (gensym)))
(eval `(defmacro ,sym () t))
(let ((i 0) a b)
(values
(funcall (macro-function (progn (setf a (incf i)) sym)
(progn (setf b (incf i)) nil))
(list sym) nil)
i a b)))
t 2 1 2)
(deftest macro-function.14
(let ((sym (gensym))
(i 0))
(setf (macro-function (progn (incf i) sym)) (macro-function 'pop))
(values
(eval `(let ((x '(a b c)))
(list
(,sym x)
x)))
i))
(a (b c)) 1)
(deftest macro-function.15
(let ((sym (gensym))
(i 0) a b)
(setf (macro-function (progn (setf a (incf i)) sym)
(progn (setf b (incf i)) nil))
(macro-function 'pop))
(values
(eval `(let ((x '(a b c)))
(list
(,sym x)
x)))
i a b))
(a (b c)) 2 1 2)
;;; Error tests
(deftest macro-function.error.1
(signals-error (macro-function) program-error)
t)
(deftest macro-function.error.2
(signals-error (macro-function 'pop nil nil) program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/eval-and-compile/macro-function.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of MACRO-FUNCTION
Error tests | Author :
Created : Fri Jun 3 22:17:34 2005
(deftest macro-function.1
(loop for n in *cl-macro-symbols*
unless (macro-function n)
collect n)
nil)
(deftest macro-function.2
(loop for n in *cl-macro-symbols*
unless (macro-function n nil)
collect n)
nil)
(deftest macro-function.3
(loop for n in *cl-macro-symbols*
unless (eval `(macrolet ((%m (s &environment env)
(list 'quote
(macro-function s env))))
(%m ,n)))
collect n)
nil)
(deftest macro-function.4
(macro-function (gensym))
nil)
(deftest macro-function.5
(remove-if-not #'macro-function *cl-function-symbols*)
nil)
(deftest macro-function.6
(remove-if-not #'macro-function *cl-accessor-symbols*)
nil)
(deftest macro-function.7
(let ((fn
(macrolet ((%m () 16))
(macrolet ((%n (&environment env)
(list 'quote (macro-function '%m env))))
(%n)))))
(values
(notnot (functionp fn))
(funcall fn '(%m) nil)))
t 16)
(deftest macro-function.8
(let ((sym (gensym)))
(setf (macro-function sym) (macro-function 'pop))
(eval `(let ((x '(a b c)))
(values
(,sym x)
x))))
a (b c))
(deftest macro-function.9
(let ((sym (gensym)))
(setf (macro-function sym nil) (macro-function 'pop))
(eval `(let ((x '(a b c)))
(values
(,sym x)
x))))
a (b c))
(deftest macro-function.10
(let ((sym (gensym)))
(eval `(defun ,sym (x) :bad))
(setf (macro-function sym) (macro-function 'pop))
(eval `(let ((x '(a b c)))
(values
(,sym x)
x))))
a (b c))
(deftest macro-function.11
(let ((fn
(flet ((%m () 16))
(macrolet ((%n (&environment env)
(list 'quote (macro-function '%m env))))
(%n)))))
fn)
nil)
(deftest macro-function.12
(let ((sym (gensym)))
(eval `(defmacro ,sym () t))
(let ((i 0))
(values
(funcall (macro-function (progn (incf i) sym)) (list sym) nil)
i)))
t 1)
(deftest macro-function.13
(let ((sym (gensym)))
(eval `(defmacro ,sym () t))
(let ((i 0) a b)
(values
(funcall (macro-function (progn (setf a (incf i)) sym)
(progn (setf b (incf i)) nil))
(list sym) nil)
i a b)))
t 2 1 2)
(deftest macro-function.14
(let ((sym (gensym))
(i 0))
(setf (macro-function (progn (incf i) sym)) (macro-function 'pop))
(values
(eval `(let ((x '(a b c)))
(list
(,sym x)
x)))
i))
(a (b c)) 1)
(deftest macro-function.15
(let ((sym (gensym))
(i 0) a b)
(setf (macro-function (progn (setf a (incf i)) sym)
(progn (setf b (incf i)) nil))
(macro-function 'pop))
(values
(eval `(let ((x '(a b c)))
(list
(,sym x)
x)))
i a b))
(a (b c)) 2 1 2)
(deftest macro-function.error.1
(signals-error (macro-function) program-error)
t)
(deftest macro-function.error.2
(signals-error (macro-function 'pop nil nil) program-error)
t)
|
b8579f2596152bc214102717611f1f3794c77b9ba9c46d5dba1055f0ce76d92d | korya/efuns | wX_display.mli | (***********************************************************************)
(* *)
(* ____ *)
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
class from :
Xtypes.display ->
object
val display : Xtypes.display
val eloop : Eloop.display
method broken : (unit -> unit) -> unit
method close : unit
method display : Xtypes.display
method eloop : Eloop.display
end
class t : string -> from
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/toolkit/wX_display.mli | ocaml | *********************************************************************
____
********************************************************************* | Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
class from :
Xtypes.display ->
object
val display : Xtypes.display
val eloop : Eloop.display
method broken : (unit -> unit) -> unit
method close : unit
method display : Xtypes.display
method eloop : Eloop.display
end
class t : string -> from
|
0a0813e469eb017ee9f9ff6cfb024b2cd4261b9cae940b6dea19f09760b6a111 | privet-kitty/cl-competitive | util.lisp | (defpackage :cp/util
(:use :cl)
(:import-from :fiveam)
#+sbcl (:import-from :sb-sprof)
(:export #:run #:get-clipbrd #:submit #:sub #:login #:*lisp-file-pathname* #:*problem-url*))
(in-package :cp/util)
(defvar *lisp-file-pathname*)
(defvar *problem-url*)
(defun get-clipbrd ()
(with-output-to-string (out)
#+os-windows
(uiop:run-program '("powershell.exe" "-Command" "Get-Clipboard") :output out)
#+os-unix
(uiop:run-program '("xsel" "-b" "-o") :output out)))
(defun run (&optional input (out *standard-output*) main)
"INPUT := null | string | symbol | pathname
null: run MAIN using the text on clipboard as input.
string: run MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run MAIN using the text file as input.
- If MAIN is nil, #'cl-user::main is called.
- If OUT is nil, this function returns the whole output of MAIN as a string.
"
(let* ((main (or main
(let ((symbol (find-symbol "MAIN" :cl-user)))
(if (and symbol (fboundp symbol))
(symbol-function symbol)
(error "Don't know which function to run"))))))
(labels ((proc ()
(etypecase input
(null
(with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
(funcall main)))
(string
(with-input-from-string (*standard-input* (delete #\Return input))
(funcall main)))
(symbol (5am:run! input))
(pathname
(with-open-file (*standard-input* input)
(funcall main))))))
(etypecase out
((or string pathname)
(uiop:with-output-file (*standard-output* out :if-exists :supersede)
(proc)))
(null
(let ((*standard-output* (make-string-output-stream)))
(proc)
(get-output-stream-string *standard-output*)))
(stream
(let ((*standard-output* out))
(proc)))))))
(defun submit (&key url pathname (test t))
"Submits PATHNAME to URL. If TEST is true, this function verifies the code
with (RUN :SAMPLE) before submission."
(let ((url (or url
(if (and (boundp '*problem-url*) *problem-url*)
*problem-url*
(error "Don't know to which URL to do submission"))))
(pathname (or pathname
(if (boundp '*lisp-file-pathname*)
*lisp-file-pathname*
(error "Don't know which file to submit"))))
(wait 0.0))
(when (or (not test) (run :sample))
(format t "Submit in ~A seconds~%" wait)
(sleep wait)
(uiop:run-program `("oj" "submit" "--yes" "--wait" "0" ,url ,(namestring pathname))
:output *standard-output*))))
(defun sub (&key url pathname (test t))
"Is an alias of CP/TOOLS:SUBMIT."
(submit :url url :pathname pathname :test test))
(defun login (&optional url)
(let ((url (or url
(if (boundp '*problem-url*)
*problem-url*
(error "Don't know to which URL to login")))))
(uiop:run-program `("oj" "login" ,url) :output *standard-output*)))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/77cf767213ee8f6673b90715a10dca07fd35f138/module/util.lisp | lisp | (defpackage :cp/util
(:use :cl)
(:import-from :fiveam)
#+sbcl (:import-from :sb-sprof)
(:export #:run #:get-clipbrd #:submit #:sub #:login #:*lisp-file-pathname* #:*problem-url*))
(in-package :cp/util)
(defvar *lisp-file-pathname*)
(defvar *problem-url*)
(defun get-clipbrd ()
(with-output-to-string (out)
#+os-windows
(uiop:run-program '("powershell.exe" "-Command" "Get-Clipboard") :output out)
#+os-unix
(uiop:run-program '("xsel" "-b" "-o") :output out)))
(defun run (&optional input (out *standard-output*) main)
"INPUT := null | string | symbol | pathname
null: run MAIN using the text on clipboard as input.
string: run MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run MAIN using the text file as input.
- If MAIN is nil, #'cl-user::main is called.
- If OUT is nil, this function returns the whole output of MAIN as a string.
"
(let* ((main (or main
(let ((symbol (find-symbol "MAIN" :cl-user)))
(if (and symbol (fboundp symbol))
(symbol-function symbol)
(error "Don't know which function to run"))))))
(labels ((proc ()
(etypecase input
(null
(with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
(funcall main)))
(string
(with-input-from-string (*standard-input* (delete #\Return input))
(funcall main)))
(symbol (5am:run! input))
(pathname
(with-open-file (*standard-input* input)
(funcall main))))))
(etypecase out
((or string pathname)
(uiop:with-output-file (*standard-output* out :if-exists :supersede)
(proc)))
(null
(let ((*standard-output* (make-string-output-stream)))
(proc)
(get-output-stream-string *standard-output*)))
(stream
(let ((*standard-output* out))
(proc)))))))
(defun submit (&key url pathname (test t))
"Submits PATHNAME to URL. If TEST is true, this function verifies the code
with (RUN :SAMPLE) before submission."
(let ((url (or url
(if (and (boundp '*problem-url*) *problem-url*)
*problem-url*
(error "Don't know to which URL to do submission"))))
(pathname (or pathname
(if (boundp '*lisp-file-pathname*)
*lisp-file-pathname*
(error "Don't know which file to submit"))))
(wait 0.0))
(when (or (not test) (run :sample))
(format t "Submit in ~A seconds~%" wait)
(sleep wait)
(uiop:run-program `("oj" "submit" "--yes" "--wait" "0" ,url ,(namestring pathname))
:output *standard-output*))))
(defun sub (&key url pathname (test t))
"Is an alias of CP/TOOLS:SUBMIT."
(submit :url url :pathname pathname :test test))
(defun login (&optional url)
(let ((url (or url
(if (boundp '*problem-url*)
*problem-url*
(error "Don't know to which URL to login")))))
(uiop:run-program `("oj" "login" ,url) :output *standard-output*)))
|
|
2af3306dc758872c1877fbd57c26673ddb616b3c47baac4967194371b37e6554 | mdunnio/coinbase-pro | Heartbeat.hs | {-# LANGUAGE OverloadedStrings #-}
module CoinbasePro.WebSocketFeed.Channel.Heartbeat
( Heartbeat (..)
)where
import Data.Aeson (FromJSON (..), withObject, (.:))
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
data Heartbeat = Heartbeat
{ sequence :: Int
, lastTradeId :: Int
, productId :: Text
, time :: UTCTime
} deriving (Eq, Ord, Show)
instance FromJSON Heartbeat where
parseJSON = withObject "heartbeat" $ \o ->
Heartbeat <$>
o .: "sequence" <*>
o .: "last_trade_id" <*>
o .: "product_id" <*>
o .: "time"
| null | https://raw.githubusercontent.com/mdunnio/coinbase-pro/5d5fa95e66481a974786ef362a4ea55ba94c63a9/src/lib/CoinbasePro/WebSocketFeed/Channel/Heartbeat.hs | haskell | # LANGUAGE OverloadedStrings # |
module CoinbasePro.WebSocketFeed.Channel.Heartbeat
( Heartbeat (..)
)where
import Data.Aeson (FromJSON (..), withObject, (.:))
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
data Heartbeat = Heartbeat
{ sequence :: Int
, lastTradeId :: Int
, productId :: Text
, time :: UTCTime
} deriving (Eq, Ord, Show)
instance FromJSON Heartbeat where
parseJSON = withObject "heartbeat" $ \o ->
Heartbeat <$>
o .: "sequence" <*>
o .: "last_trade_id" <*>
o .: "product_id" <*>
o .: "time"
|
2105834a6f6d204c9763e9d1325a06583c1f9ec485d212ee75181507e25ece55 | alsonkemp/turbinado | Naming.hs | module Turbinado.Utility.Naming where
import Data.Char
import Data.List
--
-- * Turbinado Utility functions for Naming
--
| Lowercases the first letter to make a valid function .
underscoreToFunction [] = error "toFunction passed an empty string"
underscoreToFunction (firstL:ls) = (Data.Char.toLower firstL) : fromUnderscore ls
| Uppercases the first letter to make a valid type .
underscoreToType [] = error "toType passed an empty string"
underscoreToType l = fromUnderscore l
| to abba_ding
toUnderscore [] = error "toUnderscore passed an empty string"
toUnderscore (l:ls) = toLower l : worker ls
where worker [] = []
worker "_" = "_" -- end with "_", then end with "_"
worker (c:cs) | isUpper c = '_' : toLower c : worker cs
| otherwise = c : worker cs
| Convert abba_ding to AbbaDing
fromUnderscore [] = error "fromUnderscore passed an empty string"
fromUnderscore (l:ls) = toUpper l : worker ls
where worker [] = []
worker "_" = "_" -- end with "_", then end with "_"
worker ('_':c:cs) | isLetter c = toUpper c : worker cs
| otherwise = '_' : c : worker cs
worker (c:cs) = c : worker cs
| null | https://raw.githubusercontent.com/alsonkemp/turbinado/da2ba7c3443ddf6a51d1ec5b05cb45a85efc0809/Turbinado/Utility/Naming.hs | haskell |
* Turbinado Utility functions for Naming
end with "_", then end with "_"
end with "_", then end with "_" | module Turbinado.Utility.Naming where
import Data.Char
import Data.List
| Lowercases the first letter to make a valid function .
underscoreToFunction [] = error "toFunction passed an empty string"
underscoreToFunction (firstL:ls) = (Data.Char.toLower firstL) : fromUnderscore ls
| Uppercases the first letter to make a valid type .
underscoreToType [] = error "toType passed an empty string"
underscoreToType l = fromUnderscore l
| to abba_ding
toUnderscore [] = error "toUnderscore passed an empty string"
toUnderscore (l:ls) = toLower l : worker ls
where worker [] = []
worker (c:cs) | isUpper c = '_' : toLower c : worker cs
| otherwise = c : worker cs
| Convert abba_ding to AbbaDing
fromUnderscore [] = error "fromUnderscore passed an empty string"
fromUnderscore (l:ls) = toUpper l : worker ls
where worker [] = []
worker ('_':c:cs) | isLetter c = toUpper c : worker cs
| otherwise = '_' : c : worker cs
worker (c:cs) = c : worker cs
|
4fcba8a5ea0277ca87d531913b936c8dc0492fec8b96111c7a3fd948bcdfcba9 | joehillen/craft | Internal.hs | module Craft.Internal
(module X)
where
import Craft.DSL as X
import Craft.Helpers as X
import Craft.Run as X
import Craft.Types as X
| null | https://raw.githubusercontent.com/joehillen/craft/de31caa7f86cceaab23dbef0f05208bb853cf73b/src/Craft/Internal.hs | haskell | module Craft.Internal
(module X)
where
import Craft.DSL as X
import Craft.Helpers as X
import Craft.Run as X
import Craft.Types as X
|
|
f774a4e43676d5e1b2d65b475ef9a17245e3b6e6de486ffd089d930b398c973b | MassD/pearls | multiway_tree.ml |
multiway_tree preorder traversal & loopless
preorder is that always the root goes first
multiway_tree preorder traversal & loopless
preorder is that always the root goes first
*)
type 'a multiway_tree = Node of 'a * ('a multiway_tree list)
let mt1 = Node (1, [Node (2, [Node (3,[]); Node (4,[])]);Node (5,[])])
let rec preorder_root (Node (x, mtl)) = x::(List.map (fun mt -> preorder_root mt) mtl |> List.flatten)
(* On list of multiway_trees, so called forest *)
let rec preorder_mt_list = function
| [] -> []
| (Node (hd, cms))::ms -> hd::(preorder_mt_list (cms@ms)) (* crs is child tree list, ms is list of multiway_trees *)
the following is not a good ` step_f ` as it is not O(1 ) at ft@rs
let preorder_step_bad = function
| [] -> None
| Node (hd, cms)::ms -> Some (hd,cms@ms)
(*
Since the above preorder involves list concate operation, we need to transform it to :: operation
1. We can change the parameter to be list of list of multiway_trees
2. So each time we get the Node, we can directly :: its child multiway_tree list to the list of list
*)
let preorder_step = function
| [] -> None
| []::_ -> failwith "wrong"
this is constant time , mss is list of list of multiway_trees
match cms, ms with
| [], [] -> Some (hd, mss)
| mts, [] | [], mts -> Some (hd, mts::mss)
| cms, ms -> Some (hd, cms::ms::mss)
| null | https://raw.githubusercontent.com/MassD/pearls/da73f49ffe61125c1def4f2b3ed339963318dbec/28_loopless/multiway_tree.ml | ocaml | On list of multiway_trees, so called forest
crs is child tree list, ms is list of multiway_trees
Since the above preorder involves list concate operation, we need to transform it to :: operation
1. We can change the parameter to be list of list of multiway_trees
2. So each time we get the Node, we can directly :: its child multiway_tree list to the list of list
|
multiway_tree preorder traversal & loopless
preorder is that always the root goes first
multiway_tree preorder traversal & loopless
preorder is that always the root goes first
*)
type 'a multiway_tree = Node of 'a * ('a multiway_tree list)
let mt1 = Node (1, [Node (2, [Node (3,[]); Node (4,[])]);Node (5,[])])
let rec preorder_root (Node (x, mtl)) = x::(List.map (fun mt -> preorder_root mt) mtl |> List.flatten)
let rec preorder_mt_list = function
| [] -> []
the following is not a good ` step_f ` as it is not O(1 ) at ft@rs
let preorder_step_bad = function
| [] -> None
| Node (hd, cms)::ms -> Some (hd,cms@ms)
let preorder_step = function
| [] -> None
| []::_ -> failwith "wrong"
this is constant time , mss is list of list of multiway_trees
match cms, ms with
| [], [] -> Some (hd, mss)
| mts, [] | [], mts -> Some (hd, mts::mss)
| cms, ms -> Some (hd, cms::ms::mss)
|
ede99341e15790f4f7d755ab60f70d2e03c9e2873726a5f5c7e52b18f67909df | janestreet/universe | unix_extended.mli | (** Extensions to [Core.Unix]. *)
open! Core
* [ fork_exec prog args ~stdin ~stdout ~stderr ~setuid ~setgid ]
forks a new process that executes the program
in file [ prog ] , with arguments [ args ] . The pid of the new
process is returned immediately ; the new process executes
concurrently with the current process .
The function raises EPERM if when using [ set{gid , uid } ] and the user i d is
not 0 .
The standard input and outputs of the new process are connected
to the descriptors [ stdin ] , [ stdout ] and [ stderr ] .
The close_on_exec flag is cleared from [ stderr ] [ stdout ] and [ stdin ] so it 's
safe to pass in fds with [ close_on_exec ] set .
@param path_lookup if [ true ] than we use PATH to find the process to exec .
@env specifies the environment the process runs in
ERRORS :
Unix.unix_error . This function should not raise EINTR ; it will restart
itself automatically .
RATIONAL :
[ setuid ] and [ setgid ] do not do a full i d drop ( e.g. : they save the i d in
saved i d ) when the user does not have the privileges required to setuid to
anyone .
By default all file descriptors should be set_closexec ASAP after being open
to avoid being captured in parallel execution of fork_exec ; resetting the
closexec flag on the forked flag is a cleaner and more thread safe approach .
BUGS :
The capabilities for setuid in linux are not tied to the uid 0 ( man 7
capabilities ) . It is still fair to assume that under most system this
capability is there IFF uid = = 0 . A more fine grain permissionning approach
would make this function non - portable and be hard to implement in an
async - signal - way .
Because this function keeps the lock for most of its lifespan and restarts
automatically on EINTR it might prevent the OCaml signal handlers to run in
that thread .
forks a new process that executes the program
in file [prog], with arguments [args]. The pid of the new
process is returned immediately; the new process executes
concurrently with the current process.
The function raises EPERM if when using [set{gid,uid}] and the user id is
not 0.
The standard input and outputs of the new process are connected
to the descriptors [stdin], [stdout] and [stderr].
The close_on_exec flag is cleared from [stderr] [stdout] and [stdin] so it's
safe to pass in fds with [close_on_exec] set.
@param path_lookup if [true] than we use PATH to find the process to exec.
@env specifies the environment the process runs in
ERRORS:
Unix.unix_error. This function should not raise EINTR; it will restart
itself automatically.
RATIONAL:
[setuid] and [setgid] do not do a full id drop (e.g.: they save the id in
saved id) when the user does not have the privileges required to setuid to
anyone.
By default all file descriptors should be set_closexec ASAP after being open
to avoid being captured in parallel execution of fork_exec; resetting the
closexec flag on the forked flag is a cleaner and more thread safe approach.
BUGS:
The capabilities for setuid in linux are not tied to the uid 0 (man 7
capabilities). It is still fair to assume that under most system this
capability is there IFF uid == 0. A more fine grain permissionning approach
would make this function non-portable and be hard to implement in an
async-signal-way.
Because this function keeps the lock for most of its lifespan and restarts
automatically on EINTR it might prevent the OCaml signal handlers to run in
that thread.
*)
val fork_exec
: ?stdin:Unix.File_descr.t
-> ?stdout:Unix.File_descr.t
-> ?stderr:Unix.File_descr.t
-> ?path_lookup:bool
-> ?env:[ `Extend of (string * string) list | `Replace of (string * string) list ]
-> ?working_dir:string
-> ?setuid:int
-> ?setgid:int
-> string
-> string list
-> Pid.t
val seteuid : int -> unit
val setreuid : uid:int -> euid:int -> unit
(** Network to host order long, like C. *)
external ntohl : Int32.t -> Int32.t = "extended_ml_ntohl"
(** Host to network order long, like C. *)
external htonl : Int32.t -> Int32.t = "extended_ml_htonl"
type statvfs =
{ bsize : int (** file system block size *)
; frsize : int (** fragment size *)
; blocks : int (** size of fs in frsize units *)
; bfree : int (** # free blocks *)
; bavail : int (** # free blocks for non-root *)
; files : int (** # inodes *)
; ffree : int (** # free inodes *)
; favail : int (** # free inodes for non-root *)
; fsid : int (** file system ID *)
; flag : int (** mount flags *)
; namemax : int (** maximum filename length *)
}
[@@deriving sexp, bin_io]
(** get file system statistics *)
external statvfs : string -> statvfs = "statvfs_stub"
(** get load averages *)
external getloadavg : unit -> float * float * float = "getloadavg_stub"
module Extended_passwd : sig
open Unix.Passwd
(** [of_passwd_line] parse a passwd-like line *)
val of_passwd_line : string -> t option
(** [of_passwd_line_exn] parse a passwd-like line *)
val of_passwd_line_exn : string -> t
(** [of_passwd_file] parse a passwd-like file *)
val of_passwd_file : string -> t list option
(** [of_passwd_file_exn] parse a passwd-like file *)
val of_passwd_file_exn : string -> t list
end
val strptime : fmt:string -> string -> Unix.tm
[@@deprecated "[since 2019-07] use Core.Unix.strptime"]
* The CIDR module moved into Core . Unix
(** Simple int wrapper to be explicit about ports. *)
module Inet_port : sig
type t [@@deriving sexp_of, compare, hash]
val of_int : int -> t option
val of_int_exn : int -> t
val of_string : string -> t option
val of_string_exn : string -> t
val to_int : t -> int
val to_string : t -> string
val arg_type : t Command.Arg_type.t
include Comparable.S_plain with type t := t
module Stable : sig
module V1 :
Stable_comparable.V1
with type t = t
and type comparator_witness = comparator_witness
end
end
(* MAC-48 (Ethernet) adddresses *)
module Mac_address : sig
type t [@@deriving sexp, bin_io]
val equal : t -> t -> bool
Supports standard " xx : xx : xx : xx : xx : xx " , " " , and cisco
" xxxx.xxxx.xxxx " representations .
"xxxx.xxxx.xxxx" representations. *)
val of_string : string -> t
(* To standard representation "xx:xx:xx:xx:xx:xx". Note the hex chars
will be downcased! *)
val to_string : t -> string
To cisco representation " xxxx.xxxx.xxxx "
val to_string_cisco : t -> string
include Hashable.S with type t := t
end
module Quota : sig
type bytes = private Int63.t [@@deriving sexp]
type inodes = private Int63.t [@@deriving sexp]
val bytes : Int63.t -> bytes
val inodes : Int63.t -> inodes
type 'units limit =
{ soft : 'units option
; hard : 'units option
; grace : Time.t option
}
[@@deriving sexp]
type 'units usage = private 'units
val query
: [ `User | `Group ]
-> id:int
-> path:string
-> (bytes limit * bytes usage * inodes limit * inodes usage) Or_error.t
val set
: [ `User | `Group ]
-> id:int
-> path:string
-> bytes limit
-> inodes limit
-> unit Or_error.t
end
module Mount_entry : sig
see : man 3 getmntent
type t [@@deriving sexp]
val parse_line : string -> t option Or_error.t
val fsname : t -> string
val directory : t -> string
val fstype : t -> string
val options : t -> string
val dump_freq : t -> int option
val fsck_pass : t -> int option
val visible_filesystem : t list -> t String.Map.t
end
val terminal_width : int Lazy.t
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/shell/unix_extended/src/unix_extended.mli | ocaml | * Extensions to [Core.Unix].
* Network to host order long, like C.
* Host to network order long, like C.
* file system block size
* fragment size
* size of fs in frsize units
* # free blocks
* # free blocks for non-root
* # inodes
* # free inodes
* # free inodes for non-root
* file system ID
* mount flags
* maximum filename length
* get file system statistics
* get load averages
* [of_passwd_line] parse a passwd-like line
* [of_passwd_line_exn] parse a passwd-like line
* [of_passwd_file] parse a passwd-like file
* [of_passwd_file_exn] parse a passwd-like file
* Simple int wrapper to be explicit about ports.
MAC-48 (Ethernet) adddresses
To standard representation "xx:xx:xx:xx:xx:xx". Note the hex chars
will be downcased! | open! Core
* [ fork_exec prog args ~stdin ~stdout ~stderr ~setuid ~setgid ]
forks a new process that executes the program
in file [ prog ] , with arguments [ args ] . The pid of the new
process is returned immediately ; the new process executes
concurrently with the current process .
The function raises EPERM if when using [ set{gid , uid } ] and the user i d is
not 0 .
The standard input and outputs of the new process are connected
to the descriptors [ stdin ] , [ stdout ] and [ stderr ] .
The close_on_exec flag is cleared from [ stderr ] [ stdout ] and [ stdin ] so it 's
safe to pass in fds with [ close_on_exec ] set .
@param path_lookup if [ true ] than we use PATH to find the process to exec .
@env specifies the environment the process runs in
ERRORS :
Unix.unix_error . This function should not raise EINTR ; it will restart
itself automatically .
RATIONAL :
[ setuid ] and [ setgid ] do not do a full i d drop ( e.g. : they save the i d in
saved i d ) when the user does not have the privileges required to setuid to
anyone .
By default all file descriptors should be set_closexec ASAP after being open
to avoid being captured in parallel execution of fork_exec ; resetting the
closexec flag on the forked flag is a cleaner and more thread safe approach .
BUGS :
The capabilities for setuid in linux are not tied to the uid 0 ( man 7
capabilities ) . It is still fair to assume that under most system this
capability is there IFF uid = = 0 . A more fine grain permissionning approach
would make this function non - portable and be hard to implement in an
async - signal - way .
Because this function keeps the lock for most of its lifespan and restarts
automatically on EINTR it might prevent the OCaml signal handlers to run in
that thread .
forks a new process that executes the program
in file [prog], with arguments [args]. The pid of the new
process is returned immediately; the new process executes
concurrently with the current process.
The function raises EPERM if when using [set{gid,uid}] and the user id is
not 0.
The standard input and outputs of the new process are connected
to the descriptors [stdin], [stdout] and [stderr].
The close_on_exec flag is cleared from [stderr] [stdout] and [stdin] so it's
safe to pass in fds with [close_on_exec] set.
@param path_lookup if [true] than we use PATH to find the process to exec.
@env specifies the environment the process runs in
ERRORS:
Unix.unix_error. This function should not raise EINTR; it will restart
itself automatically.
RATIONAL:
[setuid] and [setgid] do not do a full id drop (e.g.: they save the id in
saved id) when the user does not have the privileges required to setuid to
anyone.
By default all file descriptors should be set_closexec ASAP after being open
to avoid being captured in parallel execution of fork_exec; resetting the
closexec flag on the forked flag is a cleaner and more thread safe approach.
BUGS:
The capabilities for setuid in linux are not tied to the uid 0 (man 7
capabilities). It is still fair to assume that under most system this
capability is there IFF uid == 0. A more fine grain permissionning approach
would make this function non-portable and be hard to implement in an
async-signal-way.
Because this function keeps the lock for most of its lifespan and restarts
automatically on EINTR it might prevent the OCaml signal handlers to run in
that thread.
*)
val fork_exec
: ?stdin:Unix.File_descr.t
-> ?stdout:Unix.File_descr.t
-> ?stderr:Unix.File_descr.t
-> ?path_lookup:bool
-> ?env:[ `Extend of (string * string) list | `Replace of (string * string) list ]
-> ?working_dir:string
-> ?setuid:int
-> ?setgid:int
-> string
-> string list
-> Pid.t
val seteuid : int -> unit
val setreuid : uid:int -> euid:int -> unit
external ntohl : Int32.t -> Int32.t = "extended_ml_ntohl"
external htonl : Int32.t -> Int32.t = "extended_ml_htonl"
type statvfs =
}
[@@deriving sexp, bin_io]
external statvfs : string -> statvfs = "statvfs_stub"
external getloadavg : unit -> float * float * float = "getloadavg_stub"
module Extended_passwd : sig
open Unix.Passwd
val of_passwd_line : string -> t option
val of_passwd_line_exn : string -> t
val of_passwd_file : string -> t list option
val of_passwd_file_exn : string -> t list
end
val strptime : fmt:string -> string -> Unix.tm
[@@deprecated "[since 2019-07] use Core.Unix.strptime"]
* The CIDR module moved into Core . Unix
module Inet_port : sig
type t [@@deriving sexp_of, compare, hash]
val of_int : int -> t option
val of_int_exn : int -> t
val of_string : string -> t option
val of_string_exn : string -> t
val to_int : t -> int
val to_string : t -> string
val arg_type : t Command.Arg_type.t
include Comparable.S_plain with type t := t
module Stable : sig
module V1 :
Stable_comparable.V1
with type t = t
and type comparator_witness = comparator_witness
end
end
module Mac_address : sig
type t [@@deriving sexp, bin_io]
val equal : t -> t -> bool
Supports standard " xx : xx : xx : xx : xx : xx " , " " , and cisco
" xxxx.xxxx.xxxx " representations .
"xxxx.xxxx.xxxx" representations. *)
val of_string : string -> t
val to_string : t -> string
To cisco representation " xxxx.xxxx.xxxx "
val to_string_cisco : t -> string
include Hashable.S with type t := t
end
module Quota : sig
type bytes = private Int63.t [@@deriving sexp]
type inodes = private Int63.t [@@deriving sexp]
val bytes : Int63.t -> bytes
val inodes : Int63.t -> inodes
type 'units limit =
{ soft : 'units option
; hard : 'units option
; grace : Time.t option
}
[@@deriving sexp]
type 'units usage = private 'units
val query
: [ `User | `Group ]
-> id:int
-> path:string
-> (bytes limit * bytes usage * inodes limit * inodes usage) Or_error.t
val set
: [ `User | `Group ]
-> id:int
-> path:string
-> bytes limit
-> inodes limit
-> unit Or_error.t
end
module Mount_entry : sig
see : man 3 getmntent
type t [@@deriving sexp]
val parse_line : string -> t option Or_error.t
val fsname : t -> string
val directory : t -> string
val fstype : t -> string
val options : t -> string
val dump_freq : t -> int option
val fsck_pass : t -> int option
val visible_filesystem : t list -> t String.Map.t
end
val terminal_width : int Lazy.t
|
2a9efecd6f85acaa7ed56faab1e41d6f1b2b570779508123c0bd7b9d90657e7a | sile/proxy | proxy_lifetime_tests.erl | -module(proxy_lifetime_tests).
-include_lib("eunit/include/eunit.hrl").
-export([sleep_infinity/0]).
restart_test_() ->
[
{"実プロセスの開始時刻と終了時刻を指定できる",
fun () ->
100ms後
200ms後
ProxyPid =
proxy:spawn(?MODULE, sleep_infinity, [],
[{proxy_lifetime, [{start_time, StartTime}, {stop_time, StopTime}]}]),
?assertEqual(hibernate, proxy:call(ProxyPid, get_real_process)),
timer:sleep(110),
?assertMatch(Pid when is_pid(Pid), proxy:call(ProxyPid, get_real_process)),
monitor(process, ProxyPid),
receive
{'DOWN', _, _, ProxyPid, _} ->
?assert(true)
after 500 ->
?assert(false)
end
end}
].
sleep_infinity() ->
timer:sleep(infinity).
now_after(Ms) ->
{MegaSecs, Secs, MicroSecs} = os:timestamp(),
{MegaSecs, Secs, MicroSecs + Ms * 1000}.
| null | https://raw.githubusercontent.com/sile/proxy/009418087d92ec44d25ae82462213f3792360f77/test/proxy_lifetime_tests.erl | erlang | -module(proxy_lifetime_tests).
-include_lib("eunit/include/eunit.hrl").
-export([sleep_infinity/0]).
restart_test_() ->
[
{"実プロセスの開始時刻と終了時刻を指定できる",
fun () ->
100ms後
200ms後
ProxyPid =
proxy:spawn(?MODULE, sleep_infinity, [],
[{proxy_lifetime, [{start_time, StartTime}, {stop_time, StopTime}]}]),
?assertEqual(hibernate, proxy:call(ProxyPid, get_real_process)),
timer:sleep(110),
?assertMatch(Pid when is_pid(Pid), proxy:call(ProxyPid, get_real_process)),
monitor(process, ProxyPid),
receive
{'DOWN', _, _, ProxyPid, _} ->
?assert(true)
after 500 ->
?assert(false)
end
end}
].
sleep_infinity() ->
timer:sleep(infinity).
now_after(Ms) ->
{MegaSecs, Secs, MicroSecs} = os:timestamp(),
{MegaSecs, Secs, MicroSecs + Ms * 1000}.
|
|
88aa1b0a9dee2b913139cbc967e830455d87c3ee736bb2a88f9cf0b00ed9defa | gonzojive/hunchentoot | test-handlers.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : HUNCHENTOOT ; Base : 10 -*-
$ Header : /usr / local / cvsrep / hunchentoot / test / test.lisp , v 1.24 2008/03/06 07:46:53 edi Exp $
Copyright ( c ) 2004 - 2010 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :hunchentoot-test)
(defvar *this-file* (load-time-value
(or #.*compile-file-pathname* *load-pathname*)))
(defmacro with-html (&body body)
`(with-html-output-to-string (*standard-output* nil :prologue t)
,@body))
(defun hunchentoot-link ()
(with-html-output (*standard-output*)
(:a :href "/" "Hunchentoot")))
(defun menu-link ()
(with-html-output (*standard-output*)
(:p (:hr
(:a :href "/hunchentoot/test" "Back to menu")))))
(defmacro with-lisp-output ((var) &body body)
`(let ((*package* (find-package :hunchentoot-test-user)))
(with-output-to-string (,var #+:lispworks nil
#+:lispworks :element-type
#+:lispworks 'lw:simple-char)
,@body)))
(defmacro info-table (&rest forms)
(let ((=value= (gensym))
(=first= (gensym)))
`(with-html-output (*standard-output*)
(:p (:table :border 1 :cellpadding 2 :cellspacing 0
(:tr (:td :colspan 2
"Some Information "
(hunchentoot-link)
" provides about this request:"))
,@(loop for form in forms
collect `(:tr (:td :valign "top"
(:pre :style "padding: 0px"
(esc (with-lisp-output (s) (pprint ',form s)))))
(:td :valign "top"
(:pre :style "padding: 0px"
(esc (with-lisp-output (s)
(loop for ,=value= in (multiple-value-list ,form)
for ,=first= = t then nil
unless ,=first=
do (princ ", " s)
do (pprint ,=value= s))))))))))
(menu-link))))
(defun authorization-page ()
(multiple-value-bind (user password)
(authorization)
(cond ((and (equal user "nanook")
(equal password "igloo"))
(with-html
(:html
(:head (:title "Hunchentoot page with Basic Authentication"))
(:body
(:h2 (hunchentoot-link)
" page with Basic Authentication")
(info-table (header-in* :authorization)
(authorization))))))
(t
(require-authorization)))))
(defparameter *test-image*
(load-time-value
(with-open-file (in (make-pathname :name "fz" :type "jpg" :version nil
:defaults *this-file*)
:element-type 'flex:octet)
(let ((image-data (make-array (file-length in)
:element-type 'flex:octet)))
(read-sequence image-data in)
image-data))))
(defun image-ram-page ()
(setf (content-type*) "image/jpeg")
*test-image*)
(let ((count 0))
(defun info ()
(with-html
(:html
(:head (:title "Hunchentoot Information"))
(:body
(:h2 (hunchentoot-link) " Information Page")
(:p "This page has been called "
(:b
(fmt "~[~;once~;twice~:;~:*~R times~]" (incf count)))
" since its handler was compiled.")
(info-table (host)
(acceptor-address *acceptor*)
(acceptor-port *acceptor*)
(remote-addr*)
(remote-port*)
(real-remote-addr)
(request-method*)
(script-name*)
(query-string*)
(get-parameters*)
(headers-in*)
(cookies-in*)
(user-agent)
(referer)
(request-uri*)
(server-protocol*)))))))
(defun oops ()
(with-html
(log-message :error "Oops \(error log level).")
(log-message :warning "Oops \(warning log level).")
(log-message :info "Oops \(info log level).")
(error "Errors were triggered on purpose. Check your error log.")
(:html
(:body "You should never see this sentence..."))))
(defun redir ()
(redirect "/hunchentoot/test/info.html?redirected=1"))
(defun forbidden ()
(setf (return-code*) +http-forbidden+)
nil)
(defun cookie-test ()
(set-cookie "pumpkin" :value "barking")
(no-cache)
(with-html
(:html
(:head (:title "Hunchentoot cookie test"))
(:body
(:h2 (hunchentoot-link)
" cookie test")
(:p "You might have to reload this page to see the cookie value.")
(info-table (cookie-in "pumpkin")
(mapcar 'car (cookies-in*)))))))
(defun session-test ()
(let ((new-foo-value (post-parameter "new-foo-value")))
(when new-foo-value
(setf (session-value 'foo) new-foo-value)))
(let ((new-bar-value (post-parameter "new-bar-value")))
(when new-bar-value
(setf (session-value 'bar) new-bar-value)))
(no-cache)
(with-html
(:html
(:head (:title "Hunchentoot session test"))
(:body
(:h2 (hunchentoot-link)
" session test")
(:p "Use the forms below to set new values for "
(:code "FOO")
" or "
(:code "BAR")
". You can later return to this page to check if
they're still set. Also, try to use another browser at the same
time or try with cookies disabled.")
(:p (:form :method :post
"New value for "
(:code "FOO")
": "
(:input :type :text
:name "new-foo-value"
:value (or (session-value 'foo) ""))))
(:p (:form :method :post
"New value for "
(:code "BAR")
": "
(:input :type :text
:name "new-bar-value"
:value (or (session-value 'bar) ""))))
(info-table (session-cookie-name *acceptor*)
(cookie-in (session-cookie-name *acceptor*))
(mapcar 'car (cookies-in*))
(session-value 'foo)
(session-value 'bar))))))
(defun parameter-test (&key (method :get) (charset :iso-8859-1))
(no-cache)
(recompute-request-parameters :external-format
(flex:make-external-format charset :eol-style :lf))
(setf (content-type*)
(format nil "text/html; charset=~A" charset))
(with-html
(:html
(:head (:title (fmt "Hunchentoot ~A parameter test" method)))
(:body
(:h2 (hunchentoot-link)
(fmt " ~A parameter test with charset ~A" method charset))
(:p "Enter some non-ASCII characters in the input field below
and see what's happening.")
(:p (:form
:method method
"Enter a value: "
(:input :type :text
:name "foo")))
(case method
(:get (info-table (query-string*)
(map 'list 'char-code (get-parameter "foo"))
(get-parameter "foo")))
(:post (info-table (raw-post-data)
(map 'list 'char-code (post-parameter "foo"))
(post-parameter "foo"))))))))
(defun parameter-test-latin1-get ()
(parameter-test :method :get :charset :iso-8859-1))
(defun parameter-test-latin1-post ()
(parameter-test :method :post :charset :iso-8859-1))
(defun parameter-test-utf8-get ()
(parameter-test :method :get :charset :utf-8))
(defun parameter-test-utf8-post ()
(parameter-test :method :post :charset :utf-8))
;; this should not be the same directory as *TMP-DIRECTORY* and it
;; should be initially empty (or non-existent)
(defvar *tmp-test-directory*
#+(or :win32 :mswindows) #p"c:\\hunchentoot-temp\\test\\"
#-(or :win32 :mswindows) #p"/tmp/hunchentoot/test/")
(defvar *tmp-test-files* nil)
(let ((counter 0))
(defun handle-file (post-parameter)
(when (and post-parameter
(listp post-parameter))
(destructuring-bind (path file-name content-type)
post-parameter
(let ((new-path (make-pathname :name (format nil "hunchentoot-test-~A"
(incf counter))
:type nil
:defaults *tmp-test-directory*)))
strip directory info sent by Windows browsers
(when (search "Windows" (user-agent) :test 'char-equal)
(setq file-name (cl-ppcre:regex-replace ".*\\\\" file-name "")))
(rename-file path (ensure-directories-exist new-path))
(push (list new-path file-name content-type) *tmp-test-files*))))))
(defun clean-tmp-dir ()
(loop for (path . nil) in *tmp-test-files*
when (probe-file path)
do (ignore-errors (delete-file path)))
(setq *tmp-test-files* nil))
(defun upload-test ()
(let (post-parameter-p)
(when (post-parameter "file1")
(handle-file (post-parameter "file1"))
(setq post-parameter-p t))
(when (post-parameter "file2")
(handle-file (post-parameter "file2"))
(setq post-parameter-p t))
(when (post-parameter "clean")
(clean-tmp-dir)
(setq post-parameter-p t))
(when post-parameter-p
;; redirect so user can safely use 'Back' button
(redirect (script-name*))))
(no-cache)
(with-html
(:html
(:head (:title "Hunchentoot file upload test"))
(:body
(:h2 (hunchentoot-link)
" file upload test")
(:form :method :post :enctype "multipart/form-data"
(:p "First file: "
(:input :type :file
:name "file1"))
(:p "Second file: "
(:input :type :file
:name "file2"))
(:p (:input :type :submit)))
(when *tmp-test-files*
(htm
(:p
(:table :border 1 :cellpadding 2 :cellspacing 0
(:tr (:td :colspan 3 (:b "Uploaded files")))
(loop for (path file-name nil) in *tmp-test-files*
for counter from 1
do (htm
(:tr (:td :align "right" (str counter))
(:td (:a :href (format nil "files/~A?path=~A"
(url-encode file-name)
(url-encode (namestring path)))
(esc file-name)))
(:td :align "right"
(str (ignore-errors
(with-open-file (in path)
(file-length in))))
" Bytes"))))))
(:form :method :post
(:p (:input :type :submit :name "clean" :value "Delete uploaded files")))))
(menu-link)))))
(defun send-file ()
(let* ((path (get-parameter "path"))
(file-info (and path
(find (pathname path) *tmp-test-files*
:key 'first :test 'equal))))
(unless file-info
(setf (return-code*) +http-not-found+)
(return-from send-file))
(handle-static-file path (third file-info))))
(defparameter *headline*
(load-time-value
(format nil "Hunchentoot test menu (see file <code>~A</code>)"
(truename (merge-pathnames (make-pathname :type "lisp") *this-file*)))))
(defvar *utf-8* (flex:make-external-format :utf-8 :eol-style :lf))
(defvar *utf-8-file* (merge-pathnames "UTF-8-demo.html" *this-file*)
"Demo file stolen from <-8-test/>.")
(defun stream-direct ()
(setf (content-type*) "text/html; charset=utf-8")
(let ((stream (send-headers))
(buffer (make-array 1024 :element-type 'flex:octet)))
(with-open-file (in *utf-8-file* :element-type 'flex:octet)
(loop for pos = (read-sequence buffer in)
until (zerop pos)
do (write-sequence buffer stream :end pos)))))
(defun stream-direct-utf-8 ()
(setf (content-type*) "text/html; charset=utf-8")
(let ((stream (flex:make-flexi-stream (send-headers) :external-format *utf-8*)))
(with-open-file (in (merge-pathnames "UTF-8-demo.html" *this-file*)
:element-type 'flex:octet)
(setq in (flex:make-flexi-stream in :external-format *utf-8*))
(loop for line = (read-line in nil nil)
while line
do (write-line line stream)))))
(defun stream-direct-utf-8-string ()
(setf (content-type*) "text/html; charset=utf-8"
(reply-external-format*) *utf-8*)
(with-open-file (in (merge-pathnames "UTF-8-demo.html" *this-file*)
:element-type 'flex:octet)
(let ((string (make-array (file-length in)
:element-type #-:lispworks 'character #+:lispworks 'lw:simple-char
:fill-pointer t)))
(setf in (flex:make-flexi-stream in :external-format *utf-8*)
(fill-pointer string) (read-sequence string in))
string)))
(define-easy-handler (easy-demo :uri "/hunchentoot/test/easy-demo.html"
:default-request-type :post)
(first-name last-name
(age :parameter-type 'integer)
(implementation :parameter-type 'keyword)
(meal :parameter-type '(hash-table boolean))
(team :parameter-type 'list))
(with-html
(:html
(:head (:title "Hunchentoot \"easy\" handler example"))
(:body
(:h2 (hunchentoot-link)
" \"Easy\" handler example")
(:p (:form :method :post
(:table :border 1 :cellpadding 2 :cellspacing 0
(:tr
(:td "First Name:")
(:td (:input :type :text
:name "first-name"
:value (or first-name "Donald"))))
(:tr
(:td "Last name:")
(:td (:input :type :text
:name "last-name"
:value (or last-name "Duck"))))
(:tr
(:td "Age:")
(:td (:input :type :text
:name "age"
:value (or age 42))))
(:tr
(:td "Implementation:")
(:td (:select :name "implementation"
(loop for (value option) in '((:lispworks "LispWorks")
(:allegro "AllegroCL")
(:cmu "CMUCL")
(:sbcl "SBCL")
(:openmcl "OpenMCL"))
do (htm
(:option :value value
:selected (eq value implementation)
(str option)))))))
(:tr
(:td :valign :top "Meal:")
(:td (loop for choice in '("Burnt weeny sandwich"
"Canard du jour"
"Easy meat"
"Muffin"
"Twenty small cigars"
"Yellow snow")
do (htm
(:input :type "checkbox"
:name (format nil "meal{~A}" choice)
:checked (gethash choice meal)
(esc choice))
(:br)))))
(:tr
(:td :valign :top "Team:")
(:td (loop for player in '("Beckenbauer"
"Cruyff"
"Maradona"
without accent ( for SBCL )
"Pele"
"Zidane")
do (htm
(:input :type "checkbox"
:name "team"
:value player
:checked (member player team :test 'string=)
(esc player))
(:br)))))
(:tr
(:td :colspan 2
(:input :type "submit"))))))
(info-table first-name
last-name
age
implementation
(loop :for choice :being :the :hash-keys :of meal :collect choice)
(gethash "Yellow snow" meal)
team)))))
(defun menu ()
(with-html
(:html
(:head
(:link :rel "shortcut icon"
:href "/hunchentoot/test/favicon.ico" :type "image/x-icon")
(:title "Hunchentoot test menu"))
(:body
(:h2 (str *headline*))
(:table :border 0 :cellspacing 4 :cellpadding 4
(:tr (:td (:a :href "/hunchentoot/test/info.html?foo=bar"
"Info provided by Hunchentoot")))
(:tr (:td (:a :href "/hunchentoot/test/cookie.html"
"Cookie test")))
(:tr (:td (:a :href "/hunchentoot/test/session.html"
"Session test")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_latin1_get.html"
"GET parameter handling with LATIN-1 charset")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_latin1_post.html"
"POST parameter handling with LATIN-1 charset")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_utf8_get.html"
"GET parameter handling with UTF-8 charset")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_utf8_post.html"
"POST parameter handling with UTF-8 charset")))
(:tr (:td (:a :href "/hunchentoot/test/redir.html"
"Redirect \(302) to info page above")))
(:tr (:td (:a :href "/hunchentoot/test/authorization.html"
"Authorization")
" (user 'nanook', password 'igloo')"))
(:tr (:td (:a :href "/hunchentoot/code/test-handlers.lisp"
"The source code of this test")))
(:tr (:td (:a :href "/hunchentoot/test/image.jpg"
"Binary data, delivered from file")
" \(a picture)"))
(:tr (:td (:a :href "/hunchentoot/test/image-ram.jpg"
"Binary data, delivered from RAM")
" \(same picture)"))
(:tr (:td (:a :href "/hunchentoot/test/easy-demo.html"
"\"Easy\" handler example")))
(:tr (:td (:a :href "/hunchentoot/test/utf8-binary.txt"
"UTF-8 demo")
" \(writing octets directly to the stream)"))
(:tr (:td (:a :href "/hunchentoot/test/utf8-character.txt"
"UTF-8 demo")
" \(writing UTF-8 characters directly to the stream)"))
(:tr (:td (:a :href "/hunchentoot/test/utf8-string.txt"
"UTF-8 demo")
" \(returning a string)"))
(:tr (:td (:a :href "/hunchentoot/test/upload.html"
"File uploads")))
(:tr (:td (:a :href "/hunchentoot/test/forbidden.html"
"Forbidden \(403) page")))
(:tr (:td (:a :href "/hunchentoot/test/oops.html"
"Error handling")
" \(output depends on "
(:a :href "/#*show-lisp-errors-p*"
(:code "*SHOW-LISP-ERRORS-P*"))
(fmt " \(currently ~S))" *show-lisp-errors-p*)))
(:tr (:td (:a :href "/hunchentoot/foo"
"URI handled by")
" "
(:a :href "/#*default-handler*"
(:code "*DEFAULT-HANDLER*")))))))))
(setq *dispatch-table*
(nconc
(list 'dispatch-easy-handlers
(create-static-file-dispatcher-and-handler
"/hunchentoot/test/image.jpg"
(make-pathname :name "fz" :type "jpg" :version nil
:defaults *this-file*)
"image/jpeg")
(create-static-file-dispatcher-and-handler
"/hunchentoot/test/favicon.ico"
(make-pathname :name "favicon" :type "ico" :version nil
:defaults *this-file*))
(create-folder-dispatcher-and-handler
"/hunchentoot/code/"
(make-pathname :name nil :type nil :version nil
:defaults *this-file*)
"text/plain"))
(mapcar (lambda (args)
(apply 'create-prefix-dispatcher args))
'(("/hunchentoot/test/form-test.html" form-test)
("/hunchentoot/test/forbidden.html" forbidden)
("/hunchentoot/test/info.html" info)
("/hunchentoot/test/authorization.html" authorization-page)
("/hunchentoot/test/image-ram.jpg" image-ram-page)
("/hunchentoot/test/cookie.html" cookie-test)
("/hunchentoot/test/session.html" session-test)
("/hunchentoot/test/parameter_latin1_get.html" parameter-test-latin1-get)
("/hunchentoot/test/parameter_latin1_post.html" parameter-test-latin1-post)
("/hunchentoot/test/parameter_utf8_get.html" parameter-test-utf8-get)
("/hunchentoot/test/parameter_utf8_post.html" parameter-test-utf8-post)
("/hunchentoot/test/upload.html" upload-test)
("/hunchentoot/test/redir.html" redir)
("/hunchentoot/test/oops.html" oops)
("/hunchentoot/test/utf8-binary.txt" stream-direct)
("/hunchentoot/test/utf8-character.txt" stream-direct-utf-8)
("/hunchentoot/test/utf8-string.txt" stream-direct-utf-8-string)
("/hunchentoot/test/files/" send-file)
("/hunchentoot/test" menu)))
(list 'default-dispatcher)))
| null | https://raw.githubusercontent.com/gonzojive/hunchentoot/36e3a81655be0eeb8084efd853dd3ac3e5afc91b/test/test-handlers.lisp | lisp | Syntax : COMMON - LISP ; Package : HUNCHENTOOT ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
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 AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
this should not be the same directory as *TMP-DIRECTORY* and it
should be initially empty (or non-existent)
redirect so user can safely use 'Back' button | $ Header : /usr / local / cvsrep / hunchentoot / test / test.lisp , v 1.24 2008/03/06 07:46:53 edi Exp $
Copyright ( c ) 2004 - 2010 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :hunchentoot-test)
(defvar *this-file* (load-time-value
(or #.*compile-file-pathname* *load-pathname*)))
(defmacro with-html (&body body)
`(with-html-output-to-string (*standard-output* nil :prologue t)
,@body))
(defun hunchentoot-link ()
(with-html-output (*standard-output*)
(:a :href "/" "Hunchentoot")))
(defun menu-link ()
(with-html-output (*standard-output*)
(:p (:hr
(:a :href "/hunchentoot/test" "Back to menu")))))
(defmacro with-lisp-output ((var) &body body)
`(let ((*package* (find-package :hunchentoot-test-user)))
(with-output-to-string (,var #+:lispworks nil
#+:lispworks :element-type
#+:lispworks 'lw:simple-char)
,@body)))
(defmacro info-table (&rest forms)
(let ((=value= (gensym))
(=first= (gensym)))
`(with-html-output (*standard-output*)
(:p (:table :border 1 :cellpadding 2 :cellspacing 0
(:tr (:td :colspan 2
"Some Information "
(hunchentoot-link)
" provides about this request:"))
,@(loop for form in forms
collect `(:tr (:td :valign "top"
(:pre :style "padding: 0px"
(esc (with-lisp-output (s) (pprint ',form s)))))
(:td :valign "top"
(:pre :style "padding: 0px"
(esc (with-lisp-output (s)
(loop for ,=value= in (multiple-value-list ,form)
for ,=first= = t then nil
unless ,=first=
do (princ ", " s)
do (pprint ,=value= s))))))))))
(menu-link))))
(defun authorization-page ()
(multiple-value-bind (user password)
(authorization)
(cond ((and (equal user "nanook")
(equal password "igloo"))
(with-html
(:html
(:head (:title "Hunchentoot page with Basic Authentication"))
(:body
(:h2 (hunchentoot-link)
" page with Basic Authentication")
(info-table (header-in* :authorization)
(authorization))))))
(t
(require-authorization)))))
(defparameter *test-image*
(load-time-value
(with-open-file (in (make-pathname :name "fz" :type "jpg" :version nil
:defaults *this-file*)
:element-type 'flex:octet)
(let ((image-data (make-array (file-length in)
:element-type 'flex:octet)))
(read-sequence image-data in)
image-data))))
(defun image-ram-page ()
(setf (content-type*) "image/jpeg")
*test-image*)
(let ((count 0))
(defun info ()
(with-html
(:html
(:head (:title "Hunchentoot Information"))
(:body
(:h2 (hunchentoot-link) " Information Page")
(:p "This page has been called "
(:b
(fmt "~[~;once~;twice~:;~:*~R times~]" (incf count)))
" since its handler was compiled.")
(info-table (host)
(acceptor-address *acceptor*)
(acceptor-port *acceptor*)
(remote-addr*)
(remote-port*)
(real-remote-addr)
(request-method*)
(script-name*)
(query-string*)
(get-parameters*)
(headers-in*)
(cookies-in*)
(user-agent)
(referer)
(request-uri*)
(server-protocol*)))))))
(defun oops ()
(with-html
(log-message :error "Oops \(error log level).")
(log-message :warning "Oops \(warning log level).")
(log-message :info "Oops \(info log level).")
(error "Errors were triggered on purpose. Check your error log.")
(:html
(:body "You should never see this sentence..."))))
(defun redir ()
(redirect "/hunchentoot/test/info.html?redirected=1"))
(defun forbidden ()
(setf (return-code*) +http-forbidden+)
nil)
(defun cookie-test ()
(set-cookie "pumpkin" :value "barking")
(no-cache)
(with-html
(:html
(:head (:title "Hunchentoot cookie test"))
(:body
(:h2 (hunchentoot-link)
" cookie test")
(:p "You might have to reload this page to see the cookie value.")
(info-table (cookie-in "pumpkin")
(mapcar 'car (cookies-in*)))))))
(defun session-test ()
(let ((new-foo-value (post-parameter "new-foo-value")))
(when new-foo-value
(setf (session-value 'foo) new-foo-value)))
(let ((new-bar-value (post-parameter "new-bar-value")))
(when new-bar-value
(setf (session-value 'bar) new-bar-value)))
(no-cache)
(with-html
(:html
(:head (:title "Hunchentoot session test"))
(:body
(:h2 (hunchentoot-link)
" session test")
(:p "Use the forms below to set new values for "
(:code "FOO")
" or "
(:code "BAR")
". You can later return to this page to check if
they're still set. Also, try to use another browser at the same
time or try with cookies disabled.")
(:p (:form :method :post
"New value for "
(:code "FOO")
": "
(:input :type :text
:name "new-foo-value"
:value (or (session-value 'foo) ""))))
(:p (:form :method :post
"New value for "
(:code "BAR")
": "
(:input :type :text
:name "new-bar-value"
:value (or (session-value 'bar) ""))))
(info-table (session-cookie-name *acceptor*)
(cookie-in (session-cookie-name *acceptor*))
(mapcar 'car (cookies-in*))
(session-value 'foo)
(session-value 'bar))))))
(defun parameter-test (&key (method :get) (charset :iso-8859-1))
(no-cache)
(recompute-request-parameters :external-format
(flex:make-external-format charset :eol-style :lf))
(setf (content-type*)
(format nil "text/html; charset=~A" charset))
(with-html
(:html
(:head (:title (fmt "Hunchentoot ~A parameter test" method)))
(:body
(:h2 (hunchentoot-link)
(fmt " ~A parameter test with charset ~A" method charset))
(:p "Enter some non-ASCII characters in the input field below
and see what's happening.")
(:p (:form
:method method
"Enter a value: "
(:input :type :text
:name "foo")))
(case method
(:get (info-table (query-string*)
(map 'list 'char-code (get-parameter "foo"))
(get-parameter "foo")))
(:post (info-table (raw-post-data)
(map 'list 'char-code (post-parameter "foo"))
(post-parameter "foo"))))))))
(defun parameter-test-latin1-get ()
(parameter-test :method :get :charset :iso-8859-1))
(defun parameter-test-latin1-post ()
(parameter-test :method :post :charset :iso-8859-1))
(defun parameter-test-utf8-get ()
(parameter-test :method :get :charset :utf-8))
(defun parameter-test-utf8-post ()
(parameter-test :method :post :charset :utf-8))
(defvar *tmp-test-directory*
#+(or :win32 :mswindows) #p"c:\\hunchentoot-temp\\test\\"
#-(or :win32 :mswindows) #p"/tmp/hunchentoot/test/")
(defvar *tmp-test-files* nil)
(let ((counter 0))
(defun handle-file (post-parameter)
(when (and post-parameter
(listp post-parameter))
(destructuring-bind (path file-name content-type)
post-parameter
(let ((new-path (make-pathname :name (format nil "hunchentoot-test-~A"
(incf counter))
:type nil
:defaults *tmp-test-directory*)))
strip directory info sent by Windows browsers
(when (search "Windows" (user-agent) :test 'char-equal)
(setq file-name (cl-ppcre:regex-replace ".*\\\\" file-name "")))
(rename-file path (ensure-directories-exist new-path))
(push (list new-path file-name content-type) *tmp-test-files*))))))
(defun clean-tmp-dir ()
(loop for (path . nil) in *tmp-test-files*
when (probe-file path)
do (ignore-errors (delete-file path)))
(setq *tmp-test-files* nil))
(defun upload-test ()
(let (post-parameter-p)
(when (post-parameter "file1")
(handle-file (post-parameter "file1"))
(setq post-parameter-p t))
(when (post-parameter "file2")
(handle-file (post-parameter "file2"))
(setq post-parameter-p t))
(when (post-parameter "clean")
(clean-tmp-dir)
(setq post-parameter-p t))
(when post-parameter-p
(redirect (script-name*))))
(no-cache)
(with-html
(:html
(:head (:title "Hunchentoot file upload test"))
(:body
(:h2 (hunchentoot-link)
" file upload test")
(:form :method :post :enctype "multipart/form-data"
(:p "First file: "
(:input :type :file
:name "file1"))
(:p "Second file: "
(:input :type :file
:name "file2"))
(:p (:input :type :submit)))
(when *tmp-test-files*
(htm
(:p
(:table :border 1 :cellpadding 2 :cellspacing 0
(:tr (:td :colspan 3 (:b "Uploaded files")))
(loop for (path file-name nil) in *tmp-test-files*
for counter from 1
do (htm
(:tr (:td :align "right" (str counter))
(:td (:a :href (format nil "files/~A?path=~A"
(url-encode file-name)
(url-encode (namestring path)))
(esc file-name)))
(:td :align "right"
(str (ignore-errors
(with-open-file (in path)
(file-length in))))
" Bytes"))))))
(:form :method :post
(:p (:input :type :submit :name "clean" :value "Delete uploaded files")))))
(menu-link)))))
(defun send-file ()
(let* ((path (get-parameter "path"))
(file-info (and path
(find (pathname path) *tmp-test-files*
:key 'first :test 'equal))))
(unless file-info
(setf (return-code*) +http-not-found+)
(return-from send-file))
(handle-static-file path (third file-info))))
(defparameter *headline*
(load-time-value
(format nil "Hunchentoot test menu (see file <code>~A</code>)"
(truename (merge-pathnames (make-pathname :type "lisp") *this-file*)))))
(defvar *utf-8* (flex:make-external-format :utf-8 :eol-style :lf))
(defvar *utf-8-file* (merge-pathnames "UTF-8-demo.html" *this-file*)
"Demo file stolen from <-8-test/>.")
(defun stream-direct ()
(setf (content-type*) "text/html; charset=utf-8")
(let ((stream (send-headers))
(buffer (make-array 1024 :element-type 'flex:octet)))
(with-open-file (in *utf-8-file* :element-type 'flex:octet)
(loop for pos = (read-sequence buffer in)
until (zerop pos)
do (write-sequence buffer stream :end pos)))))
(defun stream-direct-utf-8 ()
(setf (content-type*) "text/html; charset=utf-8")
(let ((stream (flex:make-flexi-stream (send-headers) :external-format *utf-8*)))
(with-open-file (in (merge-pathnames "UTF-8-demo.html" *this-file*)
:element-type 'flex:octet)
(setq in (flex:make-flexi-stream in :external-format *utf-8*))
(loop for line = (read-line in nil nil)
while line
do (write-line line stream)))))
(defun stream-direct-utf-8-string ()
(setf (content-type*) "text/html; charset=utf-8"
(reply-external-format*) *utf-8*)
(with-open-file (in (merge-pathnames "UTF-8-demo.html" *this-file*)
:element-type 'flex:octet)
(let ((string (make-array (file-length in)
:element-type #-:lispworks 'character #+:lispworks 'lw:simple-char
:fill-pointer t)))
(setf in (flex:make-flexi-stream in :external-format *utf-8*)
(fill-pointer string) (read-sequence string in))
string)))
(define-easy-handler (easy-demo :uri "/hunchentoot/test/easy-demo.html"
:default-request-type :post)
(first-name last-name
(age :parameter-type 'integer)
(implementation :parameter-type 'keyword)
(meal :parameter-type '(hash-table boolean))
(team :parameter-type 'list))
(with-html
(:html
(:head (:title "Hunchentoot \"easy\" handler example"))
(:body
(:h2 (hunchentoot-link)
" \"Easy\" handler example")
(:p (:form :method :post
(:table :border 1 :cellpadding 2 :cellspacing 0
(:tr
(:td "First Name:")
(:td (:input :type :text
:name "first-name"
:value (or first-name "Donald"))))
(:tr
(:td "Last name:")
(:td (:input :type :text
:name "last-name"
:value (or last-name "Duck"))))
(:tr
(:td "Age:")
(:td (:input :type :text
:name "age"
:value (or age 42))))
(:tr
(:td "Implementation:")
(:td (:select :name "implementation"
(loop for (value option) in '((:lispworks "LispWorks")
(:allegro "AllegroCL")
(:cmu "CMUCL")
(:sbcl "SBCL")
(:openmcl "OpenMCL"))
do (htm
(:option :value value
:selected (eq value implementation)
(str option)))))))
(:tr
(:td :valign :top "Meal:")
(:td (loop for choice in '("Burnt weeny sandwich"
"Canard du jour"
"Easy meat"
"Muffin"
"Twenty small cigars"
"Yellow snow")
do (htm
(:input :type "checkbox"
:name (format nil "meal{~A}" choice)
:checked (gethash choice meal)
(esc choice))
(:br)))))
(:tr
(:td :valign :top "Team:")
(:td (loop for player in '("Beckenbauer"
"Cruyff"
"Maradona"
without accent ( for SBCL )
"Pele"
"Zidane")
do (htm
(:input :type "checkbox"
:name "team"
:value player
:checked (member player team :test 'string=)
(esc player))
(:br)))))
(:tr
(:td :colspan 2
(:input :type "submit"))))))
(info-table first-name
last-name
age
implementation
(loop :for choice :being :the :hash-keys :of meal :collect choice)
(gethash "Yellow snow" meal)
team)))))
(defun menu ()
(with-html
(:html
(:head
(:link :rel "shortcut icon"
:href "/hunchentoot/test/favicon.ico" :type "image/x-icon")
(:title "Hunchentoot test menu"))
(:body
(:h2 (str *headline*))
(:table :border 0 :cellspacing 4 :cellpadding 4
(:tr (:td (:a :href "/hunchentoot/test/info.html?foo=bar"
"Info provided by Hunchentoot")))
(:tr (:td (:a :href "/hunchentoot/test/cookie.html"
"Cookie test")))
(:tr (:td (:a :href "/hunchentoot/test/session.html"
"Session test")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_latin1_get.html"
"GET parameter handling with LATIN-1 charset")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_latin1_post.html"
"POST parameter handling with LATIN-1 charset")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_utf8_get.html"
"GET parameter handling with UTF-8 charset")))
(:tr (:td (:a :href "/hunchentoot/test/parameter_utf8_post.html"
"POST parameter handling with UTF-8 charset")))
(:tr (:td (:a :href "/hunchentoot/test/redir.html"
"Redirect \(302) to info page above")))
(:tr (:td (:a :href "/hunchentoot/test/authorization.html"
"Authorization")
" (user 'nanook', password 'igloo')"))
(:tr (:td (:a :href "/hunchentoot/code/test-handlers.lisp"
"The source code of this test")))
(:tr (:td (:a :href "/hunchentoot/test/image.jpg"
"Binary data, delivered from file")
" \(a picture)"))
(:tr (:td (:a :href "/hunchentoot/test/image-ram.jpg"
"Binary data, delivered from RAM")
" \(same picture)"))
(:tr (:td (:a :href "/hunchentoot/test/easy-demo.html"
"\"Easy\" handler example")))
(:tr (:td (:a :href "/hunchentoot/test/utf8-binary.txt"
"UTF-8 demo")
" \(writing octets directly to the stream)"))
(:tr (:td (:a :href "/hunchentoot/test/utf8-character.txt"
"UTF-8 demo")
" \(writing UTF-8 characters directly to the stream)"))
(:tr (:td (:a :href "/hunchentoot/test/utf8-string.txt"
"UTF-8 demo")
" \(returning a string)"))
(:tr (:td (:a :href "/hunchentoot/test/upload.html"
"File uploads")))
(:tr (:td (:a :href "/hunchentoot/test/forbidden.html"
"Forbidden \(403) page")))
(:tr (:td (:a :href "/hunchentoot/test/oops.html"
"Error handling")
" \(output depends on "
(:a :href "/#*show-lisp-errors-p*"
(:code "*SHOW-LISP-ERRORS-P*"))
(fmt " \(currently ~S))" *show-lisp-errors-p*)))
(:tr (:td (:a :href "/hunchentoot/foo"
"URI handled by")
" "
(:a :href "/#*default-handler*"
(:code "*DEFAULT-HANDLER*")))))))))
(setq *dispatch-table*
(nconc
(list 'dispatch-easy-handlers
(create-static-file-dispatcher-and-handler
"/hunchentoot/test/image.jpg"
(make-pathname :name "fz" :type "jpg" :version nil
:defaults *this-file*)
"image/jpeg")
(create-static-file-dispatcher-and-handler
"/hunchentoot/test/favicon.ico"
(make-pathname :name "favicon" :type "ico" :version nil
:defaults *this-file*))
(create-folder-dispatcher-and-handler
"/hunchentoot/code/"
(make-pathname :name nil :type nil :version nil
:defaults *this-file*)
"text/plain"))
(mapcar (lambda (args)
(apply 'create-prefix-dispatcher args))
'(("/hunchentoot/test/form-test.html" form-test)
("/hunchentoot/test/forbidden.html" forbidden)
("/hunchentoot/test/info.html" info)
("/hunchentoot/test/authorization.html" authorization-page)
("/hunchentoot/test/image-ram.jpg" image-ram-page)
("/hunchentoot/test/cookie.html" cookie-test)
("/hunchentoot/test/session.html" session-test)
("/hunchentoot/test/parameter_latin1_get.html" parameter-test-latin1-get)
("/hunchentoot/test/parameter_latin1_post.html" parameter-test-latin1-post)
("/hunchentoot/test/parameter_utf8_get.html" parameter-test-utf8-get)
("/hunchentoot/test/parameter_utf8_post.html" parameter-test-utf8-post)
("/hunchentoot/test/upload.html" upload-test)
("/hunchentoot/test/redir.html" redir)
("/hunchentoot/test/oops.html" oops)
("/hunchentoot/test/utf8-binary.txt" stream-direct)
("/hunchentoot/test/utf8-character.txt" stream-direct-utf-8)
("/hunchentoot/test/utf8-string.txt" stream-direct-utf-8-string)
("/hunchentoot/test/files/" send-file)
("/hunchentoot/test" menu)))
(list 'default-dispatcher)))
|
76da48e969c7884ca2c049b5f337541a8443caa4e645313c848efe9c6c4ba6cd | Elzair/nazghul | ancient-derelict.scm | (kern-mk-map
'm_ancient_derelict 19 19 pal_expanded
(list
"^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ "
"^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ "
"^^ ^^ {{ {{ {{ {{ ^^ ^^ ^^ ^^ ^^ ^^ ^^ {{ {{ {{ {{ ^^ ^^ "
"^^ {{ {{ bb {{ {{ {{ {{ ^^ ^^ ^^ ^^ {{ {{ {3 {5 {{ {{ ^^ "
"{{ {{ {{ {{ {{ {{ {{ {{ ^^ ^^ ^^ ^^ {{ {3 #A bb {5 {{ ^^ "
"{{ {{ {{ {3 {1 {5 {{ {{ {{ ^^ ^^ ^^ {{ {2 ee .. {4 {{ ^^ "
"{{ {{ {3 .. .. #A #r #E {{ ^^ ^^ #A {{ {2 .. ee #C {{ ^^ "
"{1 {1 .. .. .. .. ee ee {{ {{ ^^ {{ {3 .. .. {4 {{ ^^ ^^ "
".. .. #E .. ee ee ee ee ee {{ {{ {{ ee ee .. #C ^^ ^^ ^^ "
".. .. bb ee ee ee ee ee ee ee {1 ee ee ee ee #F {1 {5 ^^ "
".. .. #B .. ee ee ee ee ee ee ee ee ee ee .. ee #C .. {1 "
".. .. .. .. .. ee ee ee ee ee ee .. .. #D #r .. #C .. .. "
"{8 {8 bb .. #D #r #G #H #D .. #r #r .. .. .. .. .. bb .. "
"{{ {{ {a .. .. .. .. .. .. bb .. .. .. .. .. .. .. .. .. "
"{{ {{ {{ {a {8 {8 .. .. .. .. .. .. .. {8 {8 {8 bb .. .. "
"^^ {{ bb {{ {{ {{ {a {8 .. .. .. .. {c {{ {{ {{ {{ {a {8 "
"^^ ^^ {{ {{ {{ {{ {{ {{ {2 .. .. {c {{ {{ {{ {{ {{ {{ {{ "
"^^ ^^ ^^ {{ ^^ ^^ ^^ {{ {2 .. {4 {{ ^^ ^^ ^^ {{ {{ {{ {{ "
"^^ ^^ ^^ ^^ ^^ ^^ ^^ {{ {2 .. {4 {{ ^^ ^^ ^^ ^^ ^^ {{ {{ "
)
)
;;----------------------------------------------------------------------------
;; Place
;;----------------------------------------------------------------------------
(kern-mk-place
'p_ancient_derelict ; tag
"Ancient Derelict" ; name
s_void_ship ; sprite
m_ancient_derelict ; map
#f ; wraps
#f ; underground
#f ; large-scale (wilderness)
#f ; tmp combat place
nil ; subplaces
;; neighbors
(list
)
;; objects
(list
(put (mk-monman) 0 0)
(put (spawn-pt 'wisp) 7 9)
(put (spawn-pt 'wisp) 10 9)
(put (kern-mk-obj t_power_core 1) 12 5)
(put (mk-corpse2
'(
(1 t_staff)
(1 t_vas_rel_por_scroll)
)) 9 10)
)
(list 'on-entry-to-dungeon-room) ; hooks
(list ; edge entrances
(list southeast 0 4)
(list northeast 0 14)
)
)
(mk-place-music p_ancient_derelict 'ml-outdoor-adventure)
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/ancient-derelict.scm | scheme | ----------------------------------------------------------------------------
Place
----------------------------------------------------------------------------
tag
name
sprite
map
wraps
underground
large-scale (wilderness)
tmp combat place
subplaces
neighbors
objects
hooks
edge entrances | (kern-mk-map
'm_ancient_derelict 19 19 pal_expanded
(list
"^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ "
"^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ "
"^^ ^^ {{ {{ {{ {{ ^^ ^^ ^^ ^^ ^^ ^^ ^^ {{ {{ {{ {{ ^^ ^^ "
"^^ {{ {{ bb {{ {{ {{ {{ ^^ ^^ ^^ ^^ {{ {{ {3 {5 {{ {{ ^^ "
"{{ {{ {{ {{ {{ {{ {{ {{ ^^ ^^ ^^ ^^ {{ {3 #A bb {5 {{ ^^ "
"{{ {{ {{ {3 {1 {5 {{ {{ {{ ^^ ^^ ^^ {{ {2 ee .. {4 {{ ^^ "
"{{ {{ {3 .. .. #A #r #E {{ ^^ ^^ #A {{ {2 .. ee #C {{ ^^ "
"{1 {1 .. .. .. .. ee ee {{ {{ ^^ {{ {3 .. .. {4 {{ ^^ ^^ "
".. .. #E .. ee ee ee ee ee {{ {{ {{ ee ee .. #C ^^ ^^ ^^ "
".. .. bb ee ee ee ee ee ee ee {1 ee ee ee ee #F {1 {5 ^^ "
".. .. #B .. ee ee ee ee ee ee ee ee ee ee .. ee #C .. {1 "
".. .. .. .. .. ee ee ee ee ee ee .. .. #D #r .. #C .. .. "
"{8 {8 bb .. #D #r #G #H #D .. #r #r .. .. .. .. .. bb .. "
"{{ {{ {a .. .. .. .. .. .. bb .. .. .. .. .. .. .. .. .. "
"{{ {{ {{ {a {8 {8 .. .. .. .. .. .. .. {8 {8 {8 bb .. .. "
"^^ {{ bb {{ {{ {{ {a {8 .. .. .. .. {c {{ {{ {{ {{ {a {8 "
"^^ ^^ {{ {{ {{ {{ {{ {{ {2 .. .. {c {{ {{ {{ {{ {{ {{ {{ "
"^^ ^^ ^^ {{ ^^ ^^ ^^ {{ {2 .. {4 {{ ^^ ^^ ^^ {{ {{ {{ {{ "
"^^ ^^ ^^ ^^ ^^ ^^ ^^ {{ {2 .. {4 {{ ^^ ^^ ^^ ^^ ^^ {{ {{ "
)
)
(kern-mk-place
(list
)
(list
(put (mk-monman) 0 0)
(put (spawn-pt 'wisp) 7 9)
(put (spawn-pt 'wisp) 10 9)
(put (kern-mk-obj t_power_core 1) 12 5)
(put (mk-corpse2
'(
(1 t_staff)
(1 t_vas_rel_por_scroll)
)) 9 10)
)
(list southeast 0 4)
(list northeast 0 14)
)
)
(mk-place-music p_ancient_derelict 'ml-outdoor-adventure)
|
5afada644ce4bfa8dd4bb04a10258173b9eff24830e1af5618cd4ebd4e178457 | clckwrks/clckwrks | OpenIdRealm.hs | # LANGUAGE TypeFamilies , QuasiQuotes , OverloadedStrings #
module Clckwrks.Authenticate.Page.OpenIdRealm where
import Clckwrks.Admin.Template (template)
import Clckwrks.Monad
import Clckwrks.URL (ClckURL)
import Happstack.Server (Response, ServerPartT, ok, toResponse)
import Language.Haskell.HSX.QQ (hsx)
openIdRealmPanel :: ClckT ClckURL (ServerPartT IO) Response
openIdRealmPanel =
do template "Set OpenId Realm" () $ [hsx|
<div ng-controller="OpenIdCtrl">
<openid-realm />
</div> |]
| null | https://raw.githubusercontent.com/clckwrks/clckwrks/dd4ea1e2f41066aa5779f1cc22f3b7a0ca8a0bed/Clckwrks/Authenticate/Page/OpenIdRealm.hs | haskell | # LANGUAGE TypeFamilies , QuasiQuotes , OverloadedStrings #
module Clckwrks.Authenticate.Page.OpenIdRealm where
import Clckwrks.Admin.Template (template)
import Clckwrks.Monad
import Clckwrks.URL (ClckURL)
import Happstack.Server (Response, ServerPartT, ok, toResponse)
import Language.Haskell.HSX.QQ (hsx)
openIdRealmPanel :: ClckT ClckURL (ServerPartT IO) Response
openIdRealmPanel =
do template "Set OpenId Realm" () $ [hsx|
<div ng-controller="OpenIdCtrl">
<openid-realm />
</div> |]
|
|
02e266bcc064bb1e6dac056c9555e1c52eff2a5220e606ed4f67cab250688f81 | clojure-interop/google-cloud-clients | VideoIntelligenceServiceStubSettings.clj | (ns com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings
"Settings class to configure an instance of VideoIntelligenceServiceStub.
The default instance has everything set to sensible defaults:
The default service address (videointelligence.googleapis.com) and default port (443) are
used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of annotateVideoAsync to 30 seconds:
VideoIntelligenceServiceStubSettings.Builder videoIntelligenceServiceSettingsBuilder =
VideoIntelligenceServiceStubSettings.newBuilder();
videoIntelligenceServiceSettingsBuilder.annotateVideoSettings().getRetrySettings().toBuilder()
.setTotalTimeout(Duration.ofSeconds(30));
VideoIntelligenceServiceStubSettings videoIntelligenceServiceSettings = videoIntelligenceServiceSettingsBuilder.build();"
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.videointelligence.v1beta1.stub VideoIntelligenceServiceStubSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(VideoIntelligenceServiceStubSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(VideoIntelligenceServiceStubSettings/getDefaultEndpoint )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(VideoIntelligenceServiceStubSettings/getDefaultServiceScopes )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(VideoIntelligenceServiceStubSettings/defaultCredentialsProviderBuilder )))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(VideoIntelligenceServiceStubSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(VideoIntelligenceServiceStubSettings/defaultTransportChannelProvider )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(VideoIntelligenceServiceStubSettings/defaultApiClientHeaderProviderBuilder )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder`"
(^com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(VideoIntelligenceServiceStubSettings/newBuilder client-context))
(^com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder []
(VideoIntelligenceServiceStubSettings/newBuilder )))
(defn annotate-video-settings
"Returns the object with the settings used for calls to annotateVideo.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.videointelligence.v1beta1.AnnotateVideoRequest,com.google.longrunning.Operation>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^VideoIntelligenceServiceStubSettings this]
(-> this (.annotateVideoSettings))))
(defn annotate-video-operation-settings
"Returns the object with the settings used for calls to annotateVideo.
returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallSettings<com.google.cloud.videointelligence.v1beta1.AnnotateVideoRequest,com.google.cloud.videointelligence.v1beta1.AnnotateVideoResponse,com.google.cloud.videointelligence.v1beta1.AnnotateVideoProgress>`"
([^VideoIntelligenceServiceStubSettings this]
(-> this (.annotateVideoOperationSettings))))
(defn create-stub
"returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStub`
throws: java.io.IOException"
([^VideoIntelligenceServiceStubSettings this]
(-> this (.createStub))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder`"
(^com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder [^VideoIntelligenceServiceStubSettings this]
(-> this (.toBuilder))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.videointelligence/src/com/google/cloud/videointelligence/v1beta1/stub/VideoIntelligenceServiceStubSettings.clj | clojure |
" | (ns com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings
"Settings class to configure an instance of VideoIntelligenceServiceStub.
The default instance has everything set to sensible defaults:
The default service address (videointelligence.googleapis.com) and default port (443) are
used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of annotateVideoAsync to 30 seconds:
VideoIntelligenceServiceStubSettings.Builder videoIntelligenceServiceSettingsBuilder =
videoIntelligenceServiceSettingsBuilder.annotateVideoSettings().getRetrySettings().toBuilder()
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.videointelligence.v1beta1.stub VideoIntelligenceServiceStubSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(VideoIntelligenceServiceStubSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(VideoIntelligenceServiceStubSettings/getDefaultEndpoint )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(VideoIntelligenceServiceStubSettings/getDefaultServiceScopes )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(VideoIntelligenceServiceStubSettings/defaultCredentialsProviderBuilder )))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(VideoIntelligenceServiceStubSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(VideoIntelligenceServiceStubSettings/defaultTransportChannelProvider )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(VideoIntelligenceServiceStubSettings/defaultApiClientHeaderProviderBuilder )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder`"
(^com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(VideoIntelligenceServiceStubSettings/newBuilder client-context))
(^com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder []
(VideoIntelligenceServiceStubSettings/newBuilder )))
(defn annotate-video-settings
"Returns the object with the settings used for calls to annotateVideo.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.videointelligence.v1beta1.AnnotateVideoRequest,com.google.longrunning.Operation>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^VideoIntelligenceServiceStubSettings this]
(-> this (.annotateVideoSettings))))
(defn annotate-video-operation-settings
"Returns the object with the settings used for calls to annotateVideo.
returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallSettings<com.google.cloud.videointelligence.v1beta1.AnnotateVideoRequest,com.google.cloud.videointelligence.v1beta1.AnnotateVideoResponse,com.google.cloud.videointelligence.v1beta1.AnnotateVideoProgress>`"
([^VideoIntelligenceServiceStubSettings this]
(-> this (.annotateVideoOperationSettings))))
(defn create-stub
"returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStub`
throws: java.io.IOException"
([^VideoIntelligenceServiceStubSettings this]
(-> this (.createStub))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder`"
(^com.google.cloud.videointelligence.v1beta1.stub.VideoIntelligenceServiceStubSettings$Builder [^VideoIntelligenceServiceStubSettings this]
(-> this (.toBuilder))))
|
9d649fa83a3ab9d6d5431a4d3406ec8d74fa0ba6fb1dd576ed562d4e6c35f1df | erszcz/pa | pa_SUITE.erl | -module(pa_SUITE).
-compile([export_all]).
-include_lib("common_test/include/ct.hrl").
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(eq(Expected, Actual), ?assertEqual(Expected, Actual)).
all() ->
[bind,
invalid_bind].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
Config.
end_per_testcase(_TestCase, _Config) ->
ok.
%%
%% Tests
%%
%% Partial application whose result is an N-ary function.
bind(Config) ->
property(bind, ?FORALL({{Arity, Fun}, Args}, fun_args(),
is_applied_properly(Arity, Fun, Args))).
%% Error when the input function arity or number of args make it impossible
%% to get an N-ary function.
invalid_bind(Config) ->
property(invalid_bind, ?FORALL({{_, Fun}, Args}, invalid_fun_args(),
is_not_applied(Fun, Args))).
%%
%% Generators
%%
-define(MAX_FUN_ARITY, 10).
Partially applying Fun to should give a fun of arity N.
fun_args() ->
?SUCHTHAT({{Arity, _Fun}, Args}, {function(), args()},
Arity - length(Args) >= 0).
invalid_fun_args() ->
?SUCHTHAT({{Arity, _Fun}, Args}, {function(), args()},
Arity - length(Args) < 0).
function() ->
?LET(Arity, fun_arity(), function(Arity)).
fun_arity() -> integer(0, ?MAX_FUN_ARITY).
function(0) -> {0, fun () -> 0 end};
function(1) -> {1, fun (_) -> 1 end};
function(2) -> {2, fun (_,_) -> 2 end};
function(3) -> {3, fun (_,_,_) -> 3 end};
function(4) -> {4, fun (_,_,_,_) -> 4 end};
function(5) -> {5, fun (_,_,_,_,_) -> 5 end};
function(6) -> {6, fun (_,_,_,_,_,_) -> 6 end};
function(7) -> {7, fun (_,_,_,_,_,_,_) -> 7 end};
function(8) -> {8, fun (_,_,_,_,_,_,_,_) -> 8 end};
function(9) -> {9, fun (_,_,_,_,_,_,_,_,_) -> 9 end};
function(10) -> {10, fun (_,_,_,_,_,_,_,_,_,_) -> 10 end}.
args() ->
?LET(Arity, fun_arity(), lists:seq(1, Arity)).
%%
%% Helpers
%%
property(Name, Prop) ->
Props = proper:conjunction([{Name, Prop}]),
?assert(proper:quickcheck(Props, [verbose, long_result,
{numtests, 100},
{constraint_tries, 200}])).
is_not_applied(Fun, Args) ->
try
apply(pa, bind, [Fun|Args]),
false
catch error:badarg ->
true
end.
is_applied_properly(Arity, Fun, Args) ->
Result = apply(pa, bind, [Fun|Args]),
RemainingArity = Arity - length(Args),
RemainingArgs = lists:seq(length(Args)+1, Arity),
is_function(Result, RemainingArity) andalso
apply(Result, RemainingArgs) =:= Arity.
| null | https://raw.githubusercontent.com/erszcz/pa/84b73c33bc9c95b64ef99cead65278f3a91bc635/test/pa_SUITE.erl | erlang |
Tests
Partial application whose result is an N-ary function.
Error when the input function arity or number of args make it impossible
to get an N-ary function.
Generators
Helpers
| -module(pa_SUITE).
-compile([export_all]).
-include_lib("common_test/include/ct.hrl").
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(eq(Expected, Actual), ?assertEqual(Expected, Actual)).
all() ->
[bind,
invalid_bind].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
Config.
end_per_testcase(_TestCase, _Config) ->
ok.
bind(Config) ->
property(bind, ?FORALL({{Arity, Fun}, Args}, fun_args(),
is_applied_properly(Arity, Fun, Args))).
invalid_bind(Config) ->
property(invalid_bind, ?FORALL({{_, Fun}, Args}, invalid_fun_args(),
is_not_applied(Fun, Args))).
-define(MAX_FUN_ARITY, 10).
Partially applying Fun to should give a fun of arity N.
fun_args() ->
?SUCHTHAT({{Arity, _Fun}, Args}, {function(), args()},
Arity - length(Args) >= 0).
invalid_fun_args() ->
?SUCHTHAT({{Arity, _Fun}, Args}, {function(), args()},
Arity - length(Args) < 0).
function() ->
?LET(Arity, fun_arity(), function(Arity)).
fun_arity() -> integer(0, ?MAX_FUN_ARITY).
function(0) -> {0, fun () -> 0 end};
function(1) -> {1, fun (_) -> 1 end};
function(2) -> {2, fun (_,_) -> 2 end};
function(3) -> {3, fun (_,_,_) -> 3 end};
function(4) -> {4, fun (_,_,_,_) -> 4 end};
function(5) -> {5, fun (_,_,_,_,_) -> 5 end};
function(6) -> {6, fun (_,_,_,_,_,_) -> 6 end};
function(7) -> {7, fun (_,_,_,_,_,_,_) -> 7 end};
function(8) -> {8, fun (_,_,_,_,_,_,_,_) -> 8 end};
function(9) -> {9, fun (_,_,_,_,_,_,_,_,_) -> 9 end};
function(10) -> {10, fun (_,_,_,_,_,_,_,_,_,_) -> 10 end}.
args() ->
?LET(Arity, fun_arity(), lists:seq(1, Arity)).
property(Name, Prop) ->
Props = proper:conjunction([{Name, Prop}]),
?assert(proper:quickcheck(Props, [verbose, long_result,
{numtests, 100},
{constraint_tries, 200}])).
is_not_applied(Fun, Args) ->
try
apply(pa, bind, [Fun|Args]),
false
catch error:badarg ->
true
end.
is_applied_properly(Arity, Fun, Args) ->
Result = apply(pa, bind, [Fun|Args]),
RemainingArity = Arity - length(Args),
RemainingArgs = lists:seq(length(Args)+1, Arity),
is_function(Result, RemainingArity) andalso
apply(Result, RemainingArgs) =:= Arity.
|
28f7b36992669c6841f990d6a4c351a2f60fac5a608f456c82c44e5ec26873bf | igorhvr/bedlam | k-store.scm | 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 SISCweb .
;;;
The Initial Developer of the Original Code is .
Portions created by the Initial Developer are Copyright ( C ) 2005 - 2006
. All Rights Reserved .
;;;
;;; Contributor(s):
;;;
;;; Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later ( the " GPL " ) , or
the GNU Lesser General Public License Version 2.1 or later ( the " LGPL " ) ,
;;; in which case the provisions of the GPL or the LGPL are applicable instead
;;; of those above. If you wish to allow use of your version of this file only
;;; under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL , indicate your
;;; decision by deleting the provisions above and replace them with the notice
;;; and other provisions required by the GPL or the LGPL. If you do not delete
;;; the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL , the GPL or the LGPL .
(require-library 'siscweb/context)
(require-library 'siscweb/frame)
(require-library 'util/misc)
(module siscweb/k-store
(ks/clear! ks/get ks/put! ks/get-frame)
(import s2j)
(import siscweb/context)
(import siscweb/frame)
(import util/misc)
(define-java-classes
(<continuation-store-locator> |siscweb.contcentric.ContinuationStoreLocator|))
(define-generic-java-methods
clear fetch get-frame get-servlet-context lookup store)
(define get-k-store
(let ((k-store #f))
(lambda (session)
(when (not k-store)
(set! k-store (lookup (java-null <continuation-store-locator>)
(get-servlet-context session))))
k-store)))
;; stores the given continuation and
;; returns a k-url made of the current
;; request url with the k-id added/substituted
(define (ks/put! session k-hash g-hash k ttl current-k-hash)
(store (get-k-store session) session (->jstring g-hash) (->jstring k-hash) (java-wrap k) (->jlong ttl) (current-frame)))
;; fetches the continuation identified by k-hash from the repository
;; in the session
(define (ks/get session k-hash)
(and k-hash
(let ((k-wrap (fetch (get-k-store session) session (->jstring k-hash))))
(if (java-null? k-wrap)
#f
(java-unwrap k-wrap)))))
;; clears the continuation table
(define (ks/clear! session)
(clear (get-k-store session) session))
(define (ks/get-frame session k-hash)
(get-frame (get-k-store session) session (->jstring k-hash)))
)
| null | https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/siscweb/siscweb-src-0.5/scm/siscweb/k-store.scm | scheme | you may not use this file except in compliance with
the License. You may obtain a copy of the License at
/
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
stores the given continuation and
returns a k-url made of the current
request url with the k-id added/substituted
fetches the continuation identified by k-hash from the repository
in the session
clears the continuation table | The contents of this file are subject to the Mozilla Public License Version
Software distributed under the License is distributed on an " AS IS " basis ,
The Original Code is SISCweb .
The Initial Developer of the Original Code is .
Portions created by the Initial Developer are Copyright ( C ) 2005 - 2006
. All Rights Reserved .
either the GNU General Public License Version 2 or later ( the " GPL " ) , or
the GNU Lesser General Public License Version 2.1 or later ( the " LGPL " ) ,
use your version of this file under the terms of the MPL , indicate your
the terms of any one of the MPL , the GPL or the LGPL .
(require-library 'siscweb/context)
(require-library 'siscweb/frame)
(require-library 'util/misc)
(module siscweb/k-store
(ks/clear! ks/get ks/put! ks/get-frame)
(import s2j)
(import siscweb/context)
(import siscweb/frame)
(import util/misc)
(define-java-classes
(<continuation-store-locator> |siscweb.contcentric.ContinuationStoreLocator|))
(define-generic-java-methods
clear fetch get-frame get-servlet-context lookup store)
(define get-k-store
(let ((k-store #f))
(lambda (session)
(when (not k-store)
(set! k-store (lookup (java-null <continuation-store-locator>)
(get-servlet-context session))))
k-store)))
(define (ks/put! session k-hash g-hash k ttl current-k-hash)
(store (get-k-store session) session (->jstring g-hash) (->jstring k-hash) (java-wrap k) (->jlong ttl) (current-frame)))
(define (ks/get session k-hash)
(and k-hash
(let ((k-wrap (fetch (get-k-store session) session (->jstring k-hash))))
(if (java-null? k-wrap)
#f
(java-unwrap k-wrap)))))
(define (ks/clear! session)
(clear (get-k-store session) session))
(define (ks/get-frame session k-hash)
(get-frame (get-k-store session) session (->jstring k-hash)))
)
|
e4a6135e2922acab2e9f6ae3f53e2a02d6c73d3ca57b1111f8f508eeaf6a26d8 | GaloisInc/cryptol | Fin.hs | -- |
Module : Cryptol . . Solver . Numeric . Fin
Copyright : ( c ) 2015 - 2016 Galois , Inc.
-- License : BSD3
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Simplification of `fin` constraints.
# LANGUAGE PatternGuards #
module Cryptol.TypeCheck.Solver.Numeric.Fin where
import qualified Data.Map as Map
import Cryptol.TypeCheck.Type
import Cryptol.TypeCheck.Solver.Types
import Cryptol.TypeCheck.Solver.Numeric.Interval
import Cryptol.TypeCheck.Solver.InfNat
cryIsFin :: Ctxt -> Prop -> Solved
cryIsFin ctxt p =
case pIsFin p of
Just ty -> cryIsFinType ctxt ty
Nothing -> Unsolved
cryIsFinType :: Ctxt -> Type -> Solved
cryIsFinType ctxt ty =
let varInfo = intervals ctxt in
case tNoUser ty of
TVar x | Just i <- Map.lookup x varInfo
, iIsFin i -> SolvedIf []
TCon (TC tc) []
| TCNum _ <- tc -> SolvedIf []
| TCInf <- tc -> Unsolvable
TCon (TF f) ts ->
case (f,ts) of
(TCAdd,[t1,t2]) -> SolvedIf [ pFin t1, pFin t2 ]
(TCSub,[t1,_ ]) -> SolvedIf [ pFin t1 ]
-- fin (x * y)
(TCMul,[t1,t2])
| iLower i1 >= Nat 1 && iIsFin i1 -> SolvedIf [ pFin t2 ]
| iLower i2 >= Nat 1 && iIsFin i2 -> SolvedIf [ pFin t1 ]
| iLower i1 >= Nat 1 &&
iLower i2 >= Nat 1 -> SolvedIf [ pFin t1, pFin t2 ]
| iIsFin i1 && iIsFin i2 -> SolvedIf []
where
i1 = typeInterval varInfo t1
i2 = typeInterval varInfo t2
(TCDiv, [_,_]) -> SolvedIf []
(TCMod, [_,_]) -> SolvedIf []
-- fin (x ^ y)
(TCExp, [t1,t2])
| iLower i1 == Inf -> SolvedIf [ t2 =#= tZero ]
| iLower i2 == Inf -> SolvedIf [ tOne >== t1 ]
| iLower i1 >= Nat 2 -> SolvedIf [ pFin t1, pFin t2 ]
| iLower i2 >= Nat 1 -> SolvedIf [ pFin t1, pFin t2 ]
| Just x <- iUpper i1, x <= Nat 1 -> SolvedIf []
| Just (Nat 0) <- iUpper i2 -> SolvedIf []
where
i1 = typeInterval varInfo t1
i2 = typeInterval varInfo t2
-- fin (min x y)
(TCMin, [t1,t2])
| iIsFin i1 -> SolvedIf []
| iIsFin i2 -> SolvedIf []
| Just x <- iUpper i1, x <= iLower i2 -> SolvedIf [ pFin t1 ]
| Just x <- iUpper i2, x <= iLower i1 -> SolvedIf [ pFin t2 ]
where
i1 = typeInterval varInfo t1
i2 = typeInterval varInfo t2
(TCMax, [t1,t2]) -> SolvedIf [ pFin t1, pFin t2 ]
(TCWidth, [t1]) -> SolvedIf [ pFin t1 ]
(TCCeilDiv, [t1,_]) -> SolvedIf [ pFin t1 ]
(TCCeilMod, [_,_]) -> SolvedIf []
(TCLenFromThenTo,[_,_,_]) -> SolvedIf []
_ -> Unsolved
_ -> Unsolved
| null | https://raw.githubusercontent.com/GaloisInc/cryptol/8cca24568ad499f06032c2e4eaa7dfd4c542efb6/src/Cryptol/TypeCheck/Solver/Numeric/Fin.hs | haskell | |
License : BSD3
Maintainer :
Stability : provisional
Portability : portable
Simplification of `fin` constraints.
fin (x * y)
fin (x ^ y)
fin (min x y) | Module : Cryptol . . Solver . Numeric . Fin
Copyright : ( c ) 2015 - 2016 Galois , Inc.
# LANGUAGE PatternGuards #
module Cryptol.TypeCheck.Solver.Numeric.Fin where
import qualified Data.Map as Map
import Cryptol.TypeCheck.Type
import Cryptol.TypeCheck.Solver.Types
import Cryptol.TypeCheck.Solver.Numeric.Interval
import Cryptol.TypeCheck.Solver.InfNat
cryIsFin :: Ctxt -> Prop -> Solved
cryIsFin ctxt p =
case pIsFin p of
Just ty -> cryIsFinType ctxt ty
Nothing -> Unsolved
cryIsFinType :: Ctxt -> Type -> Solved
cryIsFinType ctxt ty =
let varInfo = intervals ctxt in
case tNoUser ty of
TVar x | Just i <- Map.lookup x varInfo
, iIsFin i -> SolvedIf []
TCon (TC tc) []
| TCNum _ <- tc -> SolvedIf []
| TCInf <- tc -> Unsolvable
TCon (TF f) ts ->
case (f,ts) of
(TCAdd,[t1,t2]) -> SolvedIf [ pFin t1, pFin t2 ]
(TCSub,[t1,_ ]) -> SolvedIf [ pFin t1 ]
(TCMul,[t1,t2])
| iLower i1 >= Nat 1 && iIsFin i1 -> SolvedIf [ pFin t2 ]
| iLower i2 >= Nat 1 && iIsFin i2 -> SolvedIf [ pFin t1 ]
| iLower i1 >= Nat 1 &&
iLower i2 >= Nat 1 -> SolvedIf [ pFin t1, pFin t2 ]
| iIsFin i1 && iIsFin i2 -> SolvedIf []
where
i1 = typeInterval varInfo t1
i2 = typeInterval varInfo t2
(TCDiv, [_,_]) -> SolvedIf []
(TCMod, [_,_]) -> SolvedIf []
(TCExp, [t1,t2])
| iLower i1 == Inf -> SolvedIf [ t2 =#= tZero ]
| iLower i2 == Inf -> SolvedIf [ tOne >== t1 ]
| iLower i1 >= Nat 2 -> SolvedIf [ pFin t1, pFin t2 ]
| iLower i2 >= Nat 1 -> SolvedIf [ pFin t1, pFin t2 ]
| Just x <- iUpper i1, x <= Nat 1 -> SolvedIf []
| Just (Nat 0) <- iUpper i2 -> SolvedIf []
where
i1 = typeInterval varInfo t1
i2 = typeInterval varInfo t2
(TCMin, [t1,t2])
| iIsFin i1 -> SolvedIf []
| iIsFin i2 -> SolvedIf []
| Just x <- iUpper i1, x <= iLower i2 -> SolvedIf [ pFin t1 ]
| Just x <- iUpper i2, x <= iLower i1 -> SolvedIf [ pFin t2 ]
where
i1 = typeInterval varInfo t1
i2 = typeInterval varInfo t2
(TCMax, [t1,t2]) -> SolvedIf [ pFin t1, pFin t2 ]
(TCWidth, [t1]) -> SolvedIf [ pFin t1 ]
(TCCeilDiv, [t1,_]) -> SolvedIf [ pFin t1 ]
(TCCeilMod, [_,_]) -> SolvedIf []
(TCLenFromThenTo,[_,_,_]) -> SolvedIf []
_ -> Unsolved
_ -> Unsolved
|
36d9ce5b7f3992c9e2015a530b64c0462c8a898aac5a67d36be3179130ab2cdd | dysinger/restack | config.ml | open Mirage
let server =
cohttp_server @@ conduit_direct ~tls:false (socket_stackv4 [Ipaddr.V4.any])
let main =
let packages = [ package "reason" ] in
let port =
let doc = Key.Arg.info ~doc:"Listening HTTP port." ["port"] in
Key.(create "port" Arg.(opt int 80 doc)) in
let keys = List.map Key.abstract [ port ] in
foreign
~packages ~keys
"Unikernel.HTTP" (pclock @-> http @-> job)
let () =
register "webserver" [main $ default_posix_clock $ server]
| null | https://raw.githubusercontent.com/dysinger/restack/ef8ac0ae0542f1d81d7bd3032c6077149d403d68/001-webserver/config.ml | ocaml | open Mirage
let server =
cohttp_server @@ conduit_direct ~tls:false (socket_stackv4 [Ipaddr.V4.any])
let main =
let packages = [ package "reason" ] in
let port =
let doc = Key.Arg.info ~doc:"Listening HTTP port." ["port"] in
Key.(create "port" Arg.(opt int 80 doc)) in
let keys = List.map Key.abstract [ port ] in
foreign
~packages ~keys
"Unikernel.HTTP" (pclock @-> http @-> job)
let () =
register "webserver" [main $ default_posix_clock $ server]
|
|
df41b6c9b3d817c5ac0d609208861abe942ac354148f7d1e5f500bbf2d1be099 | ghc/ghc | Utils.hs | # LANGUAGE CPP , ScopedTypeVariables , TypeFamilies #
# LANGUAGE DataKinds #
module GHC.Stg.Utils
( mkStgAltTypeFromStgAlts
, bindersOf, bindersOfX, bindersOfTop, bindersOfTopBinds
, stripStgTicksTop, stripStgTicksTopE
, idArgs
, mkUnarisedId, mkUnarisedIds
) where
import GHC.Prelude
import GHC.Types.Id
import GHC.Core.Type
import GHC.Core.TyCon
import GHC.Core.DataCon
import GHC.Core ( AltCon(..) )
import GHC.Types.Tickish
import GHC.Types.Unique.Supply
import GHC.Types.RepType
import GHC.Stg.Syntax
import GHC.Utils.Outputable
import GHC.Utils.Panic.Plain
import GHC.Utils.Panic
import GHC.Data.FastString
mkUnarisedIds :: MonadUnique m => FastString -> [UnaryType] -> m [Id]
mkUnarisedIds fs tys = mapM (mkUnarisedId fs) tys
mkUnarisedId :: MonadUnique m => FastString -> UnaryType -> m Id
mkUnarisedId s t = mkSysLocalM s ManyTy t
-- Checks if id is a top level error application.
-- isErrorAp_maybe :: Id ->
-- | Extract the default case alternative
findDefaultStg : : [ Alt b ] - > ( [ Alt b ] , Maybe ( b ) )
findDefaultStg
:: [GenStgAlt p]
-> ([GenStgAlt p], Maybe (GenStgExpr p))
findDefaultStg (GenStgAlt{ alt_con = DEFAULT
, alt_bndrs = args
, alt_rhs = rhs} : alts) = assert( null args ) (alts, Just rhs)
findDefaultStg alts = (alts, Nothing)
mkStgAltTypeFromStgAlts :: forall p. Id -> [GenStgAlt p] -> AltType
mkStgAltTypeFromStgAlts bndr alts
| isUnboxedTupleType bndr_ty || isUnboxedSumType bndr_ty
always use MultiValAlt for unboxed tuples
| otherwise
= case prim_reps of
[rep] | isGcPtrRep rep ->
case tyConAppTyCon_maybe (unwrapType bndr_ty) of
Just tc
| isAbstractTyCon tc -> look_for_better_tycon
| isAlgTyCon tc -> AlgAlt tc
| otherwise -> assertPpr ( _is_poly_alt_tycon tc) (ppr tc)
PolyAlt
Nothing -> PolyAlt
[non_gcd] -> PrimAlt non_gcd
not_unary -> MultiValAlt (length not_unary)
where
bndr_ty = idType bndr
prim_reps = typePrimRep bndr_ty
_is_poly_alt_tycon tc
= isPrimTyCon tc -- "Any" is lifted but primitive
|| isFamilyTyCon tc -- Type family; e.g. Any, or arising from strict
-- function application where argument has a
-- type-family type
Sometimes , the is a AbstractTyCon which may not have any
constructors inside it . Then we may get a better by
-- grabbing the one from a constructor alternative
-- if one exists.
look_for_better_tycon
| (DataAlt con : _) <- alt_con <$> data_alts =
AlgAlt (dataConTyCon con)
| otherwise =
assert(null data_alts)
PolyAlt
where
(data_alts, _deflt) = findDefaultStg alts
bindersOf :: BinderP a ~ Id => GenStgBinding a -> [Id]
bindersOf (StgNonRec binder _) = [binder]
bindersOf (StgRec pairs) = [binder | (binder, _) <- pairs]
bindersOfX :: GenStgBinding a -> [BinderP a]
bindersOfX (StgNonRec binder _) = [binder]
bindersOfX (StgRec pairs) = [binder | (binder, _) <- pairs]
bindersOfTop :: BinderP a ~ Id => GenStgTopBinding a -> [Id]
bindersOfTop (StgTopLifted bind) = bindersOf bind
bindersOfTop (StgTopStringLit binder _) = [binder]
-- All ids we bind something to on the top level.
bindersOfTopBinds :: BinderP a ~ Id => [GenStgTopBinding a] -> [Id]
-- bindersOfTopBinds binds = mapUnionVarSet (mkVarSet . bindersOfTop) binds
bindersOfTopBinds binds = foldr ((++) . bindersOfTop) [] binds
idArgs :: [StgArg] -> [Id]
idArgs args = [v | StgVarArg v <- args]
| Strip ticks of a given type from an STG expression .
stripStgTicksTop :: (StgTickish -> Bool) -> GenStgExpr p -> ([StgTickish], GenStgExpr p)
stripStgTicksTop p = go []
where go ts (StgTick t e) | p t = go (t:ts) e
-- This special case avoid building a thunk for "reverse ts" when there are no ticks
go [] other = ([], other)
go ts other = (reverse ts, other)
| Strip ticks of a given type from an STG expression returning only the expression .
stripStgTicksTopE :: (StgTickish -> Bool) -> GenStgExpr p -> GenStgExpr p
stripStgTicksTopE p = go
where go (StgTick t e) | p t = go e
go other = other
| null | https://raw.githubusercontent.com/ghc/ghc/37cfe3c0f4fb16189bbe3bb735f758cd6e3d9157/compiler/GHC/Stg/Utils.hs | haskell | Checks if id is a top level error application.
isErrorAp_maybe :: Id ->
| Extract the default case alternative
"Any" is lifted but primitive
Type family; e.g. Any, or arising from strict
function application where argument has a
type-family type
grabbing the one from a constructor alternative
if one exists.
All ids we bind something to on the top level.
bindersOfTopBinds binds = mapUnionVarSet (mkVarSet . bindersOfTop) binds
This special case avoid building a thunk for "reverse ts" when there are no ticks | # LANGUAGE CPP , ScopedTypeVariables , TypeFamilies #
# LANGUAGE DataKinds #
module GHC.Stg.Utils
( mkStgAltTypeFromStgAlts
, bindersOf, bindersOfX, bindersOfTop, bindersOfTopBinds
, stripStgTicksTop, stripStgTicksTopE
, idArgs
, mkUnarisedId, mkUnarisedIds
) where
import GHC.Prelude
import GHC.Types.Id
import GHC.Core.Type
import GHC.Core.TyCon
import GHC.Core.DataCon
import GHC.Core ( AltCon(..) )
import GHC.Types.Tickish
import GHC.Types.Unique.Supply
import GHC.Types.RepType
import GHC.Stg.Syntax
import GHC.Utils.Outputable
import GHC.Utils.Panic.Plain
import GHC.Utils.Panic
import GHC.Data.FastString
mkUnarisedIds :: MonadUnique m => FastString -> [UnaryType] -> m [Id]
mkUnarisedIds fs tys = mapM (mkUnarisedId fs) tys
mkUnarisedId :: MonadUnique m => FastString -> UnaryType -> m Id
mkUnarisedId s t = mkSysLocalM s ManyTy t
findDefaultStg : : [ Alt b ] - > ( [ Alt b ] , Maybe ( b ) )
findDefaultStg
:: [GenStgAlt p]
-> ([GenStgAlt p], Maybe (GenStgExpr p))
findDefaultStg (GenStgAlt{ alt_con = DEFAULT
, alt_bndrs = args
, alt_rhs = rhs} : alts) = assert( null args ) (alts, Just rhs)
findDefaultStg alts = (alts, Nothing)
mkStgAltTypeFromStgAlts :: forall p. Id -> [GenStgAlt p] -> AltType
mkStgAltTypeFromStgAlts bndr alts
| isUnboxedTupleType bndr_ty || isUnboxedSumType bndr_ty
always use MultiValAlt for unboxed tuples
| otherwise
= case prim_reps of
[rep] | isGcPtrRep rep ->
case tyConAppTyCon_maybe (unwrapType bndr_ty) of
Just tc
| isAbstractTyCon tc -> look_for_better_tycon
| isAlgTyCon tc -> AlgAlt tc
| otherwise -> assertPpr ( _is_poly_alt_tycon tc) (ppr tc)
PolyAlt
Nothing -> PolyAlt
[non_gcd] -> PrimAlt non_gcd
not_unary -> MultiValAlt (length not_unary)
where
bndr_ty = idType bndr
prim_reps = typePrimRep bndr_ty
_is_poly_alt_tycon tc
Sometimes , the is a AbstractTyCon which may not have any
constructors inside it . Then we may get a better by
look_for_better_tycon
| (DataAlt con : _) <- alt_con <$> data_alts =
AlgAlt (dataConTyCon con)
| otherwise =
assert(null data_alts)
PolyAlt
where
(data_alts, _deflt) = findDefaultStg alts
bindersOf :: BinderP a ~ Id => GenStgBinding a -> [Id]
bindersOf (StgNonRec binder _) = [binder]
bindersOf (StgRec pairs) = [binder | (binder, _) <- pairs]
bindersOfX :: GenStgBinding a -> [BinderP a]
bindersOfX (StgNonRec binder _) = [binder]
bindersOfX (StgRec pairs) = [binder | (binder, _) <- pairs]
bindersOfTop :: BinderP a ~ Id => GenStgTopBinding a -> [Id]
bindersOfTop (StgTopLifted bind) = bindersOf bind
bindersOfTop (StgTopStringLit binder _) = [binder]
bindersOfTopBinds :: BinderP a ~ Id => [GenStgTopBinding a] -> [Id]
bindersOfTopBinds binds = foldr ((++) . bindersOfTop) [] binds
idArgs :: [StgArg] -> [Id]
idArgs args = [v | StgVarArg v <- args]
| Strip ticks of a given type from an STG expression .
stripStgTicksTop :: (StgTickish -> Bool) -> GenStgExpr p -> ([StgTickish], GenStgExpr p)
stripStgTicksTop p = go []
where go ts (StgTick t e) | p t = go (t:ts) e
go [] other = ([], other)
go ts other = (reverse ts, other)
| Strip ticks of a given type from an STG expression returning only the expression .
stripStgTicksTopE :: (StgTickish -> Bool) -> GenStgExpr p -> GenStgExpr p
stripStgTicksTopE p = go
where go (StgTick t e) | p t = go e
go other = other
|
7a29a89e660e309c810d2ba9cd19ab20a3121c03f85a56a1bdf4a7d4a306aad1 | gebi/jungerl | rdbms_verify.erl | %%%
The contents of this file are subject to the Erlang 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
%%%
%%%
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 rdbms-1.2 .
%%%
The Initial Developer of the Original Code is Ericsson Telecom
AB . Portions created by Ericsson are Copyright ( C ) , 1998 , Ericsson
Telecom AB . All Rights Reserved .
%%%
%%% Contributor(s): ______________________________________.
%%%----------------------------------------------------------------------
# 0 . BASIC INFORMATION
%%%----------------------------------------------------------------------
%%%-------------------------------------------------------------------
%%% File : rdbms_verify.erl
Author : >
%%% Description : "Slow-path" verification code for rdbms
%%%
Created : 26 Dec 2005 by >
%%%-------------------------------------------------------------------
-module(rdbms_verify).
-export([validate_rec/3, indexes/2, acl/2,
verify_access/4,
references/2,
rec_type/2,
module/2]).
-export([check_type/2, % (Type, Value)
check_type/3, % (Type, Value, ErrInfo)
filter_obj/3,
check_access/4,
access_filter/3,
on_read/3]).
-export([table_property/4, attr_property/5, table_info/3]).
-include("rdbms.hrl").
indexes(Tab, #verify{tab_property = Prop}) ->
Prop(Tab, indexes, []).
references(Tab, VRec) ->
table_property(Tab, references, VRec, []).
rec_type(Tab, VRec) ->
table_property(Tab, rec_type, VRec, no_type).
acl(Tab, VRec) ->
table_property(Tab, acl, VRec, []).
module(Tab, #verify{table_info = TI}) ->
case TI(Tab, frag_properties) of
[] ->
mnesia;
[_|_] ->
mnesia_frag
end.
verify_access(Tab, Rec, Mode, VRec) ->
case acl(Tab, VRec) of
[] ->
true;
[_|_] = Acl->
check_access(Acl, Mode, Rec, Tab)
end.
check_access([{M, What}|_], Mode, Rec, Tab) when M==Mode; M=='_' ->
case access_return(What, Tab, Mode, Rec) of
true -> true;
false ->
mnesia:abort({access_violation,[Tab,Mode]})
end;
check_access([_|T], Mode, Rec, Tab) ->
check_access(T, Mode, Rec, Tab);
check_access([], _, _, _) ->
true.
access_filter([], Objs, _Tab) ->
Objs;
access_filter(Acl, Objs, Tab) ->
What = read_access_what(Acl),
lists:filter(fun(Obj) ->
access_return(What, Tab, read, Obj)
end, Objs).
read_access_what([{read,What}|_]) ->
What;
read_access_what([{'_',What}|_]) ->
What;
read_access_what([_|T]) ->
read_access_what(T);
read_access_what([]) ->
true.
access_return(What, Tab, Mode, Rec) ->
case What of
Bool when is_boolean(Bool) ->
Bool;
{Mod,Fun} ->
true == Mod:Fun(Tab, Mode, Rec)
end.
validate_rec(Tab, Rec, VRec) ->
case rec_type(Tab, VRec) of
no_type -> true;
RecT ->
case check_type(RecT, Rec) of
false ->
mnesia:abort({type_error, [Tab, RecT, RecT]});
true ->
callback_validate(Rec, Tab, VRec)
end
end.
on_read(Tab, Objs, VRec) ->
Acl = acl(Tab, VRec),
What = read_access_what(Acl),
RFilter = table_property(Tab, read_filter, VRec, no_filter),
case {What, RFilter} of
{false, _} ->
[];
{true, no_filter} ->
Objs;
{true, RFilter} ->
rdbms_ms:run_ms(Objs, RFilter);
%%% ets:match_spec_run(Objs, ets:match_spec_compile(RFilter));
{{M,F}, no_filter} ->
lists:filter(
fun(Obj) ->
true == M:F(Tab, read, Obj)
end, Objs);
{{M,F}, RFilter} ->
lists:filter(
fun(Obj) ->
true == M:F(Tab, read, Obj)
end,
rdbms_ms:run_ms(Objs, RFilter))
ets : match_spec_run(Objs ,
%%% ets:match_spec_compile(RFilter)))
end.
table_property(Tab, Prop, #verify{tab_property = TP}, Default) ->
TP(Tab, Prop, Default).
attr_property(Tab, Attr, Prop, #verify{attr_property = AP}, Default) ->
AP(Tab, Attr, Prop, Default).
table_info(Tab, InfoItem, #verify{table_info = TI}) ->
TI(Tab, InfoItem).
filter_obj(Obj, Pattern, Info) ->
case rdbms_ms:run_ms([Obj], Pattern) of
%%% case ets:match_spec_run([Obj], ets:match_spec_compile(Pattern)) of
[] ->
mnesia:abort({filter_violation, Info});
[NewObj] ->
NewObj
end.
attribute_type(Tab , Attr , # verify{attr_property = AP } ) - >
%%% AP({Tab,Attr}, type, undefined).
check_type(Type, Value, Info) ->
case check_type(Type, Value) of
false ->
mnesia:abort({type_violation, Info});
true ->
true
end.
check_type(false, _) -> false;
check_type(true, _) -> true;
check_type(no_type, _) -> true;
check_type(any, _) -> true;
check_type(undefined, undefined) -> true;
check_type({enum, Vs}, X) -> lists:member(X, Vs);
check_type({tuple, Arity, Ts}, X) when is_tuple(X), size(X) == Arity ->
Elems = tuple_to_list(X),
lists:zipwith(fun check_type/2, Ts, Elems);
check_type({tuple, Arity}, X) when is_tuple(X), size(X) == Arity -> true;
check_type(tuple, X) when is_tuple(X) -> true;
check_type(integer, X) when is_integer(X) -> true;
check_type(float, X) when is_float(X) -> true;
check_type(number, X) when is_integer(X); is_float(X) -> true;
check_type(atom, X) when is_atom(X) -> true;
check_type(pid, X) when is_pid(X) -> true;
check_type(port, X) when is_port(X) -> true;
check_type(binary, X) when is_binary(X) -> true;
check_type(list, X) when is_list(X) -> true;
check_type(string, X) ->
try list_to_binary(X) of
_ -> true
catch
error:_ -> false
end;
check_type(nil, []) -> true;
check_type({list,false}, _) -> false; % optimization
check_type({list, T}, [_|_]) when T==any; T==undefined -> true;
check_type({list, T}, X) when is_list(X) ->
while(true, fun(Elem) -> check_type(T, Elem) end, X);
check_type(function, X) when is_function(X) -> true;
check_type({function,Arity}, X) when is_function(X, Arity) -> true;
%%% check_type({'and',Ts}, X) ->
lists : foldl(fun(T , Acc ) - >
Acc and check_type(T , X )
%%% end, true, Ts);
check_type({'and',Ts}, X) ->
%% 'andalso' semantics
while(true, fun(T) -> check_type(T, X) end, Ts);
%%% check_type({'or',Ts}, X) ->
lists : foldl(fun(T , Acc ) - >
Acc or check_type(T , X )
%%% end, false, Ts);
check_type({'or', Ts}, X) ->
%% 'orelse' semantics
while(false, fun(T) -> check_type(T, X) end, Ts);
check_type({'not', T}, X) ->
not(check_type(T, X));
check_type({O,V}, X) when O=='==';O=='=/=';O=='<';O=='>';O=='>=';O=='=<' ->
erlang:O(X,V);
check_type(oid, {Nd, {Ms,S,Us}})
when is_atom(Nd), is_integer(Ms), is_integer(S), is_integer(Us),
Ms >= 0, S >= 0, Us >= 0 ->
c.f . { node ( ) , : now ( ) }
true;
check_type(_, _) ->
false.
while(Bool, F, L) when is_list(L) ->
Not = not(Bool),
try lists:foreach(
fun(Elem) ->
case F(Elem) of
Not -> throw(Not);
Bool -> Bool
end
end, L) of
_ -> Bool
catch
throw:Not ->
Not
end.
callback_validate(Record , VRec )
%% This allows a user to register his own verification trigger for a certain
record . This trigger function should call : abort ( ) if verification
%% fails.
%%
callback_validate(Rec, Tab, #verify{tab_property = TP}) ->
case TP(Tab, verify) of
undefined ->
true;
F ->
F(Rec)
end.
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/rdbms/src/rdbms_verify.erl | erlang |
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.
Contributor(s): ______________________________________.
----------------------------------------------------------------------
----------------------------------------------------------------------
-------------------------------------------------------------------
File : rdbms_verify.erl
Description : "Slow-path" verification code for rdbms
-------------------------------------------------------------------
(Type, Value)
(Type, Value, ErrInfo)
ets:match_spec_run(Objs, ets:match_spec_compile(RFilter));
ets:match_spec_compile(RFilter)))
case ets:match_spec_run([Obj], ets:match_spec_compile(Pattern)) of
AP({Tab,Attr}, type, undefined).
optimization
check_type({'and',Ts}, X) ->
end, true, Ts);
'andalso' semantics
check_type({'or',Ts}, X) ->
end, false, Ts);
'orelse' semantics
This allows a user to register his own verification trigger for a certain
fails.
| The contents of this file are subject to the Erlang Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is rdbms-1.2 .
The Initial Developer of the Original Code is Ericsson Telecom
AB . Portions created by Ericsson are Copyright ( C ) , 1998 , Ericsson
Telecom AB . All Rights Reserved .
# 0 . BASIC INFORMATION
Author : >
Created : 26 Dec 2005 by >
-module(rdbms_verify).
-export([validate_rec/3, indexes/2, acl/2,
verify_access/4,
references/2,
rec_type/2,
module/2]).
filter_obj/3,
check_access/4,
access_filter/3,
on_read/3]).
-export([table_property/4, attr_property/5, table_info/3]).
-include("rdbms.hrl").
indexes(Tab, #verify{tab_property = Prop}) ->
Prop(Tab, indexes, []).
references(Tab, VRec) ->
table_property(Tab, references, VRec, []).
rec_type(Tab, VRec) ->
table_property(Tab, rec_type, VRec, no_type).
acl(Tab, VRec) ->
table_property(Tab, acl, VRec, []).
module(Tab, #verify{table_info = TI}) ->
case TI(Tab, frag_properties) of
[] ->
mnesia;
[_|_] ->
mnesia_frag
end.
verify_access(Tab, Rec, Mode, VRec) ->
case acl(Tab, VRec) of
[] ->
true;
[_|_] = Acl->
check_access(Acl, Mode, Rec, Tab)
end.
check_access([{M, What}|_], Mode, Rec, Tab) when M==Mode; M=='_' ->
case access_return(What, Tab, Mode, Rec) of
true -> true;
false ->
mnesia:abort({access_violation,[Tab,Mode]})
end;
check_access([_|T], Mode, Rec, Tab) ->
check_access(T, Mode, Rec, Tab);
check_access([], _, _, _) ->
true.
access_filter([], Objs, _Tab) ->
Objs;
access_filter(Acl, Objs, Tab) ->
What = read_access_what(Acl),
lists:filter(fun(Obj) ->
access_return(What, Tab, read, Obj)
end, Objs).
read_access_what([{read,What}|_]) ->
What;
read_access_what([{'_',What}|_]) ->
What;
read_access_what([_|T]) ->
read_access_what(T);
read_access_what([]) ->
true.
access_return(What, Tab, Mode, Rec) ->
case What of
Bool when is_boolean(Bool) ->
Bool;
{Mod,Fun} ->
true == Mod:Fun(Tab, Mode, Rec)
end.
validate_rec(Tab, Rec, VRec) ->
case rec_type(Tab, VRec) of
no_type -> true;
RecT ->
case check_type(RecT, Rec) of
false ->
mnesia:abort({type_error, [Tab, RecT, RecT]});
true ->
callback_validate(Rec, Tab, VRec)
end
end.
on_read(Tab, Objs, VRec) ->
Acl = acl(Tab, VRec),
What = read_access_what(Acl),
RFilter = table_property(Tab, read_filter, VRec, no_filter),
case {What, RFilter} of
{false, _} ->
[];
{true, no_filter} ->
Objs;
{true, RFilter} ->
rdbms_ms:run_ms(Objs, RFilter);
{{M,F}, no_filter} ->
lists:filter(
fun(Obj) ->
true == M:F(Tab, read, Obj)
end, Objs);
{{M,F}, RFilter} ->
lists:filter(
fun(Obj) ->
true == M:F(Tab, read, Obj)
end,
rdbms_ms:run_ms(Objs, RFilter))
ets : match_spec_run(Objs ,
end.
table_property(Tab, Prop, #verify{tab_property = TP}, Default) ->
TP(Tab, Prop, Default).
attr_property(Tab, Attr, Prop, #verify{attr_property = AP}, Default) ->
AP(Tab, Attr, Prop, Default).
table_info(Tab, InfoItem, #verify{table_info = TI}) ->
TI(Tab, InfoItem).
filter_obj(Obj, Pattern, Info) ->
case rdbms_ms:run_ms([Obj], Pattern) of
[] ->
mnesia:abort({filter_violation, Info});
[NewObj] ->
NewObj
end.
attribute_type(Tab , Attr , # verify{attr_property = AP } ) - >
check_type(Type, Value, Info) ->
case check_type(Type, Value) of
false ->
mnesia:abort({type_violation, Info});
true ->
true
end.
check_type(false, _) -> false;
check_type(true, _) -> true;
check_type(no_type, _) -> true;
check_type(any, _) -> true;
check_type(undefined, undefined) -> true;
check_type({enum, Vs}, X) -> lists:member(X, Vs);
check_type({tuple, Arity, Ts}, X) when is_tuple(X), size(X) == Arity ->
Elems = tuple_to_list(X),
lists:zipwith(fun check_type/2, Ts, Elems);
check_type({tuple, Arity}, X) when is_tuple(X), size(X) == Arity -> true;
check_type(tuple, X) when is_tuple(X) -> true;
check_type(integer, X) when is_integer(X) -> true;
check_type(float, X) when is_float(X) -> true;
check_type(number, X) when is_integer(X); is_float(X) -> true;
check_type(atom, X) when is_atom(X) -> true;
check_type(pid, X) when is_pid(X) -> true;
check_type(port, X) when is_port(X) -> true;
check_type(binary, X) when is_binary(X) -> true;
check_type(list, X) when is_list(X) -> true;
check_type(string, X) ->
try list_to_binary(X) of
_ -> true
catch
error:_ -> false
end;
check_type(nil, []) -> true;
check_type({list, T}, [_|_]) when T==any; T==undefined -> true;
check_type({list, T}, X) when is_list(X) ->
while(true, fun(Elem) -> check_type(T, Elem) end, X);
check_type(function, X) when is_function(X) -> true;
check_type({function,Arity}, X) when is_function(X, Arity) -> true;
lists : foldl(fun(T , Acc ) - >
Acc and check_type(T , X )
check_type({'and',Ts}, X) ->
while(true, fun(T) -> check_type(T, X) end, Ts);
lists : foldl(fun(T , Acc ) - >
Acc or check_type(T , X )
check_type({'or', Ts}, X) ->
while(false, fun(T) -> check_type(T, X) end, Ts);
check_type({'not', T}, X) ->
not(check_type(T, X));
check_type({O,V}, X) when O=='==';O=='=/=';O=='<';O=='>';O=='>=';O=='=<' ->
erlang:O(X,V);
check_type(oid, {Nd, {Ms,S,Us}})
when is_atom(Nd), is_integer(Ms), is_integer(S), is_integer(Us),
Ms >= 0, S >= 0, Us >= 0 ->
c.f . { node ( ) , : now ( ) }
true;
check_type(_, _) ->
false.
while(Bool, F, L) when is_list(L) ->
Not = not(Bool),
try lists:foreach(
fun(Elem) ->
case F(Elem) of
Not -> throw(Not);
Bool -> Bool
end
end, L) of
_ -> Bool
catch
throw:Not ->
Not
end.
callback_validate(Record , VRec )
record . This trigger function should call : abort ( ) if verification
callback_validate(Rec, Tab, #verify{tab_property = TP}) ->
case TP(Tab, verify) of
undefined ->
true;
F ->
F(Rec)
end.
|
cb15ffd59d4d8228373dfbfbcbd2072d24f5f0bc8582521d1cd87c4fadbc906b | FarmLogs/geojson | generators.clj | (ns geojson.generators
"A set of test.check GeoJSON generators."
(:require [clojure.test.check.generators :as gen]))
(def ^{:private true} max-count
"Keeps the vector generation within a reasonable upper bound."
100)
(def ^{:private true} lng
"Generates a valid longitude."
(->> (gen/fmap float gen/ratio)
(gen/such-that #(>= % -180))
(gen/such-that #(<= % 180))))
(def ^{:private true} lat
"Generates a valid latitude."
(->> (gen/fmap float gen/ratio)
(gen/such-that #(>= % -90))
(gen/such-that #(<= % 90))))
(def ^{:private true} point-coords
"Generates a valid [x y] point."
(gen/tuple lng lat))
(def ^{:private true} linestring-coords
"Generates a list of points for linestring types."
(->> (gen/vector point-coords 2 max-count)
(gen/fmap #(map first (partition-by identity %)))
(gen/such-that #(>= (count %) 2))))
(defn- overlapping?
"Determines whether the provided points are arranged in a line which overlaps
itself. This is a subset of self intersection and is invalid.
We know the lines between a set of points overlap if one axis remains
constant while the other is neither constantly ascending nor descending."
[& points]
(let [xs (map first points)
ys (map second points)]
(or (and (apply = xs)
(or (= (sort ys) ys)
(= (reverse (sort ys)) ys)))
(and (apply = ys)
(or (= (sort xs) xs)
(= (reverse (sort xs)) xs))))))
(defn- sort-points
"Arranges points such that there is no self-intersection.
This works by calculating the angle between the bounding box's center and
each point, then sorting those points by their angle in a counterclockwise
direction."
[points]
(let [xs (map first points)
minx (apply min xs)
maxx (apply max xs)
ys (map second points)
miny (apply min ys)
maxy (apply max ys)
mean [(+ (/ (- maxx minx) 2) minx)
(+ (/ (- maxy miny ) 2) miny)]]
(sort-by #(Math/atan2 (- (second mean) (second %)) (- (first mean) (first %))) points)))
(def ^{:private true} linear-ring-coords
"Generates a valid linear ring, ie for a Polygon geometry."
(->> (gen/vector point-coords 3 max-count)
(gen/fmap distinct)
(gen/such-that #(>= (count %) 3))
(gen/fmap sort-points)
(gen/such-that #(every? false? (map overlapping? % (drop 1 %) (drop 2 %))))
(gen/fmap #(concat (take 1 %)
(rest %)
(take 1 %)))))
(def ^{:private true} polygon-coords
"Generates coordinates for a polygon.
TODO: add support polygons with interior rings."
(gen/vector linear-ring-coords 1))
(def point
"Generates a GeoJSON Point."
(gen/hash-map :type (gen/return "Point")
:coordinates point-coords))
(def multi-point
"Generates a GeoJSON MultiPoint."
(gen/hash-map :type (gen/return "MultiPoint")
:coordinates (gen/fmap distinct (gen/vector point-coords 1 max-count))))
(def linestring
"Generates a GeoJSON LineString."
(gen/hash-map :type (gen/return "LineString")
:coordinates linestring-coords))
(def multi-linestring
"Generates a GeoJSON MultiLineString."
(gen/hash-map :type (gen/return "MultiLineString")
:coordinates (gen/vector linestring-coords)))
(def polygon
"Generates a GeoJSON Polygon.
TODO: add support polygons with interior rings."
(gen/hash-map :type (gen/return "Polygon")
:coordinates polygon-coords))
(def multi-polygon
"Generates a GeoJSON MultiPolygon.
TODO: make sure polygons do not intersect each other."
(gen/hash-map :type (gen/return "MultiPolygon")
:coordinates (gen/vector polygon-coords)))
(def geometry
"Generates a GeoJSON geometry object of any basic type.
Note that this does not include GeometryCollection objects."
(gen/one-of [point multi-point linestring multi-linestring polygon multi-polygon]))
(def geometry-collection
"Generates a GeoJSON GeometryCollection."
(gen/hash-map :type (gen/return "GeometryCollection")
:geometries (gen/vector geometry)))
(def feature
"Generates a GeoJSON Feature."
(gen/hash-map :type (gen/return "Feature")
:geometry (gen/one-of [(gen/return nil) geometry])
:properties (gen/one-of [(gen/return nil) (gen/map gen/keyword gen/any)])))
(def feature-collection
"Generates a GeoJSON FeatureCollection."
(gen/hash-map :type (gen/return "FeatureCollection")
:features (gen/vector feature)))
(def geojson
"Generates any valid GeoJSON object."
(gen/one-of [geometry geometry-collection feature feature-collection]))
| null | https://raw.githubusercontent.com/FarmLogs/geojson/a21338f24ca2b16128c24ff1d163b69ca207c77f/src/geojson/generators.clj | clojure | (ns geojson.generators
"A set of test.check GeoJSON generators."
(:require [clojure.test.check.generators :as gen]))
(def ^{:private true} max-count
"Keeps the vector generation within a reasonable upper bound."
100)
(def ^{:private true} lng
"Generates a valid longitude."
(->> (gen/fmap float gen/ratio)
(gen/such-that #(>= % -180))
(gen/such-that #(<= % 180))))
(def ^{:private true} lat
"Generates a valid latitude."
(->> (gen/fmap float gen/ratio)
(gen/such-that #(>= % -90))
(gen/such-that #(<= % 90))))
(def ^{:private true} point-coords
"Generates a valid [x y] point."
(gen/tuple lng lat))
(def ^{:private true} linestring-coords
"Generates a list of points for linestring types."
(->> (gen/vector point-coords 2 max-count)
(gen/fmap #(map first (partition-by identity %)))
(gen/such-that #(>= (count %) 2))))
(defn- overlapping?
"Determines whether the provided points are arranged in a line which overlaps
itself. This is a subset of self intersection and is invalid.
We know the lines between a set of points overlap if one axis remains
constant while the other is neither constantly ascending nor descending."
[& points]
(let [xs (map first points)
ys (map second points)]
(or (and (apply = xs)
(or (= (sort ys) ys)
(= (reverse (sort ys)) ys)))
(and (apply = ys)
(or (= (sort xs) xs)
(= (reverse (sort xs)) xs))))))
(defn- sort-points
"Arranges points such that there is no self-intersection.
This works by calculating the angle between the bounding box's center and
each point, then sorting those points by their angle in a counterclockwise
direction."
[points]
(let [xs (map first points)
minx (apply min xs)
maxx (apply max xs)
ys (map second points)
miny (apply min ys)
maxy (apply max ys)
mean [(+ (/ (- maxx minx) 2) minx)
(+ (/ (- maxy miny ) 2) miny)]]
(sort-by #(Math/atan2 (- (second mean) (second %)) (- (first mean) (first %))) points)))
(def ^{:private true} linear-ring-coords
"Generates a valid linear ring, ie for a Polygon geometry."
(->> (gen/vector point-coords 3 max-count)
(gen/fmap distinct)
(gen/such-that #(>= (count %) 3))
(gen/fmap sort-points)
(gen/such-that #(every? false? (map overlapping? % (drop 1 %) (drop 2 %))))
(gen/fmap #(concat (take 1 %)
(rest %)
(take 1 %)))))
(def ^{:private true} polygon-coords
"Generates coordinates for a polygon.
TODO: add support polygons with interior rings."
(gen/vector linear-ring-coords 1))
(def point
"Generates a GeoJSON Point."
(gen/hash-map :type (gen/return "Point")
:coordinates point-coords))
(def multi-point
"Generates a GeoJSON MultiPoint."
(gen/hash-map :type (gen/return "MultiPoint")
:coordinates (gen/fmap distinct (gen/vector point-coords 1 max-count))))
(def linestring
"Generates a GeoJSON LineString."
(gen/hash-map :type (gen/return "LineString")
:coordinates linestring-coords))
(def multi-linestring
"Generates a GeoJSON MultiLineString."
(gen/hash-map :type (gen/return "MultiLineString")
:coordinates (gen/vector linestring-coords)))
(def polygon
"Generates a GeoJSON Polygon.
TODO: add support polygons with interior rings."
(gen/hash-map :type (gen/return "Polygon")
:coordinates polygon-coords))
(def multi-polygon
"Generates a GeoJSON MultiPolygon.
TODO: make sure polygons do not intersect each other."
(gen/hash-map :type (gen/return "MultiPolygon")
:coordinates (gen/vector polygon-coords)))
(def geometry
"Generates a GeoJSON geometry object of any basic type.
Note that this does not include GeometryCollection objects."
(gen/one-of [point multi-point linestring multi-linestring polygon multi-polygon]))
(def geometry-collection
"Generates a GeoJSON GeometryCollection."
(gen/hash-map :type (gen/return "GeometryCollection")
:geometries (gen/vector geometry)))
(def feature
"Generates a GeoJSON Feature."
(gen/hash-map :type (gen/return "Feature")
:geometry (gen/one-of [(gen/return nil) geometry])
:properties (gen/one-of [(gen/return nil) (gen/map gen/keyword gen/any)])))
(def feature-collection
"Generates a GeoJSON FeatureCollection."
(gen/hash-map :type (gen/return "FeatureCollection")
:features (gen/vector feature)))
(def geojson
"Generates any valid GeoJSON object."
(gen/one-of [geometry geometry-collection feature feature-collection]))
|
|
279d436f5cac9beb6eff15b3b6cd69a0bc4903303b9f6f503e6341daabbe2873 | ocaml-flambda/flambda-backend | unboxing_epa.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
and ,
(* *)
(* Copyright 2013--2020 OCamlPro SAS *)
Copyright 2014 - -2020 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. *)
(* *)
(**************************************************************************)
open! Simplify_import
module U = Unboxing_types
module Extra_param_and_args = U.Extra_param_and_args
exception Prevent_current_unboxing
let prevent_current_unboxing () = raise Prevent_current_unboxing
type unboxed_arg =
| Poison (* used for recursive calls *)
| Available of Simple.t
| Generated of Variable.t
| Added_by_wrapper_at_rewrite_use of { nth_arg : int }
let _print_unboxed_arg ppf = function
| Poison -> Format.fprintf ppf "poison"
| Available simple -> Format.fprintf ppf "simple: %a" Simple.print simple
| Generated v -> Format.fprintf ppf "generated: %a" Variable.print v
| Added_by_wrapper_at_rewrite_use { nth_arg } ->
Format.fprintf ppf "added_by_wrapper(%d)" nth_arg
let type_of_arg_being_unboxed unboxed_arg =
match unboxed_arg with
| Poison -> None
| Available simple -> Some (T.alias_type_of K.value simple)
| Generated _ -> Some (T.unknown K.value)
| Added_by_wrapper_at_rewrite_use _ -> prevent_current_unboxing ()
let unbox_arg (unboxer : Unboxers.unboxer) ~typing_env_at_use arg_being_unboxed
=
match arg_being_unboxed with
| Poison ->
let extra_arg =
EPA.Extra_arg.Already_in_scope (Simple.const unboxer.invalid_const)
in
extra_arg, Poison
| Available arg_at_use -> (
let arg_type = T.alias_type_of K.value arg_at_use in
match
unboxer.prove_simple typing_env_at_use arg_type
~min_name_mode:Name_mode.normal
with
| Known_result simple ->
EPA.Extra_arg.Already_in_scope simple, Available simple
| Invalid ->
let extra_arg =
EPA.Extra_arg.Already_in_scope (Simple.const unboxer.invalid_const)
in
extra_arg, Poison
| Need_meet ->
let var = Variable.create unboxer.var_name in
let prim = unboxer.unboxing_prim arg_at_use in
let extra_arg = EPA.Extra_arg.New_let_binding (var, prim) in
extra_arg, Generated var)
| Generated var ->
let arg_at_use = Simple.var var in
let var = Variable.create unboxer.var_name in
let prim = unboxer.unboxing_prim arg_at_use in
let extra_arg = EPA.Extra_arg.New_let_binding (var, prim) in
extra_arg, Generated var
| Added_by_wrapper_at_rewrite_use { nth_arg } ->
let var = Variable.create "unboxed_field" in
( EPA.Extra_arg.New_let_binding_with_named_args
( var,
fun args ->
let arg_simple = List.nth args nth_arg in
unboxer.unboxing_prim arg_simple ),
Generated var )
(* Helpers for the variant case *)
(* **************************** *)
type variant_argument =
| Not_a_constant_constructor
| Maybe_constant_constructor of
{ is_int : Simple.t;
arg_being_unboxed : unboxed_arg
}
let extra_arg_for_is_int = function
| Maybe_constant_constructor { is_int; _ } ->
EPA.Extra_arg.Already_in_scope is_int
| Not_a_constant_constructor ->
EPA.Extra_arg.Already_in_scope Simple.untagged_const_false
let extra_arg_for_ctor ~typing_env_at_use = function
| Not_a_constant_constructor ->
EPA.Extra_arg.Already_in_scope
(Simple.untagged_const_int (Targetint_31_63.of_int 0))
| Maybe_constant_constructor { arg_being_unboxed; _ } -> (
match type_of_arg_being_unboxed arg_being_unboxed with
| None ->
EPA.Extra_arg.Already_in_scope
(Simple.untagged_const_int (Targetint_31_63.of_int 0))
| Some arg_type -> (
match
T.meet_tagging_of_simple typing_env_at_use
~min_name_mode:Name_mode.normal arg_type
with
| Known_result simple -> EPA.Extra_arg.Already_in_scope simple
| Need_meet -> prevent_current_unboxing ()
| Invalid ->
(* [Invalid] this means that we are in an impossible-to-reach case, and
thus as in other cases, we only need to provide well-kinded
values. *)
EPA.Extra_arg.Already_in_scope
(Simple.untagged_const_int (Targetint_31_63.of_int 0))))
let extra_args_for_const_ctor_of_variant
(const_ctors_decision : U.const_ctors_decision) ~typing_env_at_use
rewrite_id variant_arg : U.const_ctors_decision =
match const_ctors_decision with
| Zero -> (
match variant_arg with
| Not_a_constant_constructor -> const_ctors_decision
| Maybe_constant_constructor _ ->
Misc.fatal_errorf
"The unboxed variant parameter was determined to have no constant \
cases when deciding to unbox it (using the parameter type), but at \
the use site, it is a constant constructor.")
| At_least_one { ctor = Do_not_unbox reason; is_int } ->
let is_int =
Extra_param_and_args.update_param_args is_int rewrite_id
(extra_arg_for_is_int variant_arg)
in
At_least_one { ctor = Do_not_unbox reason; is_int }
| At_least_one { ctor = Unbox (Number (Naked_immediate, ctor)); is_int } -> (
let is_int =
Extra_param_and_args.update_param_args is_int rewrite_id
(extra_arg_for_is_int variant_arg)
in
try
let ctor =
Extra_param_and_args.update_param_args ctor rewrite_id
(extra_arg_for_ctor ~typing_env_at_use variant_arg)
in
At_least_one { ctor = Unbox (Number (Naked_immediate, ctor)); is_int }
with Prevent_current_unboxing ->
At_least_one { ctor = Do_not_unbox Not_enough_information_at_use; is_int }
)
| At_least_one
{ ctor =
Unbox
( Unique_tag_and_size _ | Variant _ | Closure_single_entry _
| Number
((Naked_float | Naked_int32 | Naked_int64 | Naked_nativeint), _)
);
is_int = _
} ->
Misc.fatal_errorf
"Bad kind for unboxing the constant constructor of a variant"
(* Helpers for the number case *)
(* *************************** *)
let compute_extra_arg_for_number kind unboxer epa rewrite_id ~typing_env_at_use
arg_being_unboxed : U.decision =
let extra_arg, _new_arg_being_unboxed =
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
in
let epa = Extra_param_and_args.update_param_args epa rewrite_id extra_arg in
Unbox (Number (kind, epa))
(* Recursive descent on decisions *)
(* ****************************** *)
let rec compute_extra_args_for_one_decision_and_use ~(pass : U.pass) rewrite_id
~typing_env_at_use arg_being_unboxed decision : U.decision =
try
compute_extra_args_for_one_decision_and_use_aux ~pass rewrite_id
~typing_env_at_use arg_being_unboxed decision
with Prevent_current_unboxing -> (
match pass with
| Filter -> Do_not_unbox Not_enough_information_at_use
| Compute_all_extra_args ->
Misc.fatal_errorf "This case should have been filtered out before.")
and compute_extra_args_for_one_decision_and_use_aux ~(pass : U.pass) rewrite_id
~typing_env_at_use arg_being_unboxed (decision : U.decision) : U.decision =
match decision with
| Do_not_unbox _ -> decision
| Unbox (Unique_tag_and_size { tag; fields }) ->
compute_extra_args_for_block ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed tag fields
| Unbox (Closure_single_entry { function_slot; vars_within_closure }) ->
compute_extra_args_for_closure ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed function_slot vars_within_closure
| Unbox
(Variant { tag; const_ctors = const_ctors_from_decision; fields_by_tag })
-> (
let invalid () =
Invalid here means that the Apply_cont is unreachable , i.e. the args we
generated will never be actually used at runtime , so the values of the
args do not matter , they are here to make the kind checker happy .
generated will never be actually used at runtime, so the values of the
args do not matter, they are here to make the kind checker happy. *)
compute_extra_args_for_variant ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed ~tag_from_decision:tag ~const_ctors_from_decision
~fields_by_tag_from_decision:fields_by_tag
~const_ctors_at_use:(Or_unknown.Known Targetint_31_63.Set.empty)
~non_const_ctors_with_sizes_at_use:Tag.Scannable.Map.empty
in
match type_of_arg_being_unboxed arg_being_unboxed with
| None -> invalid ()
| Some arg_type -> (
match T.meet_variant_like typing_env_at_use arg_type with
| Need_meet -> prevent_current_unboxing ()
| Invalid -> invalid ()
| Known_result { const_ctors; non_const_ctors_with_sizes } ->
compute_extra_args_for_variant ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed ~tag_from_decision:tag ~const_ctors_from_decision
~fields_by_tag_from_decision:fields_by_tag
~const_ctors_at_use:const_ctors
~non_const_ctors_with_sizes_at_use:non_const_ctors_with_sizes))
| Unbox (Number (Naked_float, epa)) ->
compute_extra_arg_for_number Naked_float Unboxers.Float.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_int32, epa)) ->
compute_extra_arg_for_number Naked_int32 Unboxers.Int32.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_int64, epa)) ->
compute_extra_arg_for_number Naked_int64 Unboxers.Int64.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_nativeint, epa)) ->
compute_extra_arg_for_number Naked_nativeint Unboxers.Nativeint.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_immediate, epa)) ->
compute_extra_arg_for_number Naked_immediate Unboxers.Immediate.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
and compute_extra_args_for_block ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed tag fields : U.decision =
let size = Or_unknown.Known (Targetint_31_63.of_int (List.length fields)) in
let bak, invalid_const =
if Tag.equal tag Tag.double_array_tag
then
( P.Block_access_kind.Naked_floats { size },
Const.naked_float Numeric_types.Float_by_bit_pattern.zero )
else
( P.Block_access_kind.Values
{ size;
tag = Known (Option.get (Tag.Scannable.of_tag tag));
field_kind = Any_value
},
Const.const_zero )
in
let _, fields =
List.fold_left_map
(fun field_nth ({ epa; decision; kind } : U.field_decision) :
(_ * U.field_decision) ->
let unboxer =
Unboxers.Field.unboxer ~invalid_const bak ~index:field_nth
in
let new_extra_arg, new_arg_being_unboxed =
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
in
let epa =
Extra_param_and_args.update_param_args epa rewrite_id new_extra_arg
in
let decision =
compute_extra_args_for_one_decision_and_use ~pass rewrite_id
~typing_env_at_use new_arg_being_unboxed decision
in
Targetint_31_63.(add one field_nth), { epa; decision; kind })
Targetint_31_63.zero fields
in
Unbox (Unique_tag_and_size { tag; fields })
and compute_extra_args_for_closure ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed function_slot vars_within_closure : U.decision =
let vars_within_closure =
Value_slot.Map.mapi
(fun var ({ epa; decision; kind } : U.field_decision) : U.field_decision ->
let unboxer = Unboxers.Closure_field.unboxer function_slot var kind in
let new_extra_arg, new_arg_being_unboxed =
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
in
let epa =
Extra_param_and_args.update_param_args epa rewrite_id new_extra_arg
in
let decision =
compute_extra_args_for_one_decision_and_use ~pass rewrite_id
~typing_env_at_use new_arg_being_unboxed decision
in
{ epa; decision; kind })
vars_within_closure
in
Unbox (Closure_single_entry { function_slot; vars_within_closure })
and compute_extra_args_for_variant ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed ~tag_from_decision ~const_ctors_from_decision
~fields_by_tag_from_decision ~const_ctors_at_use
~non_const_ctors_with_sizes_at_use : U.decision =
let are_there_const_ctors_at_use =
match (const_ctors_at_use : _ Or_unknown.t) with
| Unknown -> true
| Known set -> not (Targetint_31_63.Set.is_empty set)
in
let are_there_non_const_ctors_at_use =
not (Tag.Scannable.Map.is_empty non_const_ctors_with_sizes_at_use)
in
let const_ctors =
if not are_there_const_ctors_at_use
then
extra_args_for_const_ctor_of_variant const_ctors_from_decision
~typing_env_at_use rewrite_id Not_a_constant_constructor
else if not are_there_non_const_ctors_at_use
then
extra_args_for_const_ctor_of_variant const_ctors_from_decision
~typing_env_at_use rewrite_id
(Maybe_constant_constructor
{ arg_being_unboxed; is_int = Simple.untagged_const_true })
else
CR - someday gbury : one might want to try and use the cse at use to allow
unboxing when the tag is not known statically but can be recovered
through the cse .
unboxing when the tag is not known statically but can be recovered
through the cse. *)
prevent_current_unboxing ()
in
let tag_at_use_site =
if not are_there_non_const_ctors_at_use
then Tag.Scannable.zero
else
match
Tag.Scannable.Map.get_singleton non_const_ctors_with_sizes_at_use
with
| None -> prevent_current_unboxing ()
| Some (tag, _) -> tag
in
let tag_extra_arg =
tag_at_use_site |> Tag.Scannable.to_targetint
|> Targetint_31_63.of_targetint |> Const.untagged_const_int |> Simple.const
|> fun x -> EPA.Extra_arg.Already_in_scope x
in
let tag =
Extra_param_and_args.update_param_args tag_from_decision rewrite_id
tag_extra_arg
in
let fields_by_tag =
Tag.Scannable.Map.mapi
(fun tag_decision block_fields ->
let size = List.length block_fields in
(* See doc/unboxing.md about invalid constants, poison and aliases. *)
let invalid_const = Const.const_int (Targetint_31_63.of_int 0xbaba) in
let bak : Flambda_primitive.Block_access_kind.t =
Values
{ size = Known (Targetint_31_63.of_int size);
tag = Known tag_decision;
field_kind = Any_value
}
in
let new_fields_decisions, _ =
List.fold_left
(fun (new_decisions, field_nth)
({ epa; decision; kind } : U.field_decision) ->
let new_extra_arg, new_arg_being_unboxed =
if are_there_non_const_ctors_at_use
&& Tag.Scannable.equal tag_at_use_site tag_decision
then
let unboxer =
Unboxers.Field.unboxer ~invalid_const bak ~index:field_nth
in
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
else
( EPA.Extra_arg.Already_in_scope (Simple.const invalid_const),
Poison )
in
let epa =
Extra_param_and_args.update_param_args epa rewrite_id
new_extra_arg
in
let decision =
compute_extra_args_for_one_decision_and_use ~pass rewrite_id
~typing_env_at_use new_arg_being_unboxed decision
in
let field_decision : U.field_decision = { epa; decision; kind } in
let new_decisions = field_decision :: new_decisions in
new_decisions, Targetint_31_63.(add one field_nth))
([], Targetint_31_63.zero) block_fields
in
List.rev new_fields_decisions)
fields_by_tag_from_decision
in
Unbox (Variant { tag; const_ctors; fields_by_tag })
let add_extra_params_and_args extra_params_and_args decision =
let rec aux extra_params_and_args (decision : U.decision) =
match decision with
| Do_not_unbox _ -> extra_params_and_args
| Unbox (Unique_tag_and_size { tag = _; fields }) ->
List.fold_left
(fun extra_params_and_args ({ epa; decision; kind } : U.field_decision) ->
let extra_param = BP.create epa.param kind in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param ~extra_args:epa.args
in
aux extra_params_and_args decision)
extra_params_and_args fields
| Unbox (Closure_single_entry { function_slot = _; vars_within_closure }) ->
Value_slot.Map.fold
(fun _ ({ epa; decision; kind } : U.field_decision)
extra_params_and_args ->
let extra_param = BP.create epa.param kind in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param ~extra_args:epa.args
in
aux extra_params_and_args decision)
vars_within_closure extra_params_and_args
| Unbox (Variant { tag; const_ctors; fields_by_tag }) ->
let extra_params_and_args =
Tag.Scannable.Map.fold
(fun _ block_fields extra_params_and_args ->
List.fold_left
(fun extra_params_and_args
({ epa; decision; kind } : U.field_decision) ->
let extra_param = BP.create epa.param kind in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param
~extra_args:epa.args
in
aux extra_params_and_args decision)
extra_params_and_args block_fields)
fields_by_tag extra_params_and_args
in
let extra_params_and_args =
match const_ctors with
| Zero -> extra_params_and_args
| At_least_one { is_int; ctor = Do_not_unbox _; _ } ->
let extra_param =
BP.create is_int.param K.With_subkind.naked_immediate
in
EPA.add extra_params_and_args ~extra_param ~extra_args:is_int.args
| At_least_one { is_int; ctor = Unbox (Number (Naked_immediate, ctor)) }
->
let extra_param =
BP.create is_int.param K.With_subkind.naked_immediate
in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param ~extra_args:is_int.args
in
let extra_param =
BP.create ctor.param K.With_subkind.naked_immediate
in
EPA.add extra_params_and_args ~extra_param ~extra_args:ctor.args
| At_least_one
{ ctor =
Unbox
( Unique_tag_and_size _ | Variant _ | Closure_single_entry _
| Number
( ( Naked_float | Naked_int32 | Naked_int64
| Naked_nativeint ),
_ ) );
is_int = _
} ->
Misc.fatal_errorf
"Trying to unbox the constant constructor of a variant with a kind \
other than Naked_immediate."
in
let extra_param = BP.create tag.param K.With_subkind.naked_immediate in
EPA.add extra_params_and_args ~extra_param ~extra_args:tag.args
| Unbox (Number (naked_number_kind, epa)) ->
let kind_with_subkind =
K.With_subkind.of_naked_number_kind naked_number_kind
in
let extra_param = BP.create epa.param kind_with_subkind in
EPA.add extra_params_and_args ~extra_param ~extra_args:epa.args
in
aux extra_params_and_args decision
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/089504f86099bbf7402cbffeeb5e5295eae6d5f6/middle_end/flambda2/simplify/unboxing/unboxing_epa.ml | ocaml | ************************************************************************
OCaml
Copyright 2013--2020 OCamlPro SAS
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
used for recursive calls
Helpers for the variant case
****************************
[Invalid] this means that we are in an impossible-to-reach case, and
thus as in other cases, we only need to provide well-kinded
values.
Helpers for the number case
***************************
Recursive descent on decisions
******************************
See doc/unboxing.md about invalid constants, poison and aliases. | , OCamlPro
and ,
Copyright 2014 - -2020 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
open! Simplify_import
module U = Unboxing_types
module Extra_param_and_args = U.Extra_param_and_args
exception Prevent_current_unboxing
let prevent_current_unboxing () = raise Prevent_current_unboxing
type unboxed_arg =
| Available of Simple.t
| Generated of Variable.t
| Added_by_wrapper_at_rewrite_use of { nth_arg : int }
let _print_unboxed_arg ppf = function
| Poison -> Format.fprintf ppf "poison"
| Available simple -> Format.fprintf ppf "simple: %a" Simple.print simple
| Generated v -> Format.fprintf ppf "generated: %a" Variable.print v
| Added_by_wrapper_at_rewrite_use { nth_arg } ->
Format.fprintf ppf "added_by_wrapper(%d)" nth_arg
let type_of_arg_being_unboxed unboxed_arg =
match unboxed_arg with
| Poison -> None
| Available simple -> Some (T.alias_type_of K.value simple)
| Generated _ -> Some (T.unknown K.value)
| Added_by_wrapper_at_rewrite_use _ -> prevent_current_unboxing ()
let unbox_arg (unboxer : Unboxers.unboxer) ~typing_env_at_use arg_being_unboxed
=
match arg_being_unboxed with
| Poison ->
let extra_arg =
EPA.Extra_arg.Already_in_scope (Simple.const unboxer.invalid_const)
in
extra_arg, Poison
| Available arg_at_use -> (
let arg_type = T.alias_type_of K.value arg_at_use in
match
unboxer.prove_simple typing_env_at_use arg_type
~min_name_mode:Name_mode.normal
with
| Known_result simple ->
EPA.Extra_arg.Already_in_scope simple, Available simple
| Invalid ->
let extra_arg =
EPA.Extra_arg.Already_in_scope (Simple.const unboxer.invalid_const)
in
extra_arg, Poison
| Need_meet ->
let var = Variable.create unboxer.var_name in
let prim = unboxer.unboxing_prim arg_at_use in
let extra_arg = EPA.Extra_arg.New_let_binding (var, prim) in
extra_arg, Generated var)
| Generated var ->
let arg_at_use = Simple.var var in
let var = Variable.create unboxer.var_name in
let prim = unboxer.unboxing_prim arg_at_use in
let extra_arg = EPA.Extra_arg.New_let_binding (var, prim) in
extra_arg, Generated var
| Added_by_wrapper_at_rewrite_use { nth_arg } ->
let var = Variable.create "unboxed_field" in
( EPA.Extra_arg.New_let_binding_with_named_args
( var,
fun args ->
let arg_simple = List.nth args nth_arg in
unboxer.unboxing_prim arg_simple ),
Generated var )
type variant_argument =
| Not_a_constant_constructor
| Maybe_constant_constructor of
{ is_int : Simple.t;
arg_being_unboxed : unboxed_arg
}
let extra_arg_for_is_int = function
| Maybe_constant_constructor { is_int; _ } ->
EPA.Extra_arg.Already_in_scope is_int
| Not_a_constant_constructor ->
EPA.Extra_arg.Already_in_scope Simple.untagged_const_false
let extra_arg_for_ctor ~typing_env_at_use = function
| Not_a_constant_constructor ->
EPA.Extra_arg.Already_in_scope
(Simple.untagged_const_int (Targetint_31_63.of_int 0))
| Maybe_constant_constructor { arg_being_unboxed; _ } -> (
match type_of_arg_being_unboxed arg_being_unboxed with
| None ->
EPA.Extra_arg.Already_in_scope
(Simple.untagged_const_int (Targetint_31_63.of_int 0))
| Some arg_type -> (
match
T.meet_tagging_of_simple typing_env_at_use
~min_name_mode:Name_mode.normal arg_type
with
| Known_result simple -> EPA.Extra_arg.Already_in_scope simple
| Need_meet -> prevent_current_unboxing ()
| Invalid ->
EPA.Extra_arg.Already_in_scope
(Simple.untagged_const_int (Targetint_31_63.of_int 0))))
let extra_args_for_const_ctor_of_variant
(const_ctors_decision : U.const_ctors_decision) ~typing_env_at_use
rewrite_id variant_arg : U.const_ctors_decision =
match const_ctors_decision with
| Zero -> (
match variant_arg with
| Not_a_constant_constructor -> const_ctors_decision
| Maybe_constant_constructor _ ->
Misc.fatal_errorf
"The unboxed variant parameter was determined to have no constant \
cases when deciding to unbox it (using the parameter type), but at \
the use site, it is a constant constructor.")
| At_least_one { ctor = Do_not_unbox reason; is_int } ->
let is_int =
Extra_param_and_args.update_param_args is_int rewrite_id
(extra_arg_for_is_int variant_arg)
in
At_least_one { ctor = Do_not_unbox reason; is_int }
| At_least_one { ctor = Unbox (Number (Naked_immediate, ctor)); is_int } -> (
let is_int =
Extra_param_and_args.update_param_args is_int rewrite_id
(extra_arg_for_is_int variant_arg)
in
try
let ctor =
Extra_param_and_args.update_param_args ctor rewrite_id
(extra_arg_for_ctor ~typing_env_at_use variant_arg)
in
At_least_one { ctor = Unbox (Number (Naked_immediate, ctor)); is_int }
with Prevent_current_unboxing ->
At_least_one { ctor = Do_not_unbox Not_enough_information_at_use; is_int }
)
| At_least_one
{ ctor =
Unbox
( Unique_tag_and_size _ | Variant _ | Closure_single_entry _
| Number
((Naked_float | Naked_int32 | Naked_int64 | Naked_nativeint), _)
);
is_int = _
} ->
Misc.fatal_errorf
"Bad kind for unboxing the constant constructor of a variant"
let compute_extra_arg_for_number kind unboxer epa rewrite_id ~typing_env_at_use
arg_being_unboxed : U.decision =
let extra_arg, _new_arg_being_unboxed =
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
in
let epa = Extra_param_and_args.update_param_args epa rewrite_id extra_arg in
Unbox (Number (kind, epa))
let rec compute_extra_args_for_one_decision_and_use ~(pass : U.pass) rewrite_id
~typing_env_at_use arg_being_unboxed decision : U.decision =
try
compute_extra_args_for_one_decision_and_use_aux ~pass rewrite_id
~typing_env_at_use arg_being_unboxed decision
with Prevent_current_unboxing -> (
match pass with
| Filter -> Do_not_unbox Not_enough_information_at_use
| Compute_all_extra_args ->
Misc.fatal_errorf "This case should have been filtered out before.")
and compute_extra_args_for_one_decision_and_use_aux ~(pass : U.pass) rewrite_id
~typing_env_at_use arg_being_unboxed (decision : U.decision) : U.decision =
match decision with
| Do_not_unbox _ -> decision
| Unbox (Unique_tag_and_size { tag; fields }) ->
compute_extra_args_for_block ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed tag fields
| Unbox (Closure_single_entry { function_slot; vars_within_closure }) ->
compute_extra_args_for_closure ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed function_slot vars_within_closure
| Unbox
(Variant { tag; const_ctors = const_ctors_from_decision; fields_by_tag })
-> (
let invalid () =
Invalid here means that the Apply_cont is unreachable , i.e. the args we
generated will never be actually used at runtime , so the values of the
args do not matter , they are here to make the kind checker happy .
generated will never be actually used at runtime, so the values of the
args do not matter, they are here to make the kind checker happy. *)
compute_extra_args_for_variant ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed ~tag_from_decision:tag ~const_ctors_from_decision
~fields_by_tag_from_decision:fields_by_tag
~const_ctors_at_use:(Or_unknown.Known Targetint_31_63.Set.empty)
~non_const_ctors_with_sizes_at_use:Tag.Scannable.Map.empty
in
match type_of_arg_being_unboxed arg_being_unboxed with
| None -> invalid ()
| Some arg_type -> (
match T.meet_variant_like typing_env_at_use arg_type with
| Need_meet -> prevent_current_unboxing ()
| Invalid -> invalid ()
| Known_result { const_ctors; non_const_ctors_with_sizes } ->
compute_extra_args_for_variant ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed ~tag_from_decision:tag ~const_ctors_from_decision
~fields_by_tag_from_decision:fields_by_tag
~const_ctors_at_use:const_ctors
~non_const_ctors_with_sizes_at_use:non_const_ctors_with_sizes))
| Unbox (Number (Naked_float, epa)) ->
compute_extra_arg_for_number Naked_float Unboxers.Float.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_int32, epa)) ->
compute_extra_arg_for_number Naked_int32 Unboxers.Int32.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_int64, epa)) ->
compute_extra_arg_for_number Naked_int64 Unboxers.Int64.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_nativeint, epa)) ->
compute_extra_arg_for_number Naked_nativeint Unboxers.Nativeint.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
| Unbox (Number (Naked_immediate, epa)) ->
compute_extra_arg_for_number Naked_immediate Unboxers.Immediate.unboxer epa
rewrite_id ~typing_env_at_use arg_being_unboxed
and compute_extra_args_for_block ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed tag fields : U.decision =
let size = Or_unknown.Known (Targetint_31_63.of_int (List.length fields)) in
let bak, invalid_const =
if Tag.equal tag Tag.double_array_tag
then
( P.Block_access_kind.Naked_floats { size },
Const.naked_float Numeric_types.Float_by_bit_pattern.zero )
else
( P.Block_access_kind.Values
{ size;
tag = Known (Option.get (Tag.Scannable.of_tag tag));
field_kind = Any_value
},
Const.const_zero )
in
let _, fields =
List.fold_left_map
(fun field_nth ({ epa; decision; kind } : U.field_decision) :
(_ * U.field_decision) ->
let unboxer =
Unboxers.Field.unboxer ~invalid_const bak ~index:field_nth
in
let new_extra_arg, new_arg_being_unboxed =
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
in
let epa =
Extra_param_and_args.update_param_args epa rewrite_id new_extra_arg
in
let decision =
compute_extra_args_for_one_decision_and_use ~pass rewrite_id
~typing_env_at_use new_arg_being_unboxed decision
in
Targetint_31_63.(add one field_nth), { epa; decision; kind })
Targetint_31_63.zero fields
in
Unbox (Unique_tag_and_size { tag; fields })
and compute_extra_args_for_closure ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed function_slot vars_within_closure : U.decision =
let vars_within_closure =
Value_slot.Map.mapi
(fun var ({ epa; decision; kind } : U.field_decision) : U.field_decision ->
let unboxer = Unboxers.Closure_field.unboxer function_slot var kind in
let new_extra_arg, new_arg_being_unboxed =
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
in
let epa =
Extra_param_and_args.update_param_args epa rewrite_id new_extra_arg
in
let decision =
compute_extra_args_for_one_decision_and_use ~pass rewrite_id
~typing_env_at_use new_arg_being_unboxed decision
in
{ epa; decision; kind })
vars_within_closure
in
Unbox (Closure_single_entry { function_slot; vars_within_closure })
and compute_extra_args_for_variant ~pass rewrite_id ~typing_env_at_use
arg_being_unboxed ~tag_from_decision ~const_ctors_from_decision
~fields_by_tag_from_decision ~const_ctors_at_use
~non_const_ctors_with_sizes_at_use : U.decision =
let are_there_const_ctors_at_use =
match (const_ctors_at_use : _ Or_unknown.t) with
| Unknown -> true
| Known set -> not (Targetint_31_63.Set.is_empty set)
in
let are_there_non_const_ctors_at_use =
not (Tag.Scannable.Map.is_empty non_const_ctors_with_sizes_at_use)
in
let const_ctors =
if not are_there_const_ctors_at_use
then
extra_args_for_const_ctor_of_variant const_ctors_from_decision
~typing_env_at_use rewrite_id Not_a_constant_constructor
else if not are_there_non_const_ctors_at_use
then
extra_args_for_const_ctor_of_variant const_ctors_from_decision
~typing_env_at_use rewrite_id
(Maybe_constant_constructor
{ arg_being_unboxed; is_int = Simple.untagged_const_true })
else
CR - someday gbury : one might want to try and use the cse at use to allow
unboxing when the tag is not known statically but can be recovered
through the cse .
unboxing when the tag is not known statically but can be recovered
through the cse. *)
prevent_current_unboxing ()
in
let tag_at_use_site =
if not are_there_non_const_ctors_at_use
then Tag.Scannable.zero
else
match
Tag.Scannable.Map.get_singleton non_const_ctors_with_sizes_at_use
with
| None -> prevent_current_unboxing ()
| Some (tag, _) -> tag
in
let tag_extra_arg =
tag_at_use_site |> Tag.Scannable.to_targetint
|> Targetint_31_63.of_targetint |> Const.untagged_const_int |> Simple.const
|> fun x -> EPA.Extra_arg.Already_in_scope x
in
let tag =
Extra_param_and_args.update_param_args tag_from_decision rewrite_id
tag_extra_arg
in
let fields_by_tag =
Tag.Scannable.Map.mapi
(fun tag_decision block_fields ->
let size = List.length block_fields in
let invalid_const = Const.const_int (Targetint_31_63.of_int 0xbaba) in
let bak : Flambda_primitive.Block_access_kind.t =
Values
{ size = Known (Targetint_31_63.of_int size);
tag = Known tag_decision;
field_kind = Any_value
}
in
let new_fields_decisions, _ =
List.fold_left
(fun (new_decisions, field_nth)
({ epa; decision; kind } : U.field_decision) ->
let new_extra_arg, new_arg_being_unboxed =
if are_there_non_const_ctors_at_use
&& Tag.Scannable.equal tag_at_use_site tag_decision
then
let unboxer =
Unboxers.Field.unboxer ~invalid_const bak ~index:field_nth
in
unbox_arg unboxer ~typing_env_at_use arg_being_unboxed
else
( EPA.Extra_arg.Already_in_scope (Simple.const invalid_const),
Poison )
in
let epa =
Extra_param_and_args.update_param_args epa rewrite_id
new_extra_arg
in
let decision =
compute_extra_args_for_one_decision_and_use ~pass rewrite_id
~typing_env_at_use new_arg_being_unboxed decision
in
let field_decision : U.field_decision = { epa; decision; kind } in
let new_decisions = field_decision :: new_decisions in
new_decisions, Targetint_31_63.(add one field_nth))
([], Targetint_31_63.zero) block_fields
in
List.rev new_fields_decisions)
fields_by_tag_from_decision
in
Unbox (Variant { tag; const_ctors; fields_by_tag })
let add_extra_params_and_args extra_params_and_args decision =
let rec aux extra_params_and_args (decision : U.decision) =
match decision with
| Do_not_unbox _ -> extra_params_and_args
| Unbox (Unique_tag_and_size { tag = _; fields }) ->
List.fold_left
(fun extra_params_and_args ({ epa; decision; kind } : U.field_decision) ->
let extra_param = BP.create epa.param kind in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param ~extra_args:epa.args
in
aux extra_params_and_args decision)
extra_params_and_args fields
| Unbox (Closure_single_entry { function_slot = _; vars_within_closure }) ->
Value_slot.Map.fold
(fun _ ({ epa; decision; kind } : U.field_decision)
extra_params_and_args ->
let extra_param = BP.create epa.param kind in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param ~extra_args:epa.args
in
aux extra_params_and_args decision)
vars_within_closure extra_params_and_args
| Unbox (Variant { tag; const_ctors; fields_by_tag }) ->
let extra_params_and_args =
Tag.Scannable.Map.fold
(fun _ block_fields extra_params_and_args ->
List.fold_left
(fun extra_params_and_args
({ epa; decision; kind } : U.field_decision) ->
let extra_param = BP.create epa.param kind in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param
~extra_args:epa.args
in
aux extra_params_and_args decision)
extra_params_and_args block_fields)
fields_by_tag extra_params_and_args
in
let extra_params_and_args =
match const_ctors with
| Zero -> extra_params_and_args
| At_least_one { is_int; ctor = Do_not_unbox _; _ } ->
let extra_param =
BP.create is_int.param K.With_subkind.naked_immediate
in
EPA.add extra_params_and_args ~extra_param ~extra_args:is_int.args
| At_least_one { is_int; ctor = Unbox (Number (Naked_immediate, ctor)) }
->
let extra_param =
BP.create is_int.param K.With_subkind.naked_immediate
in
let extra_params_and_args =
EPA.add extra_params_and_args ~extra_param ~extra_args:is_int.args
in
let extra_param =
BP.create ctor.param K.With_subkind.naked_immediate
in
EPA.add extra_params_and_args ~extra_param ~extra_args:ctor.args
| At_least_one
{ ctor =
Unbox
( Unique_tag_and_size _ | Variant _ | Closure_single_entry _
| Number
( ( Naked_float | Naked_int32 | Naked_int64
| Naked_nativeint ),
_ ) );
is_int = _
} ->
Misc.fatal_errorf
"Trying to unbox the constant constructor of a variant with a kind \
other than Naked_immediate."
in
let extra_param = BP.create tag.param K.With_subkind.naked_immediate in
EPA.add extra_params_and_args ~extra_param ~extra_args:tag.args
| Unbox (Number (naked_number_kind, epa)) ->
let kind_with_subkind =
K.With_subkind.of_naked_number_kind naked_number_kind
in
let extra_param = BP.create epa.param kind_with_subkind in
EPA.add extra_params_and_args ~extra_param ~extra_args:epa.args
in
aux extra_params_and_args decision
|
414790b66a0ab4d0be7ac991576ab8466d5c0ed31ba6309dcd9a18b80dcdd654 | clash-lang/clash-compiler | File.hs | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , Google Inc. ,
2019 , Myrtle Software Ltd ,
2021 - 2022 , QBayLogic B.V.
License : BSD2 ( see the file LICENSE )
Maintainer : QBayLogic B.V. < >
= Initializing a block RAM with a data file # usingramfiles #
Block RAM primitives that can be initialized with a data file . The BNF grammar
for this data file is simple :
@
FILE = LINE+
LINE = BIT+
BIT = ' 0 '
| ' 1 '
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example , a data file @memory.bin@ containing the 9 - bit unsigned numbers
@7@ to @13@ looks like :
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
Such a file can be produced with ' memFile ' :
@
writeFile " memory.bin " ( memFile Nothing [ 7 : : Unsigned 9 .. 13 ] )
@
We can instantiate a block RAM using the contents of the file above like so :
@
f : : KnownDomain dom
= > Clock dom
- > Enable dom
- > Signal dom ( Unsigned 3 )
- > Signal dom ( Unsigned 9 )
f clk en rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' ' blockRamFile ' clk en d7 \"memory.bin\ " rd ( signal Nothing )
@
In the example above , we basically treat the block RAM as a synchronous ROM .
We can see that it works as expected :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ f systemClockGen enableGen ( fromList [ 3 .. 5 ] ) _ _
[ 10,11,12 ]
@
However , we can also interpret the same data as a tuple of a 6 - bit unsigned
number , and a 3 - bit signed number :
@
g : : KnownDomain dom
= > Clock dom
- > Enable dom
- > Signal dom ( Unsigned 3 )
- > Signal dom ( Unsigned 6,Signed 3 )
g clk en rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' ' blockRamFile ' clk en d7 \"memory.bin\ " rd ( signal Nothing )
@
And then we would see :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ g systemClockGen enableGen ( fromList [ 3 .. 5 ] ) _ _
[ ( 1,2),(1,3)(1,-4 ) ]
@
Copyright : (C) 2015-2016, University of Twente,
2017 , Google Inc.,
2019 , Myrtle Software Ltd,
2021-2022, QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : QBayLogic B.V. <>
= Initializing a block RAM with a data file #usingramfiles#
Block RAM primitives that can be initialized with a data file. The BNF grammar
for this data file is simple:
@
FILE = LINE+
LINE = BIT+
BIT = '0'
| '1'
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example, a data file @memory.bin@ containing the 9-bit unsigned numbers
@7@ to @13@ looks like:
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
Such a file can be produced with 'memFile':
@
writeFile "memory.bin" (memFile Nothing [7 :: Unsigned 9 .. 13])
@
We can instantiate a block RAM using the contents of the file above like so:
@
f :: KnownDomain dom
=> Clock dom
-> Enable dom
-> Signal dom (Unsigned 3)
-> Signal dom (Unsigned 9)
f clk en rd = 'Clash.Class.BitPack.unpack' '<$>' 'blockRamFile' clk en d7 \"memory.bin\" rd (signal Nothing)
@
In the example above, we basically treat the block RAM as a synchronous ROM.
We can see that it works as expected:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ f systemClockGen enableGen (fromList [3..5])__
[10,11,12]
@
However, we can also interpret the same data as a tuple of a 6-bit unsigned
number, and a 3-bit signed number:
@
g :: KnownDomain dom
=> Clock dom
-> Enable dom
-> Signal dom (Unsigned 3)
-> Signal dom (Unsigned 6,Signed 3)
g clk en rd = 'Clash.Class.BitPack.unpack' '<$>' 'blockRamFile' clk en d7 \"memory.bin\" rd (signal Nothing)
@
And then we would see:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ g systemClockGen enableGen (fromList [3..5])__
[(1,2),(1,3)(1,-4)]
@
-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE Unsafe #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
{-# OPTIONS_HADDOCK show-extensions #-}
-- See: -lang/clash-compiler/commit/721fcfa9198925661cd836668705f817bddaae3c
-- as to why we need this.
# OPTIONS_GHC -fno - cpr - anal #
module Clash.Explicit.BlockRam.File
( -- * Block RAM synchronized to an arbitrary clock
blockRamFile
, blockRamFilePow2
-- * Producing files
, memFile
-- * Internal
, blockRamFile#
, initMem
)
where
import Control.Exception (catch, throw)
import Control.Monad (forM_)
import Control.Monad.ST (ST, runST)
import Control.Monad.ST.Unsafe (unsafeInterleaveST, unsafeIOToST, unsafeSTToIO)
import Data.Array.MArray (newArray_)
import Data.Bits ((.&.), (.|.), shiftL, xor)
import Data.Char (digitToInt)
import Data.Maybe (isJust, listToMaybe)
import GHC.Arr (STArray, unsafeReadSTArray, unsafeWriteSTArray)
import GHC.Stack (HasCallStack, withFrozenCallStack)
import GHC.TypeLits (KnownNat)
import Numeric (readInt)
import System.IO
import Clash.Annotations.Primitive (hasBlackBox)
import Clash.Class.BitPack (BitPack, BitSize, pack)
import Clash.Promoted.Nat (SNat (..), pow2SNat, natToNum, snatToNum)
import Clash.Sized.Internal.BitVector (Bit(..), BitVector(..), undefined#)
import Clash.Signal.Internal
(Clock(..), Signal (..), Enable, KnownDomain, fromEnable, (.&&.))
import Clash.Signal.Bundle (unbundle)
import Clash.Sized.Unsigned (Unsigned)
import Clash.XException (maybeIsX, seqX, fromJustX, NFDataX(..), XException (..))
-- start benchmark only
import ( unsafeFreezeSTArray , unsafeThawSTArray )
-- end benchmark only
-- $setup
-- >>> :m -Prelude
> > > : set -fplugin GHC.TypeLits .
> > > : set -fplugin GHC.TypeLits . KnownNat . Solver
> > > import Clash . Prelude
> > > import Clash . Prelude . BlockRam . File
| Create a block RAM with space for 2^@n@ elements
--
* _ _ NB _ _ : Read value is delayed by 1 cycle
-- * __NB__: Initial output value is /undefined/, reading it will throw an
-- 'XException'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- +----------------+----------+----------+---------------+
-- | | VHDL | Verilog | SystemVerilog |
-- +================+==========+==========+===============+
-- | Altera/Quartus | Broken | Works | Works |
-- +----------------+----------+----------+---------------+
-- | Xilinx/ISE | Works | Works | Works |
-- +----------------+----------+----------+---------------+
-- | ASIC | Untested | Untested | Untested |
-- +----------------+----------+----------+---------------+
--
-- === See also:
--
-- * See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a
block RAM .
* Use the adapter ' Clash . Explicit . BlockRam.readNew ' for obtaining write - before - read semantics like this : . Explicit . ' clk rst en ( blockRamFilePow2 ' clk en file ) rd wrM@.
* See " Clash . Explicit . BlockRam . File#usingramfiles " for more information on how
to instantiate a block RAM with the contents of a data file .
* See ' memFile ' for creating a data file with Clash .
-- * See "Clash.Explicit.Fixed#creatingdatafiles" for more ideas on how to
-- create your own data files.
blockRamFilePow2
:: forall dom n m
. (KnownDomain dom, KnownNat m, KnownNat n, HasCallStack)
=> Clock dom
-- ^ 'Clock' to synchronize to
-> Enable dom
-- ^ 'Enable' line
-> FilePath
^ File describing the initial content of the
-> Signal dom (Unsigned n)
-- ^ Read address @r@
-> Signal dom (Maybe (Unsigned n, BitVector m))
-- ^ (write address @w@, value to write)
-> Signal dom (BitVector m)
^ Value of the at address @r@ from the previous clock cycle
blockRamFilePow2 = \clk en file rd wrM -> withFrozenCallStack
(blockRamFile clk en (pow2SNat (SNat @n)) file rd wrM)
# INLINE blockRamFilePow2 #
| Create a block RAM with space for @n@ elements
--
* _ _ NB _ _ : Read value is delayed by 1 cycle
-- * __NB__: Initial output value is /undefined/, reading it will throw an
-- 'XException'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- +----------------+----------+----------+---------------+
-- | | VHDL | Verilog | SystemVerilog |
-- +================+==========+==========+===============+
-- | Altera/Quartus | Broken | Works | Works |
-- +----------------+----------+----------+---------------+
-- | Xilinx/ISE | Works | Works | Works |
-- +----------------+----------+----------+---------------+
-- | ASIC | Untested | Untested | Untested |
-- +----------------+----------+----------+---------------+
--
-- === See also:
--
-- * See "Clash.Explicit.BlockRam#usingrams" for more information on how to use a
block RAM .
* Use the adapter ' Clash . Explicit . BlockRam.readNew ' for obtaining write - before - read semantics like this : . Explicit . ' clk rst en ( ' blockRamFile ' clk en size file ) rd wrM@.
* See " Clash . Explicit . BlockRam . File#usingramfiles " for more information on how
to instantiate a block RAM with the contents of a data file .
* See ' memFile ' for creating a data file with Clash .
-- * See "Clash.Sized.Fixed#creatingdatafiles" for more ideas on how to create
-- your own data files.
blockRamFile
:: (KnownDomain dom, KnownNat m, Enum addr, NFDataX addr, HasCallStack)
=> Clock dom
-- ^ 'Clock' to synchronize to
-> Enable dom
-- ^ 'Enable' line
-> SNat n
^ Size of the
-> FilePath
^ File describing the initial content of the
-> Signal dom addr
-- ^ Read address @r@
-> Signal dom (Maybe (addr, BitVector m))
-- ^ (write address @w@, value to write)
-> Signal dom (BitVector m)
^ Value of the at address @r@ from the previous clock cycle
blockRamFile = \clk gen sz file rd wrM ->
let en = isJust <$> wrM
(wr,din) = unbundle (fromJustX <$> wrM)
in withFrozenCallStack
(blockRamFile# clk gen sz file (fromEnum <$> rd) en (fromEnum <$> wr) din)
# INLINE blockRamFile #
-- | Convert data to the 'String' contents of a memory file.
--
-- * __NB__: Not synthesizable
-- * The following document the several ways to instantiate components with
-- files:
--
* " Clash . Prelude . BlockRam . File#usingramfiles "
* " Clash . Prelude . ROM.File#usingromfiles "
* " Clash . Explicit . BlockRam . File#usingramfiles "
-- * "Clash.Explicit.ROM.File#usingromfiles"
--
-- * See "Clash.Sized.Fixed#creatingdatafiles" for more ideas on how to create
-- your own data files.
--
-- = Example
--
The @Maybe@ datatype has do n't care bits , where the actual value does not
matter . But the bits need a defined value in the memory . Either 0 or 1 can be
-- used, and both are valid representations of the data.
--
> > > let es = [ Nothing , Just ( 7 : : Unsigned 8) , Just 8 ]
-- >>> mapM_ (putStrLn . show . pack) es
0b0 _ .... _ ....
0b1_0000_0111
0b1_0000_1000
-- >>> putStr (memFile (Just 0) es)
000000000
100000111
100001000
-- >>> putStr (memFile (Just 1) es)
011111111
100000111
100001000
--
memFile
:: forall a f
. ( BitPack a
, Foldable f
, HasCallStack)
=> Maybe Bit
-- ^ Value to map don't care bits to. 'Nothing' means throwing an error on
-- don't care bits.
-> f a
-- ^ Values to convert
-> String
-- ^ Contents of the memory file
memFile care = foldr (\e -> showsBV $ pack e) ""
where
showsBV :: BitVector (BitSize a) -> String -> String
showsBV (BV mask val) s =
if n == 0 then
'0' : '\n' : s
else
case care of
Just (Bit 0 0) -> go n (val .&. (mask `xor` fullMask)) ('\n' : s)
Just (Bit 0 1) -> go n (val .|. mask) ('\n' : s)
_ -> if mask /= 0 then
err
else
go n val ('\n' : s)
where
n = natToNum @(BitSize a) @Int
fullMask = (1 `shiftL` n) - 1
err = withFrozenCallStack $ error $
"memFile: cannot convert don't-care values. "
++ "Please specify mapping to definite value."
go 0 _ s0 = s0
go n0 v s0 =
let (!v0, !vBit) = quotRem v 2
in if vBit == 0 then
go (n0 - 1) v0 $ '0' : s0
else
go (n0 - 1) v0 $ '1' : s0
-- | blockRamFile primitive
blockRamFile#
:: forall m dom n
. (KnownDomain dom, KnownNat m, HasCallStack)
=> Clock dom
-- ^ 'Clock' to synchronize to
-> Enable dom
-- ^ 'Enable' line
-> SNat n
^ Size of the
-> FilePath
^ File describing the initial content of the
-> Signal dom Int
-- ^ Read address @r@
-> Signal dom Bool
-- ^ Write enable
-> Signal dom Int
-- ^ Write address @w@
-> Signal dom (BitVector m)
-- ^ Value to write (at address @w@)
-> Signal dom (BitVector m)
^ Value of the at address @r@ from the previous clock cycle
blockRamFile# (Clock _ Nothing) ena sz file = \rd wen waS wd -> runST $ do
ramStart <- newArray_ (0,szI)
unsafeIOToST (withFile file ReadMode (\h ->
forM_ [0..(szI-1)] (\i -> do
l <- hGetLine h
let bv = parseBV l
bv `seq` unsafeSTToIO (unsafeWriteSTArray ramStart i bv)
)))
-- start benchmark only
< - unsafeThawSTArray ramArr
-- end benchmark only
go
ramStart
(withFrozenCallStack (deepErrorX "blockRamFile: intial value undefined"))
(fromEnable ena)
rd
(fromEnable ena .&&. wen)
waS
wd
where
szI = snatToNum sz :: Int
-- start benchmark only
ramArr = runST $ do
ram < - newArray _ ( 0,szI-1 ) -- 0 -- ( error " QQ " )
-- unsafeIOToST (withFile file ReadMode (\h ->
-- forM_ [0..(szI-1)] (\i -> do
-- l <- hGetLine h
-- let bv = parseBV l
-- bv `seq` unsafeSTToIO (unsafeWriteSTArray ram i bv))
-- ))
-- unsafeFreezeSTArray ram
-- end benchmark only
go :: STArray s Int (BitVector m) -> (BitVector m) -> Signal dom Bool -> Signal dom Int
-> Signal dom Bool -> Signal dom Int -> Signal dom (BitVector m)
-> ST s (Signal dom (BitVector m))
go !ram o ret@(~(re :- res)) rt@(~(r :- rs)) et@(~(e :- en)) wt@(~(w :- wr)) dt@(~(d :- din)) = do
o `seqX` (o :-) <$> (ret `seq` rt `seq` et `seq` wt `seq` dt `seq`
unsafeInterleaveST
(do o' <- unsafeIOToST
(catch (if re then unsafeSTToIO (ram `safeAt` r) else pure o)
(\err@XException {} -> pure (throw err)))
d `seqX` upd ram e (fromEnum w) d
go ram o' res rs en wr din))
upd :: STArray s Int (BitVector m) -> Bool -> Int -> (BitVector m) -> ST s ()
upd ram we waddr d = case maybeIsX we of
Nothing -> case maybeIsX waddr of
Nothing -> -- Put the XException from `waddr` as the value in all
-- locations of `ram`.
forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d))
Just wa -> -- Put the XException from `we` as the value at address
-- `waddr`.
safeUpdate wa (seq we d) ram
Just True -> case maybeIsX waddr of
Nothing -> -- Put the XException from `waddr` as the value in all
-- locations of `ram`.
forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d))
Just wa -> safeUpdate wa d ram
_ -> return ()
safeAt :: HasCallStack => STArray s Int (BitVector m) -> Int -> ST s (BitVector m)
safeAt s i =
if (0 <= i) && (i < szI) then
unsafeReadSTArray s i
else pure $
withFrozenCallStack
(deepErrorX ("blockRamFile: read address " <> show i <>
" not in range [0.." <> show szI <> ")"))
# INLINE safeAt #
safeUpdate :: HasCallStack => Int -> BitVector m
-> STArray s Int (BitVector m) -> ST s ()
safeUpdate i a s =
if (0 <= i) && (i < szI) then
unsafeWriteSTArray s i a
else
let d = withFrozenCallStack
(deepErrorX ("blockRamFile: write address " <> show i <>
" not in range [0.." <> show szI <> ")"))
in forM_ [0..(szI-1)] (\j -> unsafeWriteSTArray s j d)
# INLINE safeUpdate #
parseBV :: String -> BitVector m
parseBV s = case parseBV' s of
Just i -> fromInteger i
Nothing -> undefined#
parseBV' = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
blockRamFile# _ _ _ _ = error "blockRamFile#: dynamic clocks not supported"
# NOINLINE blockRamFile # #
{-# ANN blockRamFile# hasBlackBox #-}
-- | __NB:__ Not synthesizable
initMem :: KnownNat n => FilePath -> IO [BitVector n]
initMem = fmap (map parseBV . lines) . readFile
where
parseBV s = case parseBV' s of
Just i -> fromInteger i
Nothing -> error ("Failed to parse: " ++ s)
parseBV' = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
# NOINLINE initMem #
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/d09e154ef674cea92c8f345d763606cf85e96403/clash-prelude/src/Clash/Explicit/BlockRam/File.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE GADTs #
# OPTIONS_HADDOCK show-extensions #
See: -lang/clash-compiler/commit/721fcfa9198925661cd836668705f817bddaae3c
as to why we need this.
* Block RAM synchronized to an arbitrary clock
* Producing files
* Internal
start benchmark only
end benchmark only
$setup
>>> :m -Prelude
* __NB__: Initial output value is /undefined/, reading it will throw an
'XException'
* __NB__: This function might not work for specific combinations of
code-generation backends and hardware targets. Please check the support table
below:
+----------------+----------+----------+---------------+
| | VHDL | Verilog | SystemVerilog |
+================+==========+==========+===============+
| Altera/Quartus | Broken | Works | Works |
+----------------+----------+----------+---------------+
| Xilinx/ISE | Works | Works | Works |
+----------------+----------+----------+---------------+
| ASIC | Untested | Untested | Untested |
+----------------+----------+----------+---------------+
=== See also:
* See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a
* See "Clash.Explicit.Fixed#creatingdatafiles" for more ideas on how to
create your own data files.
^ 'Clock' to synchronize to
^ 'Enable' line
^ Read address @r@
^ (write address @w@, value to write)
* __NB__: Initial output value is /undefined/, reading it will throw an
'XException'
* __NB__: This function might not work for specific combinations of
code-generation backends and hardware targets. Please check the support table
below:
+----------------+----------+----------+---------------+
| | VHDL | Verilog | SystemVerilog |
+================+==========+==========+===============+
| Altera/Quartus | Broken | Works | Works |
+----------------+----------+----------+---------------+
| Xilinx/ISE | Works | Works | Works |
+----------------+----------+----------+---------------+
| ASIC | Untested | Untested | Untested |
+----------------+----------+----------+---------------+
=== See also:
* See "Clash.Explicit.BlockRam#usingrams" for more information on how to use a
* See "Clash.Sized.Fixed#creatingdatafiles" for more ideas on how to create
your own data files.
^ 'Clock' to synchronize to
^ 'Enable' line
^ Read address @r@
^ (write address @w@, value to write)
| Convert data to the 'String' contents of a memory file.
* __NB__: Not synthesizable
* The following document the several ways to instantiate components with
files:
* "Clash.Explicit.ROM.File#usingromfiles"
* See "Clash.Sized.Fixed#creatingdatafiles" for more ideas on how to create
your own data files.
= Example
used, and both are valid representations of the data.
>>> mapM_ (putStrLn . show . pack) es
>>> putStr (memFile (Just 0) es)
>>> putStr (memFile (Just 1) es)
^ Value to map don't care bits to. 'Nothing' means throwing an error on
don't care bits.
^ Values to convert
^ Contents of the memory file
| blockRamFile primitive
^ 'Clock' to synchronize to
^ 'Enable' line
^ Read address @r@
^ Write enable
^ Write address @w@
^ Value to write (at address @w@)
start benchmark only
end benchmark only
start benchmark only
0 -- ( error " QQ " )
unsafeIOToST (withFile file ReadMode (\h ->
forM_ [0..(szI-1)] (\i -> do
l <- hGetLine h
let bv = parseBV l
bv `seq` unsafeSTToIO (unsafeWriteSTArray ram i bv))
))
unsafeFreezeSTArray ram
end benchmark only
Put the XException from `waddr` as the value in all
locations of `ram`.
Put the XException from `we` as the value at address
`waddr`.
Put the XException from `waddr` as the value in all
locations of `ram`.
# ANN blockRamFile# hasBlackBox #
| __NB:__ Not synthesizable | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , Google Inc. ,
2019 , Myrtle Software Ltd ,
2021 - 2022 , QBayLogic B.V.
License : BSD2 ( see the file LICENSE )
Maintainer : QBayLogic B.V. < >
= Initializing a block RAM with a data file # usingramfiles #
Block RAM primitives that can be initialized with a data file . The BNF grammar
for this data file is simple :
@
FILE = LINE+
LINE = BIT+
BIT = ' 0 '
| ' 1 '
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example , a data file @memory.bin@ containing the 9 - bit unsigned numbers
@7@ to @13@ looks like :
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
Such a file can be produced with ' memFile ' :
@
writeFile " memory.bin " ( memFile Nothing [ 7 : : Unsigned 9 .. 13 ] )
@
We can instantiate a block RAM using the contents of the file above like so :
@
f : : KnownDomain dom
= > Clock dom
- > Enable dom
- > Signal dom ( Unsigned 3 )
- > Signal dom ( Unsigned 9 )
f clk en rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' ' blockRamFile ' clk en d7 \"memory.bin\ " rd ( signal Nothing )
@
In the example above , we basically treat the block RAM as a synchronous ROM .
We can see that it works as expected :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ f systemClockGen enableGen ( fromList [ 3 .. 5 ] ) _ _
[ 10,11,12 ]
@
However , we can also interpret the same data as a tuple of a 6 - bit unsigned
number , and a 3 - bit signed number :
@
g : : KnownDomain dom
= > Clock dom
- > Enable dom
- > Signal dom ( Unsigned 3 )
- > Signal dom ( Unsigned 6,Signed 3 )
g clk en rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' ' blockRamFile ' clk en d7 \"memory.bin\ " rd ( signal Nothing )
@
And then we would see :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ g systemClockGen enableGen ( fromList [ 3 .. 5 ] ) _ _
[ ( 1,2),(1,3)(1,-4 ) ]
@
Copyright : (C) 2015-2016, University of Twente,
2017 , Google Inc.,
2019 , Myrtle Software Ltd,
2021-2022, QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : QBayLogic B.V. <>
= Initializing a block RAM with a data file #usingramfiles#
Block RAM primitives that can be initialized with a data file. The BNF grammar
for this data file is simple:
@
FILE = LINE+
LINE = BIT+
BIT = '0'
| '1'
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example, a data file @memory.bin@ containing the 9-bit unsigned numbers
@7@ to @13@ looks like:
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
Such a file can be produced with 'memFile':
@
writeFile "memory.bin" (memFile Nothing [7 :: Unsigned 9 .. 13])
@
We can instantiate a block RAM using the contents of the file above like so:
@
f :: KnownDomain dom
=> Clock dom
-> Enable dom
-> Signal dom (Unsigned 3)
-> Signal dom (Unsigned 9)
f clk en rd = 'Clash.Class.BitPack.unpack' '<$>' 'blockRamFile' clk en d7 \"memory.bin\" rd (signal Nothing)
@
In the example above, we basically treat the block RAM as a synchronous ROM.
We can see that it works as expected:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ f systemClockGen enableGen (fromList [3..5])__
[10,11,12]
@
However, we can also interpret the same data as a tuple of a 6-bit unsigned
number, and a 3-bit signed number:
@
g :: KnownDomain dom
=> Clock dom
-> Enable dom
-> Signal dom (Unsigned 3)
-> Signal dom (Unsigned 6,Signed 3)
g clk en rd = 'Clash.Class.BitPack.unpack' '<$>' 'blockRamFile' clk en d7 \"memory.bin\" rd (signal Nothing)
@
And then we would see:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ g systemClockGen enableGen (fromList [3..5])__
[(1,2),(1,3)(1,-4)]
@
-}
# LANGUAGE Unsafe #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
# OPTIONS_GHC -fno - cpr - anal #
module Clash.Explicit.BlockRam.File
blockRamFile
, blockRamFilePow2
, memFile
, blockRamFile#
, initMem
)
where
import Control.Exception (catch, throw)
import Control.Monad (forM_)
import Control.Monad.ST (ST, runST)
import Control.Monad.ST.Unsafe (unsafeInterleaveST, unsafeIOToST, unsafeSTToIO)
import Data.Array.MArray (newArray_)
import Data.Bits ((.&.), (.|.), shiftL, xor)
import Data.Char (digitToInt)
import Data.Maybe (isJust, listToMaybe)
import GHC.Arr (STArray, unsafeReadSTArray, unsafeWriteSTArray)
import GHC.Stack (HasCallStack, withFrozenCallStack)
import GHC.TypeLits (KnownNat)
import Numeric (readInt)
import System.IO
import Clash.Annotations.Primitive (hasBlackBox)
import Clash.Class.BitPack (BitPack, BitSize, pack)
import Clash.Promoted.Nat (SNat (..), pow2SNat, natToNum, snatToNum)
import Clash.Sized.Internal.BitVector (Bit(..), BitVector(..), undefined#)
import Clash.Signal.Internal
(Clock(..), Signal (..), Enable, KnownDomain, fromEnable, (.&&.))
import Clash.Signal.Bundle (unbundle)
import Clash.Sized.Unsigned (Unsigned)
import Clash.XException (maybeIsX, seqX, fromJustX, NFDataX(..), XException (..))
import ( unsafeFreezeSTArray , unsafeThawSTArray )
> > > : set -fplugin GHC.TypeLits .
> > > : set -fplugin GHC.TypeLits . KnownNat . Solver
> > > import Clash . Prelude
> > > import Clash . Prelude . BlockRam . File
| Create a block RAM with space for 2^@n@ elements
* _ _ NB _ _ : Read value is delayed by 1 cycle
block RAM .
* Use the adapter ' Clash . Explicit . BlockRam.readNew ' for obtaining write - before - read semantics like this : . Explicit . ' clk rst en ( blockRamFilePow2 ' clk en file ) rd wrM@.
* See " Clash . Explicit . BlockRam . File#usingramfiles " for more information on how
to instantiate a block RAM with the contents of a data file .
* See ' memFile ' for creating a data file with Clash .
blockRamFilePow2
:: forall dom n m
. (KnownDomain dom, KnownNat m, KnownNat n, HasCallStack)
=> Clock dom
-> Enable dom
-> FilePath
^ File describing the initial content of the
-> Signal dom (Unsigned n)
-> Signal dom (Maybe (Unsigned n, BitVector m))
-> Signal dom (BitVector m)
^ Value of the at address @r@ from the previous clock cycle
blockRamFilePow2 = \clk en file rd wrM -> withFrozenCallStack
(blockRamFile clk en (pow2SNat (SNat @n)) file rd wrM)
# INLINE blockRamFilePow2 #
| Create a block RAM with space for @n@ elements
* _ _ NB _ _ : Read value is delayed by 1 cycle
block RAM .
* Use the adapter ' Clash . Explicit . BlockRam.readNew ' for obtaining write - before - read semantics like this : . Explicit . ' clk rst en ( ' blockRamFile ' clk en size file ) rd wrM@.
* See " Clash . Explicit . BlockRam . File#usingramfiles " for more information on how
to instantiate a block RAM with the contents of a data file .
* See ' memFile ' for creating a data file with Clash .
blockRamFile
:: (KnownDomain dom, KnownNat m, Enum addr, NFDataX addr, HasCallStack)
=> Clock dom
-> Enable dom
-> SNat n
^ Size of the
-> FilePath
^ File describing the initial content of the
-> Signal dom addr
-> Signal dom (Maybe (addr, BitVector m))
-> Signal dom (BitVector m)
^ Value of the at address @r@ from the previous clock cycle
blockRamFile = \clk gen sz file rd wrM ->
let en = isJust <$> wrM
(wr,din) = unbundle (fromJustX <$> wrM)
in withFrozenCallStack
(blockRamFile# clk gen sz file (fromEnum <$> rd) en (fromEnum <$> wr) din)
# INLINE blockRamFile #
* " Clash . Prelude . BlockRam . File#usingramfiles "
* " Clash . Prelude . ROM.File#usingromfiles "
* " Clash . Explicit . BlockRam . File#usingramfiles "
The @Maybe@ datatype has do n't care bits , where the actual value does not
matter . But the bits need a defined value in the memory . Either 0 or 1 can be
> > > let es = [ Nothing , Just ( 7 : : Unsigned 8) , Just 8 ]
0b0 _ .... _ ....
0b1_0000_0111
0b1_0000_1000
000000000
100000111
100001000
011111111
100000111
100001000
memFile
:: forall a f
. ( BitPack a
, Foldable f
, HasCallStack)
=> Maybe Bit
-> f a
-> String
memFile care = foldr (\e -> showsBV $ pack e) ""
where
showsBV :: BitVector (BitSize a) -> String -> String
showsBV (BV mask val) s =
if n == 0 then
'0' : '\n' : s
else
case care of
Just (Bit 0 0) -> go n (val .&. (mask `xor` fullMask)) ('\n' : s)
Just (Bit 0 1) -> go n (val .|. mask) ('\n' : s)
_ -> if mask /= 0 then
err
else
go n val ('\n' : s)
where
n = natToNum @(BitSize a) @Int
fullMask = (1 `shiftL` n) - 1
err = withFrozenCallStack $ error $
"memFile: cannot convert don't-care values. "
++ "Please specify mapping to definite value."
go 0 _ s0 = s0
go n0 v s0 =
let (!v0, !vBit) = quotRem v 2
in if vBit == 0 then
go (n0 - 1) v0 $ '0' : s0
else
go (n0 - 1) v0 $ '1' : s0
blockRamFile#
:: forall m dom n
. (KnownDomain dom, KnownNat m, HasCallStack)
=> Clock dom
-> Enable dom
-> SNat n
^ Size of the
-> FilePath
^ File describing the initial content of the
-> Signal dom Int
-> Signal dom Bool
-> Signal dom Int
-> Signal dom (BitVector m)
-> Signal dom (BitVector m)
^ Value of the at address @r@ from the previous clock cycle
blockRamFile# (Clock _ Nothing) ena sz file = \rd wen waS wd -> runST $ do
ramStart <- newArray_ (0,szI)
unsafeIOToST (withFile file ReadMode (\h ->
forM_ [0..(szI-1)] (\i -> do
l <- hGetLine h
let bv = parseBV l
bv `seq` unsafeSTToIO (unsafeWriteSTArray ramStart i bv)
)))
< - unsafeThawSTArray ramArr
go
ramStart
(withFrozenCallStack (deepErrorX "blockRamFile: intial value undefined"))
(fromEnable ena)
rd
(fromEnable ena .&&. wen)
waS
wd
where
szI = snatToNum sz :: Int
ramArr = runST $ do
go :: STArray s Int (BitVector m) -> (BitVector m) -> Signal dom Bool -> Signal dom Int
-> Signal dom Bool -> Signal dom Int -> Signal dom (BitVector m)
-> ST s (Signal dom (BitVector m))
go !ram o ret@(~(re :- res)) rt@(~(r :- rs)) et@(~(e :- en)) wt@(~(w :- wr)) dt@(~(d :- din)) = do
o `seqX` (o :-) <$> (ret `seq` rt `seq` et `seq` wt `seq` dt `seq`
unsafeInterleaveST
(do o' <- unsafeIOToST
(catch (if re then unsafeSTToIO (ram `safeAt` r) else pure o)
(\err@XException {} -> pure (throw err)))
d `seqX` upd ram e (fromEnum w) d
go ram o' res rs en wr din))
upd :: STArray s Int (BitVector m) -> Bool -> Int -> (BitVector m) -> ST s ()
upd ram we waddr d = case maybeIsX we of
Nothing -> case maybeIsX waddr of
forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d))
safeUpdate wa (seq we d) ram
Just True -> case maybeIsX waddr of
forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d))
Just wa -> safeUpdate wa d ram
_ -> return ()
safeAt :: HasCallStack => STArray s Int (BitVector m) -> Int -> ST s (BitVector m)
safeAt s i =
if (0 <= i) && (i < szI) then
unsafeReadSTArray s i
else pure $
withFrozenCallStack
(deepErrorX ("blockRamFile: read address " <> show i <>
" not in range [0.." <> show szI <> ")"))
# INLINE safeAt #
safeUpdate :: HasCallStack => Int -> BitVector m
-> STArray s Int (BitVector m) -> ST s ()
safeUpdate i a s =
if (0 <= i) && (i < szI) then
unsafeWriteSTArray s i a
else
let d = withFrozenCallStack
(deepErrorX ("blockRamFile: write address " <> show i <>
" not in range [0.." <> show szI <> ")"))
in forM_ [0..(szI-1)] (\j -> unsafeWriteSTArray s j d)
# INLINE safeUpdate #
parseBV :: String -> BitVector m
parseBV s = case parseBV' s of
Just i -> fromInteger i
Nothing -> undefined#
parseBV' = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
blockRamFile# _ _ _ _ = error "blockRamFile#: dynamic clocks not supported"
# NOINLINE blockRamFile # #
initMem :: KnownNat n => FilePath -> IO [BitVector n]
initMem = fmap (map parseBV . lines) . readFile
where
parseBV s = case parseBV' s of
Just i -> fromInteger i
Nothing -> error ("Failed to parse: " ++ s)
parseBV' = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
# NOINLINE initMem #
|
d40e81b402d57c7b51c7d52953236c932fbff314265c743aca1f7ca4e14971f7 | FPBench/FPBench | core2smtlib2.rkt | #lang racket
(require math/bigfloat)
(require "lisp.rkt")
(provide core->smtlib2 smt-supported rm->smt number->smt)
(define smt-supported
(supported-list
(disjoin ieee754-ops
(curry set-member?
'(remainder fmax fmin trunc round nearbyint
< > <= >= == and or not
isinf isnan isnormal signbit
let let* array dim size ref for for* tensor tensor*)))
(invert-const-proc (curry set-member? '(LOG2E LOG10E M_1_PI M_2_PI M_2_SQRTPI)))
(curry set-member? '(binary32 binary64))
ieee754-rounding-modes
#f))
(define smt-reserved ; Language-specific reserved names (avoid name collisions)
'(BINARY DECIMAL HEXADECIMAL NUMERAL STRING
_ ! as exists forall let match par
assert check-sate check-sat-assuming declare-const
declare-datatype declare-datatypes declare-fun
declare-sort define-fun defined-fun-rec define-funs-rec
define-sort echo exit get-assertions get-assignment
get-info get-model get-option get-proof get-unsat-assumptions
get-unsat-core get-value pop push reset reset-assertions
set-info set-logic set-option))
;; Extremely simple html-inspired escapes. The understanding is that the
only difference between symbols is that allows : in names ,
while SML - LIB does not .
(define (fix-name name)
(string-join
(for/list ([char (~a name)])
(match char
[#\& "&"]
[#\: "&col"]
[_ (string char)]))
""))
(define/match (fpbits type)
[('binary16) (values 5 11)]
[('binary32) (values 8 24)]
[('binary64) (values 11 53)]
[('binary128) (values 15 113)])
(define (bits->prec es sig)
(match (list es sig)
['(5 11) 'binary16]
['(8 24) 'binary32]
['(11 53) 'binary64]
['(15 113) 'binary128]))
(define (fptype type)
(define-values (w p) (fpbits type))
(format "(_ FloatingPoint ~a ~a)" w p))
(define/match (rm->bf rm)
[('nearestEven) 'nearest]
;[('nearestAway) ] ;; math/bigfloat does not support this mode
[('toPositive) 'up]
[('toNegative) 'down]
[('toZero) 'zero]
[(_) (error 'rm->bf "Unsupported rounding mode ~a" rm)])
(define/match (rm->smt rm)
[('nearestEven) "roundNearestTiesToEven"]
[('nearestAway) "roundNearestTiesToAway"]
[('toPositive) "roundTowardPositive"]
[('toNegative) "roundTowardNegative"]
[('toZero) "roundTowardZero"]
[(_) (error 'rm->smt "Unsupported rounding mode ~a" rm)])
(define (round->smt expr ctx)
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(define rm (ctx-lookup-prop ctx ':round))
(format "((_ to_fp ~a ~a) ~a ~a)" w p (rm->smt rm) expr))
;; Any exact number can be written out (exactly) as a division. In general, adding
;; lots of real divisions to a formula is probably not wise.
;; However, at least with z3, defining constants in this way does not seem to cause
;; any significant issues.
(define (number->smt x w p rm)
(cond
[(and (infinite? x) (positive? x)) (format "(_ +oo ~a ~a)" w p)]
[(and (infinite? x) (negative? x)) (format "(_ -oo ~a ~a)" w p)]
[(nan? x) (format "(_ NaN ~a ~a)" w p)]
[else
(let* ([q (inexact->exact (real->double-flonum x))]
[n (numerator q)]
[d (denominator q)])
(if (= d 1)
(format "((_ to_fp ~a ~a) ~a ~a)" w p (rm->smt rm) n)
(format "((_ to_fp ~a ~a) ~a (/ ~a ~a))" w p (rm->smt rm) n d)))]))
Macro should grab the computation specified in the constants table
;; and wrap it with the right precision context.
;; It is critical that we use the correct rounding mode, and the correct number of bits,
;; here where we are generating the exact (but rounded) value of the constant.
;; In theory the rounding mode used here doesn't matter.
(define-syntax-rule (bf-constant expr w p rm)
(parameterize ([bf-precision p] [bf-rounding-mode (rm->bf rm)])
(let ([qbf expr]) (number->smt (bigfloat->rational qbf) w p rm))))
(define (constant->smt expr ctx)
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(define rm (ctx-lookup-prop ctx ':round))
(match expr
['E (bf-constant (bfexp 1.bf) w p rm)]
['LN2 (bf-constant (bflog 2.bf) w p rm)]
['LN10 (bf-constant (bflog 10.bf) w p rm)]
['PI (bf-constant pi.bf w p rm)]
ok since division by 2 is exact
ok since division by 4 is exact
['SQRT2 (bf-constant (bfsqrt 2.bf) w p rm)]
['SQRT1_2 (bf-constant (bfsqrt (bf/ 1.bf 2.bf)) w p rm)]
['TRUE "true"]
['FALSE "false"]
['INFINITY (format "(_ +oo ~a ~a)" w p)]
['NAN (format "(_ NaN ~a ~a)" w p)]
[(? hex?) (~a (hex->racket expr))]
[(? number?) (~a (number->smt expr w p rm))]
[(? symbol?) (~a expr)]))
(define (operator-format op rm)
(match op
['+ (format "(fp.add ~a ~~a ~~a)" (rm->smt rm))]
['- (format "(fp.sub ~a ~~a ~~a)" (rm->smt rm))]
['* (format "(fp.mul ~a ~~a ~~a)" (rm->smt rm))]
['/ (format "(fp.div ~a ~~a ~~a)" (rm->smt rm))]
['fabs "(fp.abs ~a)"]
['fma (format "(fp.fma ~a ~~a ~~a ~~a)" (rm->smt rm))]
['sqrt (format "(fp.sqrt ~a ~~a)" (rm->smt rm))]
The behavior of fp.rem may not be fully compliant with C11
;; remainder function, however based on the documentation things
;; seem promising.
['remainder "(fp.rem ~a ~a)"]
['fmax "(fp.max ~a ~a)"]
['fmin "(fp.min ~a ~a)"]
['trunc (format "(fp.roundToIntegral ~a ~~a)" (rm->smt 'toZero))]
['round (format "(fp.roundToIntegral ~a ~~a)" (rm->smt 'nearestAway))]
['nearbyint (format "(fp.roundToIntegral ~a ~~a)" (rm->smt rm))]
Comparisons and logical ops take one format argument ,
;; which is a pre-concatenated string of inputs.
['< "(fp.lt ~a)"]
['> "(fp.gt ~a)"]
['<= "(fp.leq ~a)"]
['>= "(fp.geq ~a)"]
['== "(fp.eq ~a)"]
;['!= ""] ;; needs special logic
['and "(and ~a)"]
['or "(or ~a)"]
['not "(not ~a)"]
;['isfinite ""] ;; needs special logic to avoid computing inner expression twice
['isinf "(fp.isInfinite ~a)"]
['isnan "(fp.isNaN ~a)"]
['isnormal "(fp.isNormal ~a)"]
['signbit "(fp.isNegative ~a)"]))
(define (operator->smt op args ctx)
(define rm (ctx-lookup-prop ctx ':round))
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(match (cons op args)
[(list (or '< '> '<= '>= '== 'and 'or) args ...)
(format (operator-format op rm)
(string-join (map ~a args) " "))]
[(list '!= args ...)
(format "(and ~a)"
(string-join
(let loop ([args args])
(cond
[(null? args) '()]
[else (append
(for/list ([b (cdr args)])
(format "(not (fp.eq ~a ~a))" (car args) b))
(loop (cdr args)))]))
" "))]
[(list '- a)
(format "(fp.neg ~a)" a)]
[(list (or 'not 'isinf 'isnan 'isnormal 'signbit) a) ;; avoid rounding on a boolean
(format (operator-format op rm) a)]
[(list (? operator? op) args ...)
(round->smt (apply format (operator-format op rm) args) ctx)]))
(define (program->smt name args arg-ctxs body ctx)
(define prec (ctx-lookup-prop ctx ':precision))
(define rm (ctx-lookup-prop ctx ':round))
(define-values (w p) (fpbits prec))
(define type-str (fptype prec))
(define args*
(for/list ([arg args] [ctx arg-ctxs])
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(define rm (ctx-lookup-prop ctx ':round))
(define type-str (fptype prec))
(format "(~a ~a)" arg type-str)))
(format "(define-fun ~a (~a) ~a\n ~a)\n"
name (string-join args* " ") type-str
(round->smt body ctx)))
(define core->smtlib2
(make-lisp-compiler "lisp"
#:operator operator->smt
#:constant constant->smt
#:if-format "(ife ~a ~a ~a)"
#:round round->smt
#:program program->smt
#:flags '(round-after-operation)
#:reserved smt-reserved))
(define-compiler '("smt" "smt2" "smtlib" "smtlib2") (const "") core->smtlib2 (const "") smt-supported)
| null | https://raw.githubusercontent.com/FPBench/FPBench/ecdfbfc484cc7f392c46bfba43813458a6406608/src/core2smtlib2.rkt | racket | Language-specific reserved names (avoid name collisions)
Extremely simple html-inspired escapes. The understanding is that the
[('nearestAway) ] ;; math/bigfloat does not support this mode
Any exact number can be written out (exactly) as a division. In general, adding
lots of real divisions to a formula is probably not wise.
However, at least with z3, defining constants in this way does not seem to cause
any significant issues.
and wrap it with the right precision context.
It is critical that we use the correct rounding mode, and the correct number of bits,
here where we are generating the exact (but rounded) value of the constant.
In theory the rounding mode used here doesn't matter.
remainder function, however based on the documentation things
seem promising.
which is a pre-concatenated string of inputs.
['!= ""] ;; needs special logic
['isfinite ""] ;; needs special logic to avoid computing inner expression twice
avoid rounding on a boolean | #lang racket
(require math/bigfloat)
(require "lisp.rkt")
(provide core->smtlib2 smt-supported rm->smt number->smt)
(define smt-supported
(supported-list
(disjoin ieee754-ops
(curry set-member?
'(remainder fmax fmin trunc round nearbyint
< > <= >= == and or not
isinf isnan isnormal signbit
let let* array dim size ref for for* tensor tensor*)))
(invert-const-proc (curry set-member? '(LOG2E LOG10E M_1_PI M_2_PI M_2_SQRTPI)))
(curry set-member? '(binary32 binary64))
ieee754-rounding-modes
#f))
'(BINARY DECIMAL HEXADECIMAL NUMERAL STRING
_ ! as exists forall let match par
assert check-sate check-sat-assuming declare-const
declare-datatype declare-datatypes declare-fun
declare-sort define-fun defined-fun-rec define-funs-rec
define-sort echo exit get-assertions get-assignment
get-info get-model get-option get-proof get-unsat-assumptions
get-unsat-core get-value pop push reset reset-assertions
set-info set-logic set-option))
only difference between symbols is that allows : in names ,
while SML - LIB does not .
(define (fix-name name)
(string-join
(for/list ([char (~a name)])
(match char
[#\& "&"]
[#\: "&col"]
[_ (string char)]))
""))
(define/match (fpbits type)
[('binary16) (values 5 11)]
[('binary32) (values 8 24)]
[('binary64) (values 11 53)]
[('binary128) (values 15 113)])
(define (bits->prec es sig)
(match (list es sig)
['(5 11) 'binary16]
['(8 24) 'binary32]
['(11 53) 'binary64]
['(15 113) 'binary128]))
(define (fptype type)
(define-values (w p) (fpbits type))
(format "(_ FloatingPoint ~a ~a)" w p))
(define/match (rm->bf rm)
[('nearestEven) 'nearest]
[('toPositive) 'up]
[('toNegative) 'down]
[('toZero) 'zero]
[(_) (error 'rm->bf "Unsupported rounding mode ~a" rm)])
(define/match (rm->smt rm)
[('nearestEven) "roundNearestTiesToEven"]
[('nearestAway) "roundNearestTiesToAway"]
[('toPositive) "roundTowardPositive"]
[('toNegative) "roundTowardNegative"]
[('toZero) "roundTowardZero"]
[(_) (error 'rm->smt "Unsupported rounding mode ~a" rm)])
(define (round->smt expr ctx)
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(define rm (ctx-lookup-prop ctx ':round))
(format "((_ to_fp ~a ~a) ~a ~a)" w p (rm->smt rm) expr))
(define (number->smt x w p rm)
(cond
[(and (infinite? x) (positive? x)) (format "(_ +oo ~a ~a)" w p)]
[(and (infinite? x) (negative? x)) (format "(_ -oo ~a ~a)" w p)]
[(nan? x) (format "(_ NaN ~a ~a)" w p)]
[else
(let* ([q (inexact->exact (real->double-flonum x))]
[n (numerator q)]
[d (denominator q)])
(if (= d 1)
(format "((_ to_fp ~a ~a) ~a ~a)" w p (rm->smt rm) n)
(format "((_ to_fp ~a ~a) ~a (/ ~a ~a))" w p (rm->smt rm) n d)))]))
Macro should grab the computation specified in the constants table
(define-syntax-rule (bf-constant expr w p rm)
(parameterize ([bf-precision p] [bf-rounding-mode (rm->bf rm)])
(let ([qbf expr]) (number->smt (bigfloat->rational qbf) w p rm))))
(define (constant->smt expr ctx)
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(define rm (ctx-lookup-prop ctx ':round))
(match expr
['E (bf-constant (bfexp 1.bf) w p rm)]
['LN2 (bf-constant (bflog 2.bf) w p rm)]
['LN10 (bf-constant (bflog 10.bf) w p rm)]
['PI (bf-constant pi.bf w p rm)]
ok since division by 2 is exact
ok since division by 4 is exact
['SQRT2 (bf-constant (bfsqrt 2.bf) w p rm)]
['SQRT1_2 (bf-constant (bfsqrt (bf/ 1.bf 2.bf)) w p rm)]
['TRUE "true"]
['FALSE "false"]
['INFINITY (format "(_ +oo ~a ~a)" w p)]
['NAN (format "(_ NaN ~a ~a)" w p)]
[(? hex?) (~a (hex->racket expr))]
[(? number?) (~a (number->smt expr w p rm))]
[(? symbol?) (~a expr)]))
(define (operator-format op rm)
(match op
['+ (format "(fp.add ~a ~~a ~~a)" (rm->smt rm))]
['- (format "(fp.sub ~a ~~a ~~a)" (rm->smt rm))]
['* (format "(fp.mul ~a ~~a ~~a)" (rm->smt rm))]
['/ (format "(fp.div ~a ~~a ~~a)" (rm->smt rm))]
['fabs "(fp.abs ~a)"]
['fma (format "(fp.fma ~a ~~a ~~a ~~a)" (rm->smt rm))]
['sqrt (format "(fp.sqrt ~a ~~a)" (rm->smt rm))]
The behavior of fp.rem may not be fully compliant with C11
['remainder "(fp.rem ~a ~a)"]
['fmax "(fp.max ~a ~a)"]
['fmin "(fp.min ~a ~a)"]
['trunc (format "(fp.roundToIntegral ~a ~~a)" (rm->smt 'toZero))]
['round (format "(fp.roundToIntegral ~a ~~a)" (rm->smt 'nearestAway))]
['nearbyint (format "(fp.roundToIntegral ~a ~~a)" (rm->smt rm))]
Comparisons and logical ops take one format argument ,
['< "(fp.lt ~a)"]
['> "(fp.gt ~a)"]
['<= "(fp.leq ~a)"]
['>= "(fp.geq ~a)"]
['== "(fp.eq ~a)"]
['and "(and ~a)"]
['or "(or ~a)"]
['not "(not ~a)"]
['isinf "(fp.isInfinite ~a)"]
['isnan "(fp.isNaN ~a)"]
['isnormal "(fp.isNormal ~a)"]
['signbit "(fp.isNegative ~a)"]))
(define (operator->smt op args ctx)
(define rm (ctx-lookup-prop ctx ':round))
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(match (cons op args)
[(list (or '< '> '<= '>= '== 'and 'or) args ...)
(format (operator-format op rm)
(string-join (map ~a args) " "))]
[(list '!= args ...)
(format "(and ~a)"
(string-join
(let loop ([args args])
(cond
[(null? args) '()]
[else (append
(for/list ([b (cdr args)])
(format "(not (fp.eq ~a ~a))" (car args) b))
(loop (cdr args)))]))
" "))]
[(list '- a)
(format "(fp.neg ~a)" a)]
(format (operator-format op rm) a)]
[(list (? operator? op) args ...)
(round->smt (apply format (operator-format op rm) args) ctx)]))
(define (program->smt name args arg-ctxs body ctx)
(define prec (ctx-lookup-prop ctx ':precision))
(define rm (ctx-lookup-prop ctx ':round))
(define-values (w p) (fpbits prec))
(define type-str (fptype prec))
(define args*
(for/list ([arg args] [ctx arg-ctxs])
(define-values (w p) (fpbits (ctx-lookup-prop ctx ':precision)))
(define rm (ctx-lookup-prop ctx ':round))
(define type-str (fptype prec))
(format "(~a ~a)" arg type-str)))
(format "(define-fun ~a (~a) ~a\n ~a)\n"
name (string-join args* " ") type-str
(round->smt body ctx)))
(define core->smtlib2
(make-lisp-compiler "lisp"
#:operator operator->smt
#:constant constant->smt
#:if-format "(ife ~a ~a ~a)"
#:round round->smt
#:program program->smt
#:flags '(round-after-operation)
#:reserved smt-reserved))
(define-compiler '("smt" "smt2" "smtlib" "smtlib2") (const "") core->smtlib2 (const "") smt-supported)
|
7a1e82101874092ebdcf4164bd6f84525b788d514ea0e2033b657c5400316532 | zotonic/zotonic | action_admin_identity_dialog_set_username_password.erl | @author < >
2009
Date : 2009 - 05 - 12
%% @doc Open a dialog with some fields to add or change an username/password identity
Copyright 2009
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(action_admin_identity_dialog_set_username_password).
-author("Marc Worrell <>").
%% interface functions
-export([
render_action/4,
event/2
]).
-include_lib("zotonic_core/include/zotonic.hrl").
-define(PASSWORD_DOTS, <<"••••••"/utf8>>).
render_action(TriggerId, TargetId, Args, Context) ->
Id = z_convert:to_integer(proplists:get_value(id, Args)),
OnDelete = proplists:get_all_values(on_delete, Args),
Postback = {set_username_password, Id, OnDelete},
{PostbackMsgJS, _PickledPostback} = z_render:make_postback(Postback, click, TriggerId, TargetId, ?MODULE, Context),
{PostbackMsgJS, Context}.
%% @doc Fill the dialog with the new page form. The form will be posted back to this module.
@spec event(Event , ) - > Context2
event(#postback{message={set_username_password, Id, OnDelete}}, Context) ->
Username = m_identity:get_username(Id, Context),
Vars = [
{delegate, atom_to_binary(?MODULE, 'utf8')},
{id, Id},
{username, Username},
{on_delete, OnDelete}
],
z_render:dialog(?__("Set username / password", Context), "_action_dialog_set_username_password.tpl", Vars, Context);
event(#postback{message={delete_username, Args}}, Context) ->
Id = m_rsc:rid(proplists:get_value(id, Args), Context),
case {z_acl:is_read_only(Context), z_acl:is_allowed(use, mod_admin_identity, Context), z_acl:user(Context)} of
{true, _, _} ->
z_render:growl_error(?__("Only an administrator or the user him/herself can set a password.", Context), Context);
{false, _, Id} ->
z_render:growl_error(?__("Sorry, you can not remove your own username.", Context), Context);
{false, true, _} when Id =:= 1 ->
z_render:growl_error(?__("The admin user can not be removed.", Context), Context);
{false, true, _} ->
case m_identity:delete_username(Id, Context) of
ok ->
Context1 = z_render:growl(?__("Deleted the user account.", Context), Context),
z_render:wire(proplists:get_all_values(on_delete, Args), Context1);
{error, _} ->
z_render:growl_error(?__("You are not allowed to delete this user account.", Context), Context)
end;
{false, false, _} ->
z_render:growl_error(?__("Only an administrator or the user him/herself can set a password.", Context), Context)
end;
event(#submit{message=set_username_password}, Context) ->
Id = z_convert:to_integer(z_context:get_q(<<"id">>, Context)),
Username = z_context:get_q_validated(<<"new_username">>, Context),
Password = z_context:get_q_validated(<<"new_password">>, Context),
case not z_acl:is_read_only(Context)
andalso (
z_acl:is_allowed(use, mod_admin_identity, Context)
orelse z_acl:user(Context) == Id)
of
true ->
case Password of
<<>> ->
% Only change the username
case m_identity:set_username(Id, Username, Context) of
ok ->
z_render:wire([
{dialog_close, []},
{growl, [{text, ?__("Changed the username.", Context)}]}
], Context);
{error, eexist} ->
z_render:wire({growl, [{text, ?__("The username is already in use, please try another.", Context)},{type, "error"}]}, Context)
end;
_Password ->
case m_identity:set_username_pw(Id, Username, Password, Context) of
{error, _} ->
%% Assume duplicate key violation, user needs to pick another username.
z_render:growl_error(?__("The username is already in use, please try another.", Context), Context);
ok ->
case z_convert:to_bool(z_context:get_q(<<"send_welcome">>, Context)) of
true ->
Vars = [{id, Id},
{username, Username},
{password, Password}],
z_email:send_render(m_rsc:p(Id, email_raw, Context), "email_admin_new_user.tpl", Vars, Context);
false ->
nop
end,
z_render:wire([
{dialog_close, []},
{growl, [{text, ?__("The new username/ password has been set.", Context)}]}
], Context)
end
end;
false ->
z_render:growl_error(?__("Only an administrator or the user him/herself can set a password.", Context), Context)
end.
| null | https://raw.githubusercontent.com/zotonic/zotonic/ec05433cffa39b13585ffbbbb50119767cf522fd/apps/zotonic_mod_admin_identity/src/actions/action_admin_identity_dialog_set_username_password.erl | erlang | @doc Open a dialog with some fields to add or change an username/password identity
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
interface functions
@doc Fill the dialog with the new page form. The form will be posted back to this module.
Only change the username
Assume duplicate key violation, user needs to pick another username. | @author < >
2009
Date : 2009 - 05 - 12
Copyright 2009
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(action_admin_identity_dialog_set_username_password).
-author("Marc Worrell <>").
-export([
render_action/4,
event/2
]).
-include_lib("zotonic_core/include/zotonic.hrl").
-define(PASSWORD_DOTS, <<"••••••"/utf8>>).
render_action(TriggerId, TargetId, Args, Context) ->
Id = z_convert:to_integer(proplists:get_value(id, Args)),
OnDelete = proplists:get_all_values(on_delete, Args),
Postback = {set_username_password, Id, OnDelete},
{PostbackMsgJS, _PickledPostback} = z_render:make_postback(Postback, click, TriggerId, TargetId, ?MODULE, Context),
{PostbackMsgJS, Context}.
@spec event(Event , ) - > Context2
event(#postback{message={set_username_password, Id, OnDelete}}, Context) ->
Username = m_identity:get_username(Id, Context),
Vars = [
{delegate, atom_to_binary(?MODULE, 'utf8')},
{id, Id},
{username, Username},
{on_delete, OnDelete}
],
z_render:dialog(?__("Set username / password", Context), "_action_dialog_set_username_password.tpl", Vars, Context);
event(#postback{message={delete_username, Args}}, Context) ->
Id = m_rsc:rid(proplists:get_value(id, Args), Context),
case {z_acl:is_read_only(Context), z_acl:is_allowed(use, mod_admin_identity, Context), z_acl:user(Context)} of
{true, _, _} ->
z_render:growl_error(?__("Only an administrator or the user him/herself can set a password.", Context), Context);
{false, _, Id} ->
z_render:growl_error(?__("Sorry, you can not remove your own username.", Context), Context);
{false, true, _} when Id =:= 1 ->
z_render:growl_error(?__("The admin user can not be removed.", Context), Context);
{false, true, _} ->
case m_identity:delete_username(Id, Context) of
ok ->
Context1 = z_render:growl(?__("Deleted the user account.", Context), Context),
z_render:wire(proplists:get_all_values(on_delete, Args), Context1);
{error, _} ->
z_render:growl_error(?__("You are not allowed to delete this user account.", Context), Context)
end;
{false, false, _} ->
z_render:growl_error(?__("Only an administrator or the user him/herself can set a password.", Context), Context)
end;
event(#submit{message=set_username_password}, Context) ->
Id = z_convert:to_integer(z_context:get_q(<<"id">>, Context)),
Username = z_context:get_q_validated(<<"new_username">>, Context),
Password = z_context:get_q_validated(<<"new_password">>, Context),
case not z_acl:is_read_only(Context)
andalso (
z_acl:is_allowed(use, mod_admin_identity, Context)
orelse z_acl:user(Context) == Id)
of
true ->
case Password of
<<>> ->
case m_identity:set_username(Id, Username, Context) of
ok ->
z_render:wire([
{dialog_close, []},
{growl, [{text, ?__("Changed the username.", Context)}]}
], Context);
{error, eexist} ->
z_render:wire({growl, [{text, ?__("The username is already in use, please try another.", Context)},{type, "error"}]}, Context)
end;
_Password ->
case m_identity:set_username_pw(Id, Username, Password, Context) of
{error, _} ->
z_render:growl_error(?__("The username is already in use, please try another.", Context), Context);
ok ->
case z_convert:to_bool(z_context:get_q(<<"send_welcome">>, Context)) of
true ->
Vars = [{id, Id},
{username, Username},
{password, Password}],
z_email:send_render(m_rsc:p(Id, email_raw, Context), "email_admin_new_user.tpl", Vars, Context);
false ->
nop
end,
z_render:wire([
{dialog_close, []},
{growl, [{text, ?__("The new username/ password has been set.", Context)}]}
], Context)
end
end;
false ->
z_render:growl_error(?__("Only an administrator or the user him/herself can set a password.", Context), Context)
end.
|
79a173c9a5af8eb7030f82421f3d802248844772e0f2aba4b6c4b241f3ce0691 | mcorbin/meuse | log.clj | (ns meuse.log
"Functions for structured logging"
(:require [unilog.context :as context]
[clojure.tools.logging :as log]))
(defmacro info
[data & args]
`(context/with-context~ data
(log/info ~@args)))
(defmacro infof
[data & args]
`(context/with-context~ data
(log/infof ~@args)))
(defmacro debug
[data & args]
`(context/with-context~ data
(log/debug ~@args)))
(defmacro error
[data & args]
`(context/with-context~ data
(log/error ~@args)))
(defn req-ctx
[request]
(cond-> {:request-id (:id request)}
(get-in request [:auth :user-name]) (assoc :user (get-in request [:auth :user-name]))
(get-in request [:auth :user-id]) (assoc :user (get-in request [:auth :user-id]))))
| null | https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/log.clj | clojure | (ns meuse.log
"Functions for structured logging"
(:require [unilog.context :as context]
[clojure.tools.logging :as log]))
(defmacro info
[data & args]
`(context/with-context~ data
(log/info ~@args)))
(defmacro infof
[data & args]
`(context/with-context~ data
(log/infof ~@args)))
(defmacro debug
[data & args]
`(context/with-context~ data
(log/debug ~@args)))
(defmacro error
[data & args]
`(context/with-context~ data
(log/error ~@args)))
(defn req-ctx
[request]
(cond-> {:request-id (:id request)}
(get-in request [:auth :user-name]) (assoc :user (get-in request [:auth :user-name]))
(get-in request [:auth :user-id]) (assoc :user (get-in request [:auth :user-id]))))
|
|
8fce1d8c46a05b0f8f5048104537a34afed1ef634e5f981fd361a14750c8eb1f | Frama-C/Frama-C-snapshot | gtk_compat.2.ml | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
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 ) .
(* *)
(**************************************************************************)
module Pango = struct
open Wutil_once
let small_font =
once (fun f ->
let f = Pango.Font.copy f in
let s = Pango.Font.get_size f in
Pango.Font.set_size f (s-2) ; f)
let bold_font =
once (fun f ->
let f = Pango.Font.copy f in
Pango.Font.set_weight f `BOLD ; f)
let modify_font phi widget =
widget#misc#modify_font (phi widget#misc#pango_context#font_description)
let set_small_font w = modify_font small_font w
let set_bold_font w = modify_font bold_font w
end
let get_toolbar_index (toolbar:GButton.toolbar) (item:GButton.tool_item) =
toolbar#get_item_index item
let window
?(kind:Gtk.Tags.window_type option)
?(title:string option)
?(decorated:bool option)
?(deletable:bool option)
?(focus_on_map:bool option)
?(icon:GdkPixbuf.pixbuf option)
?(icon_name:string option)
?(modal:bool option)
?(position:Gtk.Tags.window_position option)
?(resizable:bool option)
?(screen:Gdk.screen option)
?(type_hint:Gdk.Tags.window_type_hint option)
?(urgency_hint:bool option)
?(wmclass:(string * string) option)
?(border_width:int option)
?(width:int option)
?(height:int option)
?(show:bool option)
()
=
let allow_shrink = resizable in
let allow_grow = resizable in
ignore wmclass;
GWindow.window
?kind ?title ?decorated ?deletable ?focus_on_map ?icon ?icon_name
?modal ?position ?resizable ?allow_grow ?allow_shrink ?screen
?type_hint ?urgency_hint ?border_width ?width ?height ?show ()
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/gui/gtk_compat.2.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.
************************************************************************ | This file is part of Frama - C.
Copyright ( C ) 2007 - 2019
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 Pango = struct
open Wutil_once
let small_font =
once (fun f ->
let f = Pango.Font.copy f in
let s = Pango.Font.get_size f in
Pango.Font.set_size f (s-2) ; f)
let bold_font =
once (fun f ->
let f = Pango.Font.copy f in
Pango.Font.set_weight f `BOLD ; f)
let modify_font phi widget =
widget#misc#modify_font (phi widget#misc#pango_context#font_description)
let set_small_font w = modify_font small_font w
let set_bold_font w = modify_font bold_font w
end
let get_toolbar_index (toolbar:GButton.toolbar) (item:GButton.tool_item) =
toolbar#get_item_index item
let window
?(kind:Gtk.Tags.window_type option)
?(title:string option)
?(decorated:bool option)
?(deletable:bool option)
?(focus_on_map:bool option)
?(icon:GdkPixbuf.pixbuf option)
?(icon_name:string option)
?(modal:bool option)
?(position:Gtk.Tags.window_position option)
?(resizable:bool option)
?(screen:Gdk.screen option)
?(type_hint:Gdk.Tags.window_type_hint option)
?(urgency_hint:bool option)
?(wmclass:(string * string) option)
?(border_width:int option)
?(width:int option)
?(height:int option)
?(show:bool option)
()
=
let allow_shrink = resizable in
let allow_grow = resizable in
ignore wmclass;
GWindow.window
?kind ?title ?decorated ?deletable ?focus_on_map ?icon ?icon_name
?modal ?position ?resizable ?allow_grow ?allow_shrink ?screen
?type_hint ?urgency_hint ?border_width ?width ?height ?show ()
|
a634fc3525810cf59152afa4a557241e8806b45bd6e47fbaa9724a46fddffecb | erlangonrails/devdb | p1_fsm.erl | ` ` 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 via the world wide web 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 Initial Developer of the Original Code is Ericsson Utvecklings AB .
Portions created by Ericsson are Copyright 1999 ,
%% AB. All Rights Reserved.''
%%
The code has been modified and improved by ProcessOne .
Copyright 2007 - 2010 , ProcessOne
%%
%% The change adds the following features:
- You can send ) to the p1_fsm process to
terminate immediatetly . If the fsm trap_exit process flag has been
set to true , the FSM terminate function will called .
%% - You can pass the gen_fsm options to control resource usage.
%% {max_queue, N} will exit the process with priority_shutdown
- You can limit the time processing a message ( TODO ): If the
%% message processing does not return in a given period of time, the
%% process will be terminated.
- You might customize the State data before sending it to error_logger
%% in case of a crash (just export the function print_state/1)
%% $Id$
%%
-module(p1_fsm).
%%%-----------------------------------------------------------------
%%%
%%% This state machine is somewhat more pure than state_lib. It is
still based on State dispatching ( one function per state ) , but
%%% allows a function handle_event to take care of events in all states.
%%% It's not that pure anymore :( We also allow synchronized event sending.
%%%
%%% If the Parent process terminates the Module:terminate/2
%%% function is called.
%%%
%%% The user module should export:
%%%
%%% init(Args)
= = > { ok , , StateData }
{ ok , , StateData , Timeout }
%%% ignore
%%% {stop, Reason}
%%%
%%% StateName(Msg, StateData)
%%%
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
%%% StateName(Msg, From, StateData)
%%%
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ reply , Reply , NewStateName , NewStateData }
{ reply , Reply , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
%%% handle_event(Msg, StateName, StateData)
%%%
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
%%% {stop, Reason, Reply, NewStateData}
{ stop , , NewStateData }
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
%%% handle_sync_event(Msg, From, StateName, StateData)
%%%
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ reply , Reply , NewStateName , NewStateData }
{ reply , Reply , NewStateName , NewStateData , Timeout }
%%% {stop, Reason, Reply, NewStateData}
{ stop , , NewStateData }
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
handle_info(Info , StateName ) ( e.g. { ' EXIT ' , P , R } , { nodedown , N } , ...
%%%
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
%%% terminate(Reason, StateName, StateData) Let the user module clean up
%%% always called when server terminates
%%%
%%% ==> the return value is ignored
%%%
%%%
The work flow ( of the fsm ) can be described as follows :
%%%
User module fsm
%%% ----------- -------
%%% start -----> start
%%% init <----- .
%%%
%%% loop
%%% StateName <----- .
%%%
%%% handle_event <----- .
%%%
%%% handle__sunc_event <----- .
%%%
%%% handle_info <----- .
%%%
%%% terminate <----- .
%%%
%%%
%%% ---------------------------------------------------
-export([start/3, start/4,
start_link/3, start_link/4,
send_event/2, sync_send_event/2, sync_send_event/3,
send_all_state_event/2,
sync_send_all_state_event/2, sync_send_all_state_event/3,
reply/2,
start_timer/2,send_event_after/2,cancel_timer/1,
enter_loop/4, enter_loop/5, enter_loop/6, wake_hib/7]).
-export([behaviour_info/1]).
%% Internal exports
-export([init_it/6, print_event/3,
system_continue/3,
system_terminate/4,
system_code_change/4,
format_status/2]).
-import(error_logger , [format/2]).
Internal gen_fsm state
%%% This state is used to defined resource control values:
-record(limits, {max_queue}).
%%% ---------------------------------------------------
Interface functions .
%%% ---------------------------------------------------
behaviour_info(callbacks) ->
[{init,1},{handle_event,3},{handle_sync_event,4},{handle_info,3},
{terminate,3},{code_change,4}, {print_state,1}];
behaviour_info(_Other) ->
undefined.
%%% ---------------------------------------------------
%%% Starts a generic state machine.
start(Mod , , Options )
start(Name , , , Options )
start_link(Mod , , Options )
start_link(Name , , , Options ) where :
%%% Name ::= {local, atom()} | {global, atom()}
Mod : : = atom ( ) , callback module implementing the ' real ' fsm
: : = term ( ) , init arguments ( to Mod : init/1 )
%%% Options ::= [{debug, [Flag]}]
%%% Flag ::= trace | log | {logfile, File} | statistics | debug
( debug = = log & & statistics )
Returns : { ok , Pid } |
{ error , { already_started , Pid } } |
%%% {error, Reason}
%%% ---------------------------------------------------
start(Mod, Args, Options) ->
gen:start(?MODULE, nolink, Mod, Args, Options).
start(Name, Mod, Args, Options) ->
gen:start(?MODULE, nolink, Name, Mod, Args, Options).
start_link(Mod, Args, Options) ->
gen:start(?MODULE, link, Mod, Args, Options).
start_link(Name, Mod, Args, Options) ->
gen:start(?MODULE, link, Name, Mod, Args, Options).
send_event({global, Name}, Event) ->
catch global:send(Name, {'$gen_event', Event}),
ok;
send_event(Name, Event) ->
Name ! {'$gen_event', Event},
ok.
sync_send_event(Name, Event) ->
case catch gen:call(Name, '$gen_sync_event', Event) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_event, [Name, Event]}})
end.
sync_send_event(Name, Event, Timeout) ->
case catch gen:call(Name, '$gen_sync_event', Event, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_event, [Name, Event, Timeout]}})
end.
send_all_state_event({global, Name}, Event) ->
catch global:send(Name, {'$gen_all_state_event', Event}),
ok;
send_all_state_event(Name, Event) ->
Name ! {'$gen_all_state_event', Event},
ok.
sync_send_all_state_event(Name, Event) ->
case catch gen:call(Name, '$gen_sync_all_state_event', Event) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_all_state_event, [Name, Event]}})
end.
sync_send_all_state_event(Name, Event, Timeout) ->
case catch gen:call(Name, '$gen_sync_all_state_event', Event, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_all_state_event,
[Name, Event, Timeout]}})
end.
Designed to be only callable within one of the callbacks
%% hence using the self() of this instance of the process.
%% This is to ensure that timers don't go astray in global
%% e.g. when straddling a failover, or turn up in a restarted
%% instance of the process.
Returns Ref , sends event { timeout , Ref , Msg } after Time
%% to the (then) current state.
start_timer(Time, Msg) ->
erlang:start_timer(Time, self(), {'$gen_timer', Msg}).
%% Returns Ref, sends Event after Time to the (then) current state.
send_event_after(Time, Event) ->
erlang:start_timer(Time, self(), {'$gen_event', Event}).
Returns the remaing time for the timer if Ref referred to
%% an active timer/send_event_after, false otherwise.
cancel_timer(Ref) ->
case erlang:cancel_timer(Ref) of
false ->
receive {timeout, Ref, _} -> 0
after 0 -> false
end;
RemainingTime ->
RemainingTime
end.
%% enter_loop/4,5,6
%% Makes an existing process into a gen_fsm.
%% The calling process will enter the gen_fsm receive loop and become a
%% gen_fsm process.
The process * must * have been started using one of the start functions
in proc_lib , see proc_lib(3 ) .
%% The user is responsible for any initialization of the process,
%% including registering a name for it.
enter_loop(Mod, Options, StateName, StateData) ->
enter_loop(Mod, Options, StateName, StateData, self(), infinity).
enter_loop(Mod, Options, StateName, StateData, ServerName = {_,_}) ->
enter_loop(Mod, Options, StateName, StateData, ServerName,infinity);
enter_loop(Mod, Options, StateName, StateData, Timeout) ->
enter_loop(Mod, Options, StateName, StateData, self(), Timeout).
enter_loop(Mod, Options, StateName, StateData, ServerName, Timeout) ->
Name = get_proc_name(ServerName),
Parent = get_parent(),
Debug = gen:debug_options(Options),
Limits = limit_options(Options),
Queue = queue:new(),
QueueLen = 0,
loop(Parent, Name, StateName, StateData, Mod, Timeout, Debug,
Limits, Queue, QueueLen).
get_proc_name(Pid) when is_pid(Pid) ->
Pid;
get_proc_name({local, Name}) ->
case process_info(self(), registered_name) of
{registered_name, Name} ->
Name;
{registered_name, _Name} ->
exit(process_not_registered);
[] ->
exit(process_not_registered)
end;
get_proc_name({global, Name}) ->
case global:safe_whereis_name(Name) of
undefined ->
exit(process_not_registered_globally);
Pid when Pid==self() ->
Name;
_Pid ->
exit(process_not_registered_globally)
end.
get_parent() ->
case get('$ancestors') of
[Parent | _] when is_pid(Parent) ->
Parent;
[Parent | _] when is_atom(Parent) ->
name_to_pid(Parent);
_ ->
exit(process_was_not_started_by_proc_lib)
end.
name_to_pid(Name) ->
case whereis(Name) of
undefined ->
case global:safe_whereis_name(Name) of
undefined ->
exit(could_not_find_registerd_name);
Pid ->
Pid
end;
Pid ->
Pid
end.
%%% ---------------------------------------------------
%%% Initiate the new process.
Register the name using the Rfunc function
%%% Calls the Mod:init/Args function.
%%% Finally an acknowledge is sent to Parent and the main
%%% loop is entered.
%%% ---------------------------------------------------
init_it(Starter, self, Name, Mod, Args, Options) ->
init_it(Starter, self(), Name, Mod, Args, Options);
init_it(Starter, Parent, Name0, Mod, Args, Options) ->
Name = name(Name0),
Debug = gen:debug_options(Options),
Limits = limit_options(Options),
Queue = queue:new(),
QueueLen = 0,
case catch Mod:init(Args) of
{ok, StateName, StateData} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(Parent, Name, StateName, StateData, Mod, infinity, Debug, Limits, Queue, QueueLen);
{ok, StateName, StateData, Timeout} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(Parent, Name, StateName, StateData, Mod, Timeout, Debug, Limits, Queue, QueueLen);
{stop, Reason} ->
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
ignore ->
proc_lib:init_ack(Starter, ignore),
exit(normal);
{'EXIT', Reason} ->
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
Else ->
Error = {bad_return_value, Else},
proc_lib:init_ack(Starter, {error, Error}),
exit(Error)
end.
name({local,Name}) -> Name;
name({global,Name}) -> Name;
name(Pid) when is_pid(Pid) -> Pid.
%%-----------------------------------------------------------------
%% The MAIN loop
%%-----------------------------------------------------------------
loop(Parent, Name, StateName, StateData, Mod, hibernate, Debug,
Limits, Queue, QueueLen)
when QueueLen > 0 ->
case queue:out(Queue) of
{{value, Msg}, Queue1} ->
decode_msg(Msg, Parent, Name, StateName, StateData, Mod, hibernate,
Debug, Limits, Queue1, QueueLen - 1, false);
{empty, _} ->
Reason = internal_queue_error,
error_info(Mod, Reason, Name, hibernate, StateName, StateData, Debug),
exit(Reason)
end;
loop(Parent, Name, StateName, StateData, Mod, hibernate, Debug,
Limits, _Queue, _QueueLen) ->
proc_lib:hibernate(?MODULE,wake_hib,
[Parent, Name, StateName, StateData, Mod,
Debug, Limits]);
%% First we test if we have reach a defined limit ...
loop(Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen) ->
try
message_queue_len(Limits, QueueLen)
%% TODO: We can add more limit checking here...
catch
{process_limit, Limit} ->
Reason = {process_limit, Limit},
Msg = {'EXIT', Parent, {error, {process_limit, Limit}}},
terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug)
end,
process_message(Parent, Name, StateName, StateData,
Mod, Time, Debug, Limits, Queue, QueueLen).
%% ... then we can process a new message:
process_message(Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen) ->
{Msg, Queue1, QueueLen1} = collect_messages(Queue, QueueLen, Time),
decode_msg(Msg,Parent, Name, StateName, StateData, Mod, Time,
Debug, Limits, Queue1, QueueLen1, false).
collect_messages(Queue, QueueLen, Time) ->
receive
Input ->
case Input of
{'EXIT', _Parent, priority_shutdown} ->
{Input, Queue, QueueLen};
_ ->
collect_messages(
queue:in(Input, Queue), QueueLen + 1, Time)
end
after 0 ->
case queue:out(Queue) of
{{value, Msg}, Queue1} ->
{Msg, Queue1, QueueLen - 1};
{empty, _} ->
receive
Input ->
{Input, Queue, QueueLen}
after Time ->
{{'$gen_event', timeout}, Queue, QueueLen}
end
end
end.
wake_hib(Parent, Name, StateName, StateData, Mod, Debug,
Limits) ->
Msg = receive
Input ->
Input
end,
Queue = queue:new(),
QueueLen = 0,
decode_msg(Msg, Parent, Name, StateName, StateData, Mod, hibernate,
Debug, Limits, Queue, QueueLen, true).
decode_msg(Msg,Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen, Hib) ->
put('$internal_queue_len', QueueLen),
case Msg of
{system, From, Req} ->
sys:handle_system_msg(Req, From, Parent, ?MODULE, Debug,
[Name, StateName, StateData,
Mod, Time, Limits, Queue, QueueLen], Hib);
{'EXIT', Parent, Reason} ->
terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug);
_Msg when Debug == [] ->
handle_msg(Msg, Parent, Name, StateName, StateData,
Mod, Time, Limits, Queue, QueueLen);
_Msg ->
Debug1 = sys:handle_debug(Debug, {?MODULE, print_event},
{Name, StateName}, {in, Msg}),
handle_msg(Msg, Parent, Name, StateName, StateData,
Mod, Time, Debug1, Limits, Queue, QueueLen)
end.
%%-----------------------------------------------------------------
%% Callback functions for system messages handling.
%%-----------------------------------------------------------------
system_continue(Parent, Debug, [Name, StateName, StateData,
Mod, Time, Limits, Queue, QueueLen]) ->
loop(Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen).
system_terminate(Reason, _Parent, Debug,
[Name, StateName, StateData, Mod, _Time, _Limits]) ->
terminate(Reason, Name, [], Mod, StateName, StateData, Debug).
system_code_change([Name, StateName, StateData, Mod, Time,
Limits, Queue, QueueLen],
_Module, OldVsn, Extra) ->
case catch Mod:code_change(OldVsn, StateName, StateData, Extra) of
{ok, NewStateName, NewStateData} ->
{ok, [Name, NewStateName, NewStateData, Mod, Time,
Limits, Queue, QueueLen]};
Else -> Else
end.
%%-----------------------------------------------------------------
%% Format debug messages. Print them as the call-back module sees
%% them, not as the real erlang messages. Use trace for that.
%%-----------------------------------------------------------------
print_event(Dev, {in, Msg}, {Name, StateName}) ->
case Msg of
{'$gen_event', Event} ->
io:format(Dev, "*DBG* ~p got event ~p in state ~w~n",
[Name, Event, StateName]);
{'$gen_all_state_event', Event} ->
io:format(Dev,
"*DBG* ~p got all_state_event ~p in state ~w~n",
[Name, Event, StateName]);
{timeout, Ref, {'$gen_timer', Message}} ->
io:format(Dev,
"*DBG* ~p got timer ~p in state ~w~n",
[Name, {timeout, Ref, Message}, StateName]);
{timeout, _Ref, {'$gen_event', Event}} ->
io:format(Dev,
"*DBG* ~p got timer ~p in state ~w~n",
[Name, Event, StateName]);
_ ->
io:format(Dev, "*DBG* ~p got ~p in state ~w~n",
[Name, Msg, StateName])
end;
print_event(Dev, {out, Msg, To, StateName}, Name) ->
io:format(Dev, "*DBG* ~p sent ~p to ~w~n"
" and switched to state ~w~n",
[Name, Msg, To, StateName]);
print_event(Dev, return, {Name, StateName}) ->
io:format(Dev, "*DBG* ~p switched to state ~w~n",
[Name, StateName]).
handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time,
Limits, Queue, QueueLen) -> %No debug here
From = from(Msg),
case catch dispatch(Msg, Mod, StateName, StateData) of
{next_state, NStateName, NStateData} ->
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, [], Limits, Queue, QueueLen);
{next_state, NStateName, NStateData, Time1} ->
loop(Parent, Name, NStateName, NStateData, Mod, Time1, [],
Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData} when From =/= undefined ->
reply(From, Reply),
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, [], Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData, Time1} when From =/= undefined ->
reply(From, Reply),
loop(Parent, Name, NStateName, NStateData, Mod, Time1, [],
Limits, Queue, QueueLen);
{stop, Reason, NStateData} ->
terminate(Reason, Name, Msg, Mod, StateName, NStateData, []);
{stop, Reason, Reply, NStateData} when From =/= undefined ->
{'EXIT', R} = (catch terminate(Reason, Name, Msg, Mod,
StateName, NStateData, [])),
reply(From, Reply),
exit(R);
{'EXIT', What} ->
terminate(What, Name, Msg, Mod, StateName, StateData, []);
Reply ->
terminate({bad_return_value, Reply},
Name, Msg, Mod, StateName, StateData, [])
end.
handle_msg(Msg, Parent, Name, StateName, StateData,
Mod, _Time, Debug, Limits, Queue, QueueLen) ->
From = from(Msg),
case catch dispatch(Msg, Mod, StateName, StateData) of
{next_state, NStateName, NStateData} ->
Debug1 = sys:handle_debug(Debug, {?MODULE, print_event},
{Name, NStateName}, return),
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, Debug1, Limits, Queue, QueueLen);
{next_state, NStateName, NStateData, Time1} ->
Debug1 = sys:handle_debug(Debug, {?MODULE, print_event},
{Name, NStateName}, return),
loop(Parent, Name, NStateName, NStateData,
Mod, Time1, Debug1, Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData} when From =/= undefined ->
Debug1 = reply(Name, From, Reply, Debug, NStateName),
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, Debug1, Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData, Time1} when From =/= undefined ->
Debug1 = reply(Name, From, Reply, Debug, NStateName),
loop(Parent, Name, NStateName, NStateData,
Mod, Time1, Debug1, Limits, Queue, QueueLen);
{stop, Reason, NStateData} ->
terminate(Reason, Name, Msg, Mod, StateName, NStateData, Debug);
{stop, Reason, Reply, NStateData} when From =/= undefined ->
{'EXIT', R} = (catch terminate(Reason, Name, Msg, Mod,
StateName, NStateData, Debug)),
reply(Name, From, Reply, Debug, StateName),
exit(R);
{'EXIT', What} ->
terminate(What, Name, Msg, Mod, StateName, StateData, Debug);
Reply ->
terminate({bad_return_value, Reply},
Name, Msg, Mod, StateName, StateData, Debug)
end.
dispatch({'$gen_event', Event}, Mod, StateName, StateData) ->
Mod:StateName(Event, StateData);
dispatch({'$gen_all_state_event', Event}, Mod, StateName, StateData) ->
Mod:handle_event(Event, StateName, StateData);
dispatch({'$gen_sync_event', From, Event}, Mod, StateName, StateData) ->
Mod:StateName(Event, From, StateData);
dispatch({'$gen_sync_all_state_event', From, Event},
Mod, StateName, StateData) ->
Mod:handle_sync_event(Event, From, StateName, StateData);
dispatch({timeout, Ref, {'$gen_timer', Msg}}, Mod, StateName, StateData) ->
Mod:StateName({timeout, Ref, Msg}, StateData);
dispatch({timeout, _Ref, {'$gen_event', Event}}, Mod, StateName, StateData) ->
Mod:StateName(Event, StateData);
dispatch(Info, Mod, StateName, StateData) ->
Mod:handle_info(Info, StateName, StateData).
from({'$gen_sync_event', From, _Event}) -> From;
from({'$gen_sync_all_state_event', From, _Event}) -> From;
from(_) -> undefined.
%% Send a reply to the client.
reply({To, Tag}, Reply) ->
catch To ! {Tag, Reply}.
reply(Name, {To, Tag}, Reply, Debug, StateName) ->
reply({To, Tag}, Reply),
sys:handle_debug(Debug, {?MODULE, print_event}, Name,
{out, Reply, To, StateName}).
%%% ---------------------------------------------------
%%% Terminate the server.
%%% ---------------------------------------------------
terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug) ->
case catch Mod:terminate(Reason, StateName, StateData) of
{'EXIT', R} ->
error_info(Mod, R, Name, Msg, StateName, StateData, Debug),
exit(R);
_ ->
case Reason of
normal ->
exit(normal);
shutdown ->
exit(shutdown);
priority_shutdown ->
%% Priority shutdown should be considered as
%% shutdown by SASL
exit(shutdown);
{process_limit, Limit} ->
%% Priority shutdown should be considered as
%% shutdown by SASL
error_logger:error_msg("FSM limit reached (~p): ~p~n",
[self(), Limit]),
exit(shutdown);
_ ->
error_info(Mod, Reason, Name, Msg, StateName, StateData, Debug),
exit(Reason)
end
end.
error_info(Mod, Reason, Name, Msg, StateName, StateData, Debug) ->
Reason1 =
case Reason of
{undef,[{M,F,A}|MFAs]} ->
case code:is_loaded(M) of
false ->
{'module could not be loaded',[{M,F,A}|MFAs]};
_ ->
case erlang:function_exported(M, F, length(A)) of
true ->
Reason;
false ->
{'function not exported',[{M,F,A}|MFAs]}
end
end;
_ ->
Reason
end,
StateToPrint = case erlang:function_exported(Mod, print_state, 1) of
true -> (catch Mod:print_state(StateData));
false -> StateData
end,
Str = "** State machine ~p terminating \n" ++
get_msg_str(Msg) ++
"** When State == ~p~n"
"** Data == ~p~n"
"** Reason for termination = ~n** ~p~n",
format(Str, [Name, get_msg(Msg), StateName, StateToPrint, Reason1]),
sys:print_log(Debug),
ok.
get_msg_str({'$gen_event', _Event}) ->
"** Last event in was ~p~n";
get_msg_str({'$gen_sync_event', _Event}) ->
"** Last sync event in was ~p~n";
get_msg_str({'$gen_all_state_event', _Event}) ->
"** Last event in was ~p (for all states)~n";
get_msg_str({'$gen_sync_all_state_event', _Event}) ->
"** Last sync event in was ~p (for all states)~n";
get_msg_str({timeout, _Ref, {'$gen_timer', _Msg}}) ->
"** Last timer event in was ~p~n";
get_msg_str({timeout, _Ref, {'$gen_event', _Msg}}) ->
"** Last timer event in was ~p~n";
get_msg_str(_Msg) ->
"** Last message in was ~p~n".
get_msg({'$gen_event', Event}) -> Event;
get_msg({'$gen_sync_event', Event}) -> Event;
get_msg({'$gen_all_state_event', Event}) -> Event;
get_msg({'$gen_sync_all_state_event', Event}) -> Event;
get_msg({timeout, Ref, {'$gen_timer', Msg}}) -> {timeout, Ref, Msg};
get_msg({timeout, _Ref, {'$gen_event', Event}}) -> Event;
get_msg(Msg) -> Msg.
%%-----------------------------------------------------------------
%% Status information
%%-----------------------------------------------------------------
format_status(Opt, StatusData) ->
[PDict, SysState, Parent, Debug, [Name, StateName, StateData, Mod, _Time]] =
StatusData,
Header = lists:concat(["Status for state machine ", Name]),
Log = sys:get_debug(log, Debug, []),
Specfic =
case erlang:function_exported(Mod, format_status, 2) of
true ->
case catch Mod:format_status(Opt,[PDict,StateData]) of
{'EXIT', _} -> [{data, [{"StateData", StateData}]}];
Else -> Else
end;
_ ->
[{data, [{"StateData", StateData}]}]
end,
[{header, Header},
{data, [{"Status", SysState},
{"Parent", Parent},
{"Logged events", Log},
{"StateName", StateName}]} |
Specfic].
%%-----------------------------------------------------------------
%% Resources limit management
%%-----------------------------------------------------------------
%% Extract know limit options
limit_options(Options) ->
limit_options(Options, #limits{}).
limit_options([], Limits) ->
Limits;
%% Maximum number of messages allowed in the process message queue
limit_options([{max_queue,N}|Options], Limits)
when is_integer(N) ->
NewLimits = Limits#limits{max_queue=N},
limit_options(Options, NewLimits);
limit_options([_|Options], Limits) ->
limit_options(Options, Limits).
%% Throw max_queue if we have reach the max queue size
%% Returns ok otherwise
message_queue_len(#limits{max_queue = undefined}, _QueueLen) ->
ok;
message_queue_len(#limits{max_queue = MaxQueue}, QueueLen) ->
Pid = self(),
case process_info(Pid, message_queue_len) of
{message_queue_len, N} when N + QueueLen > MaxQueue ->
throw({process_limit, {max_queue, N + QueueLen}});
_ ->
ok
end.
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/ejabberd-2.1.4/src/p1_fsm.erl | erlang | 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 via the world wide web 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.
AB. All Rights Reserved.''
The change adds the following features:
- You can pass the gen_fsm options to control resource usage.
{max_queue, N} will exit the process with priority_shutdown
message processing does not return in a given period of time, the
process will be terminated.
in case of a crash (just export the function print_state/1)
$Id$
-----------------------------------------------------------------
This state machine is somewhat more pure than state_lib. It is
allows a function handle_event to take care of events in all states.
It's not that pure anymore :( We also allow synchronized event sending.
If the Parent process terminates the Module:terminate/2
function is called.
The user module should export:
init(Args)
ignore
{stop, Reason}
StateName(Msg, StateData)
Reason = normal | shutdown | Term terminate(State) is called
StateName(Msg, From, StateData)
Reason = normal | shutdown | Term terminate(State) is called
handle_event(Msg, StateName, StateData)
{stop, Reason, Reply, NewStateData}
Reason = normal | shutdown | Term terminate(State) is called
handle_sync_event(Msg, From, StateName, StateData)
{stop, Reason, Reply, NewStateData}
Reason = normal | shutdown | Term terminate(State) is called
Reason = normal | shutdown | Term terminate(State) is called
terminate(Reason, StateName, StateData) Let the user module clean up
always called when server terminates
==> the return value is ignored
----------- -------
start -----> start
init <----- .
loop
StateName <----- .
handle_event <----- .
handle__sunc_event <----- .
handle_info <----- .
terminate <----- .
---------------------------------------------------
Internal exports
This state is used to defined resource control values:
---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
Starts a generic state machine.
Name ::= {local, atom()} | {global, atom()}
Options ::= [{debug, [Flag]}]
Flag ::= trace | log | {logfile, File} | statistics | debug
{error, Reason}
---------------------------------------------------
hence using the self() of this instance of the process.
This is to ensure that timers don't go astray in global
e.g. when straddling a failover, or turn up in a restarted
instance of the process.
to the (then) current state.
Returns Ref, sends Event after Time to the (then) current state.
an active timer/send_event_after, false otherwise.
enter_loop/4,5,6
Makes an existing process into a gen_fsm.
The calling process will enter the gen_fsm receive loop and become a
gen_fsm process.
The user is responsible for any initialization of the process,
including registering a name for it.
---------------------------------------------------
Initiate the new process.
Calls the Mod:init/Args function.
Finally an acknowledge is sent to Parent and the main
loop is entered.
---------------------------------------------------
-----------------------------------------------------------------
The MAIN loop
-----------------------------------------------------------------
First we test if we have reach a defined limit ...
TODO: We can add more limit checking here...
... then we can process a new message:
-----------------------------------------------------------------
Callback functions for system messages handling.
-----------------------------------------------------------------
-----------------------------------------------------------------
Format debug messages. Print them as the call-back module sees
them, not as the real erlang messages. Use trace for that.
-----------------------------------------------------------------
No debug here
Send a reply to the client.
---------------------------------------------------
Terminate the server.
---------------------------------------------------
Priority shutdown should be considered as
shutdown by SASL
Priority shutdown should be considered as
shutdown by SASL
-----------------------------------------------------------------
Status information
-----------------------------------------------------------------
-----------------------------------------------------------------
Resources limit management
-----------------------------------------------------------------
Extract know limit options
Maximum number of messages allowed in the process message queue
Throw max_queue if we have reach the max queue size
Returns ok otherwise | ` ` 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 "
The Initial Developer of the Original Code is Ericsson Utvecklings AB .
Portions created by Ericsson are Copyright 1999 ,
The code has been modified and improved by ProcessOne .
Copyright 2007 - 2010 , ProcessOne
- You can send ) to the p1_fsm process to
terminate immediatetly . If the fsm trap_exit process flag has been
set to true , the FSM terminate function will called .
- You can limit the time processing a message ( TODO ): If the
- You might customize the State data before sending it to error_logger
-module(p1_fsm).
still based on State dispatching ( one function per state ) , but
= = > { ok , , StateData }
{ ok , , StateData , Timeout }
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ reply , Reply , NewStateName , NewStateData }
{ reply , Reply , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ reply , Reply , NewStateName , NewStateData }
{ reply , Reply , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
handle_info(Info , StateName ) ( e.g. { ' EXIT ' , P , R } , { nodedown , N } , ...
= = > { next_state , NewStateName , NewStateData }
{ next_state , NewStateName , NewStateData , Timeout }
{ stop , , NewStateData }
The work flow ( of the fsm ) can be described as follows :
User module fsm
-export([start/3, start/4,
start_link/3, start_link/4,
send_event/2, sync_send_event/2, sync_send_event/3,
send_all_state_event/2,
sync_send_all_state_event/2, sync_send_all_state_event/3,
reply/2,
start_timer/2,send_event_after/2,cancel_timer/1,
enter_loop/4, enter_loop/5, enter_loop/6, wake_hib/7]).
-export([behaviour_info/1]).
-export([init_it/6, print_event/3,
system_continue/3,
system_terminate/4,
system_code_change/4,
format_status/2]).
-import(error_logger , [format/2]).
Internal gen_fsm state
-record(limits, {max_queue}).
Interface functions .
behaviour_info(callbacks) ->
[{init,1},{handle_event,3},{handle_sync_event,4},{handle_info,3},
{terminate,3},{code_change,4}, {print_state,1}];
behaviour_info(_Other) ->
undefined.
start(Mod , , Options )
start(Name , , , Options )
start_link(Mod , , Options )
start_link(Name , , , Options ) where :
Mod : : = atom ( ) , callback module implementing the ' real ' fsm
: : = term ( ) , init arguments ( to Mod : init/1 )
( debug = = log & & statistics )
Returns : { ok , Pid } |
{ error , { already_started , Pid } } |
start(Mod, Args, Options) ->
gen:start(?MODULE, nolink, Mod, Args, Options).
start(Name, Mod, Args, Options) ->
gen:start(?MODULE, nolink, Name, Mod, Args, Options).
start_link(Mod, Args, Options) ->
gen:start(?MODULE, link, Mod, Args, Options).
start_link(Name, Mod, Args, Options) ->
gen:start(?MODULE, link, Name, Mod, Args, Options).
send_event({global, Name}, Event) ->
catch global:send(Name, {'$gen_event', Event}),
ok;
send_event(Name, Event) ->
Name ! {'$gen_event', Event},
ok.
sync_send_event(Name, Event) ->
case catch gen:call(Name, '$gen_sync_event', Event) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_event, [Name, Event]}})
end.
sync_send_event(Name, Event, Timeout) ->
case catch gen:call(Name, '$gen_sync_event', Event, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_event, [Name, Event, Timeout]}})
end.
send_all_state_event({global, Name}, Event) ->
catch global:send(Name, {'$gen_all_state_event', Event}),
ok;
send_all_state_event(Name, Event) ->
Name ! {'$gen_all_state_event', Event},
ok.
sync_send_all_state_event(Name, Event) ->
case catch gen:call(Name, '$gen_sync_all_state_event', Event) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_all_state_event, [Name, Event]}})
end.
sync_send_all_state_event(Name, Event, Timeout) ->
case catch gen:call(Name, '$gen_sync_all_state_event', Event, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, sync_send_all_state_event,
[Name, Event, Timeout]}})
end.
Designed to be only callable within one of the callbacks
Returns Ref , sends event { timeout , Ref , Msg } after Time
start_timer(Time, Msg) ->
erlang:start_timer(Time, self(), {'$gen_timer', Msg}).
send_event_after(Time, Event) ->
erlang:start_timer(Time, self(), {'$gen_event', Event}).
Returns the remaing time for the timer if Ref referred to
cancel_timer(Ref) ->
case erlang:cancel_timer(Ref) of
false ->
receive {timeout, Ref, _} -> 0
after 0 -> false
end;
RemainingTime ->
RemainingTime
end.
The process * must * have been started using one of the start functions
in proc_lib , see proc_lib(3 ) .
enter_loop(Mod, Options, StateName, StateData) ->
enter_loop(Mod, Options, StateName, StateData, self(), infinity).
enter_loop(Mod, Options, StateName, StateData, ServerName = {_,_}) ->
enter_loop(Mod, Options, StateName, StateData, ServerName,infinity);
enter_loop(Mod, Options, StateName, StateData, Timeout) ->
enter_loop(Mod, Options, StateName, StateData, self(), Timeout).
enter_loop(Mod, Options, StateName, StateData, ServerName, Timeout) ->
Name = get_proc_name(ServerName),
Parent = get_parent(),
Debug = gen:debug_options(Options),
Limits = limit_options(Options),
Queue = queue:new(),
QueueLen = 0,
loop(Parent, Name, StateName, StateData, Mod, Timeout, Debug,
Limits, Queue, QueueLen).
get_proc_name(Pid) when is_pid(Pid) ->
Pid;
get_proc_name({local, Name}) ->
case process_info(self(), registered_name) of
{registered_name, Name} ->
Name;
{registered_name, _Name} ->
exit(process_not_registered);
[] ->
exit(process_not_registered)
end;
get_proc_name({global, Name}) ->
case global:safe_whereis_name(Name) of
undefined ->
exit(process_not_registered_globally);
Pid when Pid==self() ->
Name;
_Pid ->
exit(process_not_registered_globally)
end.
get_parent() ->
case get('$ancestors') of
[Parent | _] when is_pid(Parent) ->
Parent;
[Parent | _] when is_atom(Parent) ->
name_to_pid(Parent);
_ ->
exit(process_was_not_started_by_proc_lib)
end.
name_to_pid(Name) ->
case whereis(Name) of
undefined ->
case global:safe_whereis_name(Name) of
undefined ->
exit(could_not_find_registerd_name);
Pid ->
Pid
end;
Pid ->
Pid
end.
Register the name using the Rfunc function
init_it(Starter, self, Name, Mod, Args, Options) ->
init_it(Starter, self(), Name, Mod, Args, Options);
init_it(Starter, Parent, Name0, Mod, Args, Options) ->
Name = name(Name0),
Debug = gen:debug_options(Options),
Limits = limit_options(Options),
Queue = queue:new(),
QueueLen = 0,
case catch Mod:init(Args) of
{ok, StateName, StateData} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(Parent, Name, StateName, StateData, Mod, infinity, Debug, Limits, Queue, QueueLen);
{ok, StateName, StateData, Timeout} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(Parent, Name, StateName, StateData, Mod, Timeout, Debug, Limits, Queue, QueueLen);
{stop, Reason} ->
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
ignore ->
proc_lib:init_ack(Starter, ignore),
exit(normal);
{'EXIT', Reason} ->
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
Else ->
Error = {bad_return_value, Else},
proc_lib:init_ack(Starter, {error, Error}),
exit(Error)
end.
name({local,Name}) -> Name;
name({global,Name}) -> Name;
name(Pid) when is_pid(Pid) -> Pid.
loop(Parent, Name, StateName, StateData, Mod, hibernate, Debug,
Limits, Queue, QueueLen)
when QueueLen > 0 ->
case queue:out(Queue) of
{{value, Msg}, Queue1} ->
decode_msg(Msg, Parent, Name, StateName, StateData, Mod, hibernate,
Debug, Limits, Queue1, QueueLen - 1, false);
{empty, _} ->
Reason = internal_queue_error,
error_info(Mod, Reason, Name, hibernate, StateName, StateData, Debug),
exit(Reason)
end;
loop(Parent, Name, StateName, StateData, Mod, hibernate, Debug,
Limits, _Queue, _QueueLen) ->
proc_lib:hibernate(?MODULE,wake_hib,
[Parent, Name, StateName, StateData, Mod,
Debug, Limits]);
loop(Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen) ->
try
message_queue_len(Limits, QueueLen)
catch
{process_limit, Limit} ->
Reason = {process_limit, Limit},
Msg = {'EXIT', Parent, {error, {process_limit, Limit}}},
terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug)
end,
process_message(Parent, Name, StateName, StateData,
Mod, Time, Debug, Limits, Queue, QueueLen).
process_message(Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen) ->
{Msg, Queue1, QueueLen1} = collect_messages(Queue, QueueLen, Time),
decode_msg(Msg,Parent, Name, StateName, StateData, Mod, Time,
Debug, Limits, Queue1, QueueLen1, false).
collect_messages(Queue, QueueLen, Time) ->
receive
Input ->
case Input of
{'EXIT', _Parent, priority_shutdown} ->
{Input, Queue, QueueLen};
_ ->
collect_messages(
queue:in(Input, Queue), QueueLen + 1, Time)
end
after 0 ->
case queue:out(Queue) of
{{value, Msg}, Queue1} ->
{Msg, Queue1, QueueLen - 1};
{empty, _} ->
receive
Input ->
{Input, Queue, QueueLen}
after Time ->
{{'$gen_event', timeout}, Queue, QueueLen}
end
end
end.
wake_hib(Parent, Name, StateName, StateData, Mod, Debug,
Limits) ->
Msg = receive
Input ->
Input
end,
Queue = queue:new(),
QueueLen = 0,
decode_msg(Msg, Parent, Name, StateName, StateData, Mod, hibernate,
Debug, Limits, Queue, QueueLen, true).
decode_msg(Msg,Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen, Hib) ->
put('$internal_queue_len', QueueLen),
case Msg of
{system, From, Req} ->
sys:handle_system_msg(Req, From, Parent, ?MODULE, Debug,
[Name, StateName, StateData,
Mod, Time, Limits, Queue, QueueLen], Hib);
{'EXIT', Parent, Reason} ->
terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug);
_Msg when Debug == [] ->
handle_msg(Msg, Parent, Name, StateName, StateData,
Mod, Time, Limits, Queue, QueueLen);
_Msg ->
Debug1 = sys:handle_debug(Debug, {?MODULE, print_event},
{Name, StateName}, {in, Msg}),
handle_msg(Msg, Parent, Name, StateName, StateData,
Mod, Time, Debug1, Limits, Queue, QueueLen)
end.
system_continue(Parent, Debug, [Name, StateName, StateData,
Mod, Time, Limits, Queue, QueueLen]) ->
loop(Parent, Name, StateName, StateData, Mod, Time, Debug,
Limits, Queue, QueueLen).
system_terminate(Reason, _Parent, Debug,
[Name, StateName, StateData, Mod, _Time, _Limits]) ->
terminate(Reason, Name, [], Mod, StateName, StateData, Debug).
system_code_change([Name, StateName, StateData, Mod, Time,
Limits, Queue, QueueLen],
_Module, OldVsn, Extra) ->
case catch Mod:code_change(OldVsn, StateName, StateData, Extra) of
{ok, NewStateName, NewStateData} ->
{ok, [Name, NewStateName, NewStateData, Mod, Time,
Limits, Queue, QueueLen]};
Else -> Else
end.
print_event(Dev, {in, Msg}, {Name, StateName}) ->
case Msg of
{'$gen_event', Event} ->
io:format(Dev, "*DBG* ~p got event ~p in state ~w~n",
[Name, Event, StateName]);
{'$gen_all_state_event', Event} ->
io:format(Dev,
"*DBG* ~p got all_state_event ~p in state ~w~n",
[Name, Event, StateName]);
{timeout, Ref, {'$gen_timer', Message}} ->
io:format(Dev,
"*DBG* ~p got timer ~p in state ~w~n",
[Name, {timeout, Ref, Message}, StateName]);
{timeout, _Ref, {'$gen_event', Event}} ->
io:format(Dev,
"*DBG* ~p got timer ~p in state ~w~n",
[Name, Event, StateName]);
_ ->
io:format(Dev, "*DBG* ~p got ~p in state ~w~n",
[Name, Msg, StateName])
end;
print_event(Dev, {out, Msg, To, StateName}, Name) ->
io:format(Dev, "*DBG* ~p sent ~p to ~w~n"
" and switched to state ~w~n",
[Name, Msg, To, StateName]);
print_event(Dev, return, {Name, StateName}) ->
io:format(Dev, "*DBG* ~p switched to state ~w~n",
[Name, StateName]).
handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time,
From = from(Msg),
case catch dispatch(Msg, Mod, StateName, StateData) of
{next_state, NStateName, NStateData} ->
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, [], Limits, Queue, QueueLen);
{next_state, NStateName, NStateData, Time1} ->
loop(Parent, Name, NStateName, NStateData, Mod, Time1, [],
Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData} when From =/= undefined ->
reply(From, Reply),
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, [], Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData, Time1} when From =/= undefined ->
reply(From, Reply),
loop(Parent, Name, NStateName, NStateData, Mod, Time1, [],
Limits, Queue, QueueLen);
{stop, Reason, NStateData} ->
terminate(Reason, Name, Msg, Mod, StateName, NStateData, []);
{stop, Reason, Reply, NStateData} when From =/= undefined ->
{'EXIT', R} = (catch terminate(Reason, Name, Msg, Mod,
StateName, NStateData, [])),
reply(From, Reply),
exit(R);
{'EXIT', What} ->
terminate(What, Name, Msg, Mod, StateName, StateData, []);
Reply ->
terminate({bad_return_value, Reply},
Name, Msg, Mod, StateName, StateData, [])
end.
handle_msg(Msg, Parent, Name, StateName, StateData,
Mod, _Time, Debug, Limits, Queue, QueueLen) ->
From = from(Msg),
case catch dispatch(Msg, Mod, StateName, StateData) of
{next_state, NStateName, NStateData} ->
Debug1 = sys:handle_debug(Debug, {?MODULE, print_event},
{Name, NStateName}, return),
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, Debug1, Limits, Queue, QueueLen);
{next_state, NStateName, NStateData, Time1} ->
Debug1 = sys:handle_debug(Debug, {?MODULE, print_event},
{Name, NStateName}, return),
loop(Parent, Name, NStateName, NStateData,
Mod, Time1, Debug1, Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData} when From =/= undefined ->
Debug1 = reply(Name, From, Reply, Debug, NStateName),
loop(Parent, Name, NStateName, NStateData,
Mod, infinity, Debug1, Limits, Queue, QueueLen);
{reply, Reply, NStateName, NStateData, Time1} when From =/= undefined ->
Debug1 = reply(Name, From, Reply, Debug, NStateName),
loop(Parent, Name, NStateName, NStateData,
Mod, Time1, Debug1, Limits, Queue, QueueLen);
{stop, Reason, NStateData} ->
terminate(Reason, Name, Msg, Mod, StateName, NStateData, Debug);
{stop, Reason, Reply, NStateData} when From =/= undefined ->
{'EXIT', R} = (catch terminate(Reason, Name, Msg, Mod,
StateName, NStateData, Debug)),
reply(Name, From, Reply, Debug, StateName),
exit(R);
{'EXIT', What} ->
terminate(What, Name, Msg, Mod, StateName, StateData, Debug);
Reply ->
terminate({bad_return_value, Reply},
Name, Msg, Mod, StateName, StateData, Debug)
end.
dispatch({'$gen_event', Event}, Mod, StateName, StateData) ->
Mod:StateName(Event, StateData);
dispatch({'$gen_all_state_event', Event}, Mod, StateName, StateData) ->
Mod:handle_event(Event, StateName, StateData);
dispatch({'$gen_sync_event', From, Event}, Mod, StateName, StateData) ->
Mod:StateName(Event, From, StateData);
dispatch({'$gen_sync_all_state_event', From, Event},
Mod, StateName, StateData) ->
Mod:handle_sync_event(Event, From, StateName, StateData);
dispatch({timeout, Ref, {'$gen_timer', Msg}}, Mod, StateName, StateData) ->
Mod:StateName({timeout, Ref, Msg}, StateData);
dispatch({timeout, _Ref, {'$gen_event', Event}}, Mod, StateName, StateData) ->
Mod:StateName(Event, StateData);
dispatch(Info, Mod, StateName, StateData) ->
Mod:handle_info(Info, StateName, StateData).
from({'$gen_sync_event', From, _Event}) -> From;
from({'$gen_sync_all_state_event', From, _Event}) -> From;
from(_) -> undefined.
reply({To, Tag}, Reply) ->
catch To ! {Tag, Reply}.
reply(Name, {To, Tag}, Reply, Debug, StateName) ->
reply({To, Tag}, Reply),
sys:handle_debug(Debug, {?MODULE, print_event}, Name,
{out, Reply, To, StateName}).
terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug) ->
case catch Mod:terminate(Reason, StateName, StateData) of
{'EXIT', R} ->
error_info(Mod, R, Name, Msg, StateName, StateData, Debug),
exit(R);
_ ->
case Reason of
normal ->
exit(normal);
shutdown ->
exit(shutdown);
priority_shutdown ->
exit(shutdown);
{process_limit, Limit} ->
error_logger:error_msg("FSM limit reached (~p): ~p~n",
[self(), Limit]),
exit(shutdown);
_ ->
error_info(Mod, Reason, Name, Msg, StateName, StateData, Debug),
exit(Reason)
end
end.
error_info(Mod, Reason, Name, Msg, StateName, StateData, Debug) ->
Reason1 =
case Reason of
{undef,[{M,F,A}|MFAs]} ->
case code:is_loaded(M) of
false ->
{'module could not be loaded',[{M,F,A}|MFAs]};
_ ->
case erlang:function_exported(M, F, length(A)) of
true ->
Reason;
false ->
{'function not exported',[{M,F,A}|MFAs]}
end
end;
_ ->
Reason
end,
StateToPrint = case erlang:function_exported(Mod, print_state, 1) of
true -> (catch Mod:print_state(StateData));
false -> StateData
end,
Str = "** State machine ~p terminating \n" ++
get_msg_str(Msg) ++
"** When State == ~p~n"
"** Data == ~p~n"
"** Reason for termination = ~n** ~p~n",
format(Str, [Name, get_msg(Msg), StateName, StateToPrint, Reason1]),
sys:print_log(Debug),
ok.
get_msg_str({'$gen_event', _Event}) ->
"** Last event in was ~p~n";
get_msg_str({'$gen_sync_event', _Event}) ->
"** Last sync event in was ~p~n";
get_msg_str({'$gen_all_state_event', _Event}) ->
"** Last event in was ~p (for all states)~n";
get_msg_str({'$gen_sync_all_state_event', _Event}) ->
"** Last sync event in was ~p (for all states)~n";
get_msg_str({timeout, _Ref, {'$gen_timer', _Msg}}) ->
"** Last timer event in was ~p~n";
get_msg_str({timeout, _Ref, {'$gen_event', _Msg}}) ->
"** Last timer event in was ~p~n";
get_msg_str(_Msg) ->
"** Last message in was ~p~n".
get_msg({'$gen_event', Event}) -> Event;
get_msg({'$gen_sync_event', Event}) -> Event;
get_msg({'$gen_all_state_event', Event}) -> Event;
get_msg({'$gen_sync_all_state_event', Event}) -> Event;
get_msg({timeout, Ref, {'$gen_timer', Msg}}) -> {timeout, Ref, Msg};
get_msg({timeout, _Ref, {'$gen_event', Event}}) -> Event;
get_msg(Msg) -> Msg.
format_status(Opt, StatusData) ->
[PDict, SysState, Parent, Debug, [Name, StateName, StateData, Mod, _Time]] =
StatusData,
Header = lists:concat(["Status for state machine ", Name]),
Log = sys:get_debug(log, Debug, []),
Specfic =
case erlang:function_exported(Mod, format_status, 2) of
true ->
case catch Mod:format_status(Opt,[PDict,StateData]) of
{'EXIT', _} -> [{data, [{"StateData", StateData}]}];
Else -> Else
end;
_ ->
[{data, [{"StateData", StateData}]}]
end,
[{header, Header},
{data, [{"Status", SysState},
{"Parent", Parent},
{"Logged events", Log},
{"StateName", StateName}]} |
Specfic].
limit_options(Options) ->
limit_options(Options, #limits{}).
limit_options([], Limits) ->
Limits;
limit_options([{max_queue,N}|Options], Limits)
when is_integer(N) ->
NewLimits = Limits#limits{max_queue=N},
limit_options(Options, NewLimits);
limit_options([_|Options], Limits) ->
limit_options(Options, Limits).
message_queue_len(#limits{max_queue = undefined}, _QueueLen) ->
ok;
message_queue_len(#limits{max_queue = MaxQueue}, QueueLen) ->
Pid = self(),
case process_info(Pid, message_queue_len) of
{message_queue_len, N} when N + QueueLen > MaxQueue ->
throw({process_limit, {max_queue, N + QueueLen}});
_ ->
ok
end.
|
abb4d5bc77b3486598b75329a187ee9aa5516b5de6503fdbe76333a9d3e68c59 | nuprl/gradual-typing-performance | data.rkt | #lang racket/base
(provide
(struct-out Array)
(struct-out Settable-Array)
(struct-out Mutable-Array))
(define-struct Array (shape
size
strict?
strict!
unsafe-proc) #:prefab)
(define-struct (Settable-Array Array) (set-proc) #:prefab)
(define-struct (Mutable-Array Settable-Array) (data) #:prefab)
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/unsafe/synth/both/data.rkt | racket | #lang racket/base
(provide
(struct-out Array)
(struct-out Settable-Array)
(struct-out Mutable-Array))
(define-struct Array (shape
size
strict?
strict!
unsafe-proc) #:prefab)
(define-struct (Settable-Array Array) (set-proc) #:prefab)
(define-struct (Mutable-Array Settable-Array) (data) #:prefab)
|
|
81855e9551053992956bd99561cfd8049e66e92e823e117b6cecca890396842d | f-o-a-m/kepler | Prometheus.hs | # LANGUAGE TemplateHaskell #
module Tendermint.SDK.BaseApp.Metrics.Prometheus
(
-- | Config and Setup
MetricsScrapingConfig(..)
, prometheusPort
, MetricsState(..)
, metricsRegistry
, metricsCounters
, metricsHistograms
, PrometheusEnv(..)
, envMetricsState
, envMetricsScrapingConfig
, emptyState
, forkMetricsServer
-- * Utils
, mkPrometheusMetricId
, metricIdStorable
, countToIdentifier
, histogramToIdentifier
-- * Eval
, evalWithMetrics
, evalNothing
, evalMetrics
) where
import Control.Arrow ((***))
import Control.Concurrent (ThreadId,
forkIO)
import Control.Concurrent.MVar (MVar,
modifyMVar_,
newMVar)
import Control.Lens (makeLenses)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Map.Strict (Map, insert)
import qualified Data.Map.Strict as Map
import Data.String (IsString,
fromString)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Time (diffUTCTime,
getCurrentTime)
import Polysemy (Embed, Member,
Sem, interpretH,
pureT, raise,
runT)
import Polysemy.Reader (Reader (..),
ask)
import qualified System.Metrics.Prometheus.Concurrent.Registry as Registry
import qualified System.Metrics.Prometheus.Http.Scrape as Http
import qualified System.Metrics.Prometheus.Metric.Counter as Counter
import qualified System.Metrics.Prometheus.Metric.Histogram as Histogram
import qualified System.Metrics.Prometheus.MetricId as MetricId
import Tendermint.SDK.BaseApp.Metrics (CountName (..), HistogramName (..),
Metrics (..))
--------------------------------------------------------------------------------
-- Metrics Types
--------------------------------------------------------------------------------
-- | Core metrics state
type MetricsMap a = Map (Text, MetricId.Labels) a
data MetricsState = MetricsState
{ _metricsRegistry :: Registry.Registry
, _metricsCounters :: MVar (MetricsMap Counter.Counter)
, _metricsHistograms :: MVar (MetricsMap Histogram.Histogram)
}
makeLenses ''MetricsState
-- | Intermediary prometheus registry index key
data MetricIdentifier = MetricIdentifier
{ metricIdName :: Text
, metricIdLabels :: MetricId.Labels
, metricIdHistoBuckets :: [Double]
}
instance IsString MetricIdentifier where
fromString s = MetricIdentifier (fromString s) mempty mempty
fixMetricName :: Text -> Text
fixMetricName = Text.map fixer
where fixer c = if c `elem` validChars then c else '_'
validChars = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "_"
-- indexes
countToIdentifier :: CountName -> MetricIdentifier
countToIdentifier (CountName name labels) = MetricIdentifier
{ metricIdName = fixMetricName name
, metricIdLabels = MetricId.fromList labels
, metricIdHistoBuckets = []
}
histogramToIdentifier :: HistogramName -> MetricIdentifier
histogramToIdentifier (HistogramName name labels buckets) = MetricIdentifier
{ metricIdName = fixMetricName name
, metricIdLabels = MetricId.fromList labels
, metricIdHistoBuckets = buckets
}
-- | Prometheus registry index key
mkPrometheusMetricId :: MetricIdentifier -> MetricId.MetricId
mkPrometheusMetricId MetricIdentifier{..} =
MetricId.MetricId (MetricId.Name metricIdName) metricIdLabels
-- | Index key for storing metrics
metricIdStorable :: MetricIdentifier -> (Text, MetricId.Labels)
metricIdStorable c = (fixMetricName $ metricIdName c, fixMetricLabels $ metricIdLabels c)
where fixMetricLabels =
MetricId.fromList .
map (fixMetricName *** fixMetricName) .
MetricId.toList
--------------------------------------------------------------------------------
-- Config
--------------------------------------------------------------------------------
-- | Core metrics config
data MetricsScrapingConfig = MetricsScrapingConfig
{ _prometheusPort :: Int
}
makeLenses ''MetricsScrapingConfig
data PrometheusEnv = PrometheusEnv
{ _envMetricsState :: MetricsState
, _envMetricsScrapingConfig :: MetricsScrapingConfig
}
makeLenses ''PrometheusEnv
emptyState :: IO MetricsState
emptyState = do
counters <- newMVar Map.empty
histos <- newMVar Map.empty
registry <- Registry.new
return $ MetricsState registry counters histos
forkMetricsServer
:: MonadIO m
=> PrometheusEnv
-> m ThreadId
forkMetricsServer metCfg = liftIO $
let PrometheusEnv{..} = metCfg
port = _prometheusPort $ _envMetricsScrapingConfig
MetricsState{..} = _envMetricsState
in forkIO $ Http.serveHttpTextMetrics port ["metrics"] (Registry.sample _metricsRegistry)
--------------------------------------------------------------------------------
-- eval
--------------------------------------------------------------------------------
evalWithMetrics
:: Member (Embed IO) r
=> Member (Reader (Maybe PrometheusEnv)) r
=> Sem (Metrics ': r) a
-> Sem r a
evalWithMetrics action = do
mCfg <- ask
case mCfg of
Nothing -> evalNothing action
Just cfg -> evalMetrics (_envMetricsState cfg) action
evalNothing
:: Sem (Metrics ': r) a
-> Sem r a
evalNothing = do
interpretH (\case
IncCount _ -> pureT ()
WithTimer _ action -> do
a <- runT action
raise $ evalNothing a
)
-- | Increments existing count, if it doesn't exist, creates a new
-- | counter and increments it.
evalMetrics
:: Member (Embed IO) r
=> MetricsState
-> Sem (Metrics ': r) a
-> Sem r a
evalMetrics state@MetricsState{..} = do
interpretH (\case
IncCount ctrName -> do
let c@MetricIdentifier{..} = countToIdentifier ctrName
cid = metricIdStorable c
cMetricIdName = MetricId.Name metricIdName
liftIO $ modifyMVar_ _metricsCounters $ \counterMap ->
case Map.lookup cid counterMap of
Nothing -> do
newCtr <- liftIO $
Registry.registerCounter cMetricIdName metricIdLabels _metricsRegistry
let newCounterMap = insert cid newCtr counterMap
liftIO $ Counter.inc newCtr
pure newCounterMap
Just ctr -> do
liftIO $ Counter.inc ctr
pure counterMap
pureT ()
-- Updates a histogram with the time it takes to do an action
-- If histogram doesn't exist, creates a new one and observes it.
WithTimer histName action -> do
start <- liftIO $ getCurrentTime
a <- runT action
end <- liftIO $ getCurrentTime
let time = realToFrac (end `diffUTCTime` start)
observeHistogram state histName time
raise $ evalMetrics state a
)
-- | Updates a histogram with an observed value
observeHistogram :: MonadIO m => MetricsState -> HistogramName -> Double -> m ()
observeHistogram MetricsState{..} histName val = liftIO $ do
let h@MetricIdentifier{..} = histogramToIdentifier histName
hid = metricIdStorable h
hMetricIdName = MetricId.Name metricIdName
modifyMVar_ _metricsHistograms $ \histMap ->
case Map.lookup hid histMap of
Nothing -> do
newHist <-
Registry.registerHistogram hMetricIdName metricIdLabels metricIdHistoBuckets _metricsRegistry
let newHistMap = insert hid newHist histMap
Histogram.observe val newHist
pure $ newHistMap
Just hist -> do
Histogram.observe val hist
pure histMap
| null | https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-sdk/src/Tendermint/SDK/BaseApp/Metrics/Prometheus.hs | haskell | | Config and Setup
* Utils
* Eval
------------------------------------------------------------------------------
Metrics Types
------------------------------------------------------------------------------
| Core metrics state
| Intermediary prometheus registry index key
indexes
| Prometheus registry index key
| Index key for storing metrics
------------------------------------------------------------------------------
Config
------------------------------------------------------------------------------
| Core metrics config
------------------------------------------------------------------------------
eval
------------------------------------------------------------------------------
| Increments existing count, if it doesn't exist, creates a new
| counter and increments it.
Updates a histogram with the time it takes to do an action
If histogram doesn't exist, creates a new one and observes it.
| Updates a histogram with an observed value | # LANGUAGE TemplateHaskell #
module Tendermint.SDK.BaseApp.Metrics.Prometheus
(
MetricsScrapingConfig(..)
, prometheusPort
, MetricsState(..)
, metricsRegistry
, metricsCounters
, metricsHistograms
, PrometheusEnv(..)
, envMetricsState
, envMetricsScrapingConfig
, emptyState
, forkMetricsServer
, mkPrometheusMetricId
, metricIdStorable
, countToIdentifier
, histogramToIdentifier
, evalWithMetrics
, evalNothing
, evalMetrics
) where
import Control.Arrow ((***))
import Control.Concurrent (ThreadId,
forkIO)
import Control.Concurrent.MVar (MVar,
modifyMVar_,
newMVar)
import Control.Lens (makeLenses)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Map.Strict (Map, insert)
import qualified Data.Map.Strict as Map
import Data.String (IsString,
fromString)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Time (diffUTCTime,
getCurrentTime)
import Polysemy (Embed, Member,
Sem, interpretH,
pureT, raise,
runT)
import Polysemy.Reader (Reader (..),
ask)
import qualified System.Metrics.Prometheus.Concurrent.Registry as Registry
import qualified System.Metrics.Prometheus.Http.Scrape as Http
import qualified System.Metrics.Prometheus.Metric.Counter as Counter
import qualified System.Metrics.Prometheus.Metric.Histogram as Histogram
import qualified System.Metrics.Prometheus.MetricId as MetricId
import Tendermint.SDK.BaseApp.Metrics (CountName (..), HistogramName (..),
Metrics (..))
type MetricsMap a = Map (Text, MetricId.Labels) a
data MetricsState = MetricsState
{ _metricsRegistry :: Registry.Registry
, _metricsCounters :: MVar (MetricsMap Counter.Counter)
, _metricsHistograms :: MVar (MetricsMap Histogram.Histogram)
}
makeLenses ''MetricsState
data MetricIdentifier = MetricIdentifier
{ metricIdName :: Text
, metricIdLabels :: MetricId.Labels
, metricIdHistoBuckets :: [Double]
}
instance IsString MetricIdentifier where
fromString s = MetricIdentifier (fromString s) mempty mempty
fixMetricName :: Text -> Text
fixMetricName = Text.map fixer
where fixer c = if c `elem` validChars then c else '_'
validChars = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "_"
countToIdentifier :: CountName -> MetricIdentifier
countToIdentifier (CountName name labels) = MetricIdentifier
{ metricIdName = fixMetricName name
, metricIdLabels = MetricId.fromList labels
, metricIdHistoBuckets = []
}
histogramToIdentifier :: HistogramName -> MetricIdentifier
histogramToIdentifier (HistogramName name labels buckets) = MetricIdentifier
{ metricIdName = fixMetricName name
, metricIdLabels = MetricId.fromList labels
, metricIdHistoBuckets = buckets
}
mkPrometheusMetricId :: MetricIdentifier -> MetricId.MetricId
mkPrometheusMetricId MetricIdentifier{..} =
MetricId.MetricId (MetricId.Name metricIdName) metricIdLabels
metricIdStorable :: MetricIdentifier -> (Text, MetricId.Labels)
metricIdStorable c = (fixMetricName $ metricIdName c, fixMetricLabels $ metricIdLabels c)
where fixMetricLabels =
MetricId.fromList .
map (fixMetricName *** fixMetricName) .
MetricId.toList
data MetricsScrapingConfig = MetricsScrapingConfig
{ _prometheusPort :: Int
}
makeLenses ''MetricsScrapingConfig
data PrometheusEnv = PrometheusEnv
{ _envMetricsState :: MetricsState
, _envMetricsScrapingConfig :: MetricsScrapingConfig
}
makeLenses ''PrometheusEnv
emptyState :: IO MetricsState
emptyState = do
counters <- newMVar Map.empty
histos <- newMVar Map.empty
registry <- Registry.new
return $ MetricsState registry counters histos
forkMetricsServer
:: MonadIO m
=> PrometheusEnv
-> m ThreadId
forkMetricsServer metCfg = liftIO $
let PrometheusEnv{..} = metCfg
port = _prometheusPort $ _envMetricsScrapingConfig
MetricsState{..} = _envMetricsState
in forkIO $ Http.serveHttpTextMetrics port ["metrics"] (Registry.sample _metricsRegistry)
evalWithMetrics
:: Member (Embed IO) r
=> Member (Reader (Maybe PrometheusEnv)) r
=> Sem (Metrics ': r) a
-> Sem r a
evalWithMetrics action = do
mCfg <- ask
case mCfg of
Nothing -> evalNothing action
Just cfg -> evalMetrics (_envMetricsState cfg) action
evalNothing
:: Sem (Metrics ': r) a
-> Sem r a
evalNothing = do
interpretH (\case
IncCount _ -> pureT ()
WithTimer _ action -> do
a <- runT action
raise $ evalNothing a
)
evalMetrics
:: Member (Embed IO) r
=> MetricsState
-> Sem (Metrics ': r) a
-> Sem r a
evalMetrics state@MetricsState{..} = do
interpretH (\case
IncCount ctrName -> do
let c@MetricIdentifier{..} = countToIdentifier ctrName
cid = metricIdStorable c
cMetricIdName = MetricId.Name metricIdName
liftIO $ modifyMVar_ _metricsCounters $ \counterMap ->
case Map.lookup cid counterMap of
Nothing -> do
newCtr <- liftIO $
Registry.registerCounter cMetricIdName metricIdLabels _metricsRegistry
let newCounterMap = insert cid newCtr counterMap
liftIO $ Counter.inc newCtr
pure newCounterMap
Just ctr -> do
liftIO $ Counter.inc ctr
pure counterMap
pureT ()
WithTimer histName action -> do
start <- liftIO $ getCurrentTime
a <- runT action
end <- liftIO $ getCurrentTime
let time = realToFrac (end `diffUTCTime` start)
observeHistogram state histName time
raise $ evalMetrics state a
)
observeHistogram :: MonadIO m => MetricsState -> HistogramName -> Double -> m ()
observeHistogram MetricsState{..} histName val = liftIO $ do
let h@MetricIdentifier{..} = histogramToIdentifier histName
hid = metricIdStorable h
hMetricIdName = MetricId.Name metricIdName
modifyMVar_ _metricsHistograms $ \histMap ->
case Map.lookup hid histMap of
Nothing -> do
newHist <-
Registry.registerHistogram hMetricIdName metricIdLabels metricIdHistoBuckets _metricsRegistry
let newHistMap = insert hid newHist histMap
Histogram.observe val newHist
pure $ newHistMap
Just hist -> do
Histogram.observe val hist
pure histMap
|
8f05773d9231b235156b8d5c49c5202da4366ac4be114f2b594e65ca4856de86 | metaocaml/ber-metaocaml | w58.ml | TEST
flags = " -w A "
files = " module_without_cmx.mli "
* setup - ocamlc.byte - build - env
* * ocamlc.byte
module = " module_without_cmx.mli "
* * * ocamlc.byte
module = " w58.ml "
* * * * check - ocamlc.byte - output
* setup - ocamlopt.byte - build - env
* * ocamlopt.byte
module = " module_without_cmx.mli "
* * * ocamlopt.byte
module = " w58.ml "
* * * * check - ocamlopt.byte - output
flags = "-w A"
files = "module_without_cmx.mli"
* setup-ocamlc.byte-build-env
** ocamlc.byte
module = "module_without_cmx.mli"
*** ocamlc.byte
module = "w58.ml"
**** check-ocamlc.byte-output
* setup-ocamlopt.byte-build-env
** ocamlopt.byte
module = "module_without_cmx.mli"
*** ocamlopt.byte
module = "w58.ml"
**** check-ocamlopt.byte-output
*)
let () = print_endline (Module_without_cmx.id "Hello World")
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/warnings/w58.ml | ocaml | TEST
flags = " -w A "
files = " module_without_cmx.mli "
* setup - ocamlc.byte - build - env
* * ocamlc.byte
module = " module_without_cmx.mli "
* * * ocamlc.byte
module = " w58.ml "
* * * * check - ocamlc.byte - output
* setup - ocamlopt.byte - build - env
* * ocamlopt.byte
module = " module_without_cmx.mli "
* * * ocamlopt.byte
module = " w58.ml "
* * * * check - ocamlopt.byte - output
flags = "-w A"
files = "module_without_cmx.mli"
* setup-ocamlc.byte-build-env
** ocamlc.byte
module = "module_without_cmx.mli"
*** ocamlc.byte
module = "w58.ml"
**** check-ocamlc.byte-output
* setup-ocamlopt.byte-build-env
** ocamlopt.byte
module = "module_without_cmx.mli"
*** ocamlopt.byte
module = "w58.ml"
**** check-ocamlopt.byte-output
*)
let () = print_endline (Module_without_cmx.id "Hello World")
|
|
e27274cd2e2bf84151eee8904b2070551ef0bbcd6e1ab44bc39c6145a23ae631 | ocsigen/js_of_ocaml | state.ml |
Copyright ( c ) 2015 , < >
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
Copyright (c) 2015, KC Sivaramakrishnan <>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
(* state.ml *)
This file introduces the type [ CELL ] formalizing a memory cell
as a functor that , for any given type , implements the [ STATE ]
interface .
Three cell implementations are given :
( 1 ) [ GlobalMutVar ] , an implementation using global state .
( 2 ) [ LocalMutVar ] , an implementation using local state .
( 3 ) [ ] , a functional implementation in state - passing style .
The stating - passing -- style implementation comes from
.
as a functor that, for any given type, implements the [STATE]
interface.
Three cell implementations are given:
(1) [GlobalMutVar], an implementation using global state.
(2) [LocalMutVar], an implementation using local state.
(3) [StPassing], a functional implementation in state-passing style.
The stating-passing--style implementation comes from
.
*)
open Effect
open Effect.Deep
(* --------------------------------------------------------------------------- *)
(** Type Definitions. *)
(* [TYPE] specifies a type [t]. *)
module type TYPE = sig
type t
end
(* [STATE] is the type of a module that offers the functions [get] and [set]
for manipulating a piece of mutable state with contents in the type [t].
This module must also offer a function [run] for handling computations
that perform the operations [get] and [set].
*)
module type STATE = sig
type t
val get : unit -> t
val set : t -> unit
val run : init:t -> (unit -> 'a) -> t * 'a
end
(* [CELL] is the type of a functor that produces an
implementation of [STATE] for any given type.
*)
module type CELL = functor (T : TYPE) -> STATE with type t = T.t
Note .
The signatures [ STATE ] and [ CELL ] are equivalent to the following
record types , respectively :
` ` ` ocaml
type 's state = {
get : unit - > 's ;
set : 's - > unit ;
run : ' a. init : 's - > ( unit - > ' a ) - > 's * ' a
}
type cell = {
fresh : ' s. unit - > 's state
}
` ` `
We prefer the signatures [ STATE ] and [ CELL ] over the record types ,
because implementations of these interfaces often need to declare
new effect names ( which comes more naturally in the scope of a
module definition ) and because we need a module signature of cells
to declare the functor signature [ HEAP ] in the file [ ref.ml ] ( if we
want to avoid types such as [ cell - > ( module REF ) ] ) .
The signatures [STATE] and [CELL] are equivalent to the following
record types, respectively:
```ocaml
type 's state = {
get : unit -> 's;
set : 's -> unit;
run : 'a. init:'s -> (unit -> 'a) -> 's * 'a
}
type cell = {
fresh : 's. unit -> 's state
}
```
We prefer the signatures [STATE] and [CELL] over the record types,
because implementations of these interfaces often need to declare
new effect names (which comes more naturally in the scope of a
module definition) and because we need a module signature of cells
to declare the functor signature [HEAP] in the file [ref.ml] (if we
want to avoid types such as [cell -> (module REF)]).
*)
(* --------------------------------------------------------------------------- *)
(** Global State. *)
[ GlobalMutVar ] implements a cell using the global state .
The module produced by this functor allocates a fresh reference [ var ] ,
which initially holds the value [ None ] . The operations [ get ] and [ set ]
perform accesses to this reference , but can be called only in the scope
of [ run ] .
Nested applications of [ run ] ( given by the same module ) , such as
` ` ` ocaml
let open GlobalMutVar(struct type t = int end ) in
run ~init:0 ( fun _ - > run ~init:1 ( fun _ - > ( ) ) )
` ` ` ,
are unsafe , because the innermost [ run ] resets [ var ] to [ None ] .
The final read to [ var ] performed by the outermost [ run ] ( to construct
the pair [ t * ' a ] ) is thus invalidated .
applications of [ run ] ( given by the same module ) are unsafe ,
because an instance of [ run ] can reset [ var ] to [ None ] while parallel
instances are still ongoing . Moreover , accesses to [ var ] will suffer
from race conditions .
The module produced by this functor allocates a fresh reference [var],
which initially holds the value [None]. The operations [get] and [set]
perform accesses to this reference, but can be called only in the scope
of [run].
Nested applications of [run] (given by the same module), such as
```ocaml
let open GlobalMutVar(struct type t = int end) in
run ~init:0 (fun _ -> run ~init:1 (fun _ -> ()))
```,
are unsafe, because the innermost [run] resets [var] to [None].
The final read to [var] performed by the outermost [run] (to construct
the pair [t * 'a]) is thus invalidated.
Parallel applications of [run] (given by the same module) are unsafe,
because an instance of [run] can reset [var] to [None] while parallel
instances are still ongoing. Moreover, accesses to [var] will suffer
from race conditions.
*)
module GlobalMutVar : CELL =
functor
(T : TYPE)
->
struct
type t = T.t
let var = ref None
let get () =
match !var with
| Some x -> x
| None -> assert false
let set y = var := Some y
let run ~init main =
set init
|> fun _ ->
main () |> fun res -> get () |> fun x -> (var := None) |> fun _ -> x, res
end
(* --------------------------------------------------------------------------- *)
(** Local State. *)
[ LocalMutVar ] implements a cell using effect handlers and local mutable
state . The operations [ get ] and [ set ] are opaque : they are simply defined
as [ perform ] instructions to the effects [ Get ] and [ Set ] , respectively .
The program [ run ] interprets these effects as accesses to a local
reference [ var ] .
Nested applications of [ run ] are safe , but [ get ] and [ set ] are handled
by the innermost [ run ] . As an example , the program
` ` ` ocaml
let open LocalMutVar(struct type t = int end ) in
run ~init:0 ( fun _ - > set 3 ; run ~init:1 ( fun _ - > get ( ) + get ( ) ) )
` ` `
evaluates to [ ( 3 , ( 1 , 2 ) ) ] .
Parallel executions of [ run ] in separate stacks are safe . Even though
the effect names [ Get ] and [ Set ] are shared among multiple instances
of [ get ] and [ set ] , there is no interference among these instances ,
because effect names are immutable .
state. The operations [get] and [set] are opaque: they are simply defined
as [perform] instructions to the effects [Get] and [Set], respectively.
The program [run] interprets these effects as accesses to a local
reference [var].
Nested applications of [run] are safe, but [get] and [set] are handled
by the innermost [run]. As an example, the program
```ocaml
let open LocalMutVar(struct type t = int end) in
run ~init:0 (fun _ -> set 3; run ~init:1 (fun _ -> get() + get()))
```
evaluates to [(3, (1, 2))].
Parallel executions of [run] in separate stacks are safe. Even though
the effect names [Get] and [Set] are shared among multiple instances
of [get] and [set], there is no interference among these instances,
because effect names are immutable.
*)
module LocalMutVar : CELL =
functor
(T : TYPE)
->
struct
type t = T.t
type _ Effect.t += Get : t Effect.t
type _ Effect.t += Set : t -> unit Effect.t
let get () = perform Get
let set y = perform (Set y)
let run (type a) ~init main : t * a =
let var = ref init in
match_with
main
()
{ retc = (fun res -> !var, res)
; exnc = raise
; effc =
(fun (type b) (e : b Effect.t) ->
match e with
| Get -> Some (fun (k : (b, t * a) continuation) -> continue k (!var : t))
| Set y ->
Some
(fun k ->
var := y;
continue k ())
| _ -> None)
}
end
(* --------------------------------------------------------------------------- *)
(** State-Passing Style. *)
[ ] implements a cell using effect handlers and the state - passing
technique .
Like the functor [ LocalMutVar ] , the operations [ get ] and [ set ] are
implemented as [ perform ] instructions to the effects [ Get ] and [ Set ] ,
respectively . However , instead of interpreting these effects as accesses to
a reference , [ run ] applies the programming technique state - passing style ,
which avoids mutable state , thus assigning a functional interpretation to
[ Get ] and [ Set ] . More specifically , the program [ run main ~init ] performs
the application of the handler that monitors [ main ( ) ] to the contents of the
cell , which initially is [ init ] . When [ main ( ) ] performs an effect , the
effect branch can access the current state of the cell by immediately
returning a lambda abstraction that binds the contents of the cell as its
single formal argument . The continuation captures the evaluation context up
to ( and including ) the handler , therefore , when resuming the continuation ,
the handler must reconstruct its immediately surrounding frame
corresponding to the application to the contents of the cell .
Nested applications of [ run ] are safe . Parallel executions of [ run ] in
separate stacks are safe . The same remarks as for the functor [ LocalMutVar ]
apply .
technique.
Like the functor [LocalMutVar], the operations [get] and [set] are
implemented as [perform] instructions to the effects [Get] and [Set],
respectively. However, instead of interpreting these effects as accesses to
a reference, [run] applies the programming technique state-passing style,
which avoids mutable state, thus assigning a functional interpretation to
[Get] and [Set]. More specifically, the program [run main ~init] performs
the application of the handler that monitors [main()] to the contents of the
cell, which initially is [init]. When [main()] performs an effect, the
effect branch can access the current state of the cell by immediately
returning a lambda abstraction that binds the contents of the cell as its
single formal argument. The continuation captures the evaluation context up
to (and including) the handler, therefore, when resuming the continuation,
the handler must reconstruct its immediately surrounding frame
corresponding to the application to the contents of the cell.
Nested applications of [run] are safe. Parallel executions of [run] in
separate stacks are safe. The same remarks as for the functor [LocalMutVar]
apply.
*)
module StPassing : CELL =
functor
(T : TYPE)
->
struct
type t = T.t
type _ Effect.t += Get : t Effect.t
type _ Effect.t += Set : t -> unit Effect.t
let get () = perform Get
let set y = perform (Set y)
let run (type a) ~init (main : unit -> a) : t * a =
match_with
main
()
{ retc = (fun res x -> x, res)
; exnc = raise
; effc =
(fun (type b) (e : b Effect.t) ->
match e with
| Get ->
Some (fun (k : (b, t -> t * a) continuation) (x : t) -> continue k x x)
| Set y -> Some (fun k (_x : t) -> continue k () y)
| _ -> None)
}
init
end
(* --------------------------------------------------------------------------- *)
(** Examples. *)
open Printf
module IntCell = StPassing (struct
type t = int
end)
module StrCell = StPassing (struct
type t = string
end)
let main () : unit =
IntCell.(
printf "%d\n" (get ());
set 42;
printf "%d\n" (get ());
set 21;
printf "%d\n" (get ()));
StrCell.(
set "Hello...";
printf "%s\n" (get ());
set "...World!";
printf "%s\n" (get ()))
let%expect_test _ =
ignore (IntCell.run ~init:0 (fun () -> StrCell.run ~init:"" main));
[%expect {|
0
42
21
Hello...
...World! |}]
| null | https://raw.githubusercontent.com/ocsigen/js_of_ocaml/90d8240eed4e422f7074caf6c2516d429af48425/compiler/tests-jsoo/lib-effects/state.ml | ocaml | state.ml
---------------------------------------------------------------------------
* Type Definitions.
[TYPE] specifies a type [t].
[STATE] is the type of a module that offers the functions [get] and [set]
for manipulating a piece of mutable state with contents in the type [t].
This module must also offer a function [run] for handling computations
that perform the operations [get] and [set].
[CELL] is the type of a functor that produces an
implementation of [STATE] for any given type.
---------------------------------------------------------------------------
* Global State.
---------------------------------------------------------------------------
* Local State.
---------------------------------------------------------------------------
* State-Passing Style.
---------------------------------------------------------------------------
* Examples. |
Copyright ( c ) 2015 , < >
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
Copyright (c) 2015, KC Sivaramakrishnan <>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
This file introduces the type [ CELL ] formalizing a memory cell
as a functor that , for any given type , implements the [ STATE ]
interface .
Three cell implementations are given :
( 1 ) [ GlobalMutVar ] , an implementation using global state .
( 2 ) [ LocalMutVar ] , an implementation using local state .
( 3 ) [ ] , a functional implementation in state - passing style .
The stating - passing -- style implementation comes from
.
as a functor that, for any given type, implements the [STATE]
interface.
Three cell implementations are given:
(1) [GlobalMutVar], an implementation using global state.
(2) [LocalMutVar], an implementation using local state.
(3) [StPassing], a functional implementation in state-passing style.
The stating-passing--style implementation comes from
.
*)
open Effect
open Effect.Deep
module type TYPE = sig
type t
end
module type STATE = sig
type t
val get : unit -> t
val set : t -> unit
val run : init:t -> (unit -> 'a) -> t * 'a
end
module type CELL = functor (T : TYPE) -> STATE with type t = T.t
Note .
The signatures [ STATE ] and [ CELL ] are equivalent to the following
record types , respectively :
` ` ` ocaml
type 's state = {
get : unit - > 's ;
set : 's - > unit ;
run : ' a. init : 's - > ( unit - > ' a ) - > 's * ' a
}
type cell = {
fresh : ' s. unit - > 's state
}
` ` `
We prefer the signatures [ STATE ] and [ CELL ] over the record types ,
because implementations of these interfaces often need to declare
new effect names ( which comes more naturally in the scope of a
module definition ) and because we need a module signature of cells
to declare the functor signature [ HEAP ] in the file [ ref.ml ] ( if we
want to avoid types such as [ cell - > ( module REF ) ] ) .
The signatures [STATE] and [CELL] are equivalent to the following
record types, respectively:
```ocaml
type 's state = {
get : unit -> 's;
set : 's -> unit;
run : 'a. init:'s -> (unit -> 'a) -> 's * 'a
}
type cell = {
fresh : 's. unit -> 's state
}
```
We prefer the signatures [STATE] and [CELL] over the record types,
because implementations of these interfaces often need to declare
new effect names (which comes more naturally in the scope of a
module definition) and because we need a module signature of cells
to declare the functor signature [HEAP] in the file [ref.ml] (if we
want to avoid types such as [cell -> (module REF)]).
*)
[ GlobalMutVar ] implements a cell using the global state .
The module produced by this functor allocates a fresh reference [ var ] ,
which initially holds the value [ None ] . The operations [ get ] and [ set ]
perform accesses to this reference , but can be called only in the scope
of [ run ] .
Nested applications of [ run ] ( given by the same module ) , such as
` ` ` ocaml
let open GlobalMutVar(struct type t = int end ) in
run ~init:0 ( fun _ - > run ~init:1 ( fun _ - > ( ) ) )
` ` ` ,
are unsafe , because the innermost [ run ] resets [ var ] to [ None ] .
The final read to [ var ] performed by the outermost [ run ] ( to construct
the pair [ t * ' a ] ) is thus invalidated .
applications of [ run ] ( given by the same module ) are unsafe ,
because an instance of [ run ] can reset [ var ] to [ None ] while parallel
instances are still ongoing . Moreover , accesses to [ var ] will suffer
from race conditions .
The module produced by this functor allocates a fresh reference [var],
which initially holds the value [None]. The operations [get] and [set]
perform accesses to this reference, but can be called only in the scope
of [run].
Nested applications of [run] (given by the same module), such as
```ocaml
let open GlobalMutVar(struct type t = int end) in
run ~init:0 (fun _ -> run ~init:1 (fun _ -> ()))
```,
are unsafe, because the innermost [run] resets [var] to [None].
The final read to [var] performed by the outermost [run] (to construct
the pair [t * 'a]) is thus invalidated.
Parallel applications of [run] (given by the same module) are unsafe,
because an instance of [run] can reset [var] to [None] while parallel
instances are still ongoing. Moreover, accesses to [var] will suffer
from race conditions.
*)
module GlobalMutVar : CELL =
functor
(T : TYPE)
->
struct
type t = T.t
let var = ref None
let get () =
match !var with
| Some x -> x
| None -> assert false
let set y = var := Some y
let run ~init main =
set init
|> fun _ ->
main () |> fun res -> get () |> fun x -> (var := None) |> fun _ -> x, res
end
[ LocalMutVar ] implements a cell using effect handlers and local mutable
state . The operations [ get ] and [ set ] are opaque : they are simply defined
as [ perform ] instructions to the effects [ Get ] and [ Set ] , respectively .
The program [ run ] interprets these effects as accesses to a local
reference [ var ] .
Nested applications of [ run ] are safe , but [ get ] and [ set ] are handled
by the innermost [ run ] . As an example , the program
` ` ` ocaml
let open LocalMutVar(struct type t = int end ) in
run ~init:0 ( fun _ - > set 3 ; run ~init:1 ( fun _ - > get ( ) + get ( ) ) )
` ` `
evaluates to [ ( 3 , ( 1 , 2 ) ) ] .
Parallel executions of [ run ] in separate stacks are safe . Even though
the effect names [ Get ] and [ Set ] are shared among multiple instances
of [ get ] and [ set ] , there is no interference among these instances ,
because effect names are immutable .
state. The operations [get] and [set] are opaque: they are simply defined
as [perform] instructions to the effects [Get] and [Set], respectively.
The program [run] interprets these effects as accesses to a local
reference [var].
Nested applications of [run] are safe, but [get] and [set] are handled
by the innermost [run]. As an example, the program
```ocaml
let open LocalMutVar(struct type t = int end) in
run ~init:0 (fun _ -> set 3; run ~init:1 (fun _ -> get() + get()))
```
evaluates to [(3, (1, 2))].
Parallel executions of [run] in separate stacks are safe. Even though
the effect names [Get] and [Set] are shared among multiple instances
of [get] and [set], there is no interference among these instances,
because effect names are immutable.
*)
module LocalMutVar : CELL =
functor
(T : TYPE)
->
struct
type t = T.t
type _ Effect.t += Get : t Effect.t
type _ Effect.t += Set : t -> unit Effect.t
let get () = perform Get
let set y = perform (Set y)
let run (type a) ~init main : t * a =
let var = ref init in
match_with
main
()
{ retc = (fun res -> !var, res)
; exnc = raise
; effc =
(fun (type b) (e : b Effect.t) ->
match e with
| Get -> Some (fun (k : (b, t * a) continuation) -> continue k (!var : t))
| Set y ->
Some
(fun k ->
var := y;
continue k ())
| _ -> None)
}
end
[ ] implements a cell using effect handlers and the state - passing
technique .
Like the functor [ LocalMutVar ] , the operations [ get ] and [ set ] are
implemented as [ perform ] instructions to the effects [ Get ] and [ Set ] ,
respectively . However , instead of interpreting these effects as accesses to
a reference , [ run ] applies the programming technique state - passing style ,
which avoids mutable state , thus assigning a functional interpretation to
[ Get ] and [ Set ] . More specifically , the program [ run main ~init ] performs
the application of the handler that monitors [ main ( ) ] to the contents of the
cell , which initially is [ init ] . When [ main ( ) ] performs an effect , the
effect branch can access the current state of the cell by immediately
returning a lambda abstraction that binds the contents of the cell as its
single formal argument . The continuation captures the evaluation context up
to ( and including ) the handler , therefore , when resuming the continuation ,
the handler must reconstruct its immediately surrounding frame
corresponding to the application to the contents of the cell .
Nested applications of [ run ] are safe . Parallel executions of [ run ] in
separate stacks are safe . The same remarks as for the functor [ LocalMutVar ]
apply .
technique.
Like the functor [LocalMutVar], the operations [get] and [set] are
implemented as [perform] instructions to the effects [Get] and [Set],
respectively. However, instead of interpreting these effects as accesses to
a reference, [run] applies the programming technique state-passing style,
which avoids mutable state, thus assigning a functional interpretation to
[Get] and [Set]. More specifically, the program [run main ~init] performs
the application of the handler that monitors [main()] to the contents of the
cell, which initially is [init]. When [main()] performs an effect, the
effect branch can access the current state of the cell by immediately
returning a lambda abstraction that binds the contents of the cell as its
single formal argument. The continuation captures the evaluation context up
to (and including) the handler, therefore, when resuming the continuation,
the handler must reconstruct its immediately surrounding frame
corresponding to the application to the contents of the cell.
Nested applications of [run] are safe. Parallel executions of [run] in
separate stacks are safe. The same remarks as for the functor [LocalMutVar]
apply.
*)
module StPassing : CELL =
functor
(T : TYPE)
->
struct
type t = T.t
type _ Effect.t += Get : t Effect.t
type _ Effect.t += Set : t -> unit Effect.t
let get () = perform Get
let set y = perform (Set y)
let run (type a) ~init (main : unit -> a) : t * a =
match_with
main
()
{ retc = (fun res x -> x, res)
; exnc = raise
; effc =
(fun (type b) (e : b Effect.t) ->
match e with
| Get ->
Some (fun (k : (b, t -> t * a) continuation) (x : t) -> continue k x x)
| Set y -> Some (fun k (_x : t) -> continue k () y)
| _ -> None)
}
init
end
open Printf
module IntCell = StPassing (struct
type t = int
end)
module StrCell = StPassing (struct
type t = string
end)
let main () : unit =
IntCell.(
printf "%d\n" (get ());
set 42;
printf "%d\n" (get ());
set 21;
printf "%d\n" (get ()));
StrCell.(
set "Hello...";
printf "%s\n" (get ());
set "...World!";
printf "%s\n" (get ()))
let%expect_test _ =
ignore (IntCell.run ~init:0 (fun () -> StrCell.run ~init:"" main));
[%expect {|
0
42
21
Hello...
...World! |}]
|
cc17f9ceedb481416d03be0fee5ba51431671784109b2d030fa6c2f5538b2a02 | cronburg/antlr-haskell | DoubleSemi.hs | # LANGUAGE QuasiQuotes , , DeriveGeneric , TypeFamilies
, DataKinds , ScopedTypeVariables , OverloadedStrings , TypeSynonymInstances
, FlexibleInstances , UndecidableInstances , FlexibleContexts , TemplateHaskell #
, DataKinds, ScopedTypeVariables, OverloadedStrings, TypeSynonymInstances
, FlexibleInstances, UndecidableInstances, FlexibleContexts, TemplateHaskell #-}
module DoubleSemi where
import Language.ANTLR4
$( return [] )
[g4|
grammar Dbl;
dbl : 'a' | 'f' ; // ;
WS : [ \t\r\n]+ -> String;
|]
isWS T_WS = True
isWS _ = False
| null | https://raw.githubusercontent.com/cronburg/antlr-haskell/7a9367038eaa58f9764f2ff694269245fbebc155/test/g4/DoubleSemi.hs | haskell | # LANGUAGE QuasiQuotes , , DeriveGeneric , TypeFamilies
, DataKinds , ScopedTypeVariables , OverloadedStrings , TypeSynonymInstances
, FlexibleInstances , UndecidableInstances , FlexibleContexts , TemplateHaskell #
, DataKinds, ScopedTypeVariables, OverloadedStrings, TypeSynonymInstances
, FlexibleInstances, UndecidableInstances, FlexibleContexts, TemplateHaskell #-}
module DoubleSemi where
import Language.ANTLR4
$( return [] )
[g4|
grammar Dbl;
dbl : 'a' | 'f' ; // ;
WS : [ \t\r\n]+ -> String;
|]
isWS T_WS = True
isWS _ = False
|
|
43a4d22af48171f65c9e1863e63a8378d22d201224b0e0bad69f49b559725f61 | ghc/ghc | Word.hs | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash , UnboxedTuples #
# OPTIONS_HADDOCK not - home #
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Word
Copyright : ( c ) The University of Glasgow , 1997 - 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC Extensions )
--
Sized unsigned integral types : ' Word ' , ' Word8 ' , ' Word16 ' , ' ' , and
-- 'Word64'.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..),
-- * Shifts
uncheckedShiftL64#,
uncheckedShiftRL64#,
* Byte swapping
byteSwap16,
byteSwap32,
byteSwap64,
-- * Bit reversal
bitReverse8,
bitReverse16,
bitReverse32,
bitReverse64,
-- * Equality operators
-- | See GHC.Classes#matching_overloaded_methods_in_rules
eqWord, neWord, gtWord, geWord, ltWord, leWord,
eqWord8, neWord8, gtWord8, geWord8, ltWord8, leWord8,
eqWord16, neWord16, gtWord16, geWord16, ltWord16, leWord16,
eqWord32, neWord32, gtWord32, geWord32, ltWord32, leWord32,
eqWord64, neWord64, gtWord64, geWord64, ltWord64, leWord64
) where
import Data.Maybe
import GHC.Prim
import GHC.Base
import GHC.Bits
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Ix
import GHC.Show
------------------------------------------------------------------------
-- type Word8
------------------------------------------------------------------------
Word8 is represented in the same way as Word . Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsWord8" #-} Word8
= W8# Word8#
^ 8 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
| @since 2.01
instance Eq Word8 where
(==) = eqWord8
(/=) = neWord8
eqWord8, neWord8 :: Word8 -> Word8 -> Bool
eqWord8 (W8# x) (W8# y) = isTrue# ((word8ToWord# x) `eqWord#` (word8ToWord# y))
neWord8 (W8# x) (W8# y) = isTrue# ((word8ToWord# x) `neWord#` (word8ToWord# y))
# INLINE [ 1 ] eqWord8 #
{-# INLINE [1] neWord8 #-}
| @since 2.01
instance Ord Word8 where
(<) = ltWord8
(<=) = leWord8
(>=) = geWord8
(>) = gtWord8
{-# INLINE [1] gtWord8 #-}
{-# INLINE [1] geWord8 #-}
# INLINE [ 1 ] ltWord8 #
{-# INLINE [1] leWord8 #-}
gtWord8, geWord8, ltWord8, leWord8 :: Word8 -> Word8 -> Bool
(W8# x) `gtWord8` (W8# y) = isTrue# (x `gtWord8#` y)
(W8# x) `geWord8` (W8# y) = isTrue# (x `geWord8#` y)
(W8# x) `ltWord8` (W8# y) = isTrue# (x `ltWord8#` y)
(W8# x) `leWord8` (W8# y) = isTrue# (x `leWord8#` y)
| @since 2.01
instance Show Word8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
| @since 2.01
instance Num Word8 where
(W8# x#) + (W8# y#) = W8# (x# `plusWord8#` y#)
(W8# x#) - (W8# y#) = W8# (x# `subWord8#` y#)
(W8# x#) * (W8# y#) = W8# (x# `timesWord8#` y#)
negate (W8# x#) = W8# (int8ToWord8# (negateInt8# (word8ToInt8# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W8# (wordToWord8# (integerToWord# i))
| @since 2.01
instance Real Word8 where
toRational x = toInteger x % 1
| @since 2.01
instance Enum Word8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word8"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word8)
= W8# (wordToWord8# (int2Word# i#))
| otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)
fromEnum (W8# x#) = I# (word2Int# (word8ToWord# x#))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = boundedEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = boundedEnumFromThen
| @since 2.01
instance Integral Word8 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
{-# INLINE div #-}
{-# INLINE mod #-}
# INLINE divMod #
quot (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord8#` y#)
| otherwise = divZeroError
rem (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord8#` y#)
| otherwise = divZeroError
quotRem (W8# x#) y@(W8# y#)
| y /= 0 = case x# `quotRemWord8#` y# of
(# q, r #) -> (W8# q, W8# r)
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W8# x#) = IS (word2Int# (word8ToWord# x#))
| @since 2.01
instance Bounded Word8 where
minBound = 0
maxBound = 0xFF
| @since 2.01
instance Ix Word8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
| @since 2.01
instance Bits Word8 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W8# x#) .&. (W8# y#) = W8# (wordToWord8# ((word8ToWord# x#) `and#` (word8ToWord# y#)))
(W8# x#) .|. (W8# y#) = W8# (wordToWord8# ((word8ToWord# x#) `or#` (word8ToWord# y#)))
(W8# x#) `xor` (W8# y#) = W8# (wordToWord8# ((word8ToWord# x#) `xor#` (word8ToWord# y#)))
complement (W8# x#) = W8# (wordToWord8# (not# (word8ToWord# x#)))
(W8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W8# (wordToWord8# ((word8ToWord# x#) `shiftL#` i#))
| otherwise = W8# (wordToWord8# ((word8ToWord# x#) `shiftRL#` negateInt# i#))
(W8# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W8# (wordToWord8# ((word8ToWord# x#) `shiftL#` i#))
| otherwise = overflowError
(W8# x#) `unsafeShiftL` (I# i#) =
W8# (wordToWord8# ((word8ToWord# x#) `uncheckedShiftL#` i#))
(W8# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W8# (wordToWord8# ((word8ToWord# x#) `shiftRL#` i#))
| otherwise = overflowError
(W8# x#) `unsafeShiftR` (I# i#) = W8# (wordToWord8# ((word8ToWord# x#) `uncheckedShiftRL#` i#))
(W8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W8# x#
| otherwise = W8# (wordToWord8# (((word8ToWord# x#) `uncheckedShiftL#` i'#) `or#`
((word8ToWord# x#) `uncheckedShiftRL#` (8# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 7##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W8# x#) = I# (word2Int# (popCnt8# (word8ToWord# x#)))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word8 where
{-# INLINE countLeadingZeros #-}
# INLINE countTrailingZeros #
finiteBitSize _ = 8
countLeadingZeros (W8# x#) = I# (word2Int# (clz8# (word8ToWord# x#)))
countTrailingZeros (W8# x#) = I# (word2Int# (ctz8# (word8ToWord# x#)))
# RULES
" properFraction / Float->(Word8,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Float ) }
" truncate / Float->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Float - > Int )
" floor / Float->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Float - > Int )
" ceiling / Float->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Float - > Int )
" round / Float->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word8,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) }
"truncate/Float->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int)
"floor/Float->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int)
"ceiling/Float->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int)
"round/Float->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word8,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Double ) }
" truncate / Double->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Double - > Int )
" floor / Double->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Double - > Int )
" ceiling / Double->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Double - > Int )
" round / Double->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word8,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) }
"truncate/Double->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int)
"floor/Double->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int)
"ceiling/Double->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int)
"round/Double->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
type Word16
------------------------------------------------------------------------
is represented in the same way as Word . Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsWord16" #-} Word16 = W16# Word16#
^ 16 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
| @since 2.01
instance Eq Word16 where
(==) = eqWord16
(/=) = neWord16
eqWord16, neWord16 :: Word16 -> Word16 -> Bool
eqWord16 (W16# x) (W16# y) = isTrue# ((word16ToWord# x) `eqWord#` (word16ToWord# y))
neWord16 (W16# x) (W16# y) = isTrue# ((word16ToWord# x) `neWord#` (word16ToWord# y))
# INLINE [ 1 ] eqWord16 #
{-# INLINE [1] neWord16 #-}
| @since 2.01
instance Ord Word16 where
(<) = ltWord16
(<=) = leWord16
(>=) = geWord16
(>) = gtWord16
# INLINE [ 1 ] gtWord16 #
{-# INLINE [1] geWord16 #-}
# INLINE [ 1 ] ltWord16 #
{-# INLINE [1] leWord16 #-}
gtWord16, geWord16, ltWord16, leWord16 :: Word16 -> Word16 -> Bool
(W16# x) `gtWord16` (W16# y) = isTrue# (x `gtWord16#` y)
(W16# x) `geWord16` (W16# y) = isTrue# (x `geWord16#` y)
(W16# x) `ltWord16` (W16# y) = isTrue# (x `ltWord16#` y)
(W16# x) `leWord16` (W16# y) = isTrue# (x `leWord16#` y)
| @since 2.01
instance Show Word16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
| @since 2.01
instance Num Word16 where
(W16# x#) + (W16# y#) = W16# (x# `plusWord16#` y#)
(W16# x#) - (W16# y#) = W16# (x# `subWord16#` y#)
(W16# x#) * (W16# y#) = W16# (x# `timesWord16#` y#)
negate (W16# x#) = W16# (int16ToWord16# (negateInt16# (word16ToInt16# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W16# (wordToWord16# (integerToWord# i))
| @since 2.01
instance Real Word16 where
toRational x = toInteger x % 1
| @since 2.01
instance Enum Word16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word16"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word16)
= W16# (wordToWord16# (int2Word# i#))
| otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)
fromEnum (W16# x#) = I# (word2Int# (word16ToWord# x#))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = boundedEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = boundedEnumFromThen
| @since 2.01
instance Integral Word16 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
{-# INLINE div #-}
{-# INLINE mod #-}
# INLINE divMod #
quot (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord16#` y#)
| otherwise = divZeroError
rem (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord16#` y#)
| otherwise = divZeroError
quotRem (W16# x#) y@(W16# y#)
| y /= 0 = case x# `quotRemWord16#` y# of
(# q, r #) -> (W16# q, W16# r)
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W16# x#) = IS (word2Int# (word16ToWord# x#))
| @since 2.01
instance Bounded Word16 where
minBound = 0
maxBound = 0xFFFF
| @since 2.01
instance Ix Word16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
| @since 2.01
instance Bits Word16 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W16# x#) .&. (W16# y#) = W16# (wordToWord16# ((word16ToWord# x#) `and#` (word16ToWord# y#)))
(W16# x#) .|. (W16# y#) = W16# (wordToWord16# ((word16ToWord# x#) `or#` (word16ToWord# y#)))
(W16# x#) `xor` (W16# y#) = W16# (wordToWord16# ((word16ToWord# x#) `xor#` (word16ToWord# y#)))
complement (W16# x#) = W16# (wordToWord16# (not# (word16ToWord# x#)))
(W16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W16# (wordToWord16# ((word16ToWord# x#) `shiftL#` i#))
| otherwise = W16# (wordToWord16# ((word16ToWord# x#) `shiftRL#` negateInt# i#))
(W16# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W16# (wordToWord16# ((word16ToWord# x#) `shiftL#` i#))
| otherwise = overflowError
(W16# x#) `unsafeShiftL` (I# i#) =
W16# (wordToWord16# ((word16ToWord# x#) `uncheckedShiftL#` i#))
(W16# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W16# (wordToWord16# ((word16ToWord# x#) `shiftRL#` i#))
| otherwise = overflowError
(W16# x#) `unsafeShiftR` (I# i#) = W16# (wordToWord16# ((word16ToWord# x#) `uncheckedShiftRL#` i#))
(W16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W16# x#
| otherwise = W16# (wordToWord16# (((word16ToWord# x#) `uncheckedShiftL#` i'#) `or#`
((word16ToWord# x#) `uncheckedShiftRL#` (16# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 15##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W16# x#) = I# (word2Int# (popCnt16# (word16ToWord# x#)))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word16 where
{-# INLINE countLeadingZeros #-}
# INLINE countTrailingZeros #
finiteBitSize _ = 16
countLeadingZeros (W16# x#) = I# (word2Int# (clz16# (word16ToWord# x#)))
countTrailingZeros (W16# x#) = I# (word2Int# (ctz16# (word16ToWord# x#)))
| Reverse order of bytes in ' Word16 ' .
--
-- @since 4.7.0.0
byteSwap16 :: Word16 -> Word16
byteSwap16 (W16# w#) = W16# (wordToWord16# (byteSwap16# (word16ToWord# w#)))
# RULES
" properFraction / Float->(Word16,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Float ) }
" truncate / Float->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Float - > Int )
" floor / Float->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Float - > Int )
" ceiling / Float->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Float - > Int )
" round / Float->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word16,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) }
"truncate/Float->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int)
"floor/Float->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int)
"ceiling/Float->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int)
"round/Float->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word16,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Double ) }
" truncate / Double->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Double - > Int )
" floor / Double->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Double - > Int )
" ceiling / Double->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Double - > Int )
" round / Double->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word16,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) }
"truncate/Double->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int)
"floor/Double->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int)
"ceiling/Double->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int)
"round/Double->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
type
------------------------------------------------------------------------
is represented in the same way as Word .
#if WORD_SIZE_IN_BITS > 32
Operations may assume and must ensure that it holds only values
-- from its logical range.
We can use rewrite rules for the RealFrac methods
# RULES
" properFraction / Float->(Word32,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Float ) }
" truncate / Float->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Float - > Int )
" floor / Float->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Float - > Int )
" ceiling / Float->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Float - > Int )
" round / Float->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word32,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) }
"truncate/Float->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int)
"floor/Float->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int)
"ceiling/Float->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int)
"round/Float->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word32,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Double ) }
" truncate / Double->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Double - > Int )
" floor / Double->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Double - > Int )
" ceiling / Double->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Double - > Int )
" round / Double->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word32,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) }
"truncate/Double->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int)
"floor/Double->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int)
"ceiling/Double->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int)
"round/Double->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Double -> Int)
#-}
#endif
# CTYPE " HsWord32 " #
^ 32 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
| @since 2.01
instance Eq Word32 where
(==) = eqWord32
(/=) = neWord32
eqWord32, neWord32 :: Word32 -> Word32 -> Bool
eqWord32 (W32# x) (W32# y) = isTrue# ((word32ToWord# x) `eqWord#` (word32ToWord# y))
neWord32 (W32# x) (W32# y) = isTrue# ((word32ToWord# x) `neWord#` (word32ToWord# y))
# INLINE [ 1 ] eqWord32 #
{-# INLINE [1] neWord32 #-}
| @since 2.01
instance Ord Word32 where
(<) = ltWord32
(<=) = leWord32
(>=) = geWord32
(>) = gtWord32
{-# INLINE [1] gtWord32 #-}
{-# INLINE [1] geWord32 #-}
{-# INLINE [1] ltWord32 #-}
{-# INLINE [1] leWord32 #-}
gtWord32, geWord32, ltWord32, leWord32 :: Word32 -> Word32 -> Bool
(W32# x) `gtWord32` (W32# y) = isTrue# (x `gtWord32#` y)
(W32# x) `geWord32` (W32# y) = isTrue# (x `geWord32#` y)
(W32# x) `ltWord32` (W32# y) = isTrue# (x `ltWord32#` y)
(W32# x) `leWord32` (W32# y) = isTrue# (x `leWord32#` y)
| @since 2.01
instance Num Word32 where
(W32# x#) + (W32# y#) = W32# (x# `plusWord32#` y#)
(W32# x#) - (W32# y#) = W32# (x# `subWord32#` y#)
(W32# x#) * (W32# y#) = W32# (x# `timesWord32#` y#)
negate (W32# x#) = W32# (int32ToWord32# (negateInt32# (word32ToInt32# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W32# (wordToWord32# (integerToWord# i))
| @since 2.01
instance Enum Word32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word32"
toEnum i@(I# i#)
| i >= 0
#if WORD_SIZE_IN_BITS > 32
&& i <= fromIntegral (maxBound::Word32)
#endif
= W32# (wordToWord32# (int2Word# i#))
| otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)
#if WORD_SIZE_IN_BITS == 32
fromEnum x@(W32# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# (word32ToWord# x#))
| otherwise = fromEnumError "Word32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
#else
fromEnum (W32# x#) = I# (word2Int# (word32ToWord# x#))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = boundedEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = boundedEnumFromThen
#endif
| @since 2.01
instance Integral Word32 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
{-# INLINE div #-}
{-# INLINE mod #-}
# INLINE divMod #
quot (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord32#` y#)
| otherwise = divZeroError
rem (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord32#` y#)
| otherwise = divZeroError
quotRem (W32# x#) y@(W32# y#)
| y /= 0 = case x# `quotRemWord32#` y# of
(# q, r #) -> (W32# q, W32# r)
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W32# x#) = integerFromWord# (word32ToWord# x#)
| @since 2.01
instance Bits Word32 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W32# x#) .&. (W32# y#) = W32# (wordToWord32# ((word32ToWord# x#) `and#` (word32ToWord# y#)))
(W32# x#) .|. (W32# y#) = W32# (wordToWord32# ((word32ToWord# x#) `or#` (word32ToWord# y#)))
(W32# x#) `xor` (W32# y#) = W32# (wordToWord32# ((word32ToWord# x#) `xor#` (word32ToWord# y#)))
complement (W32# x#) = W32# (wordToWord32# (not# (word32ToWord# x#)))
(W32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W32# (wordToWord32# ((word32ToWord# x#) `shiftL#` i#))
| otherwise = W32# (wordToWord32# ((word32ToWord# x#) `shiftRL#` negateInt# i#))
(W32# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W32# (wordToWord32# ((word32ToWord# x#) `shiftL#` i#))
| otherwise = overflowError
(W32# x#) `unsafeShiftL` (I# i#) =
W32# (wordToWord32# ((word32ToWord# x#) `uncheckedShiftL#` i#))
(W32# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W32# (wordToWord32# ((word32ToWord# x#) `shiftRL#` i#))
| otherwise = overflowError
(W32# x#) `unsafeShiftR` (I# i#) = W32# (wordToWord32# ((word32ToWord# x#) `uncheckedShiftRL#` i#))
(W32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W32# x#
| otherwise = W32# (wordToWord32# (((word32ToWord# x#) `uncheckedShiftL#` i'#) `or#`
((word32ToWord# x#) `uncheckedShiftRL#` (32# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 31##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W32# x#) = I# (word2Int# (popCnt32# (word32ToWord# x#)))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word32 where
{-# INLINE countLeadingZeros #-}
# INLINE countTrailingZeros #
finiteBitSize _ = 32
countLeadingZeros (W32# x#) = I# (word2Int# (clz32# (word32ToWord# x#)))
countTrailingZeros (W32# x#) = I# (word2Int# (ctz32# (word32ToWord# x#)))
| @since 2.01
instance Show Word32 where
#if WORD_SIZE_IN_BITS < 33
showsPrec p x = showsPrec p (toInteger x)
#else
showsPrec p x = showsPrec p (fromIntegral x :: Int)
#endif
| @since 2.01
instance Real Word32 where
toRational x = toInteger x % 1
| @since 2.01
instance Bounded Word32 where
minBound = 0
maxBound = 0xFFFFFFFF
| @since 2.01
instance Ix Word32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
| Reverse order of bytes in ' ' .
--
-- @since 4.7.0.0
byteSwap32 :: Word32 -> Word32
byteSwap32 (W32# w#) = W32# (wordToWord32# (byteSwap32# (word32ToWord# w#)))
------------------------------------------------------------------------
-- type Word64
------------------------------------------------------------------------
data {-# CTYPE "HsWord64" #-} Word64 = W64# Word64#
^ 64 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
| @since 2.01
instance Eq Word64 where
(==) = eqWord64
(/=) = neWord64
eqWord64, neWord64 :: Word64 -> Word64 -> Bool
eqWord64 (W64# x) (W64# y) = isTrue# (x `eqWord64#` y)
neWord64 (W64# x) (W64# y) = isTrue# (x `neWord64#` y)
# INLINE [ 1 ] eqWord64 #
{-# INLINE [1] neWord64 #-}
| @since 2.01
instance Ord Word64 where
(<) = ltWord64
(<=) = leWord64
(>=) = geWord64
(>) = gtWord64
# INLINE [ 1 ] gtWord64 #
{-# INLINE [1] geWord64 #-}
{-# INLINE [1] ltWord64 #-}
# INLINE [ 1 ] leWord64 #
gtWord64, geWord64, ltWord64, leWord64 :: Word64 -> Word64 -> Bool
(W64# x) `gtWord64` (W64# y) = isTrue# (x `gtWord64#` y)
(W64# x) `geWord64` (W64# y) = isTrue# (x `geWord64#` y)
(W64# x) `ltWord64` (W64# y) = isTrue# (x `ltWord64#` y)
(W64# x) `leWord64` (W64# y) = isTrue# (x `leWord64#` y)
| @since 2.01
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (x# `plusWord64#` y#)
(W64# x#) - (W64# y#) = W64# (x# `subWord64#` y#)
(W64# x#) * (W64# y#) = W64# (x# `timesWord64#` y#)
negate (W64# x#) = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord64# i)
| @since 2.01
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (wordToWord64# (int2Word# i#))
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# (word64ToWord# x#))
| otherwise = fromEnumError "Word64" x
#if WORD_SIZE_IN_BITS < 64
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = integralEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = integralEnumFromThen
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromTo #
enumFromTo = integralEnumFromTo
See Note [ Stable Unfolding for list producers ] in
{-# INLINE enumFromThenTo #-}
enumFromThenTo = integralEnumFromThenTo
#else
use Word 's as it has better support for fusion . We ca n't use
` boundedEnumFrom ` and ` boundedEnumFromThen ` -- which use Int 's
instance -- because Word64 is n't compatible with Int / Int64 's domain .
--
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom x = map fromIntegral (enumFrom (fromIntegral x :: Word))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen x y = map fromIntegral (enumFromThen (fromIntegral x :: Word) (fromIntegral y))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromTo #
enumFromTo x y = map fromIntegral (enumFromTo (fromIntegral x :: Word) (fromIntegral y))
See Note [ Stable Unfolding for list producers ] in
{-# INLINE enumFromThenTo #-}
enumFromThenTo x y z = map fromIntegral (enumFromThenTo (fromIntegral x :: Word) (fromIntegral y) (fromIntegral z))
#endif
| @since 2.01
instance Integral Word64 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
{-# INLINE div #-}
{-# INLINE mod #-}
# INLINE divMod #
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord64#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord64#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
#if WORD_SIZE_IN_BITS < 64
| y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))
#else
-- we don't have a `quotRemWord64#` primitive yet.
| y /= 0 = case quotRemWord# (word64ToWord# x#) (word64ToWord# y#) of
(# q, r #) -> (W64# (wordToWord64# q), W64# (wordToWord64# r))
#endif
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W64# x#) = integerFromWord64# x#
| @since 2.01
instance Bits Word64 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W64# x#) .&. (W64# y#) = W64# (x# `and64#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or64#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor64#` y#)
complement (W64# x#) = W64# (not64# x#)
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftLWord64#` i#)
| otherwise = W64# (x# `shiftRLWord64#` negateInt# i#)
(W64# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftLWord64#` i#)
| otherwise = overflowError
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#)
(W64# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftRLWord64#` i#)
| otherwise = overflowError
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL64#` i'#) `or64#`
(x# `uncheckedShiftRL64#` (64# -# i'#)))
where
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W64# x#) = I# (word2Int# (popCnt64# x#))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word64 where
{-# INLINE countLeadingZeros #-}
# INLINE countTrailingZeros #
finiteBitSize _ = 64
countLeadingZeros (W64# x#) = I# (word2Int# (clz64# x#))
countTrailingZeros (W64# x#) = I# (word2Int# (ctz64# x#))
| @since 2.01
instance Show Word64 where
showsPrec p x = showsPrec p (toInteger x)
| @since 2.01
instance Real Word64 where
toRational x = toInteger x % 1
| @since 2.01
instance Bounded Word64 where
minBound = 0
maxBound = 0xFFFFFFFFFFFFFFFF
| @since 2.01
instance Ix Word64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
-- | Reverse order of bytes in 'Word64'.
--
-- @since 4.7.0.0
byteSwap64 :: Word64 -> Word64
byteSwap64 (W64# w#) = W64# (byteSwap64# w#)
-- | Reverse the order of the bits in a 'Word8'.
--
@since 4.14.0.0
bitReverse8 :: Word8 -> Word8
bitReverse8 (W8# w#) = W8# (wordToWord8# (bitReverse8# (word8ToWord# w#)))
| Reverse the order of the bits in a ' Word16 ' .
--
@since 4.14.0.0
bitReverse16 :: Word16 -> Word16
bitReverse16 (W16# w#) = W16# (wordToWord16# (bitReverse16# (word16ToWord# w#)))
| Reverse the order of the bits in a ' ' .
--
@since 4.14.0.0
bitReverse32 :: Word32 -> Word32
bitReverse32 (W32# w#) = W32# (wordToWord32# (bitReverse32# (word32ToWord# w#)))
-- | Reverse the order of the bits in a 'Word64'.
--
@since 4.14.0.0
bitReverse64 :: Word64 -> Word64
bitReverse64 (W64# w#) = W64# (bitReverse64# w#)
-------------------------------------------------------------------------------
-- unchecked shift primops may be lowered into C shift operations which have
-- unspecified behaviour if the amount of bits to shift is greater or equal to the word
-- size in bits.
-- The following safe shift operations wrap unchecked primops to take this into
-- account: 0 is consistently returned when the shift amount is too big.
shiftRLWord64# :: Word64# -> Int# -> Word64#
a `shiftRLWord64#` b = uncheckedShiftRL64# a b
`and64#` int64ToWord64# (intToInt64# (shift_mask 64# b))
shiftLWord64# :: Word64# -> Int# -> Word64#
a `shiftLWord64#` b = uncheckedShiftL64# a b
`and64#` int64ToWord64# (intToInt64# (shift_mask 64# b))
| null | https://raw.githubusercontent.com/ghc/ghc/929161943f19e1673288adc83d165ddc99865798/libraries/base/GHC/Word.hs | haskell | ---------------------------------------------------------------------------
|
Module : GHC.Word
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
'Word64'.
---------------------------------------------------------------------------
* Shifts
* Bit reversal
* Equality operators
| See GHC.Classes#matching_overloaded_methods_in_rules
----------------------------------------------------------------------
type Word8
----------------------------------------------------------------------
and must ensure that it holds only values from its logical range.
# CTYPE "HsWord8" #
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord8 #
# INLINE [1] gtWord8 #
# INLINE [1] geWord8 #
# INLINE [1] leWord8 #
# INLINE div #
# INLINE mod #
# INLINE shift #
# INLINE countLeadingZeros #
----------------------------------------------------------------------
----------------------------------------------------------------------
and must ensure that it holds only values from its logical range.
# CTYPE "HsWord16" #
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord16 #
# INLINE [1] geWord16 #
# INLINE [1] leWord16 #
# INLINE div #
# INLINE mod #
# INLINE shift #
# INLINE countLeadingZeros #
@since 4.7.0.0
----------------------------------------------------------------------
----------------------------------------------------------------------
from its logical range.
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord32 #
# INLINE [1] gtWord32 #
# INLINE [1] geWord32 #
# INLINE [1] ltWord32 #
# INLINE [1] leWord32 #
# INLINE div #
# INLINE mod #
# INLINE shift #
# INLINE countLeadingZeros #
@since 4.7.0.0
----------------------------------------------------------------------
type Word64
----------------------------------------------------------------------
# CTYPE "HsWord64" #
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord64 #
# INLINE [1] geWord64 #
# INLINE [1] ltWord64 #
# INLINE enumFromThenTo #
which use Int 's
because Word64 is n't compatible with Int / Int64 's domain .
# INLINE enumFromThenTo #
# INLINE div #
# INLINE mod #
we don't have a `quotRemWord64#` primitive yet.
# INLINE shift #
# INLINE countLeadingZeros #
| Reverse order of bytes in 'Word64'.
@since 4.7.0.0
| Reverse the order of the bits in a 'Word8'.
| Reverse the order of the bits in a 'Word64'.
-----------------------------------------------------------------------------
unchecked shift primops may be lowered into C shift operations which have
unspecified behaviour if the amount of bits to shift is greater or equal to the word
size in bits.
The following safe shift operations wrap unchecked primops to take this into
account: 0 is consistently returned when the shift amount is too big. | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash , UnboxedTuples #
# OPTIONS_HADDOCK not - home #
Copyright : ( c ) The University of Glasgow , 1997 - 2002
Portability : non - portable ( GHC Extensions )
Sized unsigned integral types : ' Word ' , ' Word8 ' , ' Word16 ' , ' ' , and
#include "MachDeps.h"
module GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..),
uncheckedShiftL64#,
uncheckedShiftRL64#,
* Byte swapping
byteSwap16,
byteSwap32,
byteSwap64,
bitReverse8,
bitReverse16,
bitReverse32,
bitReverse64,
eqWord, neWord, gtWord, geWord, ltWord, leWord,
eqWord8, neWord8, gtWord8, geWord8, ltWord8, leWord8,
eqWord16, neWord16, gtWord16, geWord16, ltWord16, leWord16,
eqWord32, neWord32, gtWord32, geWord32, ltWord32, leWord32,
eqWord64, neWord64, gtWord64, geWord64, ltWord64, leWord64
) where
import Data.Maybe
import GHC.Prim
import GHC.Base
import GHC.Bits
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Ix
import GHC.Show
Word8 is represented in the same way as Word . Operations may assume
= W8# Word8#
^ 8 - bit unsigned integer type
| @since 2.01
instance Eq Word8 where
(==) = eqWord8
(/=) = neWord8
eqWord8, neWord8 :: Word8 -> Word8 -> Bool
eqWord8 (W8# x) (W8# y) = isTrue# ((word8ToWord# x) `eqWord#` (word8ToWord# y))
neWord8 (W8# x) (W8# y) = isTrue# ((word8ToWord# x) `neWord#` (word8ToWord# y))
# INLINE [ 1 ] eqWord8 #
| @since 2.01
instance Ord Word8 where
(<) = ltWord8
(<=) = leWord8
(>=) = geWord8
(>) = gtWord8
# INLINE [ 1 ] ltWord8 #
gtWord8, geWord8, ltWord8, leWord8 :: Word8 -> Word8 -> Bool
(W8# x) `gtWord8` (W8# y) = isTrue# (x `gtWord8#` y)
(W8# x) `geWord8` (W8# y) = isTrue# (x `geWord8#` y)
(W8# x) `ltWord8` (W8# y) = isTrue# (x `ltWord8#` y)
(W8# x) `leWord8` (W8# y) = isTrue# (x `leWord8#` y)
| @since 2.01
instance Show Word8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
| @since 2.01
instance Num Word8 where
(W8# x#) + (W8# y#) = W8# (x# `plusWord8#` y#)
(W8# x#) - (W8# y#) = W8# (x# `subWord8#` y#)
(W8# x#) * (W8# y#) = W8# (x# `timesWord8#` y#)
negate (W8# x#) = W8# (int8ToWord8# (negateInt8# (word8ToInt8# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W8# (wordToWord8# (integerToWord# i))
| @since 2.01
instance Real Word8 where
toRational x = toInteger x % 1
| @since 2.01
instance Enum Word8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word8"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word8)
= W8# (wordToWord8# (int2Word# i#))
| otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)
fromEnum (W8# x#) = I# (word2Int# (word8ToWord# x#))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = boundedEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = boundedEnumFromThen
| @since 2.01
instance Integral Word8 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
# INLINE divMod #
quot (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord8#` y#)
| otherwise = divZeroError
rem (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord8#` y#)
| otherwise = divZeroError
quotRem (W8# x#) y@(W8# y#)
| y /= 0 = case x# `quotRemWord8#` y# of
(# q, r #) -> (W8# q, W8# r)
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W8# x#) = IS (word2Int# (word8ToWord# x#))
| @since 2.01
instance Bounded Word8 where
minBound = 0
maxBound = 0xFF
| @since 2.01
instance Ix Word8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
| @since 2.01
instance Bits Word8 where
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W8# x#) .&. (W8# y#) = W8# (wordToWord8# ((word8ToWord# x#) `and#` (word8ToWord# y#)))
(W8# x#) .|. (W8# y#) = W8# (wordToWord8# ((word8ToWord# x#) `or#` (word8ToWord# y#)))
(W8# x#) `xor` (W8# y#) = W8# (wordToWord8# ((word8ToWord# x#) `xor#` (word8ToWord# y#)))
complement (W8# x#) = W8# (wordToWord8# (not# (word8ToWord# x#)))
(W8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W8# (wordToWord8# ((word8ToWord# x#) `shiftL#` i#))
| otherwise = W8# (wordToWord8# ((word8ToWord# x#) `shiftRL#` negateInt# i#))
(W8# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W8# (wordToWord8# ((word8ToWord# x#) `shiftL#` i#))
| otherwise = overflowError
(W8# x#) `unsafeShiftL` (I# i#) =
W8# (wordToWord8# ((word8ToWord# x#) `uncheckedShiftL#` i#))
(W8# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W8# (wordToWord8# ((word8ToWord# x#) `shiftRL#` i#))
| otherwise = overflowError
(W8# x#) `unsafeShiftR` (I# i#) = W8# (wordToWord8# ((word8ToWord# x#) `uncheckedShiftRL#` i#))
(W8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W8# x#
| otherwise = W8# (wordToWord8# (((word8ToWord# x#) `uncheckedShiftL#` i'#) `or#`
((word8ToWord# x#) `uncheckedShiftRL#` (8# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 7##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W8# x#) = I# (word2Int# (popCnt8# (word8ToWord# x#)))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word8 where
# INLINE countTrailingZeros #
finiteBitSize _ = 8
countLeadingZeros (W8# x#) = I# (word2Int# (clz8# (word8ToWord# x#)))
countTrailingZeros (W8# x#) = I# (word2Int# (ctz8# (word8ToWord# x#)))
# RULES
" properFraction / Float->(Word8,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Float ) }
" truncate / Float->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Float - > Int )
" floor / Float->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Float - > Int )
" ceiling / Float->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Float - > Int )
" round / Float->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word8,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) }
"truncate/Float->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int)
"floor/Float->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int)
"ceiling/Float->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int)
"round/Float->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word8,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Double ) }
" truncate / Double->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Double - > Int )
" floor / Double->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Double - > Int )
" ceiling / Double->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Double - > Int )
" round / Double->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word8,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) }
"truncate/Double->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int)
"floor/Double->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int)
"ceiling/Double->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int)
"round/Double->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Double -> Int)
#-}
type Word16
is represented in the same way as Word . Operations may assume
^ 16 - bit unsigned integer type
| @since 2.01
instance Eq Word16 where
(==) = eqWord16
(/=) = neWord16
eqWord16, neWord16 :: Word16 -> Word16 -> Bool
eqWord16 (W16# x) (W16# y) = isTrue# ((word16ToWord# x) `eqWord#` (word16ToWord# y))
neWord16 (W16# x) (W16# y) = isTrue# ((word16ToWord# x) `neWord#` (word16ToWord# y))
# INLINE [ 1 ] eqWord16 #
| @since 2.01
instance Ord Word16 where
(<) = ltWord16
(<=) = leWord16
(>=) = geWord16
(>) = gtWord16
# INLINE [ 1 ] gtWord16 #
# INLINE [ 1 ] ltWord16 #
gtWord16, geWord16, ltWord16, leWord16 :: Word16 -> Word16 -> Bool
(W16# x) `gtWord16` (W16# y) = isTrue# (x `gtWord16#` y)
(W16# x) `geWord16` (W16# y) = isTrue# (x `geWord16#` y)
(W16# x) `ltWord16` (W16# y) = isTrue# (x `ltWord16#` y)
(W16# x) `leWord16` (W16# y) = isTrue# (x `leWord16#` y)
| @since 2.01
instance Show Word16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
| @since 2.01
instance Num Word16 where
(W16# x#) + (W16# y#) = W16# (x# `plusWord16#` y#)
(W16# x#) - (W16# y#) = W16# (x# `subWord16#` y#)
(W16# x#) * (W16# y#) = W16# (x# `timesWord16#` y#)
negate (W16# x#) = W16# (int16ToWord16# (negateInt16# (word16ToInt16# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W16# (wordToWord16# (integerToWord# i))
| @since 2.01
instance Real Word16 where
toRational x = toInteger x % 1
| @since 2.01
instance Enum Word16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word16"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word16)
= W16# (wordToWord16# (int2Word# i#))
| otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)
fromEnum (W16# x#) = I# (word2Int# (word16ToWord# x#))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = boundedEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = boundedEnumFromThen
| @since 2.01
instance Integral Word16 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
# INLINE divMod #
quot (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord16#` y#)
| otherwise = divZeroError
rem (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord16#` y#)
| otherwise = divZeroError
quotRem (W16# x#) y@(W16# y#)
| y /= 0 = case x# `quotRemWord16#` y# of
(# q, r #) -> (W16# q, W16# r)
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W16# x#) = IS (word2Int# (word16ToWord# x#))
| @since 2.01
instance Bounded Word16 where
minBound = 0
maxBound = 0xFFFF
| @since 2.01
instance Ix Word16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
| @since 2.01
instance Bits Word16 where
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W16# x#) .&. (W16# y#) = W16# (wordToWord16# ((word16ToWord# x#) `and#` (word16ToWord# y#)))
(W16# x#) .|. (W16# y#) = W16# (wordToWord16# ((word16ToWord# x#) `or#` (word16ToWord# y#)))
(W16# x#) `xor` (W16# y#) = W16# (wordToWord16# ((word16ToWord# x#) `xor#` (word16ToWord# y#)))
complement (W16# x#) = W16# (wordToWord16# (not# (word16ToWord# x#)))
(W16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W16# (wordToWord16# ((word16ToWord# x#) `shiftL#` i#))
| otherwise = W16# (wordToWord16# ((word16ToWord# x#) `shiftRL#` negateInt# i#))
(W16# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W16# (wordToWord16# ((word16ToWord# x#) `shiftL#` i#))
| otherwise = overflowError
(W16# x#) `unsafeShiftL` (I# i#) =
W16# (wordToWord16# ((word16ToWord# x#) `uncheckedShiftL#` i#))
(W16# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W16# (wordToWord16# ((word16ToWord# x#) `shiftRL#` i#))
| otherwise = overflowError
(W16# x#) `unsafeShiftR` (I# i#) = W16# (wordToWord16# ((word16ToWord# x#) `uncheckedShiftRL#` i#))
(W16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W16# x#
| otherwise = W16# (wordToWord16# (((word16ToWord# x#) `uncheckedShiftL#` i'#) `or#`
((word16ToWord# x#) `uncheckedShiftRL#` (16# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 15##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W16# x#) = I# (word2Int# (popCnt16# (word16ToWord# x#)))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word16 where
# INLINE countTrailingZeros #
finiteBitSize _ = 16
countLeadingZeros (W16# x#) = I# (word2Int# (clz16# (word16ToWord# x#)))
countTrailingZeros (W16# x#) = I# (word2Int# (ctz16# (word16ToWord# x#)))
| Reverse order of bytes in ' Word16 ' .
byteSwap16 :: Word16 -> Word16
byteSwap16 (W16# w#) = W16# (wordToWord16# (byteSwap16# (word16ToWord# w#)))
# RULES
" properFraction / Float->(Word16,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Float ) }
" truncate / Float->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Float - > Int )
" floor / Float->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Float - > Int )
" ceiling / Float->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Float - > Int )
" round / Float->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word16,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) }
"truncate/Float->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int)
"floor/Float->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int)
"ceiling/Float->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int)
"round/Float->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word16,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Double ) }
" truncate / Double->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Double - > Int )
" floor / Double->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Double - > Int )
" ceiling / Double->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Double - > Int )
" round / Double->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word16,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) }
"truncate/Double->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int)
"floor/Double->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int)
"ceiling/Double->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int)
"round/Double->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Double -> Int)
#-}
type
is represented in the same way as Word .
#if WORD_SIZE_IN_BITS > 32
Operations may assume and must ensure that it holds only values
We can use rewrite rules for the RealFrac methods
# RULES
" properFraction / Float->(Word32,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Float ) }
" truncate / Float->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Float - > Int )
" floor / Float->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Float - > Int )
" ceiling / Float->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Float - > Int )
" round / Float->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word32,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) }
"truncate/Float->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int)
"floor/Float->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int)
"ceiling/Float->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int)
"round/Float->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word32,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Double ) }
" truncate / Double->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Double - > Int )
" floor / Double->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Double - > Int )
" ceiling / Double->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Double - > Int )
" round / Double->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word32,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) }
"truncate/Double->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int)
"floor/Double->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int)
"ceiling/Double->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int)
"round/Double->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Double -> Int)
#-}
#endif
# CTYPE " HsWord32 " #
^ 32 - bit unsigned integer type
| @since 2.01
instance Eq Word32 where
(==) = eqWord32
(/=) = neWord32
eqWord32, neWord32 :: Word32 -> Word32 -> Bool
eqWord32 (W32# x) (W32# y) = isTrue# ((word32ToWord# x) `eqWord#` (word32ToWord# y))
neWord32 (W32# x) (W32# y) = isTrue# ((word32ToWord# x) `neWord#` (word32ToWord# y))
# INLINE [ 1 ] eqWord32 #
| @since 2.01
instance Ord Word32 where
(<) = ltWord32
(<=) = leWord32
(>=) = geWord32
(>) = gtWord32
gtWord32, geWord32, ltWord32, leWord32 :: Word32 -> Word32 -> Bool
(W32# x) `gtWord32` (W32# y) = isTrue# (x `gtWord32#` y)
(W32# x) `geWord32` (W32# y) = isTrue# (x `geWord32#` y)
(W32# x) `ltWord32` (W32# y) = isTrue# (x `ltWord32#` y)
(W32# x) `leWord32` (W32# y) = isTrue# (x `leWord32#` y)
| @since 2.01
instance Num Word32 where
(W32# x#) + (W32# y#) = W32# (x# `plusWord32#` y#)
(W32# x#) - (W32# y#) = W32# (x# `subWord32#` y#)
(W32# x#) * (W32# y#) = W32# (x# `timesWord32#` y#)
negate (W32# x#) = W32# (int32ToWord32# (negateInt32# (word32ToInt32# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W32# (wordToWord32# (integerToWord# i))
| @since 2.01
instance Enum Word32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word32"
toEnum i@(I# i#)
| i >= 0
#if WORD_SIZE_IN_BITS > 32
&& i <= fromIntegral (maxBound::Word32)
#endif
= W32# (wordToWord32# (int2Word# i#))
| otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)
#if WORD_SIZE_IN_BITS == 32
fromEnum x@(W32# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# (word32ToWord# x#))
| otherwise = fromEnumError "Word32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
#else
fromEnum (W32# x#) = I# (word2Int# (word32ToWord# x#))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = boundedEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = boundedEnumFromThen
#endif
| @since 2.01
instance Integral Word32 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
# INLINE divMod #
quot (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord32#` y#)
| otherwise = divZeroError
rem (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord32#` y#)
| otherwise = divZeroError
quotRem (W32# x#) y@(W32# y#)
| y /= 0 = case x# `quotRemWord32#` y# of
(# q, r #) -> (W32# q, W32# r)
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W32# x#) = integerFromWord# (word32ToWord# x#)
| @since 2.01
instance Bits Word32 where
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W32# x#) .&. (W32# y#) = W32# (wordToWord32# ((word32ToWord# x#) `and#` (word32ToWord# y#)))
(W32# x#) .|. (W32# y#) = W32# (wordToWord32# ((word32ToWord# x#) `or#` (word32ToWord# y#)))
(W32# x#) `xor` (W32# y#) = W32# (wordToWord32# ((word32ToWord# x#) `xor#` (word32ToWord# y#)))
complement (W32# x#) = W32# (wordToWord32# (not# (word32ToWord# x#)))
(W32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W32# (wordToWord32# ((word32ToWord# x#) `shiftL#` i#))
| otherwise = W32# (wordToWord32# ((word32ToWord# x#) `shiftRL#` negateInt# i#))
(W32# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W32# (wordToWord32# ((word32ToWord# x#) `shiftL#` i#))
| otherwise = overflowError
(W32# x#) `unsafeShiftL` (I# i#) =
W32# (wordToWord32# ((word32ToWord# x#) `uncheckedShiftL#` i#))
(W32# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W32# (wordToWord32# ((word32ToWord# x#) `shiftRL#` i#))
| otherwise = overflowError
(W32# x#) `unsafeShiftR` (I# i#) = W32# (wordToWord32# ((word32ToWord# x#) `uncheckedShiftRL#` i#))
(W32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W32# x#
| otherwise = W32# (wordToWord32# (((word32ToWord# x#) `uncheckedShiftL#` i'#) `or#`
((word32ToWord# x#) `uncheckedShiftRL#` (32# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 31##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W32# x#) = I# (word2Int# (popCnt32# (word32ToWord# x#)))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word32 where
# INLINE countTrailingZeros #
finiteBitSize _ = 32
countLeadingZeros (W32# x#) = I# (word2Int# (clz32# (word32ToWord# x#)))
countTrailingZeros (W32# x#) = I# (word2Int# (ctz32# (word32ToWord# x#)))
| @since 2.01
instance Show Word32 where
#if WORD_SIZE_IN_BITS < 33
showsPrec p x = showsPrec p (toInteger x)
#else
showsPrec p x = showsPrec p (fromIntegral x :: Int)
#endif
| @since 2.01
instance Real Word32 where
toRational x = toInteger x % 1
| @since 2.01
instance Bounded Word32 where
minBound = 0
maxBound = 0xFFFFFFFF
| @since 2.01
instance Ix Word32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
| Reverse order of bytes in ' ' .
byteSwap32 :: Word32 -> Word32
byteSwap32 (W32# w#) = W32# (wordToWord32# (byteSwap32# (word32ToWord# w#)))
^ 64 - bit unsigned integer type
| @since 2.01
instance Eq Word64 where
(==) = eqWord64
(/=) = neWord64
eqWord64, neWord64 :: Word64 -> Word64 -> Bool
eqWord64 (W64# x) (W64# y) = isTrue# (x `eqWord64#` y)
neWord64 (W64# x) (W64# y) = isTrue# (x `neWord64#` y)
# INLINE [ 1 ] eqWord64 #
| @since 2.01
instance Ord Word64 where
(<) = ltWord64
(<=) = leWord64
(>=) = geWord64
(>) = gtWord64
# INLINE [ 1 ] gtWord64 #
# INLINE [ 1 ] leWord64 #
gtWord64, geWord64, ltWord64, leWord64 :: Word64 -> Word64 -> Bool
(W64# x) `gtWord64` (W64# y) = isTrue# (x `gtWord64#` y)
(W64# x) `geWord64` (W64# y) = isTrue# (x `geWord64#` y)
(W64# x) `ltWord64` (W64# y) = isTrue# (x `ltWord64#` y)
(W64# x) `leWord64` (W64# y) = isTrue# (x `leWord64#` y)
| @since 2.01
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (x# `plusWord64#` y#)
(W64# x#) - (W64# y#) = W64# (x# `subWord64#` y#)
(W64# x#) * (W64# y#) = W64# (x# `timesWord64#` y#)
negate (W64# x#) = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord64# i)
| @since 2.01
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (wordToWord64# (int2Word# i#))
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# (word64ToWord# x#))
| otherwise = fromEnumError "Word64" x
#if WORD_SIZE_IN_BITS < 64
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom = integralEnumFrom
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen = integralEnumFromThen
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromTo #
enumFromTo = integralEnumFromTo
See Note [ Stable Unfolding for list producers ] in
enumFromThenTo = integralEnumFromThenTo
#else
use Word 's as it has better support for fusion . We ca n't use
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFrom #
enumFrom x = map fromIntegral (enumFrom (fromIntegral x :: Word))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromThen #
enumFromThen x y = map fromIntegral (enumFromThen (fromIntegral x :: Word) (fromIntegral y))
See Note [ Stable Unfolding for list producers ] in
# INLINE enumFromTo #
enumFromTo x y = map fromIntegral (enumFromTo (fromIntegral x :: Word) (fromIntegral y))
See Note [ Stable Unfolding for list producers ] in
enumFromThenTo x y z = map fromIntegral (enumFromThenTo (fromIntegral x :: Word) (fromIntegral y) (fromIntegral z))
#endif
| @since 2.01
instance Integral Word64 where
see Note [ INLINE division wrappers ] in
# INLINE quot #
# INLINE rem #
# INLINE quotRem #
# INLINE divMod #
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord64#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord64#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
#if WORD_SIZE_IN_BITS < 64
| y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))
#else
| y /= 0 = case quotRemWord# (word64ToWord# x#) (word64ToWord# y#) of
(# q, r #) -> (W64# (wordToWord64# q), W64# (wordToWord64# r))
#endif
| otherwise = divZeroError
div x y = quot x y
mod x y = rem x y
divMod x y = quotRem x y
toInteger (W64# x#) = integerFromWord64# x#
| @since 2.01
instance Bits Word64 where
# INLINE bit #
# INLINE testBit #
# INLINE popCount #
(W64# x#) .&. (W64# y#) = W64# (x# `and64#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or64#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor64#` y#)
complement (W64# x#) = W64# (not64# x#)
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftLWord64#` i#)
| otherwise = W64# (x# `shiftRLWord64#` negateInt# i#)
(W64# x#) `shiftL` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftLWord64#` i#)
| otherwise = overflowError
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#)
(W64# x#) `shiftR` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftRLWord64#` i#)
| otherwise = overflowError
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL64#` i'#) `or64#`
(x# `uncheckedShiftRL64#` (64# -# i'#)))
where
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W64# x#) = I# (word2Int# (popCnt64# x#))
bit i = bitDefault i
testBit a i = testBitDefault a i
| @since 4.6.0.0
instance FiniteBits Word64 where
# INLINE countTrailingZeros #
finiteBitSize _ = 64
countLeadingZeros (W64# x#) = I# (word2Int# (clz64# x#))
countTrailingZeros (W64# x#) = I# (word2Int# (ctz64# x#))
| @since 2.01
instance Show Word64 where
showsPrec p x = showsPrec p (toInteger x)
| @since 2.01
instance Real Word64 where
toRational x = toInteger x % 1
| @since 2.01
instance Bounded Word64 where
minBound = 0
maxBound = 0xFFFFFFFFFFFFFFFF
| @since 2.01
instance Ix Word64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
byteSwap64 :: Word64 -> Word64
byteSwap64 (W64# w#) = W64# (byteSwap64# w#)
@since 4.14.0.0
bitReverse8 :: Word8 -> Word8
bitReverse8 (W8# w#) = W8# (wordToWord8# (bitReverse8# (word8ToWord# w#)))
| Reverse the order of the bits in a ' Word16 ' .
@since 4.14.0.0
bitReverse16 :: Word16 -> Word16
bitReverse16 (W16# w#) = W16# (wordToWord16# (bitReverse16# (word16ToWord# w#)))
| Reverse the order of the bits in a ' ' .
@since 4.14.0.0
bitReverse32 :: Word32 -> Word32
bitReverse32 (W32# w#) = W32# (wordToWord32# (bitReverse32# (word32ToWord# w#)))
@since 4.14.0.0
bitReverse64 :: Word64 -> Word64
bitReverse64 (W64# w#) = W64# (bitReverse64# w#)
shiftRLWord64# :: Word64# -> Int# -> Word64#
a `shiftRLWord64#` b = uncheckedShiftRL64# a b
`and64#` int64ToWord64# (intToInt64# (shift_mask 64# b))
shiftLWord64# :: Word64# -> Int# -> Word64#
a `shiftLWord64#` b = uncheckedShiftL64# a b
`and64#` int64ToWord64# (intToInt64# (shift_mask 64# b))
|
1727484c18073b5e5036e12f0449fc8b75b73e9b9d6b00ee244fcefdf58d0aaf | janestreet/memtrace_viewer_with_deps | backpressure_test_shared.ml | module Protocol = Protocol
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/incr_dom/example/test_backpressure/shared/backpressure_test_shared.ml | ocaml | module Protocol = Protocol
|
|
ac59ef7baa539cc1982bb59261cb5fd44de1ae29b66909107d1572d887079bb2 | Lupino/haskell-periodic | BaseClient.hs | {-# LANGUAGE OverloadedStrings #-}
module Periodic.Trans.BaseClient
( BaseClientT
, BaseClientEnv
, getClientEnv
, close
, runBaseClientT
, ping
, submitJob_
, submitJob
, runJob_
, runJob
, checkHealth
, successRequest
) where
import Control.Monad (unless)
import Data.Binary (Binary)
import Data.ByteString (ByteString)
import Data.Int (Int64)
import Metro.Class (Transport)
import Metro.Node (getEnv1, request, stopNodeT)
import Metro.Utils (getEpochTime)
import Periodic.Node
import Periodic.Types (Packet, getResult, packetREQ)
import Periodic.Types.ClientCommand
import Periodic.Types.Job
import Periodic.Types.ServerCommand
import UnliftIO
type BaseClientEnv u = NodeEnv u ServerCommand
type BaseClientT u = NodeT u ServerCommand
runBaseClientT :: Monad m => BaseClientEnv u tp -> BaseClientT u tp m a -> m a
runBaseClientT = runNodeT
close :: (MonadUnliftIO m, Transport tp) => BaseClientT u tp m ()
close = stopNodeT
ping :: (MonadUnliftIO m, Transport tp) => BaseClientT u tp m Bool
ping = getResult False isPong <$> request Nothing (packetREQ Ping)
successRequest
:: (MonadUnliftIO m, Transport tp, Binary a)
=> Packet a -> BaseClientT u tp m Bool
successRequest pkt = getResult False isSuccess <$> request Nothing pkt
submitJob_ :: (MonadUnliftIO m, Transport tp) => Job -> BaseClientT u tp m Bool
submitJob_ j = successRequest (packetREQ (SubmitJob j))
submitJob
:: (MonadUnliftIO m, Transport tp)
=> FuncName -> JobName -> Workload -> Int64 -> Int -> BaseClientT u tp m Bool
submitJob fn jn w later tout = do
schedAt <- (+later) <$> getEpochTime
submitJob_
$ setTimeout tout
$ setSchedAt schedAt
$ setWorkload w
$ initJob fn jn
runJob_ :: (MonadUnliftIO m, Transport tp) => Job -> BaseClientT u tp m (Maybe ByteString)
runJob_ j = getResult Nothing getData <$> request Nothing (packetREQ . RunJob $ setSchedAt 0 j)
where getData :: ServerCommand -> Maybe ByteString
getData (Data bs) = Just bs
getData _ = Nothing
runJob
:: (MonadUnliftIO m, Transport tp)
=> FuncName -> JobName -> Workload -> Int -> BaseClientT u tp m (Maybe ByteString)
runJob fn jn w tout = do
runJob_ $ setTimeout tout $ setWorkload w $ initJob fn jn
checkHealth :: (MonadUnliftIO m, Transport tp) => BaseClientT u tp m ()
checkHealth = do
ret <- timeout 10000000 ping
case ret of
Nothing -> close
Just r -> unless r close
getClientEnv :: (Monad m, Transport tp) => BaseClientT u tp m (BaseClientEnv u tp)
getClientEnv = getEnv1
| null | https://raw.githubusercontent.com/Lupino/haskell-periodic/d685e806caf3bb54575fc5cb1ca5a3bf1e98969c/periodic-client/src/Periodic/Trans/BaseClient.hs | haskell | # LANGUAGE OverloadedStrings # |
module Periodic.Trans.BaseClient
( BaseClientT
, BaseClientEnv
, getClientEnv
, close
, runBaseClientT
, ping
, submitJob_
, submitJob
, runJob_
, runJob
, checkHealth
, successRequest
) where
import Control.Monad (unless)
import Data.Binary (Binary)
import Data.ByteString (ByteString)
import Data.Int (Int64)
import Metro.Class (Transport)
import Metro.Node (getEnv1, request, stopNodeT)
import Metro.Utils (getEpochTime)
import Periodic.Node
import Periodic.Types (Packet, getResult, packetREQ)
import Periodic.Types.ClientCommand
import Periodic.Types.Job
import Periodic.Types.ServerCommand
import UnliftIO
type BaseClientEnv u = NodeEnv u ServerCommand
type BaseClientT u = NodeT u ServerCommand
runBaseClientT :: Monad m => BaseClientEnv u tp -> BaseClientT u tp m a -> m a
runBaseClientT = runNodeT
close :: (MonadUnliftIO m, Transport tp) => BaseClientT u tp m ()
close = stopNodeT
ping :: (MonadUnliftIO m, Transport tp) => BaseClientT u tp m Bool
ping = getResult False isPong <$> request Nothing (packetREQ Ping)
successRequest
:: (MonadUnliftIO m, Transport tp, Binary a)
=> Packet a -> BaseClientT u tp m Bool
successRequest pkt = getResult False isSuccess <$> request Nothing pkt
submitJob_ :: (MonadUnliftIO m, Transport tp) => Job -> BaseClientT u tp m Bool
submitJob_ j = successRequest (packetREQ (SubmitJob j))
submitJob
:: (MonadUnliftIO m, Transport tp)
=> FuncName -> JobName -> Workload -> Int64 -> Int -> BaseClientT u tp m Bool
submitJob fn jn w later tout = do
schedAt <- (+later) <$> getEpochTime
submitJob_
$ setTimeout tout
$ setSchedAt schedAt
$ setWorkload w
$ initJob fn jn
runJob_ :: (MonadUnliftIO m, Transport tp) => Job -> BaseClientT u tp m (Maybe ByteString)
runJob_ j = getResult Nothing getData <$> request Nothing (packetREQ . RunJob $ setSchedAt 0 j)
where getData :: ServerCommand -> Maybe ByteString
getData (Data bs) = Just bs
getData _ = Nothing
runJob
:: (MonadUnliftIO m, Transport tp)
=> FuncName -> JobName -> Workload -> Int -> BaseClientT u tp m (Maybe ByteString)
runJob fn jn w tout = do
runJob_ $ setTimeout tout $ setWorkload w $ initJob fn jn
checkHealth :: (MonadUnliftIO m, Transport tp) => BaseClientT u tp m ()
checkHealth = do
ret <- timeout 10000000 ping
case ret of
Nothing -> close
Just r -> unless r close
getClientEnv :: (Monad m, Transport tp) => BaseClientT u tp m (BaseClientEnv u tp)
getClientEnv = getEnv1
|
4f9b07d927fc2a8a6c57befaaf9e7bed9531a9947a26bc07ab16f28cdbc17960 | hraberg/shen.clj | overwrite.clj | src / shen / overwrite.clj
(ns shen
(:use [shen.primitives])
(:require [clojure.core :as c])
(:refer-clojure :only []))
(set '*language* "Clojure")
(set '*implementation* (c/str "Clojure " (c/clojure-version)
" [jvm "(System/getProperty "java.version")"]"))
(set '*porters* "Håkan Råberg")
(set '*stinput* c/*in*)
(set '*stoutput* c/*out*)
(set '*home-directory* (System/getProperty "user.dir"))
(shen-initialise_environment)
(defun (intern "@p") (V706 V707)
(c/object-array ['shen-tuple V706 V707]))
(defun variable? (V702)
(and (c/symbol? V702) (Character/isUpperCase (.charAt (c/name V702) 0))))
(defun boolean? (V746)
(c/cond (= true V746) true
(= false V746) true
(= (intern "true") V746) true
(= (intern "false") V746) true
:else false))
(defun shen-compose (V532 V533)
(c/reduce #(%2 %) V533 V532))
(defun element? (V787 ^java.util.Collection V788)
(.contains V788 V787))
(defun macroexpand (V510)
(let Y (shen-compose (c/drop-while c/nil?
(c/map #(c/when-let [m (c/ns-resolve 'shen %)] @m)
(value '*macros*))) V510)
(if (= V510 Y) V510 (shen-walk macroexpand Y))))
Based on [ Mode]( / eschulte / shen - mode ) by .
- Shen functions taken largely from the documentation by Dr. .
(def ^:private ^:const shen-doc
`((* "number --> number --> number" "Number multiplication.")
(+ "number --> number --> number" "Number addition.")
(- "number --> number --> number" "Number subtraction.")
(/ "number --> number --> number" "Number division.")
(~(intern "/.") "_" "Abstraction builder, receives a variable and an expression; does the job of --> in the lambda calculus.")
(< "number --> number --> boolean" "Less than.")
(<-vector nil nil)
(<= "number --> number --> boolean" "Less than or equal to.")
(<e> nil nil)
(= "A --> A --> boolean" "Equal to.")
(== "A --> B --> boolean" "Equal to.")
(> "number --> number --> boolean" "Greater than.")
(>= "number --> number --> boolean" "Greater than or equal to.")
(~(intern "@p") "_" "Takes two inputs and forms an ordered pair.")
(~(intern "@s") "_" "Takes two or more inputs and forms a string.")
(~(intern "@v") "_" "Takes two or more inputs and forms a vector.")
(abort nil "throw a simple error")
(adjoin nil "add arg1 to list arg2 if not already a member")
(and "boolean --> boolean --> boolean" "Boolean and.")
(append "(list A) --> (list A) --> (list A)" "Appends two lists into one list.")
(apply "(A --> B) --> (A --> B)" "Applies a function to an input.")
(arity nil nil)
(assoc nil nil)
(assoc-type "symbol --> variable --> symbol" "Associates a Qi type (first input) with Lisp type (second input)..")
(average nil "return the average of two numbers")
(bind nil nil)
(boolean? "A --> boolean" "Recognisor for booleans.")
(bound? nil "check is a symbol is bound")
(byte->string nil "return the string represented by bytes")
(call nil nil)
(cd "string --> string" "Changes the home directory. (cd \"My Programs\") will cause (load \"hello_world.txt\") to load MyPrograms/hello_world.txt. (cd \"\") is the default.")
(character? "A --> boolean" "Recognisor for characters.")
(compile nil nil)
(complex? "A --> boolean" "Recognisor for complex numbers.")
(concat "symbol --> symbol --> symbol" "Concatenates two symbols.")
(congruent? "A --> A --> boolean" "Retrns true if objects are identical or else if they are strings or characters which are identical differing at most in case or numbers of equal value (e.g. 1 and 1.0) or tuples composed of congruent elements.")
(cons "_" "A special form that takes an object e of type A and a list l of type (list A) and produces a list of type (list A) by adding e to the front of l.")
(cons? "--> boolean" "Returns true iff the input is a non-empty list.")
(core nil nil)
(cut nil nil)
(debug "A --> string" "The input is ignored and debugging is returned; but all terminal output is echoed to the file debug.txt until the undebug function is executed.")
(declare "_" "Takes a function name f and a type t expressed as a list and gives f the type t.")
(define "_" "Define a function, takes a name, an optional type and a pattern matching body.")
(delete-file "string --> string" "The file named in the string is deleted and the string returned.")
(destroy "_" "Receives the name of a function and removes it and its type from the environment.")
(difference "(list A) --> (list A) --> (list A)" "Subtracts the elements of the second list from the first")
(do "_" "A special form: receives n well-typed expressions and evaluates each one, returning the normal form of the last one.")
(dump "string --> string" "Dumps all user-generated Lisp from the file f denoted by the argument into a file f.lsp.")
(echo "string --> string" "Echoes all terminal input/output to a file named by string (which is either appended to if it exists or created if not) until the command (echo \"\") is received which switches echo off.")
(element? "A -> (list A) --> boolean" "Returns true iff the first input is an element in the second.")
(empty? "--> boolean" "Returns true iff the input is [].")
(error "_" "A special form: takes a string followed by n (n --> 0) expressions. Prints error string.")
(eval "_" "Evaluates the input.")
(explode "A --> (list character)" "Explodes an object to a list of characters.")
(fail nil nil)
(fix "(A --> A) --> (A --> A)" "Applies a function to generate a fixpoint.")
(float? "A --> boolean" "Recognisor for floating point numbers.")
(floor nil nil)
(format nil "takes a stream, a format string and args, formats and prints to the stream")
(freeze "A --> (lazy A)" "Returns a frozen version of its input.")
(fst "(A * B) --> A" "Returns the first element of a tuple.")
(fwhen nil nil)
(gensym "_" "Generates a fresh symbol or variable from a string..")
(get nil "gets property arg2 from object arg1")
(get-array "(array A) --> (list number) --> A --> A" "3-place function that takes an array of elements of type A, an index to that array as a list of natural numbers and an expression E of type A. If an object is stored at the index, then it is returned, otherwise the normal form of E is returned.")
(get-prop "_" "3-place function that takes a symbol S, a pointer P (which can be a string, symbol or number), and an expression E of any kind and returns the value pointed by P from S (if one exists) or the normal form of E otherwise.")
(hash nil "hash an object")
(hdv nil nil)
(head "(list A) --> A" "Returns the first element of a list.")
(identical nil nil)
(if "boolean --> A --> A" "takes a boolean b and two expressions x and y and evaluates x if b evaluates to true and evaluates y if b evaluates to false.")
(if-with-checking "string --> (list A)" "If type checking is enabled, raises the string as an error otherwise returns the empty list..")
(if-without-checking "string --> (list A)" "If type checking is disabled, raises the string as an error otherwise returns the empty list.")
(include "(list symbol) --> (list symbol)" "Includes the datatype theories or synonyms for use in type checking.")
(include-all-but "(list symbol) --> (list symbol)" "Includes all loaded datatype theories and synonyms for use in type checking apart from those entered.")
(inferences "A --> number" "The input is ignored. Returns the number of logical inferences executed since the last call to the top level.")
(input "_" "0-place function. Takes a user input i and returns the normal form of i.")
(input+ "_" "Special form. Takes inputs of the form : <expr>. Where d(<expr>) is the type denoted by the choice of expression (e.g. \"number\" denotes the type number). Takes a user input i and returns the normal form of i given i is of the type d(<expr>).")
(integer? "A --> boolean" "Recognisor for integers.")
(interror nil nil)
(intersection "(list A) --> (list A) --> (list A)" "Computes the intersection of two lists.")
(intmake-string nil nil)
(intoutput nil nil)
(lambda "_" "Lambda operator from lambda calculus.")
(length "(list A) --> integer" "Returns the number of elements in a list.")
(let nil nil)
(limit nil nil)
(lineread "_" "Top level reader of read-evaluate-print loop. Reads elements into a list. lineread terminates with carriage return when brackets are balanced. ^ aborts lineread.")
(list "A .. A --> (list A)" "A special form. Assembles n (n --> 0) inputs into a list.")
(load "string --> symbol" "Takes a file name and loads the file, returning loaded as a symbol.")
(macroexpand nil nil)
(make-string "string A1 - An --> string" "A special form: takes a string followed by n (n --> 0) well-typed expressions; assembles and returns a string.")
(map "(A --> B) --> (list A) --> (list B)" "The first input is applied to each member of the second input and the results consed into one list..")
(mapcan "(A --> (list B)) --> (list A) --> (list B)" "The first input is applied to each member of the second input and the results appended into one list.")
(maxinferences "number --> number" "Returns the input and as a side-effect, sets a global variable to a number that limits the maximum number of inferences that can be expended on attempting to typecheck a program. The default is 1,000,000.")
(mod nil "arg1 mod arg2")
(newsym "symbol --> symbol" "Generates a fresh symbol from a symbol.")
(newvar "variable --> variable" "Generates a fresh variable from a variable")
(nl nil nil)
(not "boolean --> boolean" "Boolean not.")
(nth "number --> (list A) --> A" "Gets the nth element of a list numbered from 1.")
(number? "A --> boolean" "Recognisor for numbers.")
(occurences "A --> B --> number" "Returns the number of times the first argument occurs in the second.")
(occurrences nil "returns the number of occurrences of arg1 in arg2")
(occurs-check "symbol --> boolean" "Receives either + or - and enables/disables occur checking in Prolog, datatype definitions and rule closures. The default is +.")
(opaque "symbol --> symbol" "Applied to a Lisp macro makes it opaque to Qi.")
(or "boolean --> (boolean --> boolean)" "Boolean or.")
(output "string A1 - An --> string" "A special form: takes a string followed by n (n --> 0) well-typed expressions; prints a message to the screen and returns an object of type string (the string \"done\").")
(preclude "(list symbol) --> (list symbol)" "Removes the mentioned datatype theories and synonyms from use in type checking.")
(preclude-all-but "(list symbol) --> (list symbol)" "Removes all the datatype theories and synonyms from use in type checking apart from the ones given.")
(print "A --> A" "Takes an object and prints it, returning it as a result.")
(profile "(A --> B) --> (A --> B)" "Takes a function represented by a function name and inserts profiling code returning the function as an output.")
(profile-results "A --> symbol" "The input is ignored. Returns a list of profiled functions and their timings since profile-results was last used.")
(ps "_" "Receives a symbol denoting a Qi function and prints the Lisp source code associated with the function.")
(put nil "puts value of arg3 as property arg2 in object arg1")
(put-array "(array A) --> (list number) --> A --> A" "3-place function that takes an array of elements of type A, an index to that array as a list of natural numbers and an expression E of type A. The normal form of E is stored at that index and then returned.")
(put-prop "_" "3-place function that takes a symbol S, a pointer P (a string symbol or number), and an expression E. The pointer P is set to point from S to the normal form of E which is then returned.")
(quit "_" "0-place function that exits Qi.")
(random "number --> number" "Given a positive number n, generates a random number between 0 and n-1.")
(rational? "A --> boolean" "Recognisor for rational numbers.")
(read nil nil)
(read-char "A --> character" "The input is discarded and the character typed by the user is returned.")
(read-chars-as-stringlist "(list character) --> (character --> boolean) --> (list string)" "Returns a list of strings whose components are taken from the character list. The second input acts as a tokeniser. Thus (read-chars-as-stringlist [#\\H #\\i #\\Space #\\P #\\a #\\t] (/. X (= X #\\Space))) will produce [\"Hi\" \"Pat\"].")
(read-file "string --> (list unit)" "Returns the contents of an ASCII file designated by a string. Returns a list of units, where unit is an unspecified type.")
(read-file-as-charlist "string --> (list character)" "Returns the list of characters from the contents of an ASCII file designated by a string.")
(read-file-as-string nil nil)
(real? "A --> boolean" "Recognisor for real numbers.")
(remove "A --> (list A) --> (list A)" "Removes all occurrences of an element from a list.")
(return nil nil)
(reverse "(list A)--> ?(list A)" "Reverses a list.")
(round "number--> ?number" "Rounds a number.")
(save "_" "0 place function. Saves a Qi image.")
(snd "(A * B) --> B" "Returns the second element of a tuple.")
(specialise "symbol --> symbol" "Receives the name of a function and turns it into a special form. Special forms are not curried during evaluation or compilation.")
(speed "number --> number" "Receives a value 0 to 3 and sets the performance of the generated Lisp code, returning its input. 0 is the lowest setting.")
(spy "symbol --> boolean" "Receives either + or - and respectively enables/disables tracing the operation of T*.")
(sqrt "number --> number" "Returns the square root of a number.")
(step "symbol --> boolean" "Receives either + or - and enables/disables stepping in the trace.")
(stinput nil nil)
(string? "A --> boolean" "Recognisor for strings.")
(strong-warning "symbol --> boolean" "Takes + or -; if + then warnings are treated as error messages.")
(subst nil nil)
(sugar "symbol --> (A --> B) --> number --> (A --> B)" "Receives either in or out as first argument, a function f and an integer greater than 0 and returns f as a result. The function f is placed on the sugaring list at a position determined by the number.")
(sugar-list "symbol --> (list symbol)" "Receives either in or out as first argument, and returns the list of sugar functions.")
(sum nil "sum a list of numbers")
(symbol? "A --> boolean" "Recognisor for symbols.")
(systemf nil nil)
(tail "(list A) --> (list A)" "Returns all but the first element of a non-empty list.")
(tc "symbol --> boolean" "Receives either + or - and respectively enables/disables static typing.")
(tc? nil "return true if type checking")
(thaw "(lazy A) --> A" "Receives a frozen input and evaluates it to get the unthawed result..")
(time "A --> A" "Prints the run time for the evaluation of its input and returns its normal form.")
(tlv nil nil)
(track "symbol --> symbol" "Tracks the I/O behaviour of a function.")
(transparent "symbol --> symbol" "Applied to a Lisp macro makes it transparent to Qi.")
(tuple? "A --> boolean" "Recognisor for tuples.")
(type "_" "Returns a type for its input (if any) or false if the input has no type.")
(unassoc-type "symbol --> symbol" "Removes any associations with the Qi type in the type association table.")
(undebug "A --> string" "The input is ignored, undebugging is returned and all terminal output is closed to the file debug.txt.")
(unify nil nil)
(unify! nil nil)
(union "(list A) --> (list A) --> (list A)" "Forms the union of two lists.")
(unprofile "(A --> B) --> (A --> B)" "Unprofiles a function.")
(unspecialise "symbol --> symbol" "Receives the name of a function and deletes its special form status.")
(unsugar "symbol --> (A --> B) --> (A --> B)" "Receives either out or in and the name of a function and removes its status as a sugar function.")
(untrack "symbol --> symbol" "Untracks a function.")
(value "_" "Applied to a symbol, returns the global value assigned to it.")
(variable? "A --> boolean" "Applied to a variable, returns true.")
(vector nil nil)
(vector-> nil nil)
(vector? nil nil)
(version "string --> string" "Changes the version string displayed on startup.")
(warn "string --> string" "Prints the string as a warning and returns \"done\". See strong-warning")
(write-to-file "string --> A --> string" "Writes the second input into a file named in the first input. If the file does not exist, it is created, else it is overwritten. If the second input is a string then it is written to the file without the enclosing quotes. The first input is returned.")
(y-or-n? "string --> boolean" "Prints the string as a question and returns true for y and false for n.")))
(c/doseq [[fn sig doc] shen-doc
:let [v (c/resolve fn)]
:when v]
(c/alter-meta! v c/merge {:doc doc
:arglists (c/list (c/read-string (c/str "[" sig "]")))}))
| null | https://raw.githubusercontent.com/hraberg/shen.clj/41bf09e61dd3a9df03cf929f0e8415087b730396/src/shen/overwrite.clj | clojure | src / shen / overwrite.clj
(ns shen
(:use [shen.primitives])
(:require [clojure.core :as c])
(:refer-clojure :only []))
(set '*language* "Clojure")
(set '*implementation* (c/str "Clojure " (c/clojure-version)
" [jvm "(System/getProperty "java.version")"]"))
(set '*porters* "Håkan Råberg")
(set '*stinput* c/*in*)
(set '*stoutput* c/*out*)
(set '*home-directory* (System/getProperty "user.dir"))
(shen-initialise_environment)
(defun (intern "@p") (V706 V707)
(c/object-array ['shen-tuple V706 V707]))
(defun variable? (V702)
(and (c/symbol? V702) (Character/isUpperCase (.charAt (c/name V702) 0))))
(defun boolean? (V746)
(c/cond (= true V746) true
(= false V746) true
(= (intern "true") V746) true
(= (intern "false") V746) true
:else false))
(defun shen-compose (V532 V533)
(c/reduce #(%2 %) V533 V532))
(defun element? (V787 ^java.util.Collection V788)
(.contains V788 V787))
(defun macroexpand (V510)
(let Y (shen-compose (c/drop-while c/nil?
(c/map #(c/when-let [m (c/ns-resolve 'shen %)] @m)
(value '*macros*))) V510)
(if (= V510 Y) V510 (shen-walk macroexpand Y))))
Based on [ Mode]( / eschulte / shen - mode ) by .
- Shen functions taken largely from the documentation by Dr. .
(def ^:private ^:const shen-doc
`((* "number --> number --> number" "Number multiplication.")
(+ "number --> number --> number" "Number addition.")
(- "number --> number --> number" "Number subtraction.")
(/ "number --> number --> number" "Number division.")
(~(intern "/.") "_" "Abstraction builder, receives a variable and an expression; does the job of --> in the lambda calculus.")
(< "number --> number --> boolean" "Less than.")
(<-vector nil nil)
(<= "number --> number --> boolean" "Less than or equal to.")
(<e> nil nil)
(= "A --> A --> boolean" "Equal to.")
(== "A --> B --> boolean" "Equal to.")
(> "number --> number --> boolean" "Greater than.")
(>= "number --> number --> boolean" "Greater than or equal to.")
(~(intern "@p") "_" "Takes two inputs and forms an ordered pair.")
(~(intern "@s") "_" "Takes two or more inputs and forms a string.")
(~(intern "@v") "_" "Takes two or more inputs and forms a vector.")
(abort nil "throw a simple error")
(adjoin nil "add arg1 to list arg2 if not already a member")
(and "boolean --> boolean --> boolean" "Boolean and.")
(append "(list A) --> (list A) --> (list A)" "Appends two lists into one list.")
(apply "(A --> B) --> (A --> B)" "Applies a function to an input.")
(arity nil nil)
(assoc nil nil)
(assoc-type "symbol --> variable --> symbol" "Associates a Qi type (first input) with Lisp type (second input)..")
(average nil "return the average of two numbers")
(bind nil nil)
(boolean? "A --> boolean" "Recognisor for booleans.")
(bound? nil "check is a symbol is bound")
(byte->string nil "return the string represented by bytes")
(call nil nil)
(cd "string --> string" "Changes the home directory. (cd \"My Programs\") will cause (load \"hello_world.txt\") to load MyPrograms/hello_world.txt. (cd \"\") is the default.")
(character? "A --> boolean" "Recognisor for characters.")
(compile nil nil)
(complex? "A --> boolean" "Recognisor for complex numbers.")
(concat "symbol --> symbol --> symbol" "Concatenates two symbols.")
(congruent? "A --> A --> boolean" "Retrns true if objects are identical or else if they are strings or characters which are identical differing at most in case or numbers of equal value (e.g. 1 and 1.0) or tuples composed of congruent elements.")
(cons "_" "A special form that takes an object e of type A and a list l of type (list A) and produces a list of type (list A) by adding e to the front of l.")
(cons? "--> boolean" "Returns true iff the input is a non-empty list.")
(core nil nil)
(cut nil nil)
(debug "A --> string" "The input is ignored and debugging is returned; but all terminal output is echoed to the file debug.txt until the undebug function is executed.")
(declare "_" "Takes a function name f and a type t expressed as a list and gives f the type t.")
(define "_" "Define a function, takes a name, an optional type and a pattern matching body.")
(delete-file "string --> string" "The file named in the string is deleted and the string returned.")
(destroy "_" "Receives the name of a function and removes it and its type from the environment.")
(difference "(list A) --> (list A) --> (list A)" "Subtracts the elements of the second list from the first")
(do "_" "A special form: receives n well-typed expressions and evaluates each one, returning the normal form of the last one.")
(dump "string --> string" "Dumps all user-generated Lisp from the file f denoted by the argument into a file f.lsp.")
(echo "string --> string" "Echoes all terminal input/output to a file named by string (which is either appended to if it exists or created if not) until the command (echo \"\") is received which switches echo off.")
(element? "A -> (list A) --> boolean" "Returns true iff the first input is an element in the second.")
(empty? "--> boolean" "Returns true iff the input is [].")
(error "_" "A special form: takes a string followed by n (n --> 0) expressions. Prints error string.")
(eval "_" "Evaluates the input.")
(explode "A --> (list character)" "Explodes an object to a list of characters.")
(fail nil nil)
(fix "(A --> A) --> (A --> A)" "Applies a function to generate a fixpoint.")
(float? "A --> boolean" "Recognisor for floating point numbers.")
(floor nil nil)
(format nil "takes a stream, a format string and args, formats and prints to the stream")
(freeze "A --> (lazy A)" "Returns a frozen version of its input.")
(fst "(A * B) --> A" "Returns the first element of a tuple.")
(fwhen nil nil)
(gensym "_" "Generates a fresh symbol or variable from a string..")
(get nil "gets property arg2 from object arg1")
(get-array "(array A) --> (list number) --> A --> A" "3-place function that takes an array of elements of type A, an index to that array as a list of natural numbers and an expression E of type A. If an object is stored at the index, then it is returned, otherwise the normal form of E is returned.")
(get-prop "_" "3-place function that takes a symbol S, a pointer P (which can be a string, symbol or number), and an expression E of any kind and returns the value pointed by P from S (if one exists) or the normal form of E otherwise.")
(hash nil "hash an object")
(hdv nil nil)
(head "(list A) --> A" "Returns the first element of a list.")
(identical nil nil)
(if "boolean --> A --> A" "takes a boolean b and two expressions x and y and evaluates x if b evaluates to true and evaluates y if b evaluates to false.")
(if-with-checking "string --> (list A)" "If type checking is enabled, raises the string as an error otherwise returns the empty list..")
(if-without-checking "string --> (list A)" "If type checking is disabled, raises the string as an error otherwise returns the empty list.")
(include "(list symbol) --> (list symbol)" "Includes the datatype theories or synonyms for use in type checking.")
(include-all-but "(list symbol) --> (list symbol)" "Includes all loaded datatype theories and synonyms for use in type checking apart from those entered.")
(inferences "A --> number" "The input is ignored. Returns the number of logical inferences executed since the last call to the top level.")
(input "_" "0-place function. Takes a user input i and returns the normal form of i.")
(input+ "_" "Special form. Takes inputs of the form : <expr>. Where d(<expr>) is the type denoted by the choice of expression (e.g. \"number\" denotes the type number). Takes a user input i and returns the normal form of i given i is of the type d(<expr>).")
(integer? "A --> boolean" "Recognisor for integers.")
(interror nil nil)
(intersection "(list A) --> (list A) --> (list A)" "Computes the intersection of two lists.")
(intmake-string nil nil)
(intoutput nil nil)
(lambda "_" "Lambda operator from lambda calculus.")
(length "(list A) --> integer" "Returns the number of elements in a list.")
(let nil nil)
(limit nil nil)
(lineread "_" "Top level reader of read-evaluate-print loop. Reads elements into a list. lineread terminates with carriage return when brackets are balanced. ^ aborts lineread.")
(list "A .. A --> (list A)" "A special form. Assembles n (n --> 0) inputs into a list.")
(load "string --> symbol" "Takes a file name and loads the file, returning loaded as a symbol.")
(macroexpand nil nil)
(make-string "string A1 - An --> string" "A special form: takes a string followed by n (n --> 0) well-typed expressions; assembles and returns a string.")
(map "(A --> B) --> (list A) --> (list B)" "The first input is applied to each member of the second input and the results consed into one list..")
(mapcan "(A --> (list B)) --> (list A) --> (list B)" "The first input is applied to each member of the second input and the results appended into one list.")
(maxinferences "number --> number" "Returns the input and as a side-effect, sets a global variable to a number that limits the maximum number of inferences that can be expended on attempting to typecheck a program. The default is 1,000,000.")
(mod nil "arg1 mod arg2")
(newsym "symbol --> symbol" "Generates a fresh symbol from a symbol.")
(newvar "variable --> variable" "Generates a fresh variable from a variable")
(nl nil nil)
(not "boolean --> boolean" "Boolean not.")
(nth "number --> (list A) --> A" "Gets the nth element of a list numbered from 1.")
(number? "A --> boolean" "Recognisor for numbers.")
(occurences "A --> B --> number" "Returns the number of times the first argument occurs in the second.")
(occurrences nil "returns the number of occurrences of arg1 in arg2")
(occurs-check "symbol --> boolean" "Receives either + or - and enables/disables occur checking in Prolog, datatype definitions and rule closures. The default is +.")
(opaque "symbol --> symbol" "Applied to a Lisp macro makes it opaque to Qi.")
(or "boolean --> (boolean --> boolean)" "Boolean or.")
(output "string A1 - An --> string" "A special form: takes a string followed by n (n --> 0) well-typed expressions; prints a message to the screen and returns an object of type string (the string \"done\").")
(preclude "(list symbol) --> (list symbol)" "Removes the mentioned datatype theories and synonyms from use in type checking.")
(preclude-all-but "(list symbol) --> (list symbol)" "Removes all the datatype theories and synonyms from use in type checking apart from the ones given.")
(print "A --> A" "Takes an object and prints it, returning it as a result.")
(profile "(A --> B) --> (A --> B)" "Takes a function represented by a function name and inserts profiling code returning the function as an output.")
(profile-results "A --> symbol" "The input is ignored. Returns a list of profiled functions and their timings since profile-results was last used.")
(ps "_" "Receives a symbol denoting a Qi function and prints the Lisp source code associated with the function.")
(put nil "puts value of arg3 as property arg2 in object arg1")
(put-array "(array A) --> (list number) --> A --> A" "3-place function that takes an array of elements of type A, an index to that array as a list of natural numbers and an expression E of type A. The normal form of E is stored at that index and then returned.")
(put-prop "_" "3-place function that takes a symbol S, a pointer P (a string symbol or number), and an expression E. The pointer P is set to point from S to the normal form of E which is then returned.")
(quit "_" "0-place function that exits Qi.")
(random "number --> number" "Given a positive number n, generates a random number between 0 and n-1.")
(rational? "A --> boolean" "Recognisor for rational numbers.")
(read nil nil)
(read-char "A --> character" "The input is discarded and the character typed by the user is returned.")
(read-chars-as-stringlist "(list character) --> (character --> boolean) --> (list string)" "Returns a list of strings whose components are taken from the character list. The second input acts as a tokeniser. Thus (read-chars-as-stringlist [#\\H #\\i #\\Space #\\P #\\a #\\t] (/. X (= X #\\Space))) will produce [\"Hi\" \"Pat\"].")
(read-file "string --> (list unit)" "Returns the contents of an ASCII file designated by a string. Returns a list of units, where unit is an unspecified type.")
(read-file-as-charlist "string --> (list character)" "Returns the list of characters from the contents of an ASCII file designated by a string.")
(read-file-as-string nil nil)
(real? "A --> boolean" "Recognisor for real numbers.")
(remove "A --> (list A) --> (list A)" "Removes all occurrences of an element from a list.")
(return nil nil)
(reverse "(list A)--> ?(list A)" "Reverses a list.")
(round "number--> ?number" "Rounds a number.")
(save "_" "0 place function. Saves a Qi image.")
(snd "(A * B) --> B" "Returns the second element of a tuple.")
(specialise "symbol --> symbol" "Receives the name of a function and turns it into a special form. Special forms are not curried during evaluation or compilation.")
(speed "number --> number" "Receives a value 0 to 3 and sets the performance of the generated Lisp code, returning its input. 0 is the lowest setting.")
(spy "symbol --> boolean" "Receives either + or - and respectively enables/disables tracing the operation of T*.")
(sqrt "number --> number" "Returns the square root of a number.")
(step "symbol --> boolean" "Receives either + or - and enables/disables stepping in the trace.")
(stinput nil nil)
(string? "A --> boolean" "Recognisor for strings.")
(strong-warning "symbol --> boolean" "Takes + or -; if + then warnings are treated as error messages.")
(subst nil nil)
(sugar "symbol --> (A --> B) --> number --> (A --> B)" "Receives either in or out as first argument, a function f and an integer greater than 0 and returns f as a result. The function f is placed on the sugaring list at a position determined by the number.")
(sugar-list "symbol --> (list symbol)" "Receives either in or out as first argument, and returns the list of sugar functions.")
(sum nil "sum a list of numbers")
(symbol? "A --> boolean" "Recognisor for symbols.")
(systemf nil nil)
(tail "(list A) --> (list A)" "Returns all but the first element of a non-empty list.")
(tc "symbol --> boolean" "Receives either + or - and respectively enables/disables static typing.")
(tc? nil "return true if type checking")
(thaw "(lazy A) --> A" "Receives a frozen input and evaluates it to get the unthawed result..")
(time "A --> A" "Prints the run time for the evaluation of its input and returns its normal form.")
(tlv nil nil)
(track "symbol --> symbol" "Tracks the I/O behaviour of a function.")
(transparent "symbol --> symbol" "Applied to a Lisp macro makes it transparent to Qi.")
(tuple? "A --> boolean" "Recognisor for tuples.")
(type "_" "Returns a type for its input (if any) or false if the input has no type.")
(unassoc-type "symbol --> symbol" "Removes any associations with the Qi type in the type association table.")
(undebug "A --> string" "The input is ignored, undebugging is returned and all terminal output is closed to the file debug.txt.")
(unify nil nil)
(unify! nil nil)
(union "(list A) --> (list A) --> (list A)" "Forms the union of two lists.")
(unprofile "(A --> B) --> (A --> B)" "Unprofiles a function.")
(unspecialise "symbol --> symbol" "Receives the name of a function and deletes its special form status.")
(unsugar "symbol --> (A --> B) --> (A --> B)" "Receives either out or in and the name of a function and removes its status as a sugar function.")
(untrack "symbol --> symbol" "Untracks a function.")
(value "_" "Applied to a symbol, returns the global value assigned to it.")
(variable? "A --> boolean" "Applied to a variable, returns true.")
(vector nil nil)
(vector-> nil nil)
(vector? nil nil)
(version "string --> string" "Changes the version string displayed on startup.")
(warn "string --> string" "Prints the string as a warning and returns \"done\". See strong-warning")
(write-to-file "string --> A --> string" "Writes the second input into a file named in the first input. If the file does not exist, it is created, else it is overwritten. If the second input is a string then it is written to the file without the enclosing quotes. The first input is returned.")
(y-or-n? "string --> boolean" "Prints the string as a question and returns true for y and false for n.")))
(c/doseq [[fn sig doc] shen-doc
:let [v (c/resolve fn)]
:when v]
(c/alter-meta! v c/merge {:doc doc
:arglists (c/list (c/read-string (c/str "[" sig "]")))}))
|
|
82a3bcd818ec3e6ec551117b8815a3c1294961619a4ad99afe12f49fa0452f47 | kadena-io/chainweaver | Annotation.hs | # LANGUAGE CPP #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE ExtendedDefaultRules #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
-- | Annotations for our `Editor`.
--
Copyright : ( C ) 2020 - 2022 Kadena
-- License : BSD-style (see the file LICENSE)
--
module Frontend.Editor.Annotation
( -- * Types and Classes
AnnoType (..)
, Annotation (..)
, annotation_type
, annotation_msg
, annotation_source
, annotation_pos
, AnnotationSource (..)
* Parsers
, annoParser
, annoFallbackParser
, annoJsonParser
) where
------------------------------------------------------------------------------
import Control.Applicative ((<|>))
import Control.Monad (void)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Void (Void)
import Text.Read (readMaybe)
import qualified Text.Megaparsec as MP
import qualified Text.Megaparsec.Char as MP
------------------------------------------------------------------------------
import Common.Foundation (makePactLenses)
-- | Annotation type.
data AnnoType = AnnoType_Warning | AnnoType_Error
deriving (Eq, Ord)
data AnnotationSource = AnnotationSource_Pact | AnnotationSource_Json
deriving (Eq, Ord, Show)
instance Show AnnoType where
show = \case
AnnoType_Warning -> "warning"
AnnoType_Error -> "error"
-- | Annotation to report warning/errors to the user.
data Annotation = Annotation
{ _annotation_type :: AnnoType -- ^ Is it a warning or an error?
, _annotation_msg :: Text -- ^ The message to report.
, _annotation_source :: AnnotationSource
, _annotation_pos :: Maybe (Int, Int) -- row, column
}
deriving (Show, Eq, Ord)
makePactLenses ''Annotation
annoParser :: Text -> Maybe [Annotation]
annoParser = MP.parseMaybe pactErrorParser
-- | Some errors have no line number for some reason: fallback with Nothing.
annoFallbackParser :: Text -> [Annotation]
annoFallbackParser msg =
case annoParser msg of
Nothing ->
[ Annotation
{ _annotation_type = AnnoType_Error
, _annotation_msg = msg
, _annotation_source = AnnotationSource_Pact
, _annotation_pos = Nothing
}
]
Just a -> a
--TODO: fix line numbers
--TODO: collapse with json warnings
annoJsonParser :: Text -> Annotation
annoJsonParser msg = Annotation
{ _annotation_type = AnnoType_Error
, _annotation_msg = msg
, _annotation_source = AnnotationSource_Json
, _annotation_pos = Nothing
}
pactErrorParser :: MP.Parsec Void Text [Annotation]
pactErrorParser = MP.many $ do
dropOptionalQuote
startErrorParser
line <- digitsP
colonP
column <- digitsP
colonP
MP.space
annoType <- MP.withRecovery (const $ pure AnnoType_Error) $ do
void $ MP.string' "warning:"
pure AnnoType_Warning
-- Get rid of trailing quote as well:
msg <- T.dropWhileEnd (== '"') <$> msgParser
pure $ Annotation
{ _annotation_type = annoType
, _annotation_msg = msg
, _annotation_source = AnnotationSource_Pact
, _annotation_pos = Just (max line 1, max column 1) -- Some errors have linenumber 0 which is invalid.
}
where
digitsP :: MP.Parsec Void Text Int
digitsP = maybe (fail "pactErrorParser: digitsP: no parse") pure . readMaybe =<< MP.some MP.digitChar
dropOptionalQuote = MP.withRecovery (const $ pure ()) (void $ MP.char '\"')
-- | Parse the actual error message.
msgParser :: MP.Parsec Void Text Text
msgParser = linesParser <|> restParser
where
restParser = do
MP.notFollowedBy startErrorParser
MP.takeRest
linesParser = fmap T.unlines . MP.try . MP.some $ lineParser
lineParser = do
MP.notFollowedBy startErrorParser
l <- MP.takeWhileP Nothing (/= '\n')
void $ MP.newline
pure l
-- | Error/warning messages start this way:
startErrorParser :: MP.Parsec Void Text ()
startErrorParser = do
MP.space
void $ MP.many (MP.string "Property proven valid" >> MP.space)
void $ MP.oneOf ['<', '('] -- Until now we found messages with '<' and some with '('.
void $ MP.string "interactive"
void $ MP.oneOf ['>', ')']
colonP
pure ()
colonP :: MP.Parsec Void Text ()
colonP = void $ MP.char ':'
| null | https://raw.githubusercontent.com/kadena-io/chainweaver/5d40e91411995e0a9a7e782d6bb2d89ac1c65d52/frontend/src/Frontend/Editor/Annotation.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
| Annotations for our `Editor`.
License : BSD-style (see the file LICENSE)
* Types and Classes
----------------------------------------------------------------------------
----------------------------------------------------------------------------
| Annotation type.
| Annotation to report warning/errors to the user.
^ Is it a warning or an error?
^ The message to report.
row, column
| Some errors have no line number for some reason: fallback with Nothing.
TODO: fix line numbers
TODO: collapse with json warnings
Get rid of trailing quote as well:
Some errors have linenumber 0 which is invalid.
| Parse the actual error message.
| Error/warning messages start this way:
Until now we found messages with '<' and some with '('. | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE ExtendedDefaultRules #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
Copyright : ( C ) 2020 - 2022 Kadena
module Frontend.Editor.Annotation
AnnoType (..)
, Annotation (..)
, annotation_type
, annotation_msg
, annotation_source
, annotation_pos
, AnnotationSource (..)
* Parsers
, annoParser
, annoFallbackParser
, annoJsonParser
) where
import Control.Applicative ((<|>))
import Control.Monad (void)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Void (Void)
import Text.Read (readMaybe)
import qualified Text.Megaparsec as MP
import qualified Text.Megaparsec.Char as MP
import Common.Foundation (makePactLenses)
data AnnoType = AnnoType_Warning | AnnoType_Error
deriving (Eq, Ord)
data AnnotationSource = AnnotationSource_Pact | AnnotationSource_Json
deriving (Eq, Ord, Show)
instance Show AnnoType where
show = \case
AnnoType_Warning -> "warning"
AnnoType_Error -> "error"
data Annotation = Annotation
, _annotation_source :: AnnotationSource
}
deriving (Show, Eq, Ord)
makePactLenses ''Annotation
annoParser :: Text -> Maybe [Annotation]
annoParser = MP.parseMaybe pactErrorParser
annoFallbackParser :: Text -> [Annotation]
annoFallbackParser msg =
case annoParser msg of
Nothing ->
[ Annotation
{ _annotation_type = AnnoType_Error
, _annotation_msg = msg
, _annotation_source = AnnotationSource_Pact
, _annotation_pos = Nothing
}
]
Just a -> a
annoJsonParser :: Text -> Annotation
annoJsonParser msg = Annotation
{ _annotation_type = AnnoType_Error
, _annotation_msg = msg
, _annotation_source = AnnotationSource_Json
, _annotation_pos = Nothing
}
pactErrorParser :: MP.Parsec Void Text [Annotation]
pactErrorParser = MP.many $ do
dropOptionalQuote
startErrorParser
line <- digitsP
colonP
column <- digitsP
colonP
MP.space
annoType <- MP.withRecovery (const $ pure AnnoType_Error) $ do
void $ MP.string' "warning:"
pure AnnoType_Warning
msg <- T.dropWhileEnd (== '"') <$> msgParser
pure $ Annotation
{ _annotation_type = annoType
, _annotation_msg = msg
, _annotation_source = AnnotationSource_Pact
}
where
digitsP :: MP.Parsec Void Text Int
digitsP = maybe (fail "pactErrorParser: digitsP: no parse") pure . readMaybe =<< MP.some MP.digitChar
dropOptionalQuote = MP.withRecovery (const $ pure ()) (void $ MP.char '\"')
msgParser :: MP.Parsec Void Text Text
msgParser = linesParser <|> restParser
where
restParser = do
MP.notFollowedBy startErrorParser
MP.takeRest
linesParser = fmap T.unlines . MP.try . MP.some $ lineParser
lineParser = do
MP.notFollowedBy startErrorParser
l <- MP.takeWhileP Nothing (/= '\n')
void $ MP.newline
pure l
startErrorParser :: MP.Parsec Void Text ()
startErrorParser = do
MP.space
void $ MP.many (MP.string "Property proven valid" >> MP.space)
void $ MP.string "interactive"
void $ MP.oneOf ['>', ')']
colonP
pure ()
colonP :: MP.Parsec Void Text ()
colonP = void $ MP.char ':'
|
c095940ce4a21a1b8ccf4d56395ea15020594d2787b98e5f33956c467a7397d6 | uwiger/parse_trans | ex_gen_module.erl | -module(ex_gen_module).
-compile(export_all).
-compile({parse_transform, parse_trans_codegen}).
f() ->
codegen:gen_module(test, [{render,0}, {source, 0}],
[
{render, fun() ->
x end},
{source, fun() ->
ok end}
]).
| null | https://raw.githubusercontent.com/uwiger/parse_trans/56f5c6cad48eaca8e0b2626e0df3587e6bf2da6e/examples/ex_gen_module.erl | erlang | -module(ex_gen_module).
-compile(export_all).
-compile({parse_transform, parse_trans_codegen}).
f() ->
codegen:gen_module(test, [{render,0}, {source, 0}],
[
{render, fun() ->
x end},
{source, fun() ->
ok end}
]).
|
|
1f0203700c72e196b4c4f82242af7ede93c4a5674ea31ddc8f460a6f6690774e | Engil/Canopy | canopy_utils.ml | let assoc_opt k l =
match List.assoc k l with
| v -> Some v
| exception Not_found -> None
let map_opt fn default = function
| None -> default
| Some v -> fn v
let list_reduce_opt l =
let rec aux acc = function
| [] -> acc
| (Some x)::xs -> aux (x::acc) xs
| None::xs -> aux acc xs
in
aux [] l
let default_opt default = function
| None -> default
| Some v -> v
let resize len l =
List.fold_left
(fun (len, acc) x ->
if len > 0
then (len - 1, x :: acc)
else (0, acc))
(len, []) l
|> fun (_, l) -> List.rev l
let (++) = List.append
let ptime_to_pretty_date t =
Ptime.to_date t |> fun (y, m, d) ->
Printf.sprintf "%04d-%02d-%02d" y m d
module KeyMap = struct
module KeyOrd = struct
type t = string list
let compare a b =
match compare (List.length a) (List.length b) with
| 0 -> (
try List.find ((<>) 0) (List.map2 String.compare a b)
with Not_found -> 0
)
| x -> x
end
module M = Map.Make(KeyOrd)
include M
let fold_articles f =
M.fold (fun k v acc -> match v with
| `Article a -> f k a acc
| _ -> acc)
let find_opt m k =
try Some (M.find k m) with
| Not_found -> None
let find_article_opt m k =
match find_opt m k with
| Some (`Article a) -> Some a
| _ -> None
end
let add_etag_header time headers =
Cohttp.Header.add headers "Etag" (Ptime.to_rfc3339 time)
let html_headers headers time =
Cohttp.Header.add headers "Content-Type" "text/html; charset=UTF-8"
|> add_etag_header time
let atom_headers headers time =
Cohttp.Header.add headers "Content-Type" "application/atom+xml; charset=UTF-8"
|> add_etag_header time
let static_headers headers uri time =
Cohttp.Header.add headers "Content-Type" (Magic_mime.lookup uri)
|> add_etag_header time
| null | https://raw.githubusercontent.com/Engil/Canopy/7ad8691be9dffa60ba4fe9e1f2a786c12909780b/canopy_utils.ml | ocaml | let assoc_opt k l =
match List.assoc k l with
| v -> Some v
| exception Not_found -> None
let map_opt fn default = function
| None -> default
| Some v -> fn v
let list_reduce_opt l =
let rec aux acc = function
| [] -> acc
| (Some x)::xs -> aux (x::acc) xs
| None::xs -> aux acc xs
in
aux [] l
let default_opt default = function
| None -> default
| Some v -> v
let resize len l =
List.fold_left
(fun (len, acc) x ->
if len > 0
then (len - 1, x :: acc)
else (0, acc))
(len, []) l
|> fun (_, l) -> List.rev l
let (++) = List.append
let ptime_to_pretty_date t =
Ptime.to_date t |> fun (y, m, d) ->
Printf.sprintf "%04d-%02d-%02d" y m d
module KeyMap = struct
module KeyOrd = struct
type t = string list
let compare a b =
match compare (List.length a) (List.length b) with
| 0 -> (
try List.find ((<>) 0) (List.map2 String.compare a b)
with Not_found -> 0
)
| x -> x
end
module M = Map.Make(KeyOrd)
include M
let fold_articles f =
M.fold (fun k v acc -> match v with
| `Article a -> f k a acc
| _ -> acc)
let find_opt m k =
try Some (M.find k m) with
| Not_found -> None
let find_article_opt m k =
match find_opt m k with
| Some (`Article a) -> Some a
| _ -> None
end
let add_etag_header time headers =
Cohttp.Header.add headers "Etag" (Ptime.to_rfc3339 time)
let html_headers headers time =
Cohttp.Header.add headers "Content-Type" "text/html; charset=UTF-8"
|> add_etag_header time
let atom_headers headers time =
Cohttp.Header.add headers "Content-Type" "application/atom+xml; charset=UTF-8"
|> add_etag_header time
let static_headers headers uri time =
Cohttp.Header.add headers "Content-Type" (Magic_mime.lookup uri)
|> add_etag_header time
|
|
132e6e6650d7fc44876fa2f81639a7df7a2d6775e6fbdc5c7df1ebe74435477b | ghollisjr/cl-ana | package.lisp | (defpackage :cl-ana.spline
(:use :cl
:cl-ana.fitting
:cl-ana.macro-utils
:cl-ana.list-utils
:cl-ana.tensor
:cl-ana.math-functions)
(:export
:polynomial-spline ; supports polynomial splines of arbitrary order
;; struct accessors
:polynomial-spline-degree
:polynomial-spline-coefs
:polynomial-spline-xs
:polynomial-spline-deltas
supports splines provided by GSL via GSLL
:polynomial-spline-constraint ; generate consraint equations
:evaluate-polynomial-spline
:evaluate-polynomial-spline-derivative ; derivatives to any degree
:evaluate-polynomial-spline-integral ; definite integral
))
(cl-ana.gmath:use-gmath :cl-ana.spline)
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/c866a85e32da66bb23012ea151d20314db6a3bcd/spline/package.lisp | lisp | supports polynomial splines of arbitrary order
struct accessors
generate consraint equations
derivatives to any degree
definite integral | (defpackage :cl-ana.spline
(:use :cl
:cl-ana.fitting
:cl-ana.macro-utils
:cl-ana.list-utils
:cl-ana.tensor
:cl-ana.math-functions)
(:export
:polynomial-spline-degree
:polynomial-spline-coefs
:polynomial-spline-xs
:polynomial-spline-deltas
supports splines provided by GSL via GSLL
:evaluate-polynomial-spline
))
(cl-ana.gmath:use-gmath :cl-ana.spline)
|
cfee5fe8d325487ee985fab767a606827ab94fcf9e89818f341e0fb1b12487be | thizanne/cormoran | util.ml | open Batteries
Lexing
Lexing
*)
let file_lexbuf filename =
let open Lexing in
let lexbuf = from_channel @@ open_in filename in
lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = filename };
lexbuf.lex_start_p <- { lexbuf.lex_start_p with pos_fname = filename };
lexbuf
(*
Option
*)
let str_int_option = function
| None -> "∅"
| Some x -> string_of_int x
let print_int_option output opt =
String.print output (str_int_option opt)
let print_option print output = function
| None -> String.print output "∅"
| Some x -> print output x
let option_map2 f op1 op2 = match op1, op2 with
| None, _ -> None
| _, None -> None
| Some x, Some y -> Some (f x y)
let option_bind2 f op1 op2 = match op1, op2 with
| None, _ -> None
| _, None -> None
| Some x, Some y -> f x y
(*
List
*)
let set_assoc k v li =
List.map
(fun (k', v') -> k', if k' = k then v else v') li
let set_nth n v li =
List.mapi (fun i x -> if i = n then v else x) li
let rec incr_nth n = function
| [] -> failwith "incr_nth"
| x :: xs ->
if n = 0
then succ x :: xs
else x :: incr_nth (pred n) xs
let rec last = function
| [] -> raise Not_found
| [x] -> x
| _ :: xs -> last xs
let rec front = function
| [] -> failwith "front"
| [_] -> []
| x :: xs -> x :: front xs
let rec inser_all_pos x = function
| [] -> [[x]]
| y :: ys ->
(x :: y :: ys) ::
List.map (fun yy -> y :: yy) (inser_all_pos x ys)
let rec ordered_parts = function
| [] -> [[]]
| x :: xs ->
let xs = ordered_parts xs in
List.flatten @@
xs :: List.map (inser_all_pos x) xs
(*
Timing
*)
let time1 f =
let cumulative_time = ref 0. in
fun arg1 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time2 f =
let cumulative_time = ref 0. in
fun arg1 arg2 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time3 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time4 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time5 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 arg5 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 arg5 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time6 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 arg5 arg6 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 arg5 arg6 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time7 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 arg5 arg6 arg7 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 arg5 arg6 arg7 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
| null | https://raw.githubusercontent.com/thizanne/cormoran/46d13330ebd1c8224a0603fd473d8e6bed48bf53/src/util.ml | ocaml |
Option
List
Timing
| open Batteries
Lexing
Lexing
*)
let file_lexbuf filename =
let open Lexing in
let lexbuf = from_channel @@ open_in filename in
lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = filename };
lexbuf.lex_start_p <- { lexbuf.lex_start_p with pos_fname = filename };
lexbuf
let str_int_option = function
| None -> "∅"
| Some x -> string_of_int x
let print_int_option output opt =
String.print output (str_int_option opt)
let print_option print output = function
| None -> String.print output "∅"
| Some x -> print output x
let option_map2 f op1 op2 = match op1, op2 with
| None, _ -> None
| _, None -> None
| Some x, Some y -> Some (f x y)
let option_bind2 f op1 op2 = match op1, op2 with
| None, _ -> None
| _, None -> None
| Some x, Some y -> f x y
let set_assoc k v li =
List.map
(fun (k', v') -> k', if k' = k then v else v') li
let set_nth n v li =
List.mapi (fun i x -> if i = n then v else x) li
let rec incr_nth n = function
| [] -> failwith "incr_nth"
| x :: xs ->
if n = 0
then succ x :: xs
else x :: incr_nth (pred n) xs
let rec last = function
| [] -> raise Not_found
| [x] -> x
| _ :: xs -> last xs
let rec front = function
| [] -> failwith "front"
| [_] -> []
| x :: xs -> x :: front xs
let rec inser_all_pos x = function
| [] -> [[x]]
| y :: ys ->
(x :: y :: ys) ::
List.map (fun yy -> y :: yy) (inser_all_pos x ys)
let rec ordered_parts = function
| [] -> [[]]
| x :: xs ->
let xs = ordered_parts xs in
List.flatten @@
xs :: List.map (inser_all_pos x) xs
let time1 f =
let cumulative_time = ref 0. in
fun arg1 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time2 f =
let cumulative_time = ref 0. in
fun arg1 arg2 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time3 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time4 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time5 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 arg5 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 arg5 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time6 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 arg5 arg6 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 arg5 arg6 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
let time7 f =
let cumulative_time = ref 0. in
fun arg1 arg2 arg3 arg4 arg5 arg6 arg7 ->
let t1 = Unix.gettimeofday () in
let res = f arg1 arg2 arg3 arg4 arg5 arg6 arg7 in
let t2 = Unix.gettimeofday () in
let time = t2 -. t1 in
Printf.printf
"\x1b[33mTiming: %f, cumulative: %f\x1b[39;49m\n%!"
time (!cumulative_time +. time);
cumulative_time := !cumulative_time +. time;
res
|
dadea68786b8573b80c82d1f51087c7766ac12d3b796898de0656aa2a4dcd3ad | RJ/erlang-spdy | espdy_stream.erl | %%
One of these is spawned per stream ( SYN_STREAM )
%%
%% It delegates to the (currently hardcoded) callback module, which will
%% makes the request look like a normal http req to the app
%%
-module(espdy_stream).
-behaviour(gen_server).
-include("include/espdy.hrl").
-compile(export_all).
%% API
-export([start_link/5, send_data_fin/1, send_data/2, closed/2, received_data/2,
send_response/3, received_fin/1, send_frame/2, headers_updated/3
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {streamid,
clientclosed = false, %% them
serverclosed = false, %% us
pid,
mod,
mod_state,
headers,
spdy_version,
spdy_opts}).
%% API
start_link(StreamID, Pid, Headers, Mod, Opts) ->
gen_server:start(?MODULE, [StreamID, Pid, Headers, Mod, Opts], []).
send_data(Pid, Data) when is_pid(Pid), is_binary(Data) ->
gen_server:cast(Pid, {data, Data}).
send_data_fin(Pid) when is_pid(Pid) ->
gen_server:cast(Pid, {data, fin}).
closed(Pid, Reason) when is_pid(Pid) ->
gen_server:cast(Pid, {closed, Reason}).
received_data(Pid, Data) ->
gen_server:cast(Pid, {received_data, Data}).
received_fin(Pid) ->
gen_server:cast(Pid, received_fin).
send_response(Pid, Headers, Body) ->
gen_server:cast(Pid, {send_response, Headers, Body}).
send_frame(Pid, F) ->
gen_server:cast(Pid, {send_frame, F}).
headers_updated(Pid, Delta, NewMergedHeaders) ->
gen_server:cast(Pid, {headers_updated, Delta, NewMergedHeaders}).
%% gen_server callbacks
init([StreamID, Pid, Headers, Mod, Opts]) ->
self() ! init_callback,
%% Z = zlib:open(),
) ,
ok = zlib : deflateInit(Z , best_compression , deflated , 15 , 9 , default ) ,
zlib : deflateSetDictionary(Z , ? HEADERS_ZLIB_DICT ) ,
SpdyVersion = proplists:get_value(spdy_version, Opts),
{ok, #state{streamid=StreamID,
pid=Pid,
mod=Mod,
headers=Headers,
spdy_version=SpdyVersion,
spdy_opts=Opts}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({send_frame, F}, State) ->
espdy_session:snd(State#state.pid, State#state.streamid, F),
{noreply, State};
handle_cast(received_fin, State = #state{clientclosed=true}) ->
?LOG("Got FIN but client has already closed?", []),
{stop, {stream_error, protocol_error}, State};
handle_cast(received_fin, State = #state{clientclosed=false}) ->
NewState = State#state{clientclosed=true},
case both_closed(NewState) of
true -> ?LOG("Both ends closed, stopping stream ~w",[State#state.streamid]),
{stop, normal, NewState};
false -> ?LOG("Client closed, server not. stream ~w",[State#state.streamid]),
{noreply, NewState}
end;
handle_cast({received_data, Data}, State) ->
{ok, NewModState} = (State#state.mod):handle_data(Data, State#state.mod_state),
{noreply, State#state{mod_state=NewModState}};
handle_cast({headers_updated, Delta, NewMergedHeaders}, State) ->
{ok, NewModState} = (State#state.mod):headers_updated(Delta, NewMergedHeaders, State#state.mod_state),
{noreply, State#state{mod_state=NewModState}};
handle_cast({closed, Reason}, State) ->
(State#state.mod):closed(Reason, State#state.mod_state),
{stop, normal, State};
%% part of streamed body
handle_cast({data, Bin, false}, State) when is_binary(Bin) ->
F = #spdy_data{ streamid = State#state.streamid,
data=Bin},
espdy_session:snd(State#state.pid, State#state.streamid, F),
{noreply, State};
%% last of streamed body
handle_cast({data, Bin, true}, State) when is_binary(Bin) ->
F = #spdy_data{ streamid = State#state.streamid,
flags=?DATA_FLAG_FIN,
data=Bin},
espdy_session:snd(State#state.pid, State#state.streamid, F),
NewState = State#state{serverclosed=true},
case both_closed(NewState) of
true -> ?LOG("Both ends closed, stopping stream ~w",[State#state.streamid]),
{stop, normal, NewState};
false -> ?LOG("We are closed, client not. stream ~w",[State#state.streamid]),
{noreply, NewState}
end;
handle_cast({send_response, Headers, Body}, State) ->
send_http_response(Headers, Body, State),
NewState = State#state{serverclosed=true},
case both_closed(NewState) of
true -> ?LOG("Both ends closed, stopping stream ~w",[State#state.streamid]),
{stop, normal, NewState};
false -> ?LOG("We are closed, client not. stream ~w",[State#state.streamid]),
{noreply, NewState}
end.
%% Called when we got a syn_stream for this stream.
%% cb module is supposed to make and send the reply.
handle_info(init_callback, State) ->
case (State#state.mod):init(self(), State#state.headers, State#state.spdy_opts) of
%% In this case, the callback module provides the full response
%% with no need for this process to persist for streaming the body
%% so we can terminate this process after replying.
{ok, Headers, Body} when is_list(Headers), is_binary(Body) ->
%% se re-send this as a message to ourselves, because the callback
%% module may have dispatched other frames (eg, settings) before
%% returning us this response:
send_response(self(), Headers, Body),
{noreply, State};
%% The callback module will call msg us the send_http_response
%% (typically from within the guts of cowboy_http_req, so that
%% we can reuse the existing http API)
{ok, noreply} ->
TODO track state , set timeout on getting the response from CB
{noreply, State};
%% CB module is going to stream us the body data, so we keep this process
%% alive until we get the fin packet as part of the stream.
{ ok , Headers , stream , ModState } when is_list(Headers ) - >
%%%% NVPairsData = encode_name_value_pairs(Headers, State#state.z_context),
%%%% StreamID = State#state.streamid,
%%%% F = #cframe{type=?SYN_REPLY,
%%%% flags=0,
length = 6 + byte_size(NVPairsData ) ,
< < 0:1 ,
%%%% StreamID:31/big-unsigned-integer,
0:16 / big - unsigned - integer , % % UNUSED
%%%% NVPairsData/binary
%%%% >>},
%%%% espdy_session:snd(State#state.pid, StreamID, F),
{ noreply , State#state{mod_state = ModState } } ;
%% CB module can't respond, because request is invalid
{error, not_http} ->
StreamID = State#state.streamid,
F = #spdy_rst_stream{ streamid=StreamID, statuscode=?PROTOCOL_ERROR },
espdy_session:snd(State#state.pid, StreamID, F),
{stop, normal, State}
end.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
send_http_response(Headers, Body, State = #state{}) when is_list(Headers), is_binary(Body) ->
io:format("Respond with: ~p ~p\n",[Headers, Body]),
StreamID = State#state.streamid,
F = #spdy_syn_reply{ version = State#state.spdy_version,
streamid = StreamID,
headers = Headers
},
espdy_session:snd(State#state.pid, StreamID, F),
Send body response in exactly one data frame , with fin set .
TODO fragment this if we hit some maximum frame size ?
F2 = #spdy_data{streamid=StreamID,
flags=?DATA_FLAG_FIN,
data=Body},
espdy_session:snd(State#state.pid, StreamID, F2),
ok.
both_closed(#state{clientclosed=true,serverclosed=true}) -> true;
both_closed(_) -> false.
| null | https://raw.githubusercontent.com/RJ/erlang-spdy/3a15f26a80db87e0d901e8f1096682f848953d75/src/espdy_stream.erl | erlang |
It delegates to the (currently hardcoded) callback module, which will
makes the request look like a normal http req to the app
API
gen_server callbacks
them
us
API
gen_server callbacks
Z = zlib:open(),
part of streamed body
last of streamed body
Called when we got a syn_stream for this stream.
cb module is supposed to make and send the reply.
In this case, the callback module provides the full response
with no need for this process to persist for streaming the body
so we can terminate this process after replying.
se re-send this as a message to ourselves, because the callback
module may have dispatched other frames (eg, settings) before
returning us this response:
The callback module will call msg us the send_http_response
(typically from within the guts of cowboy_http_req, so that
we can reuse the existing http API)
CB module is going to stream us the body data, so we keep this process
alive until we get the fin packet as part of the stream.
NVPairsData = encode_name_value_pairs(Headers, State#state.z_context),
StreamID = State#state.streamid,
F = #cframe{type=?SYN_REPLY,
flags=0,
StreamID:31/big-unsigned-integer,
% UNUSED
NVPairsData/binary
>>},
espdy_session:snd(State#state.pid, StreamID, F),
CB module can't respond, because request is invalid | One of these is spawned per stream ( SYN_STREAM )
-module(espdy_stream).
-behaviour(gen_server).
-include("include/espdy.hrl").
-compile(export_all).
-export([start_link/5, send_data_fin/1, send_data/2, closed/2, received_data/2,
send_response/3, received_fin/1, send_frame/2, headers_updated/3
]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {streamid,
pid,
mod,
mod_state,
headers,
spdy_version,
spdy_opts}).
start_link(StreamID, Pid, Headers, Mod, Opts) ->
gen_server:start(?MODULE, [StreamID, Pid, Headers, Mod, Opts], []).
send_data(Pid, Data) when is_pid(Pid), is_binary(Data) ->
gen_server:cast(Pid, {data, Data}).
send_data_fin(Pid) when is_pid(Pid) ->
gen_server:cast(Pid, {data, fin}).
closed(Pid, Reason) when is_pid(Pid) ->
gen_server:cast(Pid, {closed, Reason}).
received_data(Pid, Data) ->
gen_server:cast(Pid, {received_data, Data}).
received_fin(Pid) ->
gen_server:cast(Pid, received_fin).
send_response(Pid, Headers, Body) ->
gen_server:cast(Pid, {send_response, Headers, Body}).
send_frame(Pid, F) ->
gen_server:cast(Pid, {send_frame, F}).
headers_updated(Pid, Delta, NewMergedHeaders) ->
gen_server:cast(Pid, {headers_updated, Delta, NewMergedHeaders}).
init([StreamID, Pid, Headers, Mod, Opts]) ->
self() ! init_callback,
) ,
ok = zlib : deflateInit(Z , best_compression , deflated , 15 , 9 , default ) ,
zlib : deflateSetDictionary(Z , ? HEADERS_ZLIB_DICT ) ,
SpdyVersion = proplists:get_value(spdy_version, Opts),
{ok, #state{streamid=StreamID,
pid=Pid,
mod=Mod,
headers=Headers,
spdy_version=SpdyVersion,
spdy_opts=Opts}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({send_frame, F}, State) ->
espdy_session:snd(State#state.pid, State#state.streamid, F),
{noreply, State};
handle_cast(received_fin, State = #state{clientclosed=true}) ->
?LOG("Got FIN but client has already closed?", []),
{stop, {stream_error, protocol_error}, State};
handle_cast(received_fin, State = #state{clientclosed=false}) ->
NewState = State#state{clientclosed=true},
case both_closed(NewState) of
true -> ?LOG("Both ends closed, stopping stream ~w",[State#state.streamid]),
{stop, normal, NewState};
false -> ?LOG("Client closed, server not. stream ~w",[State#state.streamid]),
{noreply, NewState}
end;
handle_cast({received_data, Data}, State) ->
{ok, NewModState} = (State#state.mod):handle_data(Data, State#state.mod_state),
{noreply, State#state{mod_state=NewModState}};
handle_cast({headers_updated, Delta, NewMergedHeaders}, State) ->
{ok, NewModState} = (State#state.mod):headers_updated(Delta, NewMergedHeaders, State#state.mod_state),
{noreply, State#state{mod_state=NewModState}};
handle_cast({closed, Reason}, State) ->
(State#state.mod):closed(Reason, State#state.mod_state),
{stop, normal, State};
handle_cast({data, Bin, false}, State) when is_binary(Bin) ->
F = #spdy_data{ streamid = State#state.streamid,
data=Bin},
espdy_session:snd(State#state.pid, State#state.streamid, F),
{noreply, State};
handle_cast({data, Bin, true}, State) when is_binary(Bin) ->
F = #spdy_data{ streamid = State#state.streamid,
flags=?DATA_FLAG_FIN,
data=Bin},
espdy_session:snd(State#state.pid, State#state.streamid, F),
NewState = State#state{serverclosed=true},
case both_closed(NewState) of
true -> ?LOG("Both ends closed, stopping stream ~w",[State#state.streamid]),
{stop, normal, NewState};
false -> ?LOG("We are closed, client not. stream ~w",[State#state.streamid]),
{noreply, NewState}
end;
handle_cast({send_response, Headers, Body}, State) ->
send_http_response(Headers, Body, State),
NewState = State#state{serverclosed=true},
case both_closed(NewState) of
true -> ?LOG("Both ends closed, stopping stream ~w",[State#state.streamid]),
{stop, normal, NewState};
false -> ?LOG("We are closed, client not. stream ~w",[State#state.streamid]),
{noreply, NewState}
end.
handle_info(init_callback, State) ->
case (State#state.mod):init(self(), State#state.headers, State#state.spdy_opts) of
{ok, Headers, Body} when is_list(Headers), is_binary(Body) ->
send_response(self(), Headers, Body),
{noreply, State};
{ok, noreply} ->
TODO track state , set timeout on getting the response from CB
{noreply, State};
{ ok , Headers , stream , ModState } when is_list(Headers ) - >
length = 6 + byte_size(NVPairsData ) ,
< < 0:1 ,
{ noreply , State#state{mod_state = ModState } } ;
{error, not_http} ->
StreamID = State#state.streamid,
F = #spdy_rst_stream{ streamid=StreamID, statuscode=?PROTOCOL_ERROR },
espdy_session:snd(State#state.pid, StreamID, F),
{stop, normal, State}
end.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
send_http_response(Headers, Body, State = #state{}) when is_list(Headers), is_binary(Body) ->
io:format("Respond with: ~p ~p\n",[Headers, Body]),
StreamID = State#state.streamid,
F = #spdy_syn_reply{ version = State#state.spdy_version,
streamid = StreamID,
headers = Headers
},
espdy_session:snd(State#state.pid, StreamID, F),
Send body response in exactly one data frame , with fin set .
TODO fragment this if we hit some maximum frame size ?
F2 = #spdy_data{streamid=StreamID,
flags=?DATA_FLAG_FIN,
data=Body},
espdy_session:snd(State#state.pid, StreamID, F2),
ok.
both_closed(#state{clientclosed=true,serverclosed=true}) -> true;
both_closed(_) -> false.
|
0a685e5ab04a2ad315d4df56ed4311b6aea2cab972c716be1d9fedac1c1bec34 | ml4tp/tcoq | cUnix.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
* { 5 System utilities }
type physical_path = string
type load_path = physical_path list
val physical_path_of_string : string -> physical_path
val string_of_physical_path : physical_path -> string
val canonical_path_name : string -> string
* remove all initial " ./ " in a path
val remove_path_dot : string -> string
* If a path [ p ] starts with the current directory $ PWD then
[ strip_path p ] returns the sub - path relative to $ PWD .
Any leading " ./ " are also removed from the result .
[strip_path p] returns the sub-path relative to $PWD.
Any leading "./" are also removed from the result. *)
val strip_path : string -> string
(** correct_path f dir = dir/f if f is relative *)
val correct_path : string -> string -> string
val path_to_list : string -> string list
(** [make_suffix file suf] catenate [file] with [suf] when
[file] does not already end with [suf]. *)
val make_suffix : string -> string -> string
(** Return the extension of a file, i.e. its smaller suffix starting
with "." if any, or "" otherwise. *)
val get_extension : string -> string
val file_readable_p : string -> bool
* { 6 Executing commands }
(** [run_command com] launches command [com], and returns
the contents of stdout and stderr. If given, [~hook]
is called on each elements read on stdout or stderr. *)
val run_command :
?hook:(string->unit) -> string -> Unix.process_status * string
(** [sys_command] launches program [prog] with arguments [args].
It behaves like [Sys.command], except that we rely on
[Unix.create_process], it's hardly more complex and avoids dealing
with shells. In particular, no need to quote arguments
(against whitespace or other funny chars in paths), hence no need
to care about the different quoting conventions of /bin/sh and cmd.exe. *)
val sys_command : string -> string list -> Unix.process_status
(** A version of [Unix.waitpid] immune to EINTR exceptions *)
val waitpid_non_intr : int -> Unix.process_status
* checks if two file names refer to the same ( existing ) file
val same_file : string -> string -> bool
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/lib/cUnix.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* correct_path f dir = dir/f if f is relative
* [make_suffix file suf] catenate [file] with [suf] when
[file] does not already end with [suf].
* Return the extension of a file, i.e. its smaller suffix starting
with "." if any, or "" otherwise.
* [run_command com] launches command [com], and returns
the contents of stdout and stderr. If given, [~hook]
is called on each elements read on stdout or stderr.
* [sys_command] launches program [prog] with arguments [args].
It behaves like [Sys.command], except that we rely on
[Unix.create_process], it's hardly more complex and avoids dealing
with shells. In particular, no need to quote arguments
(against whitespace or other funny chars in paths), hence no need
to care about the different quoting conventions of /bin/sh and cmd.exe.
* A version of [Unix.waitpid] immune to EINTR exceptions | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* { 5 System utilities }
type physical_path = string
type load_path = physical_path list
val physical_path_of_string : string -> physical_path
val string_of_physical_path : physical_path -> string
val canonical_path_name : string -> string
* remove all initial " ./ " in a path
val remove_path_dot : string -> string
* If a path [ p ] starts with the current directory $ PWD then
[ strip_path p ] returns the sub - path relative to $ PWD .
Any leading " ./ " are also removed from the result .
[strip_path p] returns the sub-path relative to $PWD.
Any leading "./" are also removed from the result. *)
val strip_path : string -> string
val correct_path : string -> string -> string
val path_to_list : string -> string list
val make_suffix : string -> string -> string
val get_extension : string -> string
val file_readable_p : string -> bool
* { 6 Executing commands }
val run_command :
?hook:(string->unit) -> string -> Unix.process_status * string
val sys_command : string -> string list -> Unix.process_status
val waitpid_non_intr : int -> Unix.process_status
* checks if two file names refer to the same ( existing ) file
val same_file : string -> string -> bool
|
28d995faf29cb89371609e6ad0b883abe07ea7359d36d8502d93dbc1880e4052 | gelisam/ludum-dare-31 | Ending.hs | module Ending where
import Control.Applicative
import Data.Monoid
import Graphics.Gloss
import Animation
import Graphics.Gloss.Extra
import InputBlocking
import Popup
import Vec2d
endingAnimation :: InputBlockingAnimation Picture
endingAnimation = inputBlockingAnimation
$ mappend fadeToWhite
$ mappend staticWhite
<$> rollCredits
<> static endingScreen
where
fadeToWhite = makeWhiteFilter <$> interpolate 5 0 1
staticWhite = makeWhiteFilter 1
rollCredits = translate 0 <$> interpolate 20 (-800) 0
<*> pure credits
credits = mappend endingScreen
$ translate (-210) 240
$ pictureCol 20
$ reverse
[ title "Credits"
, blank
, blank
, sectionTitle "Programming"
, author
, blank
, sectionTitle "Art"
, author
, blank
, sectionTitle "Playtesting"
, text' "Nadezda Ershova"
, blank
, blank
, text' "Created in 48h for Ludum Dare 31, with"
, text' "the theme \"Entire Game on One Screen\"."
]
where
title :: String -> Picture
title = rectBoldPicture (V 2 1) . text'
sectionTitle :: String -> Picture
sectionTitle = rectBoldPicture (V 1 1) . text'
text' :: String -> Picture
text' = uscale 0.15 . blackText
author :: Picture
author = text' "Samuel Gelineau"
<> accent
accent :: Picture
accent = blackLine [(x, y), (x + dx, y + dy)]
where
(x, y) = (97, 12)
(dx, dy) = (4, 2)
endingScreen = rectBoldPicture (V 8 2)
$ translate (-270) 0
$ blackText "The End"
| null | https://raw.githubusercontent.com/gelisam/ludum-dare-31/4bdd2937b290c41118503bc85a2a16a73139edd2/src/Ending.hs | haskell | module Ending where
import Control.Applicative
import Data.Monoid
import Graphics.Gloss
import Animation
import Graphics.Gloss.Extra
import InputBlocking
import Popup
import Vec2d
endingAnimation :: InputBlockingAnimation Picture
endingAnimation = inputBlockingAnimation
$ mappend fadeToWhite
$ mappend staticWhite
<$> rollCredits
<> static endingScreen
where
fadeToWhite = makeWhiteFilter <$> interpolate 5 0 1
staticWhite = makeWhiteFilter 1
rollCredits = translate 0 <$> interpolate 20 (-800) 0
<*> pure credits
credits = mappend endingScreen
$ translate (-210) 240
$ pictureCol 20
$ reverse
[ title "Credits"
, blank
, blank
, sectionTitle "Programming"
, author
, blank
, sectionTitle "Art"
, author
, blank
, sectionTitle "Playtesting"
, text' "Nadezda Ershova"
, blank
, blank
, text' "Created in 48h for Ludum Dare 31, with"
, text' "the theme \"Entire Game on One Screen\"."
]
where
title :: String -> Picture
title = rectBoldPicture (V 2 1) . text'
sectionTitle :: String -> Picture
sectionTitle = rectBoldPicture (V 1 1) . text'
text' :: String -> Picture
text' = uscale 0.15 . blackText
author :: Picture
author = text' "Samuel Gelineau"
<> accent
accent :: Picture
accent = blackLine [(x, y), (x + dx, y + dy)]
where
(x, y) = (97, 12)
(dx, dy) = (4, 2)
endingScreen = rectBoldPicture (V 8 2)
$ translate (-270) 0
$ blackText "The End"
|
|
b635c9d23e08f5bf318dd6d01eebe34da7d595447920eb0bae35de9ca35355f9 | kayceesrk/Quelea | SimpleBroker.hs | {-# LANGUAGE OverloadedStrings #-}
module Quelea.NameService.SimpleBroker (
startBroker,
mkNameService
) where
import qualified System.ZMQ4 as ZMQ4
import System.ZMQ4.Monadic
import Control.Concurrent
import Control.Monad
import Data.ByteString.Char8 (unpack, pack)
import System.Directory
import System.Posix.Process
import Control.Monad.Trans (liftIO)
import Quelea.NameService.Types
debugPrint :: String -> IO ()
#ifdef DEBUG
debugPrint s = do
tid <- myThreadId
putStrLn $ "[" ++ (show tid) ++ "] " ++ s
#else
debugPrint _ = return ()
#endif
startBroker :: Frontend -> Backend -> IO ()
startBroker f b = runZMQ $ do
fes <- socket Router
bind fes $ unFE f
bes <- socket Dealer
bind bes $ unBE b
proxy fes bes Nothing
clientJoin :: Frontend -> IO (String, ZMQ4.Socket ZMQ4.Req)
clientJoin f = do
serverAddr <- runZMQ $ do
requester <- socket Req
liftIO $ debugPrint "clientJoin(1)"
connect requester $ unFE f
liftIO $ debugPrint "clientJoin(2)"
send requester [] "Howdy Server! send your socket info"
liftIO $ debugPrint "clientJoin(3)"
msg <- receive requester
liftIO $ debugPrint "clientJoin(4)"
return $ unpack msg
Connect to the shim layer node .
ctxt <- ZMQ4.context
sock <- ZMQ4.socket ctxt ZMQ4.Req
ZMQ4.connect sock serverAddr
return (serverAddr, sock)
serverJoin :: Backend -> String {- ip -} -> Int {- Port# -} -> IO ()
serverJoin b ip port = do
void $ forkIO $ runZMQ $ do
liftIO $ debugPrint "serverJoin(5)"
{- Create a router and a dealer -}
routerSock <- socket Router
let myaddr = "tcp://*:" ++ show port
bind routerSock myaddr
dealerSock <- socket Dealer
liftIO $ createDirectoryIfMissing False "/tmp/quelea"
pid <- liftIO $ getProcessID
bind dealerSock $ "ipc/" ++ show pid
liftIO $ debugPrint "serverJoin(6): starting proxy"
{- Start proxy to distribute requests to workers -}
proxy routerSock dealerSock Nothing
{- Fork a daemon thread that joins with the backend. The daemon shares the
- servers address for every client request. The client then joins with the
- server.
-}
runZMQ $ do
responder <- socket Rep
liftIO $ debugPrint "serverJoin(1)"
connect responder $ unBE b
liftIO $ debugPrint "serverJoin(2)"
forever $ do
message <- receive responder
liftIO $ debugPrint $ "serverJoin(3) " ++ ip
send responder [] $ pack $ "tcp://" ++ ip ++ ":" ++ show port
liftIO $ debugPrint "serverJoin(4)"
mkNameService :: Frontend -> Backend
-> String {- Backend ip (only for sticky) -}
-> Int {- Backend port (only for sticky) -}
-> NameService
mkNameService fe be ip port =
NameService fe (clientJoin fe) (serverJoin be ip port)
| null | https://raw.githubusercontent.com/kayceesrk/Quelea/73db79a5d5513b9aeeb475867a67bacb6a5313d0/src/Quelea/NameService/SimpleBroker.hs | haskell | # LANGUAGE OverloadedStrings #
ip
Port#
Create a router and a dealer
Start proxy to distribute requests to workers
Fork a daemon thread that joins with the backend. The daemon shares the
- servers address for every client request. The client then joins with the
- server.
Backend ip (only for sticky)
Backend port (only for sticky) |
module Quelea.NameService.SimpleBroker (
startBroker,
mkNameService
) where
import qualified System.ZMQ4 as ZMQ4
import System.ZMQ4.Monadic
import Control.Concurrent
import Control.Monad
import Data.ByteString.Char8 (unpack, pack)
import System.Directory
import System.Posix.Process
import Control.Monad.Trans (liftIO)
import Quelea.NameService.Types
debugPrint :: String -> IO ()
#ifdef DEBUG
debugPrint s = do
tid <- myThreadId
putStrLn $ "[" ++ (show tid) ++ "] " ++ s
#else
debugPrint _ = return ()
#endif
startBroker :: Frontend -> Backend -> IO ()
startBroker f b = runZMQ $ do
fes <- socket Router
bind fes $ unFE f
bes <- socket Dealer
bind bes $ unBE b
proxy fes bes Nothing
clientJoin :: Frontend -> IO (String, ZMQ4.Socket ZMQ4.Req)
clientJoin f = do
serverAddr <- runZMQ $ do
requester <- socket Req
liftIO $ debugPrint "clientJoin(1)"
connect requester $ unFE f
liftIO $ debugPrint "clientJoin(2)"
send requester [] "Howdy Server! send your socket info"
liftIO $ debugPrint "clientJoin(3)"
msg <- receive requester
liftIO $ debugPrint "clientJoin(4)"
return $ unpack msg
Connect to the shim layer node .
ctxt <- ZMQ4.context
sock <- ZMQ4.socket ctxt ZMQ4.Req
ZMQ4.connect sock serverAddr
return (serverAddr, sock)
serverJoin b ip port = do
void $ forkIO $ runZMQ $ do
liftIO $ debugPrint "serverJoin(5)"
routerSock <- socket Router
let myaddr = "tcp://*:" ++ show port
bind routerSock myaddr
dealerSock <- socket Dealer
liftIO $ createDirectoryIfMissing False "/tmp/quelea"
pid <- liftIO $ getProcessID
bind dealerSock $ "ipc/" ++ show pid
liftIO $ debugPrint "serverJoin(6): starting proxy"
proxy routerSock dealerSock Nothing
runZMQ $ do
responder <- socket Rep
liftIO $ debugPrint "serverJoin(1)"
connect responder $ unBE b
liftIO $ debugPrint "serverJoin(2)"
forever $ do
message <- receive responder
liftIO $ debugPrint $ "serverJoin(3) " ++ ip
send responder [] $ pack $ "tcp://" ++ ip ++ ":" ++ show port
liftIO $ debugPrint "serverJoin(4)"
mkNameService :: Frontend -> Backend
-> NameService
mkNameService fe be ip port =
NameService fe (clientJoin fe) (serverJoin be ip port)
|
d21e5676ec3e564ef9caa199195ef616ffa819cbeae058318f7b400888ca4cf1 | Deep-Symmetry/beat-link-trigger | settings_loader.clj | (ns beat-link-trigger.settings-loader
"Provides the user inerface for configuring a My Settings profile and
sending it to players found on the network."
(:require [beat-link-trigger.prefs :as prefs]
[beat-link-trigger.track-loader :as track-loader]
[clojure.string :as str]
[seesaw.core :as seesaw]
[seesaw.mig :as mig]
[taoensso.timbre :as timbre])
(:import [beat_link_trigger.util PlayerChoice]
[java.awt.event WindowEvent]
[org.deepsymmetry.beatlink CdjStatus DeviceAnnouncementListener DeviceFinder
DeviceUpdateListener LifecycleListener PlayerSettings PlayerSettings$AutoCueLevel
PlayerSettings$AutoLoadMode PlayerSettings$Illumination
PlayerSettings$JogMode PlayerSettings$JogWheelDisplay
PlayerSettings$LcdBrightness PlayerSettings$Language
PlayerSettings$PadButtonBrightness PlayerSettings$PhaseMeterType PlayerSettings$PlayMode
PlayerSettings$QuantizeMode PlayerSettings$TempoRange PlayerSettings$TimeDisplayMode
PlayerSettings$Toggle PlayerSettings$VinylSpeedAdjust VirtualCdj]))
(defonce ^{:private true
:doc "Holds the frame allowing the user to adjust settings
and tell a player to load them."} loader-window
(atom nil))
(def ^DeviceFinder device-finder
"A convenient reference to the [Beat Link
`DeviceFinder`]()
singleton."
(DeviceFinder/getInstance))
(def ^VirtualCdj virtual-cdj
"A convenient reference to the [Beat Link
`VirtualCdj`]()
singleton."
(VirtualCdj/getInstance))
(defn- enum-picker
"Creates a menu for choosing a setting based on one of the special
enums used by `PlayerSettings`, and handles initializing it based on
the current preferences, as well as updating the settings object and
preferences appropriately when the user chooses a different value."
[enum settings defaults field-name]
(let [field (.. settings getClass (getDeclaredField field-name))
value-of (.. enum (getDeclaredMethod "valueOf" (into-array Class [String])))
display-value (.. enum (getDeclaredField "displayValue"))]
;; If there is a stored preference for this setting, establish it.
(when-let [default (get defaults field-name)]
(. field (set settings (. value-of (invoke enum (to-array [default]))))))
;; Create the combo box with a model that uses the specified enumeration constants,
;; and a custom cell renderer which draws the displayValue, rather than the persistence-oriented
;; toString() value, and install a state change handler which updates both the settings
;; object and the stored preferences values to reflect the user's wish.
(let [box (seesaw/combobox :model (.getEnumConstants enum)
:selected-item (. field (get settings))
:listen [:item-state-changed
(fn [e]
(when-let [selection (seesaw/selection e)]
(. field (set settings selection))
(prefs/put-preferences (update-in (prefs/get-preferences) [:my-settings]
assoc field-name (str selection)))))])
orig (.getRenderer box)
draw (proxy [javax.swing.DefaultListCellRenderer] []
(getListCellRendererComponent [the-list value index is-selected has-focus]
(let [display (. display-value (get value))]
(.getListCellRendererComponent orig the-list display index is-selected has-focus))))]
(.setRenderer box draw)
box)))
(defn- create-window
"Builds an interface in which the user can adjust their My Settings
preferences and load them into a player."
[]
(seesaw/invoke-later
(try
(let [selected-player (atom {:number nil :playing false})
root (seesaw/frame :title "My Settings" :on-close :dispose :resizable? true)
load-button (seesaw/button :text "Load" :enabled? false)
problem-label (seesaw/label :text "" :foreground "red")
update-load-ui (fn []
(let [playing (:playing @selected-player)
problem (if playing "Playing." "")]
(seesaw/value! problem-label problem)
(seesaw/config! load-button :enabled? (str/blank? problem))))
player-changed (fn [e]
(let [^Long number (when-let [^PlayerChoice selection (seesaw/selection e)]
(.number selection))
^CdjStatus status (when number (.getLatestStatusFor virtual-cdj number))]
(reset! selected-player {:number number :playing (and status (.isPlaying status))})
(update-load-ui)))
players (seesaw/combobox :id :players
:listen [:item-state-changed player-changed])
player-panel (mig/mig-panel :background "#ddd"
:items [[(seesaw/label :text "Load on:")]
[players "gap unrelated"]
[problem-label "push, gap unrelated"]
[load-button]])
settings (PlayerSettings.)
defaults (:my-settings (prefs/get-preferences))
settings-panel (mig/mig-panel ; Starts with DJ Settings
:items [[(seesaw/label :text "Play Mode:") "align right"]
[(enum-picker PlayerSettings$PlayMode settings defaults "autoPlayMode") "wrap"]
[(seesaw/label :text "Eject/Load Lock:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "ejectLoadLock") "wrap"]
[(seesaw/label :text "Needle Lock:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "needleLock") "wrap"]
[(seesaw/label :text "Quantize Beat Value:") "align right"]
[(enum-picker PlayerSettings$QuantizeMode settings defaults "quantizeBeatValue")
"wrap"]
[(seesaw/label :text "Hot Cue Auto Load:") "align right"]
[(enum-picker PlayerSettings$AutoLoadMode settings defaults "autoLoadMode")
"wrap"]
[(seesaw/label :text "Hot Cue Color:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "hotCueColor") "wrap"]
[(seesaw/label :text "Auto Cue Level:") "align right"]
[(enum-picker PlayerSettings$AutoCueLevel settings defaults "autoCueLevel") "wrap"]
[(seesaw/label :text "Time Display Mode:") "align right"]
[(enum-picker PlayerSettings$TimeDisplayMode settings defaults "timeDisplayMode")
"wrap"]
[(seesaw/label :text "Auto Cue:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "autoCue") "wrap"]
[(seesaw/label :text "Jog Mode:") "align right"]
[(enum-picker PlayerSettings$JogMode settings defaults "jogMode") "wrap"]
[(seesaw/label :text "Tempo Range:") "align right"]
[(enum-picker PlayerSettings$TempoRange settings defaults "tempoRange") "wrap"]
[(seesaw/label :text "Master Tempo:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "masterTempo") "wrap"]
[(seesaw/label :text "Quantize:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "quantize") "wrap"]
[(seesaw/label :text "Sync:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "sync") "wrap"]
[(seesaw/label :text "Phase Meter:") "align right"]
[(enum-picker PlayerSettings$PhaseMeterType settings defaults "phaseMeterType")
"wrap"]
[(seesaw/label :text "Vinyl Speed Adjust:") "align right"]
[(enum-picker PlayerSettings$VinylSpeedAdjust settings defaults "vinylSpeedAdjust")
"wrap unrelated"]
;; Display (LCD) settings
[(seesaw/label :text "Language:") "align right"]
[(enum-picker PlayerSettings$Language settings defaults "language") "wrap"]
[(seesaw/label :text "LCD Brightness:") "align right"]
[(enum-picker PlayerSettings$LcdBrightness settings defaults "lcdBrightness")
"wrap"]
[(seesaw/label :text "Jog Wheel LCD Brightness:") "align right"]
[(enum-picker PlayerSettings$LcdBrightness settings defaults
"jogWheelLcdBrightness") "wrap"]
[(seesaw/label :text "Jog Wheel Display Mode:") "align right"]
[(enum-picker PlayerSettings$JogWheelDisplay settings defaults "jogWheelDisplay")
"wrap unrelated"]
;; Display (Indicator) settings
[(seesaw/label :text "Slip Flashing:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "slipFlashing") "wrap"]
[(seesaw/label :text "On Air Display:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "onAirDisplay") "wrap"]
[(seesaw/label :text "Jog Ring Brightness:") "align right"]
[(enum-picker PlayerSettings$Illumination settings defaults "jogRingIllumination")
"wrap"]
[(seesaw/label :text "Jog Ring Indicator:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "jogRingIndicator") "wrap"]
[(seesaw/label :text "Disc Slot Illumination:") "align right"]
[(enum-picker PlayerSettings$Illumination settings defaults "discSlotIllumination")
"wrap"]
[(seesaw/label :text "Pad/Button Brightness:") "align right"]
[(enum-picker PlayerSettings$PadButtonBrightness settings defaults
"padButtonBrightness") "wrap"]])
layout (seesaw/border-panel :center (seesaw/scrollable settings-panel) :south player-panel)
stop-listener (reify LifecycleListener
(started [_this _]) ; Nothing to do, we exited as soon as a stop happened anyway.
Close our window if VirtualCdj stops ( we need it ) .
(seesaw/invoke-later
(.dispatchEvent root (WindowEvent. root WindowEvent/WINDOW_CLOSING)))))
dev-listener (reify DeviceAnnouncementListener
(deviceFound [_this announcement]
(seesaw/invoke-later (track-loader/add-device players (.getDeviceNumber announcement))))
(deviceLost [_this announcement]
(seesaw/invoke-later (track-loader/remove-device players (.getDeviceNumber announcement)
stop-listener))))
status-listener (reify DeviceUpdateListener
(received [_this status]
(let [player @selected-player]
(when (and (= (.getDeviceNumber status) (:number player))
(not= (.isPlaying ^CdjStatus status) (:playing player)))
(swap! selected-player assoc :playing (.isPlaying ^CdjStatus status))
(update-load-ui)))))
remove-listeners (fn []
(.removeLifecycleListener virtual-cdj stop-listener)
(.removeDeviceAnnouncementListener device-finder dev-listener)
(.removeUpdateListener virtual-cdj status-listener))]
(.addDeviceAnnouncementListener device-finder dev-listener)
(.addUpdateListener virtual-cdj status-listener)
(track-loader/build-device-choices players)
(reset! loader-window root)
(.addLifecycleListener virtual-cdj stop-listener)
(seesaw/listen root :window-closed (fn [_]
(reset! loader-window nil)
(remove-listeners)))
(seesaw/listen load-button
:action-performed
(fn [_]
(let [^Long selected-player (.number ^PlayerChoice (.getSelectedItem players))]
(.sendLoadSettingsCommand virtual-cdj selected-player settings))))
(when-not (.isRunning virtual-cdj) ; In case it shut down during our setup.
(when @loader-window (.stopped stop-listener virtual-cdj))) ; Give up unless we already did.
(if @loader-window
(do ; We made it! Show the window.
(seesaw/config! root :content layout)
(seesaw/pack! root)
(.setLocationRelativeTo root nil) ; TODO: Save/restore this window position?
root)
(do ; Something failed, clean up.
(remove-listeners)
(.dispose root))))
(catch Exception e
(timbre/error e "Problem Loading Settings")
(seesaw/alert (str "<html>Unable to Load Settings on Player:<br><br>" (.getMessage e)
"<br><br>See the log file for more details.")
:title "Problem Loading Settings" :type :error)))))
(defn show-dialog
"Displays an interface in whcih the user can adjust their preferred
player settings and load them into players."
[]
(seesaw/invoke-later
(locking loader-window
(when-not @loader-window (create-window))
(seesaw/invoke-later
(when-let [window @loader-window]
(seesaw/show! window)
(.toFront window))))))
| null | https://raw.githubusercontent.com/Deep-Symmetry/beat-link-trigger/f25a79b70d7da55b4feeca5690cf2c40e00a2dee/src/beat_link_trigger/settings_loader.clj | clojure | If there is a stored preference for this setting, establish it.
Create the combo box with a model that uses the specified enumeration constants,
and a custom cell renderer which draws the displayValue, rather than the persistence-oriented
toString() value, and install a state change handler which updates both the settings
object and the stored preferences values to reflect the user's wish.
Starts with DJ Settings
Display (LCD) settings
Display (Indicator) settings
Nothing to do, we exited as soon as a stop happened anyway.
In case it shut down during our setup.
Give up unless we already did.
We made it! Show the window.
TODO: Save/restore this window position?
Something failed, clean up. | (ns beat-link-trigger.settings-loader
"Provides the user inerface for configuring a My Settings profile and
sending it to players found on the network."
(:require [beat-link-trigger.prefs :as prefs]
[beat-link-trigger.track-loader :as track-loader]
[clojure.string :as str]
[seesaw.core :as seesaw]
[seesaw.mig :as mig]
[taoensso.timbre :as timbre])
(:import [beat_link_trigger.util PlayerChoice]
[java.awt.event WindowEvent]
[org.deepsymmetry.beatlink CdjStatus DeviceAnnouncementListener DeviceFinder
DeviceUpdateListener LifecycleListener PlayerSettings PlayerSettings$AutoCueLevel
PlayerSettings$AutoLoadMode PlayerSettings$Illumination
PlayerSettings$JogMode PlayerSettings$JogWheelDisplay
PlayerSettings$LcdBrightness PlayerSettings$Language
PlayerSettings$PadButtonBrightness PlayerSettings$PhaseMeterType PlayerSettings$PlayMode
PlayerSettings$QuantizeMode PlayerSettings$TempoRange PlayerSettings$TimeDisplayMode
PlayerSettings$Toggle PlayerSettings$VinylSpeedAdjust VirtualCdj]))
(defonce ^{:private true
:doc "Holds the frame allowing the user to adjust settings
and tell a player to load them."} loader-window
(atom nil))
(def ^DeviceFinder device-finder
"A convenient reference to the [Beat Link
`DeviceFinder`]()
singleton."
(DeviceFinder/getInstance))
(def ^VirtualCdj virtual-cdj
"A convenient reference to the [Beat Link
`VirtualCdj`]()
singleton."
(VirtualCdj/getInstance))
(defn- enum-picker
"Creates a menu for choosing a setting based on one of the special
enums used by `PlayerSettings`, and handles initializing it based on
the current preferences, as well as updating the settings object and
preferences appropriately when the user chooses a different value."
[enum settings defaults field-name]
(let [field (.. settings getClass (getDeclaredField field-name))
value-of (.. enum (getDeclaredMethod "valueOf" (into-array Class [String])))
display-value (.. enum (getDeclaredField "displayValue"))]
(when-let [default (get defaults field-name)]
(. field (set settings (. value-of (invoke enum (to-array [default]))))))
(let [box (seesaw/combobox :model (.getEnumConstants enum)
:selected-item (. field (get settings))
:listen [:item-state-changed
(fn [e]
(when-let [selection (seesaw/selection e)]
(. field (set settings selection))
(prefs/put-preferences (update-in (prefs/get-preferences) [:my-settings]
assoc field-name (str selection)))))])
orig (.getRenderer box)
draw (proxy [javax.swing.DefaultListCellRenderer] []
(getListCellRendererComponent [the-list value index is-selected has-focus]
(let [display (. display-value (get value))]
(.getListCellRendererComponent orig the-list display index is-selected has-focus))))]
(.setRenderer box draw)
box)))
(defn- create-window
"Builds an interface in which the user can adjust their My Settings
preferences and load them into a player."
[]
(seesaw/invoke-later
(try
(let [selected-player (atom {:number nil :playing false})
root (seesaw/frame :title "My Settings" :on-close :dispose :resizable? true)
load-button (seesaw/button :text "Load" :enabled? false)
problem-label (seesaw/label :text "" :foreground "red")
update-load-ui (fn []
(let [playing (:playing @selected-player)
problem (if playing "Playing." "")]
(seesaw/value! problem-label problem)
(seesaw/config! load-button :enabled? (str/blank? problem))))
player-changed (fn [e]
(let [^Long number (when-let [^PlayerChoice selection (seesaw/selection e)]
(.number selection))
^CdjStatus status (when number (.getLatestStatusFor virtual-cdj number))]
(reset! selected-player {:number number :playing (and status (.isPlaying status))})
(update-load-ui)))
players (seesaw/combobox :id :players
:listen [:item-state-changed player-changed])
player-panel (mig/mig-panel :background "#ddd"
:items [[(seesaw/label :text "Load on:")]
[players "gap unrelated"]
[problem-label "push, gap unrelated"]
[load-button]])
settings (PlayerSettings.)
defaults (:my-settings (prefs/get-preferences))
:items [[(seesaw/label :text "Play Mode:") "align right"]
[(enum-picker PlayerSettings$PlayMode settings defaults "autoPlayMode") "wrap"]
[(seesaw/label :text "Eject/Load Lock:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "ejectLoadLock") "wrap"]
[(seesaw/label :text "Needle Lock:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "needleLock") "wrap"]
[(seesaw/label :text "Quantize Beat Value:") "align right"]
[(enum-picker PlayerSettings$QuantizeMode settings defaults "quantizeBeatValue")
"wrap"]
[(seesaw/label :text "Hot Cue Auto Load:") "align right"]
[(enum-picker PlayerSettings$AutoLoadMode settings defaults "autoLoadMode")
"wrap"]
[(seesaw/label :text "Hot Cue Color:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "hotCueColor") "wrap"]
[(seesaw/label :text "Auto Cue Level:") "align right"]
[(enum-picker PlayerSettings$AutoCueLevel settings defaults "autoCueLevel") "wrap"]
[(seesaw/label :text "Time Display Mode:") "align right"]
[(enum-picker PlayerSettings$TimeDisplayMode settings defaults "timeDisplayMode")
"wrap"]
[(seesaw/label :text "Auto Cue:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "autoCue") "wrap"]
[(seesaw/label :text "Jog Mode:") "align right"]
[(enum-picker PlayerSettings$JogMode settings defaults "jogMode") "wrap"]
[(seesaw/label :text "Tempo Range:") "align right"]
[(enum-picker PlayerSettings$TempoRange settings defaults "tempoRange") "wrap"]
[(seesaw/label :text "Master Tempo:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "masterTempo") "wrap"]
[(seesaw/label :text "Quantize:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "quantize") "wrap"]
[(seesaw/label :text "Sync:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "sync") "wrap"]
[(seesaw/label :text "Phase Meter:") "align right"]
[(enum-picker PlayerSettings$PhaseMeterType settings defaults "phaseMeterType")
"wrap"]
[(seesaw/label :text "Vinyl Speed Adjust:") "align right"]
[(enum-picker PlayerSettings$VinylSpeedAdjust settings defaults "vinylSpeedAdjust")
"wrap unrelated"]
[(seesaw/label :text "Language:") "align right"]
[(enum-picker PlayerSettings$Language settings defaults "language") "wrap"]
[(seesaw/label :text "LCD Brightness:") "align right"]
[(enum-picker PlayerSettings$LcdBrightness settings defaults "lcdBrightness")
"wrap"]
[(seesaw/label :text "Jog Wheel LCD Brightness:") "align right"]
[(enum-picker PlayerSettings$LcdBrightness settings defaults
"jogWheelLcdBrightness") "wrap"]
[(seesaw/label :text "Jog Wheel Display Mode:") "align right"]
[(enum-picker PlayerSettings$JogWheelDisplay settings defaults "jogWheelDisplay")
"wrap unrelated"]
[(seesaw/label :text "Slip Flashing:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "slipFlashing") "wrap"]
[(seesaw/label :text "On Air Display:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "onAirDisplay") "wrap"]
[(seesaw/label :text "Jog Ring Brightness:") "align right"]
[(enum-picker PlayerSettings$Illumination settings defaults "jogRingIllumination")
"wrap"]
[(seesaw/label :text "Jog Ring Indicator:") "align right"]
[(enum-picker PlayerSettings$Toggle settings defaults "jogRingIndicator") "wrap"]
[(seesaw/label :text "Disc Slot Illumination:") "align right"]
[(enum-picker PlayerSettings$Illumination settings defaults "discSlotIllumination")
"wrap"]
[(seesaw/label :text "Pad/Button Brightness:") "align right"]
[(enum-picker PlayerSettings$PadButtonBrightness settings defaults
"padButtonBrightness") "wrap"]])
layout (seesaw/border-panel :center (seesaw/scrollable settings-panel) :south player-panel)
stop-listener (reify LifecycleListener
Close our window if VirtualCdj stops ( we need it ) .
(seesaw/invoke-later
(.dispatchEvent root (WindowEvent. root WindowEvent/WINDOW_CLOSING)))))
dev-listener (reify DeviceAnnouncementListener
(deviceFound [_this announcement]
(seesaw/invoke-later (track-loader/add-device players (.getDeviceNumber announcement))))
(deviceLost [_this announcement]
(seesaw/invoke-later (track-loader/remove-device players (.getDeviceNumber announcement)
stop-listener))))
status-listener (reify DeviceUpdateListener
(received [_this status]
(let [player @selected-player]
(when (and (= (.getDeviceNumber status) (:number player))
(not= (.isPlaying ^CdjStatus status) (:playing player)))
(swap! selected-player assoc :playing (.isPlaying ^CdjStatus status))
(update-load-ui)))))
remove-listeners (fn []
(.removeLifecycleListener virtual-cdj stop-listener)
(.removeDeviceAnnouncementListener device-finder dev-listener)
(.removeUpdateListener virtual-cdj status-listener))]
(.addDeviceAnnouncementListener device-finder dev-listener)
(.addUpdateListener virtual-cdj status-listener)
(track-loader/build-device-choices players)
(reset! loader-window root)
(.addLifecycleListener virtual-cdj stop-listener)
(seesaw/listen root :window-closed (fn [_]
(reset! loader-window nil)
(remove-listeners)))
(seesaw/listen load-button
:action-performed
(fn [_]
(let [^Long selected-player (.number ^PlayerChoice (.getSelectedItem players))]
(.sendLoadSettingsCommand virtual-cdj selected-player settings))))
(if @loader-window
(seesaw/config! root :content layout)
(seesaw/pack! root)
root)
(remove-listeners)
(.dispose root))))
(catch Exception e
(timbre/error e "Problem Loading Settings")
(seesaw/alert (str "<html>Unable to Load Settings on Player:<br><br>" (.getMessage e)
"<br><br>See the log file for more details.")
:title "Problem Loading Settings" :type :error)))))
(defn show-dialog
"Displays an interface in whcih the user can adjust their preferred
player settings and load them into players."
[]
(seesaw/invoke-later
(locking loader-window
(when-not @loader-window (create-window))
(seesaw/invoke-later
(when-let [window @loader-window]
(seesaw/show! window)
(.toFront window))))))
|
1a54370a7dee4720e0cff2e3328b5cc9dbb5facba9b6ee9d3ecd02c1d2088839 | roosta/herb | handler.clj | (ns site.handler
(:require [reitit.ring :as reitit-ring]
[site.middleware :refer [middleware]]
[hiccup.page :refer [include-js include-css html5]]
[config.core :refer [env]]))
(def mount-target
[:div#app])
(defn head []
[:head
[:meta {:charset "utf-8"}]
[:title "Herb: ClojureScript styling using functions"]
[:link {:rel "icon" :type "image/icon" :href "assets/favicon.png"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css (if (env :dev) "/css/atelier-forest-light.css" "/css/atelier-forest-light.min.css"))])
(defn loading-page []
(html5
(head)
[:body {:class "body-container"}
mount-target
(include-js "/js/app.js")]))
(defn index-handler
[_request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (loading-page)})
(def app
(reitit-ring/ring-handler
(reitit-ring/router
[["/" {:get {:handler index-handler}}]
#_["/items"
["" {:get {:handler index-handler}}]
["/:item-id" {:get {:handler index-handler
:parameters {:path {:item-id int?}}}}]]
#_["/about" {:get {:handler index-handler}}]]
{:data {:middleware middleware}})
(reitit-ring/routes
(reitit-ring/create-resource-handler {:path "/" :root "/public"})
(reitit-ring/create-default-handler))))
| null | https://raw.githubusercontent.com/roosta/herb/5718582956a3f6c52092e663412debc3983c2ff0/site/src/site/handler.clj | clojure | (ns site.handler
(:require [reitit.ring :as reitit-ring]
[site.middleware :refer [middleware]]
[hiccup.page :refer [include-js include-css html5]]
[config.core :refer [env]]))
(def mount-target
[:div#app])
(defn head []
[:head
[:meta {:charset "utf-8"}]
[:title "Herb: ClojureScript styling using functions"]
[:link {:rel "icon" :type "image/icon" :href "assets/favicon.png"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css (if (env :dev) "/css/atelier-forest-light.css" "/css/atelier-forest-light.min.css"))])
(defn loading-page []
(html5
(head)
[:body {:class "body-container"}
mount-target
(include-js "/js/app.js")]))
(defn index-handler
[_request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (loading-page)})
(def app
(reitit-ring/ring-handler
(reitit-ring/router
[["/" {:get {:handler index-handler}}]
#_["/items"
["" {:get {:handler index-handler}}]
["/:item-id" {:get {:handler index-handler
:parameters {:path {:item-id int?}}}}]]
#_["/about" {:get {:handler index-handler}}]]
{:data {:middleware middleware}})
(reitit-ring/routes
(reitit-ring/create-resource-handler {:path "/" :root "/public"})
(reitit-ring/create-default-handler))))
|
|
881caceb2618d981629c26d39d1cdad16ffa8dedc79f789e8fc5f8e906387a71 | replikativ/datahike-frontend | rest_remote.cljs | (ns app.dashboard.rest-remote
(:require
[clojure.core.async :refer [go]]
[com.wsscode.async.async-cljs :refer [<?maybe]]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[edn-query-language.core :as eql]
[taoensso.timbre :as log]
))
(defn remote [parser]
{:transmit!
(fn [_ {::txn/keys [ast result-handler]}]
(let [edn (eql/ast->query ast)]
(go
(try
( log / info " Rest - remote ( defn remote ... ) 2 ! ! ! ! ! : " edn " --- " )
(result-handler {:transaction edn
:body (<?maybe (parser {} edn))
:status-code 200})
(catch :default e
(js/console.error "Pathom remote error:" e)
(result-handler {:transaction edn
:body e
:status-code 500}))))))})
| null | https://raw.githubusercontent.com/replikativ/datahike-frontend/6e3ab3bb761b41c4ffea792297286f8942a27909/src/main/app/dashboard/rest_remote.cljs | clojure | (ns app.dashboard.rest-remote
(:require
[clojure.core.async :refer [go]]
[com.wsscode.async.async-cljs :refer [<?maybe]]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[edn-query-language.core :as eql]
[taoensso.timbre :as log]
))
(defn remote [parser]
{:transmit!
(fn [_ {::txn/keys [ast result-handler]}]
(let [edn (eql/ast->query ast)]
(go
(try
( log / info " Rest - remote ( defn remote ... ) 2 ! ! ! ! ! : " edn " --- " )
(result-handler {:transaction edn
:body (<?maybe (parser {} edn))
:status-code 200})
(catch :default e
(js/console.error "Pathom remote error:" e)
(result-handler {:transaction edn
:body e
:status-code 500}))))))})
|
|
d6507588b4b15404d5a624160df4c46a9f965f764364b4dd16b9720b0d944f51 | ChrisCoffey/haskell-opentracing-light | Tracing.hs | {-# LANGUAGE RankNTypes #-}
module Servant.Tracing (
WithTracing,
TracingInstructions(..),
instructionsToHeader,
getInstructions
) where
import Tracing.Core (Tracer, TraceId(..), SpanId(..), MonadTracer, TracingInstructions(..))
import Control.Arrow (first)
import Control.Monad.Trans (liftIO, MonadIO)
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lex.Integral as BS
import Data.Text.Read(hexadecimal)
import Data.Bits (testBit, (.|.))
import Data.Maybe (catMaybes, fromMaybe)
import Data.Monoid ((<>))
import Servant.API.Header (Header)
import System.Random (randomRIO)
import Web.HttpApiData (FromHttpApiData(..))
| Constrain the ' ServerT ' 's base monad such that it provides an instance of ' MonadTracer '
type WithTracing = Header "uber-trace-id" TracingInstructions
-- | Jaeger format: /#propagation-format
-- This allows the trace backend to reassemble downstream traces.
instructionsToHeader :: TracingInstructions -> T.Text
instructionsToHeader TracingInstructions {traceId=(TraceId tid), spanId, parentSpanId, sample, debug} =
toField tid<>":"<>
(toField $ unSpanId spanId) <> ":"<>
(fromMaybe "" $ (toField . unSpanId) <$> parentSpanId) <> ":" <>
(T.pack $ show setFlags)
where
unSpanId (SpanId sid) = sid
toField = T.pack . BS.unpack . fromMaybe "" . BS.packHexadecimal
setFlags :: Int
setFlags = (if debug then 2 else 0) .|. (if sample then 1 else 0) .|. 0
instance FromHttpApiData TracingInstructions where
parseUrlPiece ::
T.Text
-> Either T.Text TracingInstructions
parseUrlPiece raw =
case T.splitOn ":" raw of
[rawTraceId, rawSpanId, rawParentId, flags] -> let
res = do
traceId <- TraceId . fromIntegral . fst <$> hexadecimal rawTraceId
spanId <- SpanId . fromIntegral . fst <$> hexadecimal rawSpanId
let resolvedPid = if T.null rawParentId
then pure (Nothing, "")
else first Just <$> hexadecimal rawParentId
parentId <- fmap (SpanId . fromIntegral) . fst <$> resolvedPid
flagField <- fromIntegral . fst <$> hexadecimal flags
let [sample, debug]= [sampleFlag, debugFlag] <*> [flagField]
pure TracingInstructions {
traceId = traceId,
spanId = spanId,
parentSpanId = parentId,
sample = sample,
debug = debug
}
in case res of
Left err -> Left $ T.pack err
Right val -> Right val
_ -> Left $ raw <> " is not a valid uber-trace-id header"
where
sampleFlag :: Int -> Bool
sampleFlag = (`testBit` 0)
debugFlag :: Int -> Bool
debugFlag = (`testBit` 1)
TODO write a monad that wraps servant & determines if it should sample or not . Takes a sampling determinant . Only evaluates if the header is not present
-- | In the event that there are no 'TracingInstructions' for this call, generate new instructions.
--
-- This has a
getInstructions :: MonadIO m =>
Bool
-> Maybe TracingInstructions
-> m TracingInstructions
getInstructions debug Nothing = do
newTraceId <- liftIO $ randomRIO (0, maxBound)
newSpanId <- liftIO $ randomRIO (0, maxBound)
sample <- liftIO $ randomRIO (0, 1000)
pure TracingInstructions {
traceId = TraceId newTraceId,
spanId = SpanId newSpanId,
parentSpanId = Nothing,
debug,
sample = sample == (1::Int)
}
getInstructions _ (Just inst) = pure inst
| null | https://raw.githubusercontent.com/ChrisCoffey/haskell-opentracing-light/82a4dfa757a7cbbbbef82e68e766e0f1a9411570/src/Servant/Tracing.hs | haskell | # LANGUAGE RankNTypes #
| Jaeger format: /#propagation-format
This allows the trace backend to reassemble downstream traces.
| In the event that there are no 'TracingInstructions' for this call, generate new instructions.
This has a | module Servant.Tracing (
WithTracing,
TracingInstructions(..),
instructionsToHeader,
getInstructions
) where
import Tracing.Core (Tracer, TraceId(..), SpanId(..), MonadTracer, TracingInstructions(..))
import Control.Arrow (first)
import Control.Monad.Trans (liftIO, MonadIO)
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lex.Integral as BS
import Data.Text.Read(hexadecimal)
import Data.Bits (testBit, (.|.))
import Data.Maybe (catMaybes, fromMaybe)
import Data.Monoid ((<>))
import Servant.API.Header (Header)
import System.Random (randomRIO)
import Web.HttpApiData (FromHttpApiData(..))
| Constrain the ' ServerT ' 's base monad such that it provides an instance of ' MonadTracer '
type WithTracing = Header "uber-trace-id" TracingInstructions
instructionsToHeader :: TracingInstructions -> T.Text
instructionsToHeader TracingInstructions {traceId=(TraceId tid), spanId, parentSpanId, sample, debug} =
toField tid<>":"<>
(toField $ unSpanId spanId) <> ":"<>
(fromMaybe "" $ (toField . unSpanId) <$> parentSpanId) <> ":" <>
(T.pack $ show setFlags)
where
unSpanId (SpanId sid) = sid
toField = T.pack . BS.unpack . fromMaybe "" . BS.packHexadecimal
setFlags :: Int
setFlags = (if debug then 2 else 0) .|. (if sample then 1 else 0) .|. 0
instance FromHttpApiData TracingInstructions where
parseUrlPiece ::
T.Text
-> Either T.Text TracingInstructions
parseUrlPiece raw =
case T.splitOn ":" raw of
[rawTraceId, rawSpanId, rawParentId, flags] -> let
res = do
traceId <- TraceId . fromIntegral . fst <$> hexadecimal rawTraceId
spanId <- SpanId . fromIntegral . fst <$> hexadecimal rawSpanId
let resolvedPid = if T.null rawParentId
then pure (Nothing, "")
else first Just <$> hexadecimal rawParentId
parentId <- fmap (SpanId . fromIntegral) . fst <$> resolvedPid
flagField <- fromIntegral . fst <$> hexadecimal flags
let [sample, debug]= [sampleFlag, debugFlag] <*> [flagField]
pure TracingInstructions {
traceId = traceId,
spanId = spanId,
parentSpanId = parentId,
sample = sample,
debug = debug
}
in case res of
Left err -> Left $ T.pack err
Right val -> Right val
_ -> Left $ raw <> " is not a valid uber-trace-id header"
where
sampleFlag :: Int -> Bool
sampleFlag = (`testBit` 0)
debugFlag :: Int -> Bool
debugFlag = (`testBit` 1)
TODO write a monad that wraps servant & determines if it should sample or not . Takes a sampling determinant . Only evaluates if the header is not present
getInstructions :: MonadIO m =>
Bool
-> Maybe TracingInstructions
-> m TracingInstructions
getInstructions debug Nothing = do
newTraceId <- liftIO $ randomRIO (0, maxBound)
newSpanId <- liftIO $ randomRIO (0, maxBound)
sample <- liftIO $ randomRIO (0, 1000)
pure TracingInstructions {
traceId = TraceId newTraceId,
spanId = SpanId newSpanId,
parentSpanId = Nothing,
debug,
sample = sample == (1::Int)
}
getInstructions _ (Just inst) = pure inst
|
d4feadd0d4576daa186961f0752dd2b9ee8e00371382b3b6f81563d3b572234e | ghc/testsuite | Check08.hs | # LANGUAGE Trustworthy , NoImplicitPrelude #
{-# OPTIONS_GHC -fpackage-trust #-}
make sure selective safe imports brings in pkg trust requirements correctly .
-- (e.g only for the imports that are safe ones)
module Check08 ( main' ) where
no pkg trust
base pkg trust
main' =
let n = a (b 1)
in n
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/safeHaskell/check/Check08.hs | haskell | # OPTIONS_GHC -fpackage-trust #
(e.g only for the imports that are safe ones) | # LANGUAGE Trustworthy , NoImplicitPrelude #
make sure selective safe imports brings in pkg trust requirements correctly .
module Check08 ( main' ) where
no pkg trust
base pkg trust
main' =
let n = a (b 1)
in n
|
0e28e4c7bc002892639c87fafd188559623944d716fe8a4c7652ab21f407159c | nubank/midje-nrepl | arithmetic_test.clj | (ns octocat.arithmetic-test
(:require [midje.sweet :refer :all]))
(facts "about arithmetic operations"
(fact (* 2 5) => 10)
(fact "this is a crazy arithmetic"
(+ 2 3) => 6)
(fact "two assertions in the same fact; the former is correct while the later is wrong"
(+ 10 1) => 11
(- 4 2) => 3)
(fact "this will throw an unexpected exception"
(/ 12 0) => 0))
| null | https://raw.githubusercontent.com/nubank/midje-nrepl/b4d505f346114db88ad5b5c6b3c8f0af4e0136fc/dev-resources/octocat/test/octocat/arithmetic_test.clj | clojure | (ns octocat.arithmetic-test
(:require [midje.sweet :refer :all]))
(facts "about arithmetic operations"
(fact (* 2 5) => 10)
(fact "this is a crazy arithmetic"
(+ 2 3) => 6)
(fact "two assertions in the same fact; the former is correct while the later is wrong"
(+ 10 1) => 11
(- 4 2) => 3)
(fact "this will throw an unexpected exception"
(/ 12 0) => 0))
|
|
528fda7b934a0699091f5f3e6121671f2c5444cdad2c638a05f3243fe0af10be | skanev/playground | 15-tests.scm | (require rackunit rackunit/text-ui)
(load-relative "../../support/eopl.scm")
(load-relative "../15.scm")
(define (run code)
(eval* code (empty-env)))
(define (expval->schemeval val)
(cases expval val
(num-val (num) num)
(bool-val (bool) bool)
(emptylist-val () '())
(pair-val (car cdr)
(cons (expval->schemeval car)
(expval->schemeval cdr)))))
(define (schemeval->expval val)
(cond ((null? val) (emptylist-val))
((pair? val) (pair-val (schemeval->expval (car val)) (schemeval->expval (cdr val))))
((number? val) (num-val val))
((boolean? val) (bool-val val))
(else (error 'schemeval->expval "Don't know how to convert ~s" val))))
(define (eval* code env)
(let* ((expr (scan&parse code))
(result (value-of expr env)))
(expval->schemeval result)))
(define (env vars vals)
(extend-env* vars
(map schemeval->expval vals)
(empty-env)))
(define eopl-3.15-tests
(test-suite
"Tests for EOPL exercise 3.15"
(check-equal? (with-output-to-string (lambda () (run "print 42")))
"42")
(check-equal? (with-output-to-string (lambda () (run "print zero?(1)")))
"#f")
(check-equal? (with-output-to-string (lambda () (run "print emptylist")))
"emptylist")
(check-equal? (with-output-to-string (lambda () (run "print cons(1, emptylist)")))
"cons(1, emptylist)")
(check-equal? (run "cond zero?(0) ==> 0
zero?(1) ==> 1
zero?(1) ==> 2
end")
0)
(check-equal? (run "cond zero?(1) ==> 0
zero?(0) ==> 1
zero?(1) ==> 2
end")
1)
(check-equal? (run "cond zero?(1) ==> 0
zero?(1) ==> 1
zero?(0) ==> 2
end")
2)
(check-equal? (run "cond zero?(1) ==> 0
zero?(1) ==> 1
zero?(1) ==> 2
end")
#f)
(check-equal? (run "list(1)") '(1))
(check-equal? (run "list(1, 2, 3)") '(1 2 3))
(check-equal? (run "let x = 4
in list(x, -(x, 1), -(x, 3))")
'(4 3 1))
(check-equal? (run "emptylist") '())
(check-equal? (run "cons(1, 2)") '(1 . 2))
(check-equal? (run "car(cons(1, 2))") 1)
(check-equal? (run "cdr(cons(1, 2))") 2)
(check-true (run "null?(emptylist)"))
(check-false (run "null?(cons(1, 2))"))
(check-equal? (run "let x = 4
in cons(x,
cons(cons(-(x, 1),
emptylist),
emptylist))")
'(4 (3)))
(check-true (run "equal?(1, 1)"))
(check-false (run "equal?(1, 2)"))
(check-true (run "less?(1, 2)"))
(check-false (run "less?(1, 1)"))
(check-false (run "less?(1, 0)"))
(check-true (run "greater?(1, 0)"))
(check-false (run "greater?(1, 1)"))
(check-false (run "greater?(1, 2)"))
(check-equal? (run "+(4, 5)") 9)
(check-equal? (run "*(7, 4)") 28)
(check-equal? (run "/(10, 3)") 3)
(check-equal? (run "minus(-(minus(5), 9))") 14)
(check-equal? (run "42") 42)
(check-equal? (eval* "x" (env '(x) '(10))) 10)
(check-equal? (eval* "-(x, 7)" (env '(x) '(10))) 3)
(check-equal? (run "% Comment\n 1") 1)
(check-equal? (run "zero?(0)") #t)
(check-equal? (run "zero?(1)") #f)
(check-equal? (run "if zero?(0) then 1 else 2") 1)
(check-equal? (run "if zero?(3) then 1 else 2") 2)
(check-equal? (run "let x = 1 in x") 1)
(check-equal? (run "let x = 1 in let x = 2 in x") 2)
(check-equal? (run "let x = 1 in let y = 2 in x") 1)
(check-equal? (run "let x = 7 % This is a comment
in let y = 2 % This is another comment
in let y = let x = -(x, 1) in -(x, y)
in -(-(x, 8),y)")
-5)
))
(exit (run-tests eopl-3.15-tests))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/tests/15-tests.scm | scheme | (require rackunit rackunit/text-ui)
(load-relative "../../support/eopl.scm")
(load-relative "../15.scm")
(define (run code)
(eval* code (empty-env)))
(define (expval->schemeval val)
(cases expval val
(num-val (num) num)
(bool-val (bool) bool)
(emptylist-val () '())
(pair-val (car cdr)
(cons (expval->schemeval car)
(expval->schemeval cdr)))))
(define (schemeval->expval val)
(cond ((null? val) (emptylist-val))
((pair? val) (pair-val (schemeval->expval (car val)) (schemeval->expval (cdr val))))
((number? val) (num-val val))
((boolean? val) (bool-val val))
(else (error 'schemeval->expval "Don't know how to convert ~s" val))))
(define (eval* code env)
(let* ((expr (scan&parse code))
(result (value-of expr env)))
(expval->schemeval result)))
(define (env vars vals)
(extend-env* vars
(map schemeval->expval vals)
(empty-env)))
(define eopl-3.15-tests
(test-suite
"Tests for EOPL exercise 3.15"
(check-equal? (with-output-to-string (lambda () (run "print 42")))
"42")
(check-equal? (with-output-to-string (lambda () (run "print zero?(1)")))
"#f")
(check-equal? (with-output-to-string (lambda () (run "print emptylist")))
"emptylist")
(check-equal? (with-output-to-string (lambda () (run "print cons(1, emptylist)")))
"cons(1, emptylist)")
(check-equal? (run "cond zero?(0) ==> 0
zero?(1) ==> 1
zero?(1) ==> 2
end")
0)
(check-equal? (run "cond zero?(1) ==> 0
zero?(0) ==> 1
zero?(1) ==> 2
end")
1)
(check-equal? (run "cond zero?(1) ==> 0
zero?(1) ==> 1
zero?(0) ==> 2
end")
2)
(check-equal? (run "cond zero?(1) ==> 0
zero?(1) ==> 1
zero?(1) ==> 2
end")
#f)
(check-equal? (run "list(1)") '(1))
(check-equal? (run "list(1, 2, 3)") '(1 2 3))
(check-equal? (run "let x = 4
in list(x, -(x, 1), -(x, 3))")
'(4 3 1))
(check-equal? (run "emptylist") '())
(check-equal? (run "cons(1, 2)") '(1 . 2))
(check-equal? (run "car(cons(1, 2))") 1)
(check-equal? (run "cdr(cons(1, 2))") 2)
(check-true (run "null?(emptylist)"))
(check-false (run "null?(cons(1, 2))"))
(check-equal? (run "let x = 4
in cons(x,
cons(cons(-(x, 1),
emptylist),
emptylist))")
'(4 (3)))
(check-true (run "equal?(1, 1)"))
(check-false (run "equal?(1, 2)"))
(check-true (run "less?(1, 2)"))
(check-false (run "less?(1, 1)"))
(check-false (run "less?(1, 0)"))
(check-true (run "greater?(1, 0)"))
(check-false (run "greater?(1, 1)"))
(check-false (run "greater?(1, 2)"))
(check-equal? (run "+(4, 5)") 9)
(check-equal? (run "*(7, 4)") 28)
(check-equal? (run "/(10, 3)") 3)
(check-equal? (run "minus(-(minus(5), 9))") 14)
(check-equal? (run "42") 42)
(check-equal? (eval* "x" (env '(x) '(10))) 10)
(check-equal? (eval* "-(x, 7)" (env '(x) '(10))) 3)
(check-equal? (run "% Comment\n 1") 1)
(check-equal? (run "zero?(0)") #t)
(check-equal? (run "zero?(1)") #f)
(check-equal? (run "if zero?(0) then 1 else 2") 1)
(check-equal? (run "if zero?(3) then 1 else 2") 2)
(check-equal? (run "let x = 1 in x") 1)
(check-equal? (run "let x = 1 in let x = 2 in x") 2)
(check-equal? (run "let x = 1 in let y = 2 in x") 1)
(check-equal? (run "let x = 7 % This is a comment
in let y = 2 % This is another comment
in let y = let x = -(x, 1) in -(x, y)
in -(-(x, 8),y)")
-5)
))
(exit (run-tests eopl-3.15-tests))
|
|
cc0ff29d6855d2e3d72e0513f6199b5dc4688bc48fc572ee72041aceeb0d138e | borodust/bodge-ui | color-picker.lisp | (cl:in-package :bodge-ui)
;;;
;;;
;;;
(defclass color-picker (widget disposable)
((color)))
(defmethod initialize-instance :after ((this color-picker) &key (color (vec4 1 1 1 1)))
(with-slots ((this-color color)) this
(setf this-color (c-let ((color-f (:struct %nuklear:colorf) :alloc t))
(setf (color-f :r) (x color)
(color-f :g) (y color)
(color-f :b) (z color)
(color-f :a) (w color))
color-f))))
(define-destructor color-picker (color)
(cffi:foreign-free color))
(defmethod compose ((this color-picker))
(with-slots (color) this
(%nuklear:color-picker color *handle* color :rgba)))
| null | https://raw.githubusercontent.com/borodust/bodge-ui/db896ca3be9026444398e0192a48b048aa7db574/src/elements/color-picker.lisp | lisp | (cl:in-package :bodge-ui)
(defclass color-picker (widget disposable)
((color)))
(defmethod initialize-instance :after ((this color-picker) &key (color (vec4 1 1 1 1)))
(with-slots ((this-color color)) this
(setf this-color (c-let ((color-f (:struct %nuklear:colorf) :alloc t))
(setf (color-f :r) (x color)
(color-f :g) (y color)
(color-f :b) (z color)
(color-f :a) (w color))
color-f))))
(define-destructor color-picker (color)
(cffi:foreign-free color))
(defmethod compose ((this color-picker))
(with-slots (color) this
(%nuklear:color-picker color *handle* color :rgba)))
|
|
cb7bb32018ab2042fb6ce9ef35dd4382dbc140dda58f448d0a4bdae640006881 | esoeylemez/netwire | Switch.hs | -- |
-- Module: Control.Wire.Switch
Copyright : ( c ) 2013
-- License: BSD3
Maintainer : < >
module Control.Wire.Switch
( -- * Simple switching
(-->),
(>--),
-- * Context switching
modes,
-- * Event-based switching
-- ** Intrinsic
switch,
dSwitch,
-- ** Intrinsic continuable
kSwitch,
dkSwitch,
-- ** Extrinsic
rSwitch,
drSwitch,
alternate,
-- ** Extrinsic continuable
krSwitch,
dkrSwitch
)
where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Wire.Core
import Control.Wire.Event
import Control.Wire.Unsafe.Event
import qualified Data.Map as M
import Data.Monoid
| Acts like the first wire until it inhibits , then switches to the
second wire . Infixr 1 .
--
-- * Depends: like current wire.
--
* Inhibits : after switching like the second wire .
--
-- * Switch: now.
(-->) :: (Monad m) => Wire s e m a b -> Wire s e m a b -> Wire s e m a b
w1' --> w2' =
WGen $ \ds mx' -> do
(mx, w1) <- stepWire w1' ds mx'
case mx of
Left _ | Right _ <- mx' -> stepWire w2' ds mx'
_ -> mx `seq` return (mx, w1 --> w2')
infixr 1 -->
| Acts like the first wire until the second starts producing , at which point
it switches to the second wire . Infixr 1 .
--
-- * Depends: like current wire.
--
* Inhibits : after switching like the second wire .
--
-- * Switch: now.
(>--) :: (Monad m) => Wire s e m a b -> Wire s e m a b -> Wire s e m a b
w1' >-- w2' =
WGen $ \ds mx' -> do
(m2, w2) <- stepWire w2' ds mx'
case m2 of
Right _ -> m2 `seq` return (m2, w2)
_ -> do (m1, w1) <- stepWire w1' ds mx'
m1 `seq` return (m1, w1 >-- w2)
infixr 1 >--
-- | Intrinsic continuable switch: Delayed version of 'kSwitch'.
--
* Inhibits : like the first argument wire , like the new wire after
switch . Inhibition of the second argument wire is ignored .
--
-- * Switch: once, after now, restart state.
dkSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, b) (Event (Wire s e m a b -> Wire s e m a b))
-> Wire s e m a b
dkSwitch w1' w2' =
WGen $ \ds mx' -> do
(mx, w1) <- stepWire w1' ds mx'
(mev, w2) <- stepWire w2' ds (liftA2 (,) mx' mx)
let w | Right (Event sw) <- mev = sw w1
| otherwise = dkSwitch w1 w2
return (mx, w)
-- | Extrinsic switch: Delayed version of 'rSwitch'.
--
-- * Inhibits: like the current wire.
--
-- * Switch: recurrent, after now, restart state.
drSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b)) b
drSwitch w' =
WGen $ \ds mx' ->
let nw w | Right (_, Event w1) <- mx' = w1
| otherwise = w
in liftM (second (drSwitch . nw)) (stepWire w' ds (fmap fst mx'))
| Acts like the first wire until an event occurs then switches
to the second wire . Behaves like this wire until the event occurs
at which point a * new * instance of the first wire is switched to .
--
-- * Depends: like current wire.
--
-- * Inhibits: like the argument wires.
--
-- * Switch: once, now, restart state.
alternate ::
(Monad m)
=> Wire s e m a b
-> Wire s e m a b
-> Wire s e m (a, Event x) b
alternate w1 w2 = go w1 w2 w1
where
go w1' w2' w' =
WGen $ \ds mx' ->
let (w1, w2, w) | Right (_, Event _) <- mx' = (w2', w1', w2')
| otherwise = (w1', w2', w')
in liftM (second (go w1 w2)) (stepWire w ds (fmap fst mx'))
-- | Intrinsic switch: Delayed version of 'switch'.
--
-- * Inhibits: like argument wire until switch, then like the new wire.
--
-- * Switch: once, after now, restart state.
dSwitch ::
(Monad m)
=> Wire s e m a (b, Event (Wire s e m a b))
-> Wire s e m a b
dSwitch w' =
WGen $ \ds mx' -> do
(mx, w) <- stepWire w' ds mx'
let nw | Right (_, Event w1) <- mx = w1
| otherwise = dSwitch w
return (fmap fst mx, nw)
-- | Extrinsic continuable switch. Delayed version of 'krSwitch'.
--
-- * Inhibits: like the current wire.
--
-- * Switch: recurrent, after now, restart state.
dkrSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b -> Wire s e m a b)) b
dkrSwitch w' =
WGen $ \ds mx' ->
let nw w | Right (_, Event f) <- mx' = f w
| otherwise = w
in liftM (second (dkrSwitch . nw)) (stepWire w' ds (fmap fst mx'))
| Intrinsic continuable switch : @kSwitch w1 w2@ starts with @w1@.
Its signal is received by @w2@ , which may choose to switch to a new
-- wire. Passes the wire we are switching away from to the new wire,
-- such that it may be reused in it.
--
* Inhibits : like the first argument wire , like the new wire after
switch . Inhibition of the second argument wire is ignored .
--
-- * Switch: once, now, restart state.
kSwitch ::
(Monad m, Monoid s)
=> Wire s e m a b
-> Wire s e m (a, b) (Event (Wire s e m a b -> Wire s e m a b))
-> Wire s e m a b
kSwitch w1' w2' =
WGen $ \ds mx' -> do
(mx, w1) <- stepWire w1' ds mx'
(mev, w2) <- stepWire w2' ds (liftA2 (,) mx' mx)
case mev of
Right (Event sw) -> stepWire (sw w1) mempty mx'
_ -> return (mx, kSwitch w1 w2)
-- | Extrinsic continuable switch. This switch works like 'rSwitch',
-- except that it passes the wire we are switching away from to the new
-- wire.
--
-- * Inhibits: like the current wire.
--
-- * Switch: recurrent, now, restart state.
krSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b -> Wire s e m a b)) b
krSwitch w'' =
WGen $ \ds mx' ->
let w' | Right (_, Event f) <- mx' = f w''
| otherwise = w''
in liftM (second krSwitch) (stepWire w' ds (fmap fst mx'))
-- | Route the left input signal based on the current mode. The right
-- input signal can be used to change the current mode. When switching
-- away from a mode and then switching back to it, it will be resumed.
-- Freezes time during inactivity.
--
-- * Complexity: O(n * log n) space, O(log n) lookup time on switch wrt
-- number of started, inactive modes.
--
-- * Depends: like currently active wire (left), now (right).
--
-- * Inhibits: when active wire inhibits.
--
-- * Switch: now on mode change.
modes ::
(Monad m, Ord k)
=> k -- ^ Initial mode.
-> (k -> Wire s e m a b) -- ^ Select wire for given mode.
-> Wire s e m (a, Event k) b
modes m0 select = loop M.empty m0 (select m0)
where
loop ms' m' w'' =
WGen $ \ds mxev' ->
case mxev' of
Left _ -> do
(mx, w) <- stepWire w'' ds (fmap fst mxev')
return (mx, loop ms' m' w)
Right (x', ev) -> do
let (ms, m, w') = switch ms' m' w'' ev
(mx, w) <- stepWire w' ds (Right x')
return (mx, loop ms m w)
switch ms' m' w' NoEvent = (ms', m', w')
switch ms' m' w' (Event m) =
let ms = M.insert m' w' ms' in
case M.lookup m ms of
Nothing -> (ms, m, select m)
Just w -> (M.delete m ms, m, w)
-- | Extrinsic switch: Start with the given wire. Each time the input
-- event occurs, switch to the wire it carries.
--
-- * Inhibits: like the current wire.
--
-- * Switch: recurrent, now, restart state.
rSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b)) b
rSwitch w'' =
WGen $ \ds mx' ->
let w' | Right (_, Event w1) <- mx' = w1
| otherwise = w''
in liftM (second rSwitch) (stepWire w' ds (fmap fst mx'))
-- | Intrinsic switch: Start with the given wire. As soon as its event
-- occurs, switch to the wire in the event's value.
--
-- * Inhibits: like argument wire until switch, then like the new wire.
--
-- * Switch: once, now, restart state.
switch ::
(Monad m, Monoid s)
=> Wire s e m a (b, Event (Wire s e m a b))
-> Wire s e m a b
switch w' =
WGen $ \ds mx' -> do
(mx, w) <- stepWire w' ds mx'
case mx of
Right (_, Event w1) -> stepWire w1 mempty mx'
_ -> return (fmap fst mx, switch w)
| null | https://raw.githubusercontent.com/esoeylemez/netwire/612daf7440e903ecc94231141145d80cf452513a/Control/Wire/Switch.hs | haskell | |
Module: Control.Wire.Switch
License: BSD3
* Simple switching
>),
),
* Context switching
* Event-based switching
** Intrinsic
** Intrinsic continuable
** Extrinsic
** Extrinsic continuable
* Depends: like current wire.
* Switch: now.
>) :: (Monad m) => Wire s e m a b -> Wire s e m a b -> Wire s e m a b
> w2' =
> w2')
>
* Depends: like current wire.
* Switch: now.
) :: (Monad m) => Wire s e m a b -> Wire s e m a b -> Wire s e m a b
w2' =
w2)
| Intrinsic continuable switch: Delayed version of 'kSwitch'.
* Switch: once, after now, restart state.
| Extrinsic switch: Delayed version of 'rSwitch'.
* Inhibits: like the current wire.
* Switch: recurrent, after now, restart state.
* Depends: like current wire.
* Inhibits: like the argument wires.
* Switch: once, now, restart state.
| Intrinsic switch: Delayed version of 'switch'.
* Inhibits: like argument wire until switch, then like the new wire.
* Switch: once, after now, restart state.
| Extrinsic continuable switch. Delayed version of 'krSwitch'.
* Inhibits: like the current wire.
* Switch: recurrent, after now, restart state.
wire. Passes the wire we are switching away from to the new wire,
such that it may be reused in it.
* Switch: once, now, restart state.
| Extrinsic continuable switch. This switch works like 'rSwitch',
except that it passes the wire we are switching away from to the new
wire.
* Inhibits: like the current wire.
* Switch: recurrent, now, restart state.
| Route the left input signal based on the current mode. The right
input signal can be used to change the current mode. When switching
away from a mode and then switching back to it, it will be resumed.
Freezes time during inactivity.
* Complexity: O(n * log n) space, O(log n) lookup time on switch wrt
number of started, inactive modes.
* Depends: like currently active wire (left), now (right).
* Inhibits: when active wire inhibits.
* Switch: now on mode change.
^ Initial mode.
^ Select wire for given mode.
| Extrinsic switch: Start with the given wire. Each time the input
event occurs, switch to the wire it carries.
* Inhibits: like the current wire.
* Switch: recurrent, now, restart state.
| Intrinsic switch: Start with the given wire. As soon as its event
occurs, switch to the wire in the event's value.
* Inhibits: like argument wire until switch, then like the new wire.
* Switch: once, now, restart state. | Copyright : ( c ) 2013
Maintainer : < >
module Control.Wire.Switch
modes,
switch,
dSwitch,
kSwitch,
dkSwitch,
rSwitch,
drSwitch,
alternate,
krSwitch,
dkrSwitch
)
where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Wire.Core
import Control.Wire.Event
import Control.Wire.Unsafe.Event
import qualified Data.Map as M
import Data.Monoid
| Acts like the first wire until it inhibits , then switches to the
second wire . Infixr 1 .
* Inhibits : after switching like the second wire .
WGen $ \ds mx' -> do
(mx, w1) <- stepWire w1' ds mx'
case mx of
Left _ | Right _ <- mx' -> stepWire w2' ds mx'
| Acts like the first wire until the second starts producing , at which point
it switches to the second wire . Infixr 1 .
* Inhibits : after switching like the second wire .
WGen $ \ds mx' -> do
(m2, w2) <- stepWire w2' ds mx'
case m2 of
Right _ -> m2 `seq` return (m2, w2)
_ -> do (m1, w1) <- stepWire w1' ds mx'
* Inhibits : like the first argument wire , like the new wire after
switch . Inhibition of the second argument wire is ignored .
dkSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, b) (Event (Wire s e m a b -> Wire s e m a b))
-> Wire s e m a b
dkSwitch w1' w2' =
WGen $ \ds mx' -> do
(mx, w1) <- stepWire w1' ds mx'
(mev, w2) <- stepWire w2' ds (liftA2 (,) mx' mx)
let w | Right (Event sw) <- mev = sw w1
| otherwise = dkSwitch w1 w2
return (mx, w)
drSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b)) b
drSwitch w' =
WGen $ \ds mx' ->
let nw w | Right (_, Event w1) <- mx' = w1
| otherwise = w
in liftM (second (drSwitch . nw)) (stepWire w' ds (fmap fst mx'))
| Acts like the first wire until an event occurs then switches
to the second wire . Behaves like this wire until the event occurs
at which point a * new * instance of the first wire is switched to .
alternate ::
(Monad m)
=> Wire s e m a b
-> Wire s e m a b
-> Wire s e m (a, Event x) b
alternate w1 w2 = go w1 w2 w1
where
go w1' w2' w' =
WGen $ \ds mx' ->
let (w1, w2, w) | Right (_, Event _) <- mx' = (w2', w1', w2')
| otherwise = (w1', w2', w')
in liftM (second (go w1 w2)) (stepWire w ds (fmap fst mx'))
dSwitch ::
(Monad m)
=> Wire s e m a (b, Event (Wire s e m a b))
-> Wire s e m a b
dSwitch w' =
WGen $ \ds mx' -> do
(mx, w) <- stepWire w' ds mx'
let nw | Right (_, Event w1) <- mx = w1
| otherwise = dSwitch w
return (fmap fst mx, nw)
dkrSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b -> Wire s e m a b)) b
dkrSwitch w' =
WGen $ \ds mx' ->
let nw w | Right (_, Event f) <- mx' = f w
| otherwise = w
in liftM (second (dkrSwitch . nw)) (stepWire w' ds (fmap fst mx'))
| Intrinsic continuable switch : @kSwitch w1 w2@ starts with @w1@.
Its signal is received by @w2@ , which may choose to switch to a new
* Inhibits : like the first argument wire , like the new wire after
switch . Inhibition of the second argument wire is ignored .
kSwitch ::
(Monad m, Monoid s)
=> Wire s e m a b
-> Wire s e m (a, b) (Event (Wire s e m a b -> Wire s e m a b))
-> Wire s e m a b
kSwitch w1' w2' =
WGen $ \ds mx' -> do
(mx, w1) <- stepWire w1' ds mx'
(mev, w2) <- stepWire w2' ds (liftA2 (,) mx' mx)
case mev of
Right (Event sw) -> stepWire (sw w1) mempty mx'
_ -> return (mx, kSwitch w1 w2)
krSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b -> Wire s e m a b)) b
krSwitch w'' =
WGen $ \ds mx' ->
let w' | Right (_, Event f) <- mx' = f w''
| otherwise = w''
in liftM (second krSwitch) (stepWire w' ds (fmap fst mx'))
modes ::
(Monad m, Ord k)
-> Wire s e m (a, Event k) b
modes m0 select = loop M.empty m0 (select m0)
where
loop ms' m' w'' =
WGen $ \ds mxev' ->
case mxev' of
Left _ -> do
(mx, w) <- stepWire w'' ds (fmap fst mxev')
return (mx, loop ms' m' w)
Right (x', ev) -> do
let (ms, m, w') = switch ms' m' w'' ev
(mx, w) <- stepWire w' ds (Right x')
return (mx, loop ms m w)
switch ms' m' w' NoEvent = (ms', m', w')
switch ms' m' w' (Event m) =
let ms = M.insert m' w' ms' in
case M.lookup m ms of
Nothing -> (ms, m, select m)
Just w -> (M.delete m ms, m, w)
rSwitch ::
(Monad m)
=> Wire s e m a b
-> Wire s e m (a, Event (Wire s e m a b)) b
rSwitch w'' =
WGen $ \ds mx' ->
let w' | Right (_, Event w1) <- mx' = w1
| otherwise = w''
in liftM (second rSwitch) (stepWire w' ds (fmap fst mx'))
switch ::
(Monad m, Monoid s)
=> Wire s e m a (b, Event (Wire s e m a b))
-> Wire s e m a b
switch w' =
WGen $ \ds mx' -> do
(mx, w) <- stepWire w' ds mx'
case mx of
Right (_, Event w1) -> stepWire w1 mempty mx'
_ -> return (fmap fst mx, switch w)
|
e0a83f31ce20ddb0b1c8bca85103ac6258087b90e0a5170f40ac1e38b64d378e | unison-code/unison | GroupCalls.hs | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module Unison.Tools.Extend.GroupCalls (groupCalls) where
import Data.List.Split
import Unison
groupCalls f @ Function {fCode = code} _target =
let code' = map groupCallsInBlock code
in f {fCode = code'}
groupCallsInBlock b @ Block {bCode = code} =
let code' = groupOperations (True, isCall, isFun) code
code'' = groupOperations (False, isFun, isKill) code'
in b {bCode = code''}
groupOperations (left, f1, f2) code =
let codes = split (whenElt (\o -> f1 o || f2 o)) code
codes' = groupOperations' (left, f1, f2) codes
in concat codes'
groupOperations' (left, f1, f2) ([o1]:(os:([o2]:codes))) | f1 o1 && f2 o2 =
(if left then os else []):[o1]:[o2]:(if left then [] else os):
groupOperations' (left, f1, f2) codes
groupOperations' info (os:codes) = os:groupOperations' info codes
groupOperations' _ [] = []
| null | https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison/src/Unison/Tools/Extend/GroupCalls.hs | haskell | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module Unison.Tools.Extend.GroupCalls (groupCalls) where
import Data.List.Split
import Unison
groupCalls f @ Function {fCode = code} _target =
let code' = map groupCallsInBlock code
in f {fCode = code'}
groupCallsInBlock b @ Block {bCode = code} =
let code' = groupOperations (True, isCall, isFun) code
code'' = groupOperations (False, isFun, isKill) code'
in b {bCode = code''}
groupOperations (left, f1, f2) code =
let codes = split (whenElt (\o -> f1 o || f2 o)) code
codes' = groupOperations' (left, f1, f2) codes
in concat codes'
groupOperations' (left, f1, f2) ([o1]:(os:([o2]:codes))) | f1 o1 && f2 o2 =
(if left then os else []):[o1]:[o2]:(if left then [] else os):
groupOperations' (left, f1, f2) codes
groupOperations' info (os:codes) = os:groupOperations' info codes
groupOperations' _ [] = []
|
|
02fab3e5b2dc683443e66658189024343dff10d4414cc251c2bc557abaf2b309 | bytekid/mkbtt | monad.ml | Copyright 2008 , Christian Sternagel ,
* GNU Lesser General Public License
*
* This file is part of TTT2 .
*
* TTT2 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 .
*
* TTT2 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 TTT2 . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of TTT2.
*
* TTT2 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.
*
* TTT2 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 TTT2. If not, see </>.
*)
(*** OPENS ********************************************************************)
open Prelude;;
open Either;;
(*** MODULES ******************************************************************)
module F = Format;;
module LL = LazyList;;
(*** MODULE TYPES *************************************************************)
module type ERROR = sig type t end
module type STATE = sig type t end
module type MINIMAL_MONAD = sig
type 'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
end
module type SIGNATURE = sig
include MINIMAL_MONAD
val (=<<) : ('a -> 'b t) -> 'a t -> 'b t
val (>>) : 'a t -> 'b t -> 'b t
val (<<) : 'b t -> 'a t -> 'b t
val (>=>) : ('a -> 'b t) -> ('b -> 'c t) -> 'a -> 'c t
val (<=<) : ('b -> 'c t) -> ('a -> 'b t) -> 'a -> 'c t
val ap : ('a -> 'b) t -> 'a t -> 'b t
val join : 'a t t -> 'a t
val lift : ('a -> 'b) -> 'a t -> 'b t
val lift2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
val lift3 : ('a -> 'b -> 'c -> 'd) -> 'a t -> 'b t -> 'c t -> 'd t
val exists : ('a -> bool t) -> 'a list -> bool t
val filter : ('a -> bool t) -> 'a list -> 'a list t
val flat_map : ('a -> 'b list t) -> 'a list -> 'b list t
val flat_mapi : (int -> 'a -> 'b list t) -> 'a list -> 'b list t
val foldl : ('a -> 'b -> 'a t) -> 'a -> 'b list -> 'a t
val foldl1 : ('a -> 'a -> 'a t) -> 'a list -> 'a t
val foldl2 : ('a -> 'b -> 'c -> 'a t) -> 'a -> 'b list -> 'c list -> 'a t
val foldli : (int -> 'a -> 'b -> 'a t) -> 'a -> 'b list -> 'a t
val foldr : ('a -> 'b -> 'b t) -> 'b -> 'a list -> 'b t
val foldr1 : ('a -> 'a -> 'a t) -> 'a list -> 'a t
val foldr2 : ('a -> 'b -> 'c -> 'c t) -> 'c -> 'a list -> 'b list -> 'c t
val foldri : (int -> 'a -> 'b -> 'b t) -> 'b -> 'a list -> 'b t
val for_all : ('a -> bool t) -> 'a list -> bool t
val iter : ('a -> unit t) -> 'a list -> unit t
val iteri : (int -> 'a -> unit t) -> 'a list -> unit t
val map : ('a -> 'b t) -> 'a list -> 'b list t
val mapi : (int -> 'a -> 'b t) -> 'a list -> 'b list t
val replicate : int -> 'a t -> 'a list t
val replicatei : int -> (int -> 'a t) -> 'a list t
val rev_map : ('a -> 'b t) -> 'a list -> 'b list t
val rev_mapi : (int -> 'a -> 'b t) -> 'a list -> 'b list t
val sequence : 'a t list -> 'a list t
val apply : ('a -> 'c t) -> ('b -> 'd t) -> 'a * 'b -> ('c * 'd) t
val cross : ('a -> 'c t) * ('b -> 'd t) -> 'a * 'b -> ('c * 'd) t
val fold : ('a -> 'c -> 'c t) -> ('b -> 'c -> 'c t) -> 'c -> 'a * 'b -> 'c t
val pair : ('a -> 'b t) * ('a -> 'c t) -> 'a -> ('b * 'c) t
val project : ('a -> 'b t) -> 'a * 'a -> ('b * 'b) t
val uncurry : ('a -> 'b -> 'c t) -> 'a * 'b -> 'c t
val ite : bool t -> ('a -> 'b t) -> ('a -> 'b t) -> 'a -> 'b t
val fprintf : (F.formatter -> 'a -> unit t)
-> (unit,F.formatter,unit) Pervasives.format -> F.formatter
-> 'a list -> unit t
val fprintfi : (int -> F.formatter -> 'a -> unit t)
-> (unit,F.formatter,unit) Pervasives.format -> F.formatter
-> 'a list -> unit t
val to_string : ('a -> string t)
-> (unit,F.formatter,unit) Pervasives.format -> 'a list -> string t
val to_stringi : (int -> 'a -> string t)
-> (unit,F.formatter,unit) Pervasives.format -> 'a list -> string t
end
module type ERROR_MONAD = sig
type error
include SIGNATURE
val ap_error : ((error,'a) either -> (error,'b) either) t -> 'a t -> 'b t
val map_error : ((error,'a) either -> (error,'b) either) -> 'a t -> 'b t
val catch : (error -> 'a t) -> 'a t -> 'a t
val fail : error -> 'a t
val failif : bool -> error -> unit t
val run : 'a t -> (error,'a) either
end
module type ID_MONAD = sig
include SIGNATURE
val run : 'a t -> 'a
end
module type STATE_MONAD = sig
type state
include SIGNATURE
val ap_state : ('a * state -> 'b * state) t -> 'a t -> 'b t
val map_state : ('a * state -> 'b * state) -> 'a t -> 'b t
val adopt : (state -> 'a * state) -> 'a t
val get : state t
val modify : (state -> state) -> state t
val set : state -> unit t
val update : (state -> state) -> unit t
val with_state : (state -> state) -> 'a t -> 'a t
val eval : state -> 'a t -> 'a * state
val execute : state -> 'a t -> state
val run : state -> 'a t -> 'a
end
(*** MODULES ******************************************************************)
module Make (M : MINIMAL_MONAD) = struct
(*** INCLUDES ****************************************************************)
include M;;
(*** FUNCTIONS ***************************************************************)
(* Miscellaneous *)
let (=<<) f m = m >>= f;;
let (>>) m n = m >>= const n;;
let (<<) m n = n >> m;;
let (>=>) f g x = f x >>= g;;
let (<=<) g f = f >=> g;;
let ap m n = m >>= fun f -> n >>= (return <.> f);;
let join m = m >>= id;;
let lift f = ap (return f);;
let lift2 f m = ap (lift f m);;
let lift3 f m n = ap (lift2 f m n);;
(* List Functions *)
let foldli f = Listx.foldli (fun i m x -> m >>= flip (f i) x) <.> return;;
let foldl f = foldli (const f);;
let foldri f = Listx.foldri (fun i x m -> m >>= (f i) x) <.> return;;
let foldr f = foldri (const f);;
let foldl1 f =
(fun xs -> foldl f (Listx.hd xs) (Listx.tl xs)) <?> "empty list"
;;
let foldr1 f =
(fun xs -> foldr f (Listx.hd xs) (Listx.tl xs)) <?> "empty list"
;;
let foldl2 f = Listx.foldl2 (fun m x y -> m >>= fun z -> f z x y) <.> return;;
let foldr2 f = Listx.foldr2 (fun x y m -> m >>= f x y) <.> return;;
let iteri f = foldli (drop f) ();;
let iter f = iteri (const f);;
let employ combine f xs =
let f i xs x = f i x >>= (return <.> flip combine xs) in foldli f [] xs
;;
let flat_mapi f xs = employ Listx.rev_append f xs >>= (return <.> Listx.rev);;
let flat_map f = flat_mapi (const f);;
let mapi f xs = employ Listx.cons f xs >>= (return <.> Listx.rev)
let map f = mapi (const f);;
let rev_mapi f = employ Listx.cons f;;
let rev_map f = rev_mapi (const f);;
let sequence ms = map id ms;;
let replicatei i m =
let rec replicatei j n =
if j < i then
m j >>= fun x -> n >>= (replicatei (j+1) <.> return <.> Listx.cons x)
else n >>= (return <.> Listx.rev)
in
replicatei 0 (return [])
;;
let replicate n = replicatei n <.> const;;
let rec for_all p = function
| [] -> return true
| x :: xs -> p x >>= fun c -> if c then for_all p xs else return false
;;
let exists p = lift not <.> for_all (lift not <.> p);;
let filter p xs =
let f xs x = p x >>= fun c -> if c then return (x :: xs) else return xs in
foldl f [] xs >>= (return <.> Listx.rev)
;;
(* Pair Functions *)
let cross (f,g) (x,y) = f x >>= (flip lift (g y) <.> Pair.make);;
let pair fs = cross fs <.> Pair.create;;
let apply f = cross <.> Pair.make f;;
let project f = apply f f;;
let uncurry f (x,y) = f x y;;
let fold f g d (x,y) = f x d >>= g y;;
(* Boolean Functions *)
let ite m f g x = m >>= fun c -> if c then f x else g x;;
(* Printers *)
let fprintfi f d fmt xs =
let rec fprintfi i = function
| [] -> return ()
| [x] -> f i fmt x
| x::xs -> f i fmt x >>= fun _ -> F.fprintf fmt d; fprintfi (i+1) xs
in
F.fprintf fmt "@["; fprintfi 0 xs >>= fun _ -> return (F.fprintf fmt "@]")
;;
let fprintf f = fprintfi (const f);;
let to_stringi f d xs =
let f i fmt x = f i x >>= (return <.> F.fprintf fmt "%s") in
fprintfi f d F.str_formatter xs >>= (return <.> F.flush_str_formatter)
;;
let to_string f = to_stringi (const f);;
end
(*** MODULES ******************************************************************)
module Transformer = struct
(*** MODULE TYPES ************************************************************)
module type COMBINED_MONAD = sig
type 'a m
include SIGNATURE
val liftm : 'a m -> 'a t
end
module type ERROR_MONAD = sig
type error
include COMBINED_MONAD
val ap_error : ((error,'a) either m -> (error,'b) either m) t -> 'a t -> 'b t
val map_error : ((error,'a) either m -> (error,'b) either m) -> 'a t -> 'b t
val catch : (error -> 'a t) -> 'a t -> 'a t
val fail : error -> 'a t
val failif : bool -> error -> unit t
val run : 'a t -> (error,'a) either m
end
module type LIST_MONAD = sig
include COMBINED_MONAD
val ap_list : ('a list m -> 'b list m) t -> 'a t -> 'b t
val map_list : ('a list m -> 'b list m) -> 'a t -> 'b t
val run : 'a t -> 'a list m
end
module type OPTION_MONAD = sig
include COMBINED_MONAD
val ap_option : ('a option m -> 'b option m) t -> 'a t -> 'b t
val map_option : ('a option m -> 'b option m) -> 'a t -> 'b t
val run : 'a t -> 'a option m
end
module type STATE_MONAD = sig
type state
include COMBINED_MONAD
val ap_state : (('a * state) m -> ('b * state) m) t -> 'a t -> 'b t
val map_state : (('a * state) m -> ('b * state) m) -> 'a t -> 'b t
val adopt : (state -> 'a * state) -> 'a t
val get : state t
val modify : (state -> state) -> state t
val set : state -> unit t
val update : (state -> state) -> unit t
val with_state : (state -> state) -> 'a t -> 'a t
val eval : state -> 'a t -> ('a * state) m
val execute : state -> 'a t -> state m
val run : state -> 'a t -> 'a m
end
(*** MODULES *****************************************************************)
module Error (E : ERROR) (M : MINIMAL_MONAD) = struct
(*** MODULES ****************************************************************)
module M = Make (M);;
(*** TYPES ******************************************************************)
type error = E.t;;
type 'a m = 'a M.t;;
(*** FUNCTIONS **************************************************************)
let error e = Left e;;
let result x = Right x;;
(*** INCLUDES ***************************************************************)
include Make (struct
type 'a t = (error,'a) either m;;
let (>>=) m = M.(>>=) m <.> either (M.return <.> error);;
let return x = M.return (result x);;
end);;
(*** FUNCTIONS **************************************************************)
let liftm m = M.(>>=) m return;;
Access Functions
let ap_error m n = m >>= swap n;;
let map_error f = ap_error (return f);;
(* Error Handling *)
let catch h m = M.(>>=) m (either h return);;
let fail e = M.return (error e);;
let failif b e = if b then fail e else return ();;
(* Evaluation Functions *)
let run = id;;
end
module List (M : MINIMAL_MONAD) = struct
(*** TYPES ******************************************************************)
type 'a m = 'a M.t;;
(*** INCLUDES ***************************************************************)
include Make (struct
type 'a t = 'a list m;;
let (>>=) m f =
let rev_append xs = M.return <.> Listx.rev_append xs in
let f x xs = M.(>>=) (f x) (flip rev_append xs) in
let g = Listx.foldl (fun m -> M.(>>=) m <.> f) (M.return []) in
M.(>>=) (M.(>>=) m g) (M.return <.> Listx.rev)
;;
let return x = M.return [x];;
end);;
(*** FUNCTIONS **************************************************************)
let liftm m = M.(>>=) m return;;
Access Functions
let ap_list m n = m >>= swap n;;
let map_list f = ap_list (return f);;
(* Evaluation Functions *)
let run = id;;
end
module Option (M : MINIMAL_MONAD) = struct
(*** TYPES ******************************************************************)
type 'a m = 'a M.t;;
(*** INCLUDES ***************************************************************)
include Make (struct
type 'a t = 'a option m;;
let (>>=) m f = M.(>>=) m (Option.fold f (M.return None));;
let return x = M.return (Some x);;
end);;
(*** FUNCTIONS **************************************************************)
let liftm m = M.(>>=) m return;;
Access Functions
let ap_option m n = m >>= swap n;;
let map_option f = ap_option (return f);;
(* Evaluation Functions *)
let run = id;;
end
module State (S : STATE) (M : MINIMAL_MONAD) = struct
(*** TYPES ******************************************************************)
type state = S.t;;
type 'a m = 'a M.t;;
(*** INCLUDES ***************************************************************)
include Make (struct
type 'a t = state -> ('a * state) m;;
let (>>=) m f = (fun s -> M.(>>=) (m s) (Pair.uncurry f));;
let return x = (fun s -> M.return (x,s));;
end);;
(*** FUNCTIONS **************************************************************)
let liftm m = (fun s -> M.(>>=) m (flip return s));;
Access Functions
let ap_state m n = m >>= fun f -> f <.> n;;
let map_state f = ap_state (return f);;
(* State Modifications *)
let adopt f = (fun s -> let (x,s) = f s in M.return (x,s));;
let modify f = adopt (Pair.create <.> f);;
let update f = (fun s -> M.return ((),f s));;
let get = (fun s -> modify id s);;
let set s = update (const s);;
let with_state f m = (fun s -> M.(>>=) (m s) (fun (x,s) -> return x (f s)));;
(* Evaluation Functions *)
let execute s m = M.(>>=) (m s) (M.return <.> snd);;
let run s m = M.(>>=) (m s) (M.return <.> fst);;
let eval s m = m s;;
end
end
module Id = Make (struct
type 'a t = 'a;;
let (>>=) = swap;;
let return = id;;
end);;
module LazyList = Make (struct
type 'a t = 'a LL.t;;
let return x = lazy (LL.Cons (x,LL.empty));;
let (>>=) xs f = LL.concat (LL.map f xs);;
end);;
module Error = Transformer.Error (Stringx) (Id);;
module List = Transformer.List (Id);;
module Option = Transformer.Option (Id);;
module State (S : STATE) = Transformer.State (S) (Id);;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/util/src/monad.ml | ocaml | ** OPENS *******************************************************************
** MODULES *****************************************************************
** MODULE TYPES ************************************************************
** MODULES *****************************************************************
** INCLUDES ***************************************************************
** FUNCTIONS **************************************************************
Miscellaneous
List Functions
Pair Functions
Boolean Functions
Printers
** MODULES *****************************************************************
** MODULE TYPES ***********************************************************
** MODULES ****************************************************************
** MODULES ***************************************************************
** TYPES *****************************************************************
** FUNCTIONS *************************************************************
** INCLUDES **************************************************************
** FUNCTIONS *************************************************************
Error Handling
Evaluation Functions
** TYPES *****************************************************************
** INCLUDES **************************************************************
** FUNCTIONS *************************************************************
Evaluation Functions
** TYPES *****************************************************************
** INCLUDES **************************************************************
** FUNCTIONS *************************************************************
Evaluation Functions
** TYPES *****************************************************************
** INCLUDES **************************************************************
** FUNCTIONS *************************************************************
State Modifications
Evaluation Functions | Copyright 2008 , Christian Sternagel ,
* GNU Lesser General Public License
*
* This file is part of TTT2 .
*
* TTT2 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 .
*
* TTT2 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 TTT2 . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of TTT2.
*
* TTT2 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.
*
* TTT2 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 TTT2. If not, see </>.
*)
open Prelude;;
open Either;;
module F = Format;;
module LL = LazyList;;
module type ERROR = sig type t end
module type STATE = sig type t end
module type MINIMAL_MONAD = sig
type 'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
end
module type SIGNATURE = sig
include MINIMAL_MONAD
val (=<<) : ('a -> 'b t) -> 'a t -> 'b t
val (>>) : 'a t -> 'b t -> 'b t
val (<<) : 'b t -> 'a t -> 'b t
val (>=>) : ('a -> 'b t) -> ('b -> 'c t) -> 'a -> 'c t
val (<=<) : ('b -> 'c t) -> ('a -> 'b t) -> 'a -> 'c t
val ap : ('a -> 'b) t -> 'a t -> 'b t
val join : 'a t t -> 'a t
val lift : ('a -> 'b) -> 'a t -> 'b t
val lift2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
val lift3 : ('a -> 'b -> 'c -> 'd) -> 'a t -> 'b t -> 'c t -> 'd t
val exists : ('a -> bool t) -> 'a list -> bool t
val filter : ('a -> bool t) -> 'a list -> 'a list t
val flat_map : ('a -> 'b list t) -> 'a list -> 'b list t
val flat_mapi : (int -> 'a -> 'b list t) -> 'a list -> 'b list t
val foldl : ('a -> 'b -> 'a t) -> 'a -> 'b list -> 'a t
val foldl1 : ('a -> 'a -> 'a t) -> 'a list -> 'a t
val foldl2 : ('a -> 'b -> 'c -> 'a t) -> 'a -> 'b list -> 'c list -> 'a t
val foldli : (int -> 'a -> 'b -> 'a t) -> 'a -> 'b list -> 'a t
val foldr : ('a -> 'b -> 'b t) -> 'b -> 'a list -> 'b t
val foldr1 : ('a -> 'a -> 'a t) -> 'a list -> 'a t
val foldr2 : ('a -> 'b -> 'c -> 'c t) -> 'c -> 'a list -> 'b list -> 'c t
val foldri : (int -> 'a -> 'b -> 'b t) -> 'b -> 'a list -> 'b t
val for_all : ('a -> bool t) -> 'a list -> bool t
val iter : ('a -> unit t) -> 'a list -> unit t
val iteri : (int -> 'a -> unit t) -> 'a list -> unit t
val map : ('a -> 'b t) -> 'a list -> 'b list t
val mapi : (int -> 'a -> 'b t) -> 'a list -> 'b list t
val replicate : int -> 'a t -> 'a list t
val replicatei : int -> (int -> 'a t) -> 'a list t
val rev_map : ('a -> 'b t) -> 'a list -> 'b list t
val rev_mapi : (int -> 'a -> 'b t) -> 'a list -> 'b list t
val sequence : 'a t list -> 'a list t
val apply : ('a -> 'c t) -> ('b -> 'd t) -> 'a * 'b -> ('c * 'd) t
val cross : ('a -> 'c t) * ('b -> 'd t) -> 'a * 'b -> ('c * 'd) t
val fold : ('a -> 'c -> 'c t) -> ('b -> 'c -> 'c t) -> 'c -> 'a * 'b -> 'c t
val pair : ('a -> 'b t) * ('a -> 'c t) -> 'a -> ('b * 'c) t
val project : ('a -> 'b t) -> 'a * 'a -> ('b * 'b) t
val uncurry : ('a -> 'b -> 'c t) -> 'a * 'b -> 'c t
val ite : bool t -> ('a -> 'b t) -> ('a -> 'b t) -> 'a -> 'b t
val fprintf : (F.formatter -> 'a -> unit t)
-> (unit,F.formatter,unit) Pervasives.format -> F.formatter
-> 'a list -> unit t
val fprintfi : (int -> F.formatter -> 'a -> unit t)
-> (unit,F.formatter,unit) Pervasives.format -> F.formatter
-> 'a list -> unit t
val to_string : ('a -> string t)
-> (unit,F.formatter,unit) Pervasives.format -> 'a list -> string t
val to_stringi : (int -> 'a -> string t)
-> (unit,F.formatter,unit) Pervasives.format -> 'a list -> string t
end
module type ERROR_MONAD = sig
type error
include SIGNATURE
val ap_error : ((error,'a) either -> (error,'b) either) t -> 'a t -> 'b t
val map_error : ((error,'a) either -> (error,'b) either) -> 'a t -> 'b t
val catch : (error -> 'a t) -> 'a t -> 'a t
val fail : error -> 'a t
val failif : bool -> error -> unit t
val run : 'a t -> (error,'a) either
end
module type ID_MONAD = sig
include SIGNATURE
val run : 'a t -> 'a
end
module type STATE_MONAD = sig
type state
include SIGNATURE
val ap_state : ('a * state -> 'b * state) t -> 'a t -> 'b t
val map_state : ('a * state -> 'b * state) -> 'a t -> 'b t
val adopt : (state -> 'a * state) -> 'a t
val get : state t
val modify : (state -> state) -> state t
val set : state -> unit t
val update : (state -> state) -> unit t
val with_state : (state -> state) -> 'a t -> 'a t
val eval : state -> 'a t -> 'a * state
val execute : state -> 'a t -> state
val run : state -> 'a t -> 'a
end
module Make (M : MINIMAL_MONAD) = struct
include M;;
let (=<<) f m = m >>= f;;
let (>>) m n = m >>= const n;;
let (<<) m n = n >> m;;
let (>=>) f g x = f x >>= g;;
let (<=<) g f = f >=> g;;
let ap m n = m >>= fun f -> n >>= (return <.> f);;
let join m = m >>= id;;
let lift f = ap (return f);;
let lift2 f m = ap (lift f m);;
let lift3 f m n = ap (lift2 f m n);;
let foldli f = Listx.foldli (fun i m x -> m >>= flip (f i) x) <.> return;;
let foldl f = foldli (const f);;
let foldri f = Listx.foldri (fun i x m -> m >>= (f i) x) <.> return;;
let foldr f = foldri (const f);;
let foldl1 f =
(fun xs -> foldl f (Listx.hd xs) (Listx.tl xs)) <?> "empty list"
;;
let foldr1 f =
(fun xs -> foldr f (Listx.hd xs) (Listx.tl xs)) <?> "empty list"
;;
let foldl2 f = Listx.foldl2 (fun m x y -> m >>= fun z -> f z x y) <.> return;;
let foldr2 f = Listx.foldr2 (fun x y m -> m >>= f x y) <.> return;;
let iteri f = foldli (drop f) ();;
let iter f = iteri (const f);;
let employ combine f xs =
let f i xs x = f i x >>= (return <.> flip combine xs) in foldli f [] xs
;;
let flat_mapi f xs = employ Listx.rev_append f xs >>= (return <.> Listx.rev);;
let flat_map f = flat_mapi (const f);;
let mapi f xs = employ Listx.cons f xs >>= (return <.> Listx.rev)
let map f = mapi (const f);;
let rev_mapi f = employ Listx.cons f;;
let rev_map f = rev_mapi (const f);;
let sequence ms = map id ms;;
let replicatei i m =
let rec replicatei j n =
if j < i then
m j >>= fun x -> n >>= (replicatei (j+1) <.> return <.> Listx.cons x)
else n >>= (return <.> Listx.rev)
in
replicatei 0 (return [])
;;
let replicate n = replicatei n <.> const;;
let rec for_all p = function
| [] -> return true
| x :: xs -> p x >>= fun c -> if c then for_all p xs else return false
;;
let exists p = lift not <.> for_all (lift not <.> p);;
let filter p xs =
let f xs x = p x >>= fun c -> if c then return (x :: xs) else return xs in
foldl f [] xs >>= (return <.> Listx.rev)
;;
let cross (f,g) (x,y) = f x >>= (flip lift (g y) <.> Pair.make);;
let pair fs = cross fs <.> Pair.create;;
let apply f = cross <.> Pair.make f;;
let project f = apply f f;;
let uncurry f (x,y) = f x y;;
let fold f g d (x,y) = f x d >>= g y;;
let ite m f g x = m >>= fun c -> if c then f x else g x;;
let fprintfi f d fmt xs =
let rec fprintfi i = function
| [] -> return ()
| [x] -> f i fmt x
| x::xs -> f i fmt x >>= fun _ -> F.fprintf fmt d; fprintfi (i+1) xs
in
F.fprintf fmt "@["; fprintfi 0 xs >>= fun _ -> return (F.fprintf fmt "@]")
;;
let fprintf f = fprintfi (const f);;
let to_stringi f d xs =
let f i fmt x = f i x >>= (return <.> F.fprintf fmt "%s") in
fprintfi f d F.str_formatter xs >>= (return <.> F.flush_str_formatter)
;;
let to_string f = to_stringi (const f);;
end
module Transformer = struct
module type COMBINED_MONAD = sig
type 'a m
include SIGNATURE
val liftm : 'a m -> 'a t
end
module type ERROR_MONAD = sig
type error
include COMBINED_MONAD
val ap_error : ((error,'a) either m -> (error,'b) either m) t -> 'a t -> 'b t
val map_error : ((error,'a) either m -> (error,'b) either m) -> 'a t -> 'b t
val catch : (error -> 'a t) -> 'a t -> 'a t
val fail : error -> 'a t
val failif : bool -> error -> unit t
val run : 'a t -> (error,'a) either m
end
module type LIST_MONAD = sig
include COMBINED_MONAD
val ap_list : ('a list m -> 'b list m) t -> 'a t -> 'b t
val map_list : ('a list m -> 'b list m) -> 'a t -> 'b t
val run : 'a t -> 'a list m
end
module type OPTION_MONAD = sig
include COMBINED_MONAD
val ap_option : ('a option m -> 'b option m) t -> 'a t -> 'b t
val map_option : ('a option m -> 'b option m) -> 'a t -> 'b t
val run : 'a t -> 'a option m
end
module type STATE_MONAD = sig
type state
include COMBINED_MONAD
val ap_state : (('a * state) m -> ('b * state) m) t -> 'a t -> 'b t
val map_state : (('a * state) m -> ('b * state) m) -> 'a t -> 'b t
val adopt : (state -> 'a * state) -> 'a t
val get : state t
val modify : (state -> state) -> state t
val set : state -> unit t
val update : (state -> state) -> unit t
val with_state : (state -> state) -> 'a t -> 'a t
val eval : state -> 'a t -> ('a * state) m
val execute : state -> 'a t -> state m
val run : state -> 'a t -> 'a m
end
module Error (E : ERROR) (M : MINIMAL_MONAD) = struct
module M = Make (M);;
type error = E.t;;
type 'a m = 'a M.t;;
let error e = Left e;;
let result x = Right x;;
include Make (struct
type 'a t = (error,'a) either m;;
let (>>=) m = M.(>>=) m <.> either (M.return <.> error);;
let return x = M.return (result x);;
end);;
let liftm m = M.(>>=) m return;;
Access Functions
let ap_error m n = m >>= swap n;;
let map_error f = ap_error (return f);;
let catch h m = M.(>>=) m (either h return);;
let fail e = M.return (error e);;
let failif b e = if b then fail e else return ();;
let run = id;;
end
module List (M : MINIMAL_MONAD) = struct
type 'a m = 'a M.t;;
include Make (struct
type 'a t = 'a list m;;
let (>>=) m f =
let rev_append xs = M.return <.> Listx.rev_append xs in
let f x xs = M.(>>=) (f x) (flip rev_append xs) in
let g = Listx.foldl (fun m -> M.(>>=) m <.> f) (M.return []) in
M.(>>=) (M.(>>=) m g) (M.return <.> Listx.rev)
;;
let return x = M.return [x];;
end);;
let liftm m = M.(>>=) m return;;
Access Functions
let ap_list m n = m >>= swap n;;
let map_list f = ap_list (return f);;
let run = id;;
end
module Option (M : MINIMAL_MONAD) = struct
type 'a m = 'a M.t;;
include Make (struct
type 'a t = 'a option m;;
let (>>=) m f = M.(>>=) m (Option.fold f (M.return None));;
let return x = M.return (Some x);;
end);;
let liftm m = M.(>>=) m return;;
Access Functions
let ap_option m n = m >>= swap n;;
let map_option f = ap_option (return f);;
let run = id;;
end
module State (S : STATE) (M : MINIMAL_MONAD) = struct
type state = S.t;;
type 'a m = 'a M.t;;
include Make (struct
type 'a t = state -> ('a * state) m;;
let (>>=) m f = (fun s -> M.(>>=) (m s) (Pair.uncurry f));;
let return x = (fun s -> M.return (x,s));;
end);;
let liftm m = (fun s -> M.(>>=) m (flip return s));;
Access Functions
let ap_state m n = m >>= fun f -> f <.> n;;
let map_state f = ap_state (return f);;
let adopt f = (fun s -> let (x,s) = f s in M.return (x,s));;
let modify f = adopt (Pair.create <.> f);;
let update f = (fun s -> M.return ((),f s));;
let get = (fun s -> modify id s);;
let set s = update (const s);;
let with_state f m = (fun s -> M.(>>=) (m s) (fun (x,s) -> return x (f s)));;
let execute s m = M.(>>=) (m s) (M.return <.> snd);;
let run s m = M.(>>=) (m s) (M.return <.> fst);;
let eval s m = m s;;
end
end
module Id = Make (struct
type 'a t = 'a;;
let (>>=) = swap;;
let return = id;;
end);;
module LazyList = Make (struct
type 'a t = 'a LL.t;;
let return x = lazy (LL.Cons (x,LL.empty));;
let (>>=) xs f = LL.concat (LL.map f xs);;
end);;
module Error = Transformer.Error (Stringx) (Id);;
module List = Transformer.List (Id);;
module Option = Transformer.Option (Id);;
module State (S : STATE) = Transformer.State (S) (Id);;
|
2dd63e362e2121f9aca23aafcb0a69fa6de1a76af23d09b96360005b1c5de5ff | ftovagliari/ocamleditor | greek.ml |
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
OCamlEditor 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 , see < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCamlEditor 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, see </>.
*)
let letters = [
"'a\\([0-9]*\\)", "\xCE\xB1\\1";
"'b\\([0-9]*\\)", "\xCE\xB2\\1";
"'c\\([0-9]*\\)", "\xCE\xB3\\1";
"'d\\([0-9]*\\)", "\xCE\xB4\\1";
"'e\\([0-9]*\\)", "\xCE\xB5\\1";
"'f\\([0-9]*\\)", "\xCE\xB6\\1";
"'g\\([0-9]*\\)", "\xCE\xB7\\1";
"'h\\([0-9]*\\)", "\xCE\xB8\\1";
"'i\\([0-9]*\\)", "\xCE\xB9\\1";
"'j\\([0-9]*\\)", "\xCE\xBA\\1";
"'k\\([0-9]*\\)", "\xCE\xBB\\1";
"'l\\([0-9]*\\)", "\xCE\xBC\\1";
"'m\\([0-9]*\\)", "\xCE\xBD\\1";
"'n\\([0-9]*\\)", "\xCE\xBE\\1";
"'o\\([0-9]*\\)", "\xCE\xBF\\1";
"'p\\([0-9]*\\)", "\xCE\xC0\\1";
"'q\\([0-9]*\\)", "\xCE\xC1\\1";
"'r\\([0-9]*\\)", "\xCE\xC2\\1";
"'s\\([0-9]*\\)", "\xCE\xC3\\1";
"'t\\([0-9]*\\)", "\xCE\xC4\\1";
"'u\\([0-9]*\\)", "\xCE\xC5\\1";
"'v\\([0-9]*\\)", "\xCE\xC6\\1";
"'w\\([0-9]*\\)", "\xCE\xC7\\1";
"'x\\([0-9]*\\)", "\xCE\xC8\\1";
"'y\\([0-9]*\\)", "\xCE\xC9\\1";
];;
let greek = Miscellanea.replace_all ~regexp:true letters
let replace (buffer : GText.buffer) =
(*let tag = buffer#create_tag [`SCALE `X_LARGE] in*)
let replace x y =
let iter = ref buffer#start_iter in
while not !iter#is_end do
match !iter#forward_search x with
| Some (start, stop) ->
let mstart = buffer#create_mark(* ~name:(Gtk_util.create_mark_name "Greek.replace1")*) start in
buffer#delete ~start ~stop;
iter := buffer#get_iter_at_mark (`MARK mstart);
buffer#insert ~iter:!iter y;
buffer#apply_tag tag
~start:(buffer#get_iter_at_mark ( ` MARK mstart ) )
~stop:((buffer#get_iter_at_mark ( ` MARK mstart))#forward_chars ( Glib.Utf8.length y ) ) ;
~start:(buffer#get_iter_at_mark (`MARK mstart))
~stop:((buffer#get_iter_at_mark (`MARK mstart))#forward_chars (Glib.Utf8.length y));*)
iter := !iter#forward_char;
buffer#delete_mark (`MARK mstart);
| None -> iter := buffer#end_iter
done;
in
let iter = ref buffer#start_iter in
while not !iter#is_end do
match !iter#forward_search "'" with
| Some (start, stop) ->
~name:(Gtk_util.create_mark_name " " )
let mstop = ref mstart in
iter := !iter#forward_char;
begin
match String.get (buffer#get_text ~start:!iter ~stop:!iter#forward_char ()) 0 with
| 'a'..'z' ->
begin
iter := !iter#forward_char;
let stop = !iter#forward_char in
let text = buffer#get_text ~start:!iter ~stop () in
if String.length text > 0 then begin
match String.get text 0 with
| '0'..'9' -> mstop := buffer#create_mark(* ~name:(Gtk_util.create_mark_name "Greek.replace3")*) stop
| _ -> mstop := buffer#create_mark(* ~name:(Gtk_util.create_mark_name "Greek.replace4")*) !iter
end else mstop := buffer#create_mark(* ~name:(Gtk_util.create_mark_name "Greek.replace5")*) stop
end;
let start = buffer#get_iter_at_mark (`MARK mstart) in
let stop = buffer#get_iter_at_mark (`MARK !mstop) in
let letter = buffer#get_text ~start ~stop () in
if letter <> "" then begin
let repl = greek letter in
buffer#delete ~start ~stop;
buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK mstart)) repl;
iter := buffer#get_iter_at_mark (`MARK !mstop);
end
| x ->
if not (GtkText.Mark.get_deleted mstart) then (buffer#delete_mark (`MARK mstart));
end;
if not (GtkText.Mark.get_deleted mstart) then (buffer#delete_mark (`MARK mstart));
if not (GtkText.Mark.get_deleted !mstop) then (buffer#delete_mark (`MARK !mstop));
| None -> iter := buffer#end_iter
done;
replace "->" "\xE2\x86\x92";
replace " * " " \xE2\xA8\xAF ";
;;
| null | https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/greek.ml | ocaml | let tag = buffer#create_tag [`SCALE `X_LARGE] in
~name:(Gtk_util.create_mark_name "Greek.replace1")
~name:(Gtk_util.create_mark_name "Greek.replace3")
~name:(Gtk_util.create_mark_name "Greek.replace4")
~name:(Gtk_util.create_mark_name "Greek.replace5") |
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
OCamlEditor 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 , see < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCamlEditor 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, see </>.
*)
let letters = [
"'a\\([0-9]*\\)", "\xCE\xB1\\1";
"'b\\([0-9]*\\)", "\xCE\xB2\\1";
"'c\\([0-9]*\\)", "\xCE\xB3\\1";
"'d\\([0-9]*\\)", "\xCE\xB4\\1";
"'e\\([0-9]*\\)", "\xCE\xB5\\1";
"'f\\([0-9]*\\)", "\xCE\xB6\\1";
"'g\\([0-9]*\\)", "\xCE\xB7\\1";
"'h\\([0-9]*\\)", "\xCE\xB8\\1";
"'i\\([0-9]*\\)", "\xCE\xB9\\1";
"'j\\([0-9]*\\)", "\xCE\xBA\\1";
"'k\\([0-9]*\\)", "\xCE\xBB\\1";
"'l\\([0-9]*\\)", "\xCE\xBC\\1";
"'m\\([0-9]*\\)", "\xCE\xBD\\1";
"'n\\([0-9]*\\)", "\xCE\xBE\\1";
"'o\\([0-9]*\\)", "\xCE\xBF\\1";
"'p\\([0-9]*\\)", "\xCE\xC0\\1";
"'q\\([0-9]*\\)", "\xCE\xC1\\1";
"'r\\([0-9]*\\)", "\xCE\xC2\\1";
"'s\\([0-9]*\\)", "\xCE\xC3\\1";
"'t\\([0-9]*\\)", "\xCE\xC4\\1";
"'u\\([0-9]*\\)", "\xCE\xC5\\1";
"'v\\([0-9]*\\)", "\xCE\xC6\\1";
"'w\\([0-9]*\\)", "\xCE\xC7\\1";
"'x\\([0-9]*\\)", "\xCE\xC8\\1";
"'y\\([0-9]*\\)", "\xCE\xC9\\1";
];;
let greek = Miscellanea.replace_all ~regexp:true letters
let replace (buffer : GText.buffer) =
let replace x y =
let iter = ref buffer#start_iter in
while not !iter#is_end do
match !iter#forward_search x with
| Some (start, stop) ->
buffer#delete ~start ~stop;
iter := buffer#get_iter_at_mark (`MARK mstart);
buffer#insert ~iter:!iter y;
buffer#apply_tag tag
~start:(buffer#get_iter_at_mark ( ` MARK mstart ) )
~stop:((buffer#get_iter_at_mark ( ` MARK mstart))#forward_chars ( Glib.Utf8.length y ) ) ;
~start:(buffer#get_iter_at_mark (`MARK mstart))
~stop:((buffer#get_iter_at_mark (`MARK mstart))#forward_chars (Glib.Utf8.length y));*)
iter := !iter#forward_char;
buffer#delete_mark (`MARK mstart);
| None -> iter := buffer#end_iter
done;
in
let iter = ref buffer#start_iter in
while not !iter#is_end do
match !iter#forward_search "'" with
| Some (start, stop) ->
~name:(Gtk_util.create_mark_name " " )
let mstop = ref mstart in
iter := !iter#forward_char;
begin
match String.get (buffer#get_text ~start:!iter ~stop:!iter#forward_char ()) 0 with
| 'a'..'z' ->
begin
iter := !iter#forward_char;
let stop = !iter#forward_char in
let text = buffer#get_text ~start:!iter ~stop () in
if String.length text > 0 then begin
match String.get text 0 with
end;
let start = buffer#get_iter_at_mark (`MARK mstart) in
let stop = buffer#get_iter_at_mark (`MARK !mstop) in
let letter = buffer#get_text ~start ~stop () in
if letter <> "" then begin
let repl = greek letter in
buffer#delete ~start ~stop;
buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK mstart)) repl;
iter := buffer#get_iter_at_mark (`MARK !mstop);
end
| x ->
if not (GtkText.Mark.get_deleted mstart) then (buffer#delete_mark (`MARK mstart));
end;
if not (GtkText.Mark.get_deleted mstart) then (buffer#delete_mark (`MARK mstart));
if not (GtkText.Mark.get_deleted !mstop) then (buffer#delete_mark (`MARK !mstop));
| None -> iter := buffer#end_iter
done;
replace "->" "\xE2\x86\x92";
replace " * " " \xE2\xA8\xAF ";
;;
|
392c0c331a79f0ebcbcd90163c7134bc2fbbbb892c5afa9c74b599d058057fa6 | mbutterick/fontland | directory.rkt | #lang racket
(require rackunit racket/runtime-path fontland)
#|
approximates
|#
(define-runtime-path open-sans-ttf "data/OpenSans/OpenSans-Regular.ttf")
(define font (open-font open-sans-ttf))
(test-case
"decodes SFNT directory values correctly"
(define dir (font-directory font))
(check-equal? (hash-ref dir 'numTables) 19)
(check-equal? (hash-ref dir 'searchRange) 256)
(check-equal? (hash-ref dir 'entrySelector) 4)
(check-equal? (hash-ref dir 'rangeShift) 48))
(test-case
"numTables matches table collection"
(define dir (font-directory font))
(check-equal? (length (hash-keys (hash-ref dir 'tables))) (hash-ref dir 'numTables)))
| null | https://raw.githubusercontent.com/mbutterick/fontland/e50e4c82f58e2014d64e87a14c1d29b546fb393b/fontland/test/directory.rkt | racket |
approximates
| #lang racket
(require rackunit racket/runtime-path fontland)
(define-runtime-path open-sans-ttf "data/OpenSans/OpenSans-Regular.ttf")
(define font (open-font open-sans-ttf))
(test-case
"decodes SFNT directory values correctly"
(define dir (font-directory font))
(check-equal? (hash-ref dir 'numTables) 19)
(check-equal? (hash-ref dir 'searchRange) 256)
(check-equal? (hash-ref dir 'entrySelector) 4)
(check-equal? (hash-ref dir 'rangeShift) 48))
(test-case
"numTables matches table collection"
(define dir (font-directory font))
(check-equal? (length (hash-keys (hash-ref dir 'tables))) (hash-ref dir 'numTables)))
|
2f611ecd6e0ea7153d815da8e5a9ea7f9d2dd381316ed4b163276c49eecb97c3 | yitzchak/common-lisp-jupyter | sys-install.lisp | (load "quicklisp.lisp")
(quicklisp-quickstart:install)
(ql-util:without-prompting
(ql:add-to-init-file))
(ql:quickload :ziz)
(ziz:with-distribution (dist :releases '("."))
(ql-dist:install-dist (ziz:distribution-info-url dist) :prompt nil)
(ql:quickload :common-lisp-jupyter))
(cl-jupyter:install :system t :prefix "./pkg/")
| null | https://raw.githubusercontent.com/yitzchak/common-lisp-jupyter/930e600cac727360e53cc44a17fde41f05125547/scripts/sys-install.lisp | lisp | (load "quicklisp.lisp")
(quicklisp-quickstart:install)
(ql-util:without-prompting
(ql:add-to-init-file))
(ql:quickload :ziz)
(ziz:with-distribution (dist :releases '("."))
(ql-dist:install-dist (ziz:distribution-info-url dist) :prompt nil)
(ql:quickload :common-lisp-jupyter))
(cl-jupyter:install :system t :prefix "./pkg/")
|
|
184807973091a76e278d0e086e3d92525395144e6b1355ef5cfe45ac8df7e70d | dyoo/ragg | support.rkt | #lang racket/base
(provide [struct-out token-struct]
token
[struct-out exn:fail:parsing])
(struct token-struct (type val offset line column span skip?)
#:transparent)
;; Token constructor.
;; This is intended to be a general token structure constructor that's nice
;; to work with.
;; It should cooperate with the tokenizers constructed with make-permissive-tokenizer.
(define token
(lambda (type ;; (U symbol string)
[val #f] ;; any
#:offset [offset #f] ;; (U #f number)
#:line [line #f] ;; (U #f number)
#:column [column #f] ;; (U #f number)
#:span [span #f] ;; boolean
#:skip? [skip? #f])
(token-struct (if (string? type) (string->symbol type) type)
val
offset line column span skip?)))
;; When bad things happen, we need to emit errors with source location.
(struct exn:fail:parsing exn:fail (srclocs)
#:transparent
#:property prop:exn:srclocs (lambda (instance)
(exn:fail:parsing-srclocs instance)))
| null | https://raw.githubusercontent.com/dyoo/ragg/9cc648e045f7195702599b88e6b8db9364f88302/ragg/support.rkt | racket | Token constructor.
This is intended to be a general token structure constructor that's nice
to work with.
It should cooperate with the tokenizers constructed with make-permissive-tokenizer.
(U symbol string)
any
(U #f number)
(U #f number)
(U #f number)
boolean
When bad things happen, we need to emit errors with source location. | #lang racket/base
(provide [struct-out token-struct]
token
[struct-out exn:fail:parsing])
(struct token-struct (type val offset line column span skip?)
#:transparent)
(define token
#:skip? [skip? #f])
(token-struct (if (string? type) (string->symbol type) type)
val
offset line column span skip?)))
(struct exn:fail:parsing exn:fail (srclocs)
#:transparent
#:property prop:exn:srclocs (lambda (instance)
(exn:fail:parsing-srclocs instance)))
|
79aae92a59a582368b186bc358631762a6bd0168007ad3f4d612b292a6484d68 | rowangithub/DOrder | split.ml | let rec loop i j k n b =
if (n < 2 * k) then
let n = n + 1 in
let i, j =
if (b = 1) then i+1, j else i, j+1 in
let b = 1 - b in
loop i j k n b
Hack : add n mod 2 = 0 as a predicate
else if (n mod 2 = 0) then assert (i = j)
else ()
add a qualifier b = 0 || b = 1 to
encode boolean variables using integer
encode boolean variables using integer *)
let main j b =
let k = 100 in
let i = j in
loop i j k 0 b
let _ = main 0 1
let _ = main 0 0
let _ = main 1 1
let _ = main 1 0 | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/folprograms/sc/split.ml | ocaml | let rec loop i j k n b =
if (n < 2 * k) then
let n = n + 1 in
let i, j =
if (b = 1) then i+1, j else i, j+1 in
let b = 1 - b in
loop i j k n b
Hack : add n mod 2 = 0 as a predicate
else if (n mod 2 = 0) then assert (i = j)
else ()
add a qualifier b = 0 || b = 1 to
encode boolean variables using integer
encode boolean variables using integer *)
let main j b =
let k = 100 in
let i = j in
loop i j k 0 b
let _ = main 0 1
let _ = main 0 0
let _ = main 1 1
let _ = main 1 0 |
|
0cf46f67813b5fe93bd0107c5fca60d2c6b4b08b0aa5628f4340d1f12b35b1eb | returntocorp/semgrep | Run.ml | (*
Entry point to the program and command-line interface
*)
[ run file ] will print on stdout some
* boilerplate code of the form :
*
* let todo _ env _ x =
* failwith " TODO "
*
* let v =
* match v with
* | Int v1 - >
* let v1 = map_int env v1 in
* todo env v1
* | Plus ( v1 , v2 ) - >
* let v1 = map_expr env v1 in
* let v2 = map_expr env v2 in
* todo env ( v1 , v2 )
* | ...
*
* for each OCaml type definitions in [ file ] .
*
* The original boilerplate generator was :
*
* boilerplate code of the form:
*
* let todo _env _x =
* failwith "TODO"
*
* let rec map_expr env v =
* match v with
* | Int v1 ->
* let v1 = map_int env v1 in
* todo env v1
* | Plus (v1, v2) ->
* let v1 = map_expr env v1 in
* let v2 = map_expr env v2 in
* todo env (v1, v2)
* | ...
*
* for each OCaml type definitions in [file].
*
* The original boilerplate generator was:
*
*)
let run (conf : Conf.t) =
let defs = Parse.extract_typedefs_from_ml_file conf.input_file in
Print.generate_boilerplate conf defs
| null | https://raw.githubusercontent.com/returntocorp/semgrep/855abad9ada6ea5fd72d437fd69ff2e5fa42c1f1/tools/otarzan/lib/Run.ml | ocaml |
Entry point to the program and command-line interface
|
[ run file ] will print on stdout some
* boilerplate code of the form :
*
* let todo _ env _ x =
* failwith " TODO "
*
* let v =
* match v with
* | Int v1 - >
* let v1 = map_int env v1 in
* todo env v1
* | Plus ( v1 , v2 ) - >
* let v1 = map_expr env v1 in
* let v2 = map_expr env v2 in
* todo env ( v1 , v2 )
* | ...
*
* for each OCaml type definitions in [ file ] .
*
* The original boilerplate generator was :
*
* boilerplate code of the form:
*
* let todo _env _x =
* failwith "TODO"
*
* let rec map_expr env v =
* match v with
* | Int v1 ->
* let v1 = map_int env v1 in
* todo env v1
* | Plus (v1, v2) ->
* let v1 = map_expr env v1 in
* let v2 = map_expr env v2 in
* todo env (v1, v2)
* | ...
*
* for each OCaml type definitions in [file].
*
* The original boilerplate generator was:
*
*)
let run (conf : Conf.t) =
let defs = Parse.extract_typedefs_from_ml_file conf.input_file in
Print.generate_boilerplate conf defs
|
338ad032c936e2879b5c270478069042816e8f7585d56c97fc9edaef716f6f4a | Zulu-Inuoe/clution | builtin-expanders.lisp | enumerable - enumerable implementation for CL , using cl - cont
Written in 2018 by < >
;;;
;;;To the extent possible under law, the author(s) have dedicated all copyright
;;;and related and neighboring rights to this software to the public domain
;;;worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along
;;;with this software. If not, see
;;;</>.
(in-package #:enumerable)
(define-do-enumerable-expander list
(type var enumerable result body env)
`(dolist (,var ,enumerable ,result)
,@body))
(define-do-enumerable-expander vector
(type var enumerable result body env)
(with-gensyms (vec i)
`(let ((,vec ,enumerable))
(dotimes (,i (length ,vec) (let (,var) (declare (ignorable ,var)) ,result))
(let ((,var (aref ,vec ,i)))
,@body)))))
(define-do-enumerable-expander hash-table
(type var enumerable result body env)
(with-gensyms (iter more? key value)
`(with-hash-table-iterator (,iter ,enumerable)
(loop
(multiple-value-bind (,more? ,key ,value)
(,iter)
(unless ,more?
(return (let ((,var)) (declare (ignorable ,var)) ,result)))
(let ((,var (cons ,key ,value)))
,@body))))))
| null | https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/enumerable-master/src/builtin-expanders.lisp | lisp |
To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
with this software. If not, see
</>.
| enumerable - enumerable implementation for CL , using cl - cont
Written in 2018 by < >
You should have received a copy of the CC0 Public Domain Dedication along
(in-package #:enumerable)
(define-do-enumerable-expander list
(type var enumerable result body env)
`(dolist (,var ,enumerable ,result)
,@body))
(define-do-enumerable-expander vector
(type var enumerable result body env)
(with-gensyms (vec i)
`(let ((,vec ,enumerable))
(dotimes (,i (length ,vec) (let (,var) (declare (ignorable ,var)) ,result))
(let ((,var (aref ,vec ,i)))
,@body)))))
(define-do-enumerable-expander hash-table
(type var enumerable result body env)
(with-gensyms (iter more? key value)
`(with-hash-table-iterator (,iter ,enumerable)
(loop
(multiple-value-bind (,more? ,key ,value)
(,iter)
(unless ,more?
(return (let ((,var)) (declare (ignorable ,var)) ,result)))
(let ((,var (cons ,key ,value)))
,@body))))))
|
2f9750622a583c059f7d39b089313dcf2c9ee5c4a7f08605f4301cd1f95381b2 | xandkar/tiger.ml | tiger_semant_escape.ml | module List = ListLabels
module A = Tiger_absyn
module Opt = Tiger_opt
module Map = Tiger_map
module Sym = Tiger_symbol
type info =
{ depth : int
; escapes : bool ref
}
type env =
(Sym.t, info) Map.t
let rec traverseExp ~(env : env) ~depth (exp : A.exp) =
(match exp with
| A.NilExp
| A.IntExp _
| A.StringExp _ ->
()
| A.CallExp {func=_; args; pos=_} ->
List.iter args ~f:(traverseExp ~env ~depth)
| A.OpExp {oper=_; left; right; pos=_} ->
traverseExp ~env ~depth left;
traverseExp ~env ~depth right
| A.RecordExp {fields=field_exps; typ=_; pos=_} ->
List.iter field_exps ~f:(fun (_, exp, _) -> traverseExp ~env ~depth exp)
| A.SeqExp exps ->
List.iter exps ~f:(fun (exp, _) -> traverseExp ~env ~depth exp)
| A.AssignExp {var; exp; pos=_} ->
traverseVar ~env ~depth var;
traverseExp ~env ~depth exp
| A.IfExp {test; then'; else'; pos=_} ->
traverseExp ~env ~depth test;
traverseExp ~env ~depth then';
Opt.iter else' ~f:(fun e -> traverseExp ~env ~depth e)
| A.WhileExp {test; body; pos=_} ->
traverseExp ~env ~depth test;
traverseExp ~env ~depth body
| A.ForExp {var=_; lo; hi; body; pos=_; escape=_} ->
traverseExp ~env ~depth lo;
traverseExp ~env ~depth hi;
traverseExp ~env ~depth body
| A.BreakExp _ ->
()
| A.LetExp {decs; body; pos=_} ->
traverseDecs ~env ~depth decs;
traverseExp ~env ~depth body
| A.ArrayExp {typ=_; size; init; pos=_} ->
traverseExp ~env ~depth size;
traverseExp ~env ~depth init
| A.VarExp var ->
traverseVar ~env ~depth var
)
and traverseVar ~env ~depth (var : A.var) =
(match var with
| A.SimpleVar _ ->
()
| A.FieldVar {var; symbol=_; pos=_} ->
traverseVar ~env ~depth var
| A.SubscriptVar {var; exp; pos=_} ->
traverseVar ~env ~depth var;
traverseExp ~env ~depth exp
)
and traverseDecs ~env ~depth (decs : A.dec list) =
List.iter decs ~f:(traverseDec ~env ~depth)
and traverseDec ~env ~depth (dec : A.dec) =
(match dec with
| A.FunDecs fundecs ->
List.iter fundecs ~f:(
fun (A.FunDec {name=_; params; result=_; body; pos=_}) ->
traverseFields ~env ~depth params;
traverseExp ~env ~depth body
)
| A.VarDec {name=_; escape=_; typ=_; init; pos=_} ->
traverseExp ~env ~depth init
| A.TypeDecs typedecs ->
List.iter typedecs ~f:(fun (A.TypeDec {name=_; ty; pos=_}) ->
match ty with
| A.NameTy _
| A.ArrayTy _ ->
()
| A.RecordTy fields ->
traverseFields ~env ~depth fields
)
)
and traverseFields ~env:_ ~depth:_ fields =
List.iter fields ~f:(fun (A.Field {name=_; escape=_; typ=_; pos=_}) -> ())
let find ~prog =
traverseExp ~env:Map.empty ~depth:0 prog
| null | https://raw.githubusercontent.com/xandkar/tiger.ml/cc540a7e2dfcee4411953075210a64de874b91e5/compiler/src/lib/tiger/tiger_semant_escape.ml | ocaml | module List = ListLabels
module A = Tiger_absyn
module Opt = Tiger_opt
module Map = Tiger_map
module Sym = Tiger_symbol
type info =
{ depth : int
; escapes : bool ref
}
type env =
(Sym.t, info) Map.t
let rec traverseExp ~(env : env) ~depth (exp : A.exp) =
(match exp with
| A.NilExp
| A.IntExp _
| A.StringExp _ ->
()
| A.CallExp {func=_; args; pos=_} ->
List.iter args ~f:(traverseExp ~env ~depth)
| A.OpExp {oper=_; left; right; pos=_} ->
traverseExp ~env ~depth left;
traverseExp ~env ~depth right
| A.RecordExp {fields=field_exps; typ=_; pos=_} ->
List.iter field_exps ~f:(fun (_, exp, _) -> traverseExp ~env ~depth exp)
| A.SeqExp exps ->
List.iter exps ~f:(fun (exp, _) -> traverseExp ~env ~depth exp)
| A.AssignExp {var; exp; pos=_} ->
traverseVar ~env ~depth var;
traverseExp ~env ~depth exp
| A.IfExp {test; then'; else'; pos=_} ->
traverseExp ~env ~depth test;
traverseExp ~env ~depth then';
Opt.iter else' ~f:(fun e -> traverseExp ~env ~depth e)
| A.WhileExp {test; body; pos=_} ->
traverseExp ~env ~depth test;
traverseExp ~env ~depth body
| A.ForExp {var=_; lo; hi; body; pos=_; escape=_} ->
traverseExp ~env ~depth lo;
traverseExp ~env ~depth hi;
traverseExp ~env ~depth body
| A.BreakExp _ ->
()
| A.LetExp {decs; body; pos=_} ->
traverseDecs ~env ~depth decs;
traverseExp ~env ~depth body
| A.ArrayExp {typ=_; size; init; pos=_} ->
traverseExp ~env ~depth size;
traverseExp ~env ~depth init
| A.VarExp var ->
traverseVar ~env ~depth var
)
and traverseVar ~env ~depth (var : A.var) =
(match var with
| A.SimpleVar _ ->
()
| A.FieldVar {var; symbol=_; pos=_} ->
traverseVar ~env ~depth var
| A.SubscriptVar {var; exp; pos=_} ->
traverseVar ~env ~depth var;
traverseExp ~env ~depth exp
)
and traverseDecs ~env ~depth (decs : A.dec list) =
List.iter decs ~f:(traverseDec ~env ~depth)
and traverseDec ~env ~depth (dec : A.dec) =
(match dec with
| A.FunDecs fundecs ->
List.iter fundecs ~f:(
fun (A.FunDec {name=_; params; result=_; body; pos=_}) ->
traverseFields ~env ~depth params;
traverseExp ~env ~depth body
)
| A.VarDec {name=_; escape=_; typ=_; init; pos=_} ->
traverseExp ~env ~depth init
| A.TypeDecs typedecs ->
List.iter typedecs ~f:(fun (A.TypeDec {name=_; ty; pos=_}) ->
match ty with
| A.NameTy _
| A.ArrayTy _ ->
()
| A.RecordTy fields ->
traverseFields ~env ~depth fields
)
)
and traverseFields ~env:_ ~depth:_ fields =
List.iter fields ~f:(fun (A.Field {name=_; escape=_; typ=_; pos=_}) -> ())
let find ~prog =
traverseExp ~env:Map.empty ~depth:0 prog
|
|
1b8dfb1cbc44af2967ad0d9310f134f7359e6a5cc5bcc849b41eb9b442cf53d7 | dyzsr/ocaml-selectml | datarepr.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
Compute constructor and label descriptions from type declarations ,
determining their representation .
determining their representation. *)
open Types
val extension_descr:
current_unit:string -> Path.t -> extension_constructor ->
constructor_description
val labels_of_type:
Path.t -> type_declaration ->
(Ident.t * label_description) list
val constructors_of_type:
current_unit:string -> Path.t -> type_declaration ->
(Ident.t * constructor_description) list
exception Constr_not_found
val find_constr_by_tag:
constructor_tag -> constructor_declaration list ->
constructor_declaration
val constructor_existentials :
constructor_arguments -> type_expr option -> type_expr list * type_expr list
(** Takes [cd_args] and [cd_res] from a [constructor_declaration] and
returns:
- the types of the constructor's arguments
- the existential variables introduced by the constructor
*)
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/typing/datarepr.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Takes [cd_args] and [cd_res] from a [constructor_declaration] and
returns:
- the types of the constructor's arguments
- the existential variables introduced by the constructor
| , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Compute constructor and label descriptions from type declarations ,
determining their representation .
determining their representation. *)
open Types
val extension_descr:
current_unit:string -> Path.t -> extension_constructor ->
constructor_description
val labels_of_type:
Path.t -> type_declaration ->
(Ident.t * label_description) list
val constructors_of_type:
current_unit:string -> Path.t -> type_declaration ->
(Ident.t * constructor_description) list
exception Constr_not_found
val find_constr_by_tag:
constructor_tag -> constructor_declaration list ->
constructor_declaration
val constructor_existentials :
constructor_arguments -> type_expr option -> type_expr list * type_expr list
|
ab551c5a56e013a20eb3a727763e7eac2b55f66cd3969c8718ccb5cca4f445ce | b0-system/b0 | b00.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
(** Build kernel *)
(** {1:b00 B00} *)
open B0_std
* Command line tools .
A tool is specified either by name , to be looked up via an
unspecified mecanism , or by a file path to an executable file . It
declares the environment variables it accesses in the process
environment and whether and how it supports response files .
By default declared environment variables are assumed to influence
the tool 's output and are part of the stamp used to memoize tool
spawns . If an environment variable is accessed by the tool but
does not influence its output it should be declared as
unstamped . Variables specifying the location of
{ { ! Tool.tmp_vars}temporary file directories } are good examples of
unstamped variables .
{ b Portability . } In order to maximize portability no [ .exe ]
suffix should be added to executable names on Windows , the
search procedure will add the suffix during the tool search
procedure if absent .
A tool is specified either by name, to be looked up via an
unspecified mecanism, or by a file path to an executable file. It
declares the environment variables it accesses in the process
environment and whether and how it supports response files.
By default declared environment variables are assumed to influence
the tool's output and are part of the stamp used to memoize tool
spawns. If an environment variable is accessed by the tool but
does not influence its output it should be declared as
unstamped. Variables specifying the location of
{{!Tool.tmp_vars}temporary file directories} are good examples of
unstamped variables.
{b Portability.} In order to maximize portability no [.exe]
suffix should be added to executable names on Windows, the
search procedure will add the suffix during the tool search
procedure if absent. *)
module Tool : sig
* { 1 : env Environment variables }
type env_vars = string list
(** The type for lists of environment variable names. *)
val tmp_vars : env_vars
* [ tmp_vars ] is [ [ " TMPDIR " ; " TEMP " ; " TMP " ] ] .
* { 1 : resp Response files }
type response_file
(** The type for response file specification. *)
val response_file_of :
(Cmd.t -> string) -> (Fpath.t -> Cmd.t) -> response_file
(** [response_file_of to_file cli] is a response file specification
that uses [to_file cmd] to convert the command line [cmd] to a
response file content and [cli f] a command line fragment to be
given to the tool so that it treats file [f] as a response
file. *)
val args0 : response_file
(** [args0] is response file support for tools that reads null byte
([0x00]) terminated arguments response files via an [-args0
FILE] command line synopsis. *)
* { 1 : tools Tools }
type t
(** The type for tools. *)
val v :
?response_file:response_file -> ?unstamped_vars:env_vars ->
?vars:env_vars -> Cmd.tool -> t
(** [v ~response_file ~unstamped_vars ~vars cmd] is a tool specified
by [cmd]. [vars] are the stamped variables accessed by the
tool (defaults to [[]]). [unstamped_vars] are the unstamped
variables accessed by the tool (defaults to {!tmp_vars}).
[response_file] defines the reponse file support for the tool
(if any). *)
val by_name :
?response_file:response_file -> ?unstamped_vars:env_vars ->
?vars:env_vars -> string -> t
(** [by_name] is like {!v} but reference the tool directly via a name.
@raise Invalid_argument if {!B0_std.Fpath.is_seg} [name] is [false]. *)
val name : t -> Cmd.tool
(** [name t] is [t]'s tool name. If this is a relative file path
with a single segment the tool is meant to be searched via an
external mecanism. *)
val vars : t -> env_vars
(** [vars t] are the stamped environment variables accessed by [t]. *)
val unstamped_vars : t -> env_vars
(** [unstamped_vars t] are the unstamped environment variables
accessed by [t]. *)
val response_file : t -> response_file option
(** [response_file t] is [t]'s response file specification (if any). *)
val read_env : t -> Os.Env.t -> Os.Env.t * Os.Env.t
(** [read_env t env] is (all, stamped) with [all] the
environment with the variables of [env] that are in [vars t]
and [unstamped_vars t] and [stamped] those of [vars t] only. *)
end
* Build environment .
Build environments specify the environment of tool spawns .
{ b TODO } Now that tool lookup moved to Memo ,
is it still worth sense to have that separate ?
Build environments specify the environment of tool spawns.
{b TODO} Now that tool lookup moved to Memo,
is it still worth sense to have that separate ? *)
module Env : sig
* { 1 : env Environment }
type t
(** The type for build environments. *)
val v : ?forced_env:Os.Env.t -> Os.Env.t -> t
* [ v ~lookup ~forced_env env ] is a build environment with :
{ ul
{ - [ forced_env ] is environment forced on any tool despite
what it declared to access , defaults to { ! B0_std.Os.Env.empty } }
{ - [ env ] the environment read by the tools ' declared environment
variables . } }
{ul
{- [forced_env] is environment forced on any tool despite
what it declared to access, defaults to {!B0_std.Os.Env.empty}}
{- [env] the environment read by the tools' declared environment
variables.}} *)
val env : t -> Os.Env.t
(** [env e] is [e]'s available spawn environment. *)
val forced_env : t -> Os.Env.t
(** [forced_env e] is [e]'s forced spawn environment. *)
end
(** Build memoizer.
A memoizer ties together and environment, an operation cache, a guard
and an executor. *)
module Memo : sig
type t
(** The type for memoizers. This ties together an environment, a
guard, an operation cache and an executor. *)
* { 1 : lookup Tool lookup }
type tool_lookup = t -> Cmd.tool -> (Fpath.t, string) result Fut.t
(** The type for tool lookups. Given a command line tool
{{!type:B0_std.Cmd.tool}specification} returns a file path to
the tool executable or an error message mentioning the tool if
it cannot be found. *)
val tool_lookup_of_os_env :
?sep:string -> ?var:string -> Os.Env.t -> tool_lookup
* [ env_tool_lookup ~sep ~var env ] is a tool lookup that gets the
value of the [ var ] variable in [ env ] treats it as a [ sep ]
separated { { ! B0_std . Fpath.list_of_search_path}search path } and
uses the result to lookup with { ! B0_std.Os.Cmd.get } with
the memo 's { ! win_exe } . [ var ] defaults to [ PATH ] and [ sep ] to
{ ! B0_std . } .
value of the [var] variable in [env] treats it as a [sep]
separated {{!B0_std.Fpath.list_of_search_path}search path} and
uses the result to lookup with {!B0_std.Os.Cmd.get} with
the memo's {!win_exe}. [var] defaults to [PATH] and [sep] to
{!B0_std.Fpath.search_path_sep}. *)
* { 1 : memo }
type feedback =
[ `Miss_tool of Tool.t * string
| `Op_complete of B000.Op.t ]
(** The type for memoizer feedback. FIXME remove `Miss_tool now
that we have notify operations. *)
val create :
?clock:Os.Mtime.counter -> ?cpu_clock:Os.Cpu.Time.counter ->
feedback:(feedback -> unit) -> cwd:Fpath.t ->
?win_exe:bool -> ?tool_lookup:tool_lookup -> Env.t -> B000.Guard.t ->
B000.Reviver.t -> B000.Exec.t -> t
val memo :
?hash_fun:(module Hash.T) -> ?win_exe:bool -> ?tool_lookup:tool_lookup ->
?env:Os.Env.t -> ?cwd:Fpath.t -> ?cache_dir:Fpath.t ->
?trash_dir:Fpath.t -> ?jobs:int ->
?feedback:([feedback | B000.Exec.feedback] -> unit) -> unit ->
(t, string) result
* [ memo ] is a simpler { ! create }
{ ul
{ - [ hash_fun ] defaults to { ! B0_std . Hash . Xxh3_64 } . }
{ - [ jobs ] defaults to { ! B0_std . Os . Cpu.logical_count } . }
{ - [ env ] defaults to { ! B0_std.Os.Env.current } }
{ - [ cwd ] defaults to { ! : B0_std . Os . Dir.cwd } }
{ - [ cache_dir ] defaults to [ Fpath.(cwd / " _ b0 " / " .cache " ) ] }
{ - [ trash_dir ] defaults to [ Fpath.(cwd / " _ b0 " / " .trash " ) ] }
{ - [ feedback ] defaults to a nop . } }
{ul
{- [hash_fun] defaults to {!B0_std.Hash.Xxh3_64}.}
{- [jobs] defaults to {!B0_std.Os.Cpu.logical_count}.}
{- [env] defaults to {!B0_std.Os.Env.current}}
{- [cwd] defaults to {!val:B0_std.Os.Dir.cwd}}
{- [cache_dir] defaults to [Fpath.(cwd / "_b0" / ".cache")]}
{- [trash_dir] defaults to [Fpath.(cwd / "_b0" / ".trash")]}
{- [feedback] defaults to a nop.}} *)
val clock : t -> Os.Mtime.counter
(** [clock m] is [m]'s clock. *)
val cpu_clock : t -> Os.Cpu.Time.counter
(** [cpu_clock m] is [m]'s cpu clock. *)
val win_exe : t -> bool
(** [win_exe m] is [true] if we spawn windows executables. This
affects tool lookups. Defaults to {!Sys.win32}. *)
val tool_lookup : t -> tool_lookup
(** [tool_lookup m] is [m]'s tool lookup function. *)
val env : t -> Env.t
(** [env m] is [m]'s environment. *)
val reviver : t -> B000.Reviver.t
(** [reviver m] is [m]'s reviver. *)
val guard : t -> B000.Guard.t
(** [guard m] is [m]'s guard. *)
val exec : t -> B000.Exec.t
(** [exec m] is [m]'s executors. *)
val trash : t -> B000.Trash.t
(** [trash m] is [m]'s trash. *)
val has_failures : t -> bool
* [ has_failures m ] is [ true ] iff at least one operation has failed .
val hash_string : t -> string -> Hash.t
(** [hash_string m s] is {!B000.Reviver.hash_string}[ (reviver m) s]. *)
val hash_file : t -> Fpath.t -> (Hash.t, string) result
(** [hash_file m f] is {!B000.Reviver.hash_file}[ (reviver m) f].
Note that these file hashes operations are memoized. *)
val stir : block:bool -> t -> unit
(** [stir ~block m] runs the memoizer a bit. If [block] is [true]
blocks until the memoizer is stuck with no operation to execute. *)
val status : t -> (unit, B000.Op.aggregate_error) result
(** [status m] looks for aggregate errors in [m] in [ops m], see
{!B000.Op.aggregate_error} for details.
Usually called after a blocking {!stir} to check everything
executed as expected. The function itself has no effect more
operations can be on [m] afterwards. If you are only interested
in checking if a failure occured in the memo {!has_failures} is
faster. *)
val delete_trash : block:bool -> t -> (unit, string) result
(** [delete_trash ~block m] is {!B000.Trash.delete}[ ~block (trash m)]. *)
val ops : t -> B000.Op.t list
(** [ops m] is the list of operations that were submitted to the
memoizer *)
(** {1:marks Activity marks}
Activity marks are just identifiers used for UI purposes to
watermark the activity – notably build operations – occuring in
the memo. *)
val mark : t -> string
(** [mark m] is [m]'s mark. *)
val with_mark : t -> string -> t
(** [mark m mark] is [m] but operations performed on [m] are marked by
[mark]. *)
* { 2 : proc Procedures }
val run_proc : t -> (unit -> unit Fut.t) -> unit
(** [run m proc] calls [proc ()] and handles any {!fail}ure. This
also catches non-asynchronous uncaught exceptions and turns them
into [`Fail] notification operations. *)
val fail : t -> ('a, Format.formatter, unit, 'b) format4 -> 'a
(** [fail m fmt ...] fails the procedure via a {!notify} operation. *)
val fail_if_error : t -> ('a, string) result -> 'a
* [ fail_if_error m r ] is [ v ] if [ r ] is [ Ok v ] and [ fail m " % s " e ] if
[ r ] is [ Error _ ] .
[r] is [Error _]. *)
* { 1 : feedback Feedback }
{ b XXX } This needs a bit of reviewing .
{b XXX} This needs a bit of reviewing. *)
val notify :
?k:(unit -> unit) -> t -> [ `Fail | `Warn | `Start | `End | `Info ] ->
('a, Format.formatter, unit, unit) format4 -> 'a
(** [notify m kind msg] is a notification [msg] of kind [kind]. Note that
a [`Fail] notification will entail an an {!has_failures} on the memo,
see also {!fail} and {!fail_if_error}. *)
val notify_if_error :
t -> [ `Fail | `Warn | `Start | `End | `Info ] -> use:'a ->
('a, string) result -> 'a
* [ notify_if_error m kind r ] is [ v ] if [ r ] is [ Ok v ] . If [ r ]
is [ Error e ] , a notification of kind [ kind ] is added to [ m ]
and [ use ] is returned . Note that a [ ` Fail ] notification will entail
an { ! has_failures } on the memo , see also { ! fail } and { ! fail_if_error } .
is [Error e], a notification of kind [kind] is added to [m]
and [use] is returned. Note that a [`Fail] notification will entail
an {!has_failures} on the memo, see also {!fail} and {!fail_if_error}. *)
* { 1 : files Files and directories }
val file_ready : t -> Fpath.t -> unit
(** [ready m p] declares path [p] to be ready, that is exists and is
up-to-date in [b]. This is typically used with source files
and files external to the build (e.g. installed libraries). *)
val read : t -> Fpath.t -> string Fut.t
(** [read m file k] is a future that determines with the contents
[s] of file [file] when it becomes ready in [m]. *)
val write :
t -> ?stamp:string -> ?reads:Fpath.t list -> ?mode:int ->
Fpath.t -> (unit -> (string, string) result) -> unit
(** [write m ~reads file w] writes [file] with data [w ()] and mode
[mode] (defaults to [0o644]) when [reads] are ready. [w]'s
result must only depend on [reads] and [stamp] (defaults to
[""]). *)
val copy :
t -> ?mode:int -> ?linenum:int -> src:Fpath.t -> Fpath.t -> unit
* [ copy m ~mode ? linenum ~src dst ] copies file [ src ] to [ dst ] with
mode [ mode ] ( defaults to [ 0o644 ] ) when [ src ] is ready . If [ linenum ]
is specified , the following line number directive is prependend
in [ dst ] to the contents of [ src ] :
{ [
# line $ ( linenum ) " $ ( src ) "
] }
mode [mode] (defaults to [0o644]) when [src] is ready. If [linenum]
is specified, the following line number directive is prependend
in [dst] to the contents of [src]:
{[
#line $(linenum) "$(src)"
]} *)
val mkdir : t -> ?mode:int -> Fpath.t -> unit Fut.t
* [ mkdir m dir p ] is a future that determines with [ ( ) ] when the
directory path [ p ] has been created with mode [ mode ] ( defaults
to [ 0o755 ] ) . The behaviour with respect to file permission
of intermediate path segments matches { ! B0_std.Os.Dir.create } .
directory path [p] has been created with mode [mode] (defaults
to [0o755]). The behaviour with respect to file permission
of intermediate path segments matches {!B0_std.Os.Dir.create}. *)
val delete : t -> Fpath.t -> unit Fut.t
(** [delete m p] is a future that determines with [()] when path [p]
is deleted (trashed in fact) and free to reuse. *)
val wait_files : t -> Fpath.t list -> unit Fut.t
(** [wait_files m files] is a future that deterines with [()]
when all [files] are ready in [m]. {b FIXME} Unclear whether
we really want this. *)
* { 1 : spawn tool spawns }
{ b TODO . } Ca n't we simplify the cmd / tool / tool_lookup dance ? .
{b TODO.} Can't we simplify the cmd/tool/tool_lookup dance ?. *)
type cmd
(** The type for memoized tool invocations. *)
type tool
(** The type for memoized tools. *)
val tool : t -> Tool.t -> (Cmd.t -> cmd)
(** [tool m t] is tool [t] memoized. Use the resulting function
to spawn the tool with the given arguments.
{b TODO} explain better how this all works. If the path given
to [Tool.t] is not made of a single path segment it is not
search in the environmet and it is the duty of the client
to ensure it gets ready at some point. Either by a direct
call to {!file_ready} or by another file write. *)
val tool_opt : t -> Tool.t -> (Cmd.t -> cmd) option Fut.t
* [ tool_opt m t ] is like { ! : tool } , except [ None ] is returned
if the tool can not be found . y
if the tool cannot be found. y*)
val spawn :
t -> ?stamp:string -> ?reads:Fpath.t list -> ?writes:Fpath.t list ->
?env:Os.Env.t -> ?cwd:Fpath.t -> ?stdin:Fpath.t ->
?stdout:B000.Op.Spawn.stdo -> ?stderr:B000.Op.Spawn.stdo ->
?success_exits:B000.Op.Spawn.success_exits ->
?post_exec:(B000.Op.t -> unit) ->
?k:(int -> unit) -> cmd -> unit
* [ spawn m ~reads ~writes ~env ~cwd ~stdin ~stdout ~stderr
~success_exits cmd ] spawns [ cmd ] once [ reads ] files are ready
and makes files [ writes ] ready if the spawn succeeds and the
file exists . The rest of the arguments are :
{ ul
{ - [ stdin ] reads input from the given file . If unspecified reads
from the standard input of the program running the build . { b
Warning . } The file is not automatically added to [ reads ] ,
this allows for example to use { ! B0_std.Fpath.null } . }
{ - [ stdout ] and [ stderr ] , the redirections for the standard
outputs of the command , see { ! } . Path to files are
created if needed . { b Warning . } File redirections
are not automatically added to [ writes ] ; this allows for example
to use { ! B0_std.Fpath.null } . }
{ - [ success_exits ] the exit codes that determine if the build operation
is successful ( defaults to [ 0 ] , use [ [ ] ] to always succeed ) }
{ - [ env ] , environment variables added to the build environment .
This overrides environment variables read by the tool in the
build environment except for forced one . It also allows to
specify environment that may not be mentioned by the running
tool 's { { ! Tool.v}environment specification } . }
{ - [ cwd ] the current working directory . Default is the memo 's [ cwd ] . In
general it 's better to avoid using relative file paths and
tweaking the [ cwd ] . Construct make your paths absolute
and invocations independent from the [ cwd ] . }
{ - [ post_exec ] , if specified is called with the build operation
after it has been executed or revived . If it was executed
this is called before the operation gets recorded . It can
be used to define the [ reads ] and [ writes ] of the operation
if they are difficult to find out before hand . { b Do not }
access [ m ] in that function . }
{ - [ k ] , if specified a function invoked once the spawn has succesfully
executed with the exit code . }
{ - [ stamp ] is used for caching if two spawns diff only in their
stamp they will cache to different keys . This can be used to
memoize tool whose outputs may not entirely depend on the environment ,
the cli stamp and the the content of read files . } }
{ b Note . } If the tool spawn acts on a sort of " main " file
( e.g. a source file ) it should be specified as the first element
of [ reads ] , this is interpreted specially by certain build
tracer .
~success_exits cmd] spawns [cmd] once [reads] files are ready
and makes files [writes] ready if the spawn succeeds and the
file exists. The rest of the arguments are:
{ul
{- [stdin] reads input from the given file. If unspecified reads
from the standard input of the program running the build. {b
Warning.} The file is not automatically added to [reads],
this allows for example to use {!B0_std.Fpath.null}.}
{- [stdout] and [stderr], the redirections for the standard
outputs of the command, see {!B000.Op.Spawn.stdo}. Path to files are
created if needed. {b Warning.} File redirections
are not automatically added to [writes]; this allows for example
to use {!B0_std.Fpath.null}.}
{- [success_exits] the exit codes that determine if the build operation
is successful (defaults to [0], use [[]] to always succeed)}
{- [env], environment variables added to the build environment.
This overrides environment variables read by the tool in the
build environment except for forced one. It also allows to
specify environment that may not be mentioned by the running
tool's {{!Tool.v}environment specification}.}
{- [cwd] the current working directory. Default is the memo's [cwd]. In
general it's better to avoid using relative file paths and
tweaking the [cwd]. Construct make your paths absolute
and invocations independent from the [cwd].}
{- [post_exec], if specified is called with the build operation
after it has been executed or revived. If it was executed
this is called before the operation gets recorded. It can
be used to define the [reads] and [writes] of the operation
if they are difficult to find out before hand. {b Do not}
access [m] in that function.}
{- [k], if specified a function invoked once the spawn has succesfully
executed with the exit code.}
{- [stamp] is used for caching if two spawns diff only in their
stamp they will cache to different keys. This can be used to
memoize tool whose outputs may not entirely depend on the environment,
the cli stamp and the the content of read files.}}
{b Note.} If the tool spawn acts on a sort of "main" file
(e.g. a source file) it should be specified as the first element
of [reads], this is interpreted specially by certain build
tracer. *)
val spawn' :
t -> ?stamp:string -> ?reads:Fpath.t list -> writes_root:Fpath.t ->
?writes:(B000.Op.t -> Fpath.t list) ->
?env:Os.Env.t -> ?cwd:Fpath.t -> ?stdin:Fpath.t ->
?stdout:B000.Op.Spawn.stdo -> ?stderr:B000.Op.Spawn.stdo ->
?success_exits:B000.Op.Spawn.success_exits ->
?k:(int -> unit) -> cmd -> unit
* [ spawn ' ] is like { ! - spawn } except the actual file paths
written by the spawn need not be determined before the
spawn . Only the root directory of writes need to be specified
via [ writes_root ] . After the spawn executes the writes can be
determined via the [ writes ] function , the returned paths must be
absolute and be prefixed by [ writes_root ] ( defaults to
recursively list all the files rootet in [ writes_root ] ) .
written by the spawn need not be determined before the
spawn. Only the root directory of writes need to be specified
via [writes_root]. After the spawn executes the writes can be
determined via the [writes] function, the returned paths must be
absolute and be prefixed by [writes_root] (defaults to
recursively list all the files rootet in [writes_root]). *)
end
* Lazy immutable stores .
These stores provide access to immutable , lazily determined , typed
key - value bindings .
The value of a key in a store is defined either :
{ ul
{ - Explicitly when the store is { { ! Store.create}created } . }
{ - Lazily on the first key { { ! Store.get}access } via a key determination
function
specified at { { ! Store.val - key}key creation time } . } }
Once determined the value of a key in the store never changes .
{ b XXX . } Maybe move that at the level .
These stores provide access to immutable, lazily determined, typed
key-value bindings.
The value of a key in a store is defined either:
{ul
{- Explicitly when the store is {{!Store.create}created}.}
{- Lazily on the first key {{!Store.get}access} via a key determination
function
specified at {{!Store.val-key}key creation time}.}}
Once determined the value of a key in the store never changes.
{b XXX.} Maybe move that at the B0 level. *)
module Store : sig
* { 1 : stores Stores }
type 'a key
(** The type for keys binding values of type ['a]. *)
type binding = B : 'a key * 'a -> binding (** *)
(** The type for store bindings. A key and its value. *)
type t
(** The type for stores. *)
val create : Memo.t -> dir:Fpath.t -> binding list -> t
* [ create memo bs ] is a store with predefined bindings [ bs ] .
If a key is mentioned more than once in [ bs ] the last binding
takes over . The store uses [ memo ] to determine other keys as
{ { ! get}needed } . [ dir ] is a scratch directory used by key determination
functions to write memoized file outputs .
If a key is mentioned more than once in [bs] the last binding
takes over. The store uses [memo] to determine other keys as
{{!get}needed}. [dir] is a scratch directory used by key determination
functions to write memoized file outputs. *)
val memo : t -> Memo.t
(** [memo s] is [s]'s memo as given on {!create}. *)
val dir : t -> Fpath.t
(** [dir s] is the scratch directory of [s]. Key determination functions
using this directory to write files should do so using nice file name
prefixes (e.g. lowercased module or lib names) to avoid name
clashes. *)
val key : ?mark:string -> (t -> Memo.t -> 'a Fut.t) -> 'a key
* [ key ~mark det ] is a new key whose value is determined on
{ { ! get}access } by the future :
{ [
det s ( Memo.with_mark mark ( Store.memo s ) )
] }
[ mark ] defaults to [ " " ] .
{{!get}access} by the future:
{[
det s (Memo.with_mark mark (Store.memo s))
]}
[mark] defaults to [""]. *)
val get : t -> 'a key -> 'a Fut.t
* [ get s k ] is a future that dermines with the value of [ k ] in
[ s ] .
[s]. *)
(**/**)
val set : t -> 'a key -> 'a -> unit
(** [set s k v] sets value [k] to [v] in [s]. {b Warning.} In general
this should not be used but it may be useful to initialize the
store. In particular this will raise [Invalid_argument] if [k] is
already set in [s]. *)
(**/**)
end
---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/b0-system/b0/403364829e51d8bb0c1c3fddcfc7d240a4714e4c/src/b00/b00.mli | ocaml | * Build kernel
* {1:b00 B00}
* The type for lists of environment variable names.
* The type for response file specification.
* [response_file_of to_file cli] is a response file specification
that uses [to_file cmd] to convert the command line [cmd] to a
response file content and [cli f] a command line fragment to be
given to the tool so that it treats file [f] as a response
file.
* [args0] is response file support for tools that reads null byte
([0x00]) terminated arguments response files via an [-args0
FILE] command line synopsis.
* The type for tools.
* [v ~response_file ~unstamped_vars ~vars cmd] is a tool specified
by [cmd]. [vars] are the stamped variables accessed by the
tool (defaults to [[]]). [unstamped_vars] are the unstamped
variables accessed by the tool (defaults to {!tmp_vars}).
[response_file] defines the reponse file support for the tool
(if any).
* [by_name] is like {!v} but reference the tool directly via a name.
@raise Invalid_argument if {!B0_std.Fpath.is_seg} [name] is [false].
* [name t] is [t]'s tool name. If this is a relative file path
with a single segment the tool is meant to be searched via an
external mecanism.
* [vars t] are the stamped environment variables accessed by [t].
* [unstamped_vars t] are the unstamped environment variables
accessed by [t].
* [response_file t] is [t]'s response file specification (if any).
* [read_env t env] is (all, stamped) with [all] the
environment with the variables of [env] that are in [vars t]
and [unstamped_vars t] and [stamped] those of [vars t] only.
* The type for build environments.
* [env e] is [e]'s available spawn environment.
* [forced_env e] is [e]'s forced spawn environment.
* Build memoizer.
A memoizer ties together and environment, an operation cache, a guard
and an executor.
* The type for memoizers. This ties together an environment, a
guard, an operation cache and an executor.
* The type for tool lookups. Given a command line tool
{{!type:B0_std.Cmd.tool}specification} returns a file path to
the tool executable or an error message mentioning the tool if
it cannot be found.
* The type for memoizer feedback. FIXME remove `Miss_tool now
that we have notify operations.
* [clock m] is [m]'s clock.
* [cpu_clock m] is [m]'s cpu clock.
* [win_exe m] is [true] if we spawn windows executables. This
affects tool lookups. Defaults to {!Sys.win32}.
* [tool_lookup m] is [m]'s tool lookup function.
* [env m] is [m]'s environment.
* [reviver m] is [m]'s reviver.
* [guard m] is [m]'s guard.
* [exec m] is [m]'s executors.
* [trash m] is [m]'s trash.
* [hash_string m s] is {!B000.Reviver.hash_string}[ (reviver m) s].
* [hash_file m f] is {!B000.Reviver.hash_file}[ (reviver m) f].
Note that these file hashes operations are memoized.
* [stir ~block m] runs the memoizer a bit. If [block] is [true]
blocks until the memoizer is stuck with no operation to execute.
* [status m] looks for aggregate errors in [m] in [ops m], see
{!B000.Op.aggregate_error} for details.
Usually called after a blocking {!stir} to check everything
executed as expected. The function itself has no effect more
operations can be on [m] afterwards. If you are only interested
in checking if a failure occured in the memo {!has_failures} is
faster.
* [delete_trash ~block m] is {!B000.Trash.delete}[ ~block (trash m)].
* [ops m] is the list of operations that were submitted to the
memoizer
* {1:marks Activity marks}
Activity marks are just identifiers used for UI purposes to
watermark the activity – notably build operations – occuring in
the memo.
* [mark m] is [m]'s mark.
* [mark m mark] is [m] but operations performed on [m] are marked by
[mark].
* [run m proc] calls [proc ()] and handles any {!fail}ure. This
also catches non-asynchronous uncaught exceptions and turns them
into [`Fail] notification operations.
* [fail m fmt ...] fails the procedure via a {!notify} operation.
* [notify m kind msg] is a notification [msg] of kind [kind]. Note that
a [`Fail] notification will entail an an {!has_failures} on the memo,
see also {!fail} and {!fail_if_error}.
* [ready m p] declares path [p] to be ready, that is exists and is
up-to-date in [b]. This is typically used with source files
and files external to the build (e.g. installed libraries).
* [read m file k] is a future that determines with the contents
[s] of file [file] when it becomes ready in [m].
* [write m ~reads file w] writes [file] with data [w ()] and mode
[mode] (defaults to [0o644]) when [reads] are ready. [w]'s
result must only depend on [reads] and [stamp] (defaults to
[""]).
* [delete m p] is a future that determines with [()] when path [p]
is deleted (trashed in fact) and free to reuse.
* [wait_files m files] is a future that deterines with [()]
when all [files] are ready in [m]. {b FIXME} Unclear whether
we really want this.
* The type for memoized tool invocations.
* The type for memoized tools.
* [tool m t] is tool [t] memoized. Use the resulting function
to spawn the tool with the given arguments.
{b TODO} explain better how this all works. If the path given
to [Tool.t] is not made of a single path segment it is not
search in the environmet and it is the duty of the client
to ensure it gets ready at some point. Either by a direct
call to {!file_ready} or by another file write.
* The type for keys binding values of type ['a].
*
* The type for store bindings. A key and its value.
* The type for stores.
* [memo s] is [s]'s memo as given on {!create}.
* [dir s] is the scratch directory of [s]. Key determination functions
using this directory to write files should do so using nice file name
prefixes (e.g. lowercased module or lib names) to avoid name
clashes.
*/*
* [set s k v] sets value [k] to [v] in [s]. {b Warning.} In general
this should not be used but it may be useful to initialize the
store. In particular this will raise [Invalid_argument] if [k] is
already set in [s].
*/* | ---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open B0_std
* Command line tools .
A tool is specified either by name , to be looked up via an
unspecified mecanism , or by a file path to an executable file . It
declares the environment variables it accesses in the process
environment and whether and how it supports response files .
By default declared environment variables are assumed to influence
the tool 's output and are part of the stamp used to memoize tool
spawns . If an environment variable is accessed by the tool but
does not influence its output it should be declared as
unstamped . Variables specifying the location of
{ { ! Tool.tmp_vars}temporary file directories } are good examples of
unstamped variables .
{ b Portability . } In order to maximize portability no [ .exe ]
suffix should be added to executable names on Windows , the
search procedure will add the suffix during the tool search
procedure if absent .
A tool is specified either by name, to be looked up via an
unspecified mecanism, or by a file path to an executable file. It
declares the environment variables it accesses in the process
environment and whether and how it supports response files.
By default declared environment variables are assumed to influence
the tool's output and are part of the stamp used to memoize tool
spawns. If an environment variable is accessed by the tool but
does not influence its output it should be declared as
unstamped. Variables specifying the location of
{{!Tool.tmp_vars}temporary file directories} are good examples of
unstamped variables.
{b Portability.} In order to maximize portability no [.exe]
suffix should be added to executable names on Windows, the
search procedure will add the suffix during the tool search
procedure if absent. *)
module Tool : sig
* { 1 : env Environment variables }
type env_vars = string list
val tmp_vars : env_vars
* [ tmp_vars ] is [ [ " TMPDIR " ; " TEMP " ; " TMP " ] ] .
* { 1 : resp Response files }
type response_file
val response_file_of :
(Cmd.t -> string) -> (Fpath.t -> Cmd.t) -> response_file
val args0 : response_file
* { 1 : tools Tools }
type t
val v :
?response_file:response_file -> ?unstamped_vars:env_vars ->
?vars:env_vars -> Cmd.tool -> t
val by_name :
?response_file:response_file -> ?unstamped_vars:env_vars ->
?vars:env_vars -> string -> t
val name : t -> Cmd.tool
val vars : t -> env_vars
val unstamped_vars : t -> env_vars
val response_file : t -> response_file option
val read_env : t -> Os.Env.t -> Os.Env.t * Os.Env.t
end
* Build environment .
Build environments specify the environment of tool spawns .
{ b TODO } Now that tool lookup moved to Memo ,
is it still worth sense to have that separate ?
Build environments specify the environment of tool spawns.
{b TODO} Now that tool lookup moved to Memo,
is it still worth sense to have that separate ? *)
module Env : sig
* { 1 : env Environment }
type t
val v : ?forced_env:Os.Env.t -> Os.Env.t -> t
* [ v ~lookup ~forced_env env ] is a build environment with :
{ ul
{ - [ forced_env ] is environment forced on any tool despite
what it declared to access , defaults to { ! B0_std.Os.Env.empty } }
{ - [ env ] the environment read by the tools ' declared environment
variables . } }
{ul
{- [forced_env] is environment forced on any tool despite
what it declared to access, defaults to {!B0_std.Os.Env.empty}}
{- [env] the environment read by the tools' declared environment
variables.}} *)
val env : t -> Os.Env.t
val forced_env : t -> Os.Env.t
end
module Memo : sig
type t
* { 1 : lookup Tool lookup }
type tool_lookup = t -> Cmd.tool -> (Fpath.t, string) result Fut.t
val tool_lookup_of_os_env :
?sep:string -> ?var:string -> Os.Env.t -> tool_lookup
* [ env_tool_lookup ~sep ~var env ] is a tool lookup that gets the
value of the [ var ] variable in [ env ] treats it as a [ sep ]
separated { { ! B0_std . Fpath.list_of_search_path}search path } and
uses the result to lookup with { ! B0_std.Os.Cmd.get } with
the memo 's { ! win_exe } . [ var ] defaults to [ PATH ] and [ sep ] to
{ ! B0_std . } .
value of the [var] variable in [env] treats it as a [sep]
separated {{!B0_std.Fpath.list_of_search_path}search path} and
uses the result to lookup with {!B0_std.Os.Cmd.get} with
the memo's {!win_exe}. [var] defaults to [PATH] and [sep] to
{!B0_std.Fpath.search_path_sep}. *)
* { 1 : memo }
type feedback =
[ `Miss_tool of Tool.t * string
| `Op_complete of B000.Op.t ]
val create :
?clock:Os.Mtime.counter -> ?cpu_clock:Os.Cpu.Time.counter ->
feedback:(feedback -> unit) -> cwd:Fpath.t ->
?win_exe:bool -> ?tool_lookup:tool_lookup -> Env.t -> B000.Guard.t ->
B000.Reviver.t -> B000.Exec.t -> t
val memo :
?hash_fun:(module Hash.T) -> ?win_exe:bool -> ?tool_lookup:tool_lookup ->
?env:Os.Env.t -> ?cwd:Fpath.t -> ?cache_dir:Fpath.t ->
?trash_dir:Fpath.t -> ?jobs:int ->
?feedback:([feedback | B000.Exec.feedback] -> unit) -> unit ->
(t, string) result
* [ memo ] is a simpler { ! create }
{ ul
{ - [ hash_fun ] defaults to { ! B0_std . Hash . Xxh3_64 } . }
{ - [ jobs ] defaults to { ! B0_std . Os . Cpu.logical_count } . }
{ - [ env ] defaults to { ! B0_std.Os.Env.current } }
{ - [ cwd ] defaults to { ! : B0_std . Os . Dir.cwd } }
{ - [ cache_dir ] defaults to [ Fpath.(cwd / " _ b0 " / " .cache " ) ] }
{ - [ trash_dir ] defaults to [ Fpath.(cwd / " _ b0 " / " .trash " ) ] }
{ - [ feedback ] defaults to a nop . } }
{ul
{- [hash_fun] defaults to {!B0_std.Hash.Xxh3_64}.}
{- [jobs] defaults to {!B0_std.Os.Cpu.logical_count}.}
{- [env] defaults to {!B0_std.Os.Env.current}}
{- [cwd] defaults to {!val:B0_std.Os.Dir.cwd}}
{- [cache_dir] defaults to [Fpath.(cwd / "_b0" / ".cache")]}
{- [trash_dir] defaults to [Fpath.(cwd / "_b0" / ".trash")]}
{- [feedback] defaults to a nop.}} *)
val clock : t -> Os.Mtime.counter
val cpu_clock : t -> Os.Cpu.Time.counter
val win_exe : t -> bool
val tool_lookup : t -> tool_lookup
val env : t -> Env.t
val reviver : t -> B000.Reviver.t
val guard : t -> B000.Guard.t
val exec : t -> B000.Exec.t
val trash : t -> B000.Trash.t
val has_failures : t -> bool
* [ has_failures m ] is [ true ] iff at least one operation has failed .
val hash_string : t -> string -> Hash.t
val hash_file : t -> Fpath.t -> (Hash.t, string) result
val stir : block:bool -> t -> unit
val status : t -> (unit, B000.Op.aggregate_error) result
val delete_trash : block:bool -> t -> (unit, string) result
val ops : t -> B000.Op.t list
val mark : t -> string
val with_mark : t -> string -> t
* { 2 : proc Procedures }
val run_proc : t -> (unit -> unit Fut.t) -> unit
val fail : t -> ('a, Format.formatter, unit, 'b) format4 -> 'a
val fail_if_error : t -> ('a, string) result -> 'a
* [ fail_if_error m r ] is [ v ] if [ r ] is [ Ok v ] and [ fail m " % s " e ] if
[ r ] is [ Error _ ] .
[r] is [Error _]. *)
* { 1 : feedback Feedback }
{ b XXX } This needs a bit of reviewing .
{b XXX} This needs a bit of reviewing. *)
val notify :
?k:(unit -> unit) -> t -> [ `Fail | `Warn | `Start | `End | `Info ] ->
('a, Format.formatter, unit, unit) format4 -> 'a
val notify_if_error :
t -> [ `Fail | `Warn | `Start | `End | `Info ] -> use:'a ->
('a, string) result -> 'a
* [ notify_if_error m kind r ] is [ v ] if [ r ] is [ Ok v ] . If [ r ]
is [ Error e ] , a notification of kind [ kind ] is added to [ m ]
and [ use ] is returned . Note that a [ ` Fail ] notification will entail
an { ! has_failures } on the memo , see also { ! fail } and { ! fail_if_error } .
is [Error e], a notification of kind [kind] is added to [m]
and [use] is returned. Note that a [`Fail] notification will entail
an {!has_failures} on the memo, see also {!fail} and {!fail_if_error}. *)
* { 1 : files Files and directories }
val file_ready : t -> Fpath.t -> unit
val read : t -> Fpath.t -> string Fut.t
val write :
t -> ?stamp:string -> ?reads:Fpath.t list -> ?mode:int ->
Fpath.t -> (unit -> (string, string) result) -> unit
val copy :
t -> ?mode:int -> ?linenum:int -> src:Fpath.t -> Fpath.t -> unit
* [ copy m ~mode ? linenum ~src dst ] copies file [ src ] to [ dst ] with
mode [ mode ] ( defaults to [ 0o644 ] ) when [ src ] is ready . If [ linenum ]
is specified , the following line number directive is prependend
in [ dst ] to the contents of [ src ] :
{ [
# line $ ( linenum ) " $ ( src ) "
] }
mode [mode] (defaults to [0o644]) when [src] is ready. If [linenum]
is specified, the following line number directive is prependend
in [dst] to the contents of [src]:
{[
#line $(linenum) "$(src)"
]} *)
val mkdir : t -> ?mode:int -> Fpath.t -> unit Fut.t
* [ mkdir m dir p ] is a future that determines with [ ( ) ] when the
directory path [ p ] has been created with mode [ mode ] ( defaults
to [ 0o755 ] ) . The behaviour with respect to file permission
of intermediate path segments matches { ! B0_std.Os.Dir.create } .
directory path [p] has been created with mode [mode] (defaults
to [0o755]). The behaviour with respect to file permission
of intermediate path segments matches {!B0_std.Os.Dir.create}. *)
val delete : t -> Fpath.t -> unit Fut.t
val wait_files : t -> Fpath.t list -> unit Fut.t
* { 1 : spawn tool spawns }
{ b TODO . } Ca n't we simplify the cmd / tool / tool_lookup dance ? .
{b TODO.} Can't we simplify the cmd/tool/tool_lookup dance ?. *)
type cmd
type tool
val tool : t -> Tool.t -> (Cmd.t -> cmd)
val tool_opt : t -> Tool.t -> (Cmd.t -> cmd) option Fut.t
* [ tool_opt m t ] is like { ! : tool } , except [ None ] is returned
if the tool can not be found . y
if the tool cannot be found. y*)
val spawn :
t -> ?stamp:string -> ?reads:Fpath.t list -> ?writes:Fpath.t list ->
?env:Os.Env.t -> ?cwd:Fpath.t -> ?stdin:Fpath.t ->
?stdout:B000.Op.Spawn.stdo -> ?stderr:B000.Op.Spawn.stdo ->
?success_exits:B000.Op.Spawn.success_exits ->
?post_exec:(B000.Op.t -> unit) ->
?k:(int -> unit) -> cmd -> unit
* [ spawn m ~reads ~writes ~env ~cwd ~stdin ~stdout ~stderr
~success_exits cmd ] spawns [ cmd ] once [ reads ] files are ready
and makes files [ writes ] ready if the spawn succeeds and the
file exists . The rest of the arguments are :
{ ul
{ - [ stdin ] reads input from the given file . If unspecified reads
from the standard input of the program running the build . { b
Warning . } The file is not automatically added to [ reads ] ,
this allows for example to use { ! B0_std.Fpath.null } . }
{ - [ stdout ] and [ stderr ] , the redirections for the standard
outputs of the command , see { ! } . Path to files are
created if needed . { b Warning . } File redirections
are not automatically added to [ writes ] ; this allows for example
to use { ! B0_std.Fpath.null } . }
{ - [ success_exits ] the exit codes that determine if the build operation
is successful ( defaults to [ 0 ] , use [ [ ] ] to always succeed ) }
{ - [ env ] , environment variables added to the build environment .
This overrides environment variables read by the tool in the
build environment except for forced one . It also allows to
specify environment that may not be mentioned by the running
tool 's { { ! Tool.v}environment specification } . }
{ - [ cwd ] the current working directory . Default is the memo 's [ cwd ] . In
general it 's better to avoid using relative file paths and
tweaking the [ cwd ] . Construct make your paths absolute
and invocations independent from the [ cwd ] . }
{ - [ post_exec ] , if specified is called with the build operation
after it has been executed or revived . If it was executed
this is called before the operation gets recorded . It can
be used to define the [ reads ] and [ writes ] of the operation
if they are difficult to find out before hand . { b Do not }
access [ m ] in that function . }
{ - [ k ] , if specified a function invoked once the spawn has succesfully
executed with the exit code . }
{ - [ stamp ] is used for caching if two spawns diff only in their
stamp they will cache to different keys . This can be used to
memoize tool whose outputs may not entirely depend on the environment ,
the cli stamp and the the content of read files . } }
{ b Note . } If the tool spawn acts on a sort of " main " file
( e.g. a source file ) it should be specified as the first element
of [ reads ] , this is interpreted specially by certain build
tracer .
~success_exits cmd] spawns [cmd] once [reads] files are ready
and makes files [writes] ready if the spawn succeeds and the
file exists. The rest of the arguments are:
{ul
{- [stdin] reads input from the given file. If unspecified reads
from the standard input of the program running the build. {b
Warning.} The file is not automatically added to [reads],
this allows for example to use {!B0_std.Fpath.null}.}
{- [stdout] and [stderr], the redirections for the standard
outputs of the command, see {!B000.Op.Spawn.stdo}. Path to files are
created if needed. {b Warning.} File redirections
are not automatically added to [writes]; this allows for example
to use {!B0_std.Fpath.null}.}
{- [success_exits] the exit codes that determine if the build operation
is successful (defaults to [0], use [[]] to always succeed)}
{- [env], environment variables added to the build environment.
This overrides environment variables read by the tool in the
build environment except for forced one. It also allows to
specify environment that may not be mentioned by the running
tool's {{!Tool.v}environment specification}.}
{- [cwd] the current working directory. Default is the memo's [cwd]. In
general it's better to avoid using relative file paths and
tweaking the [cwd]. Construct make your paths absolute
and invocations independent from the [cwd].}
{- [post_exec], if specified is called with the build operation
after it has been executed or revived. If it was executed
this is called before the operation gets recorded. It can
be used to define the [reads] and [writes] of the operation
if they are difficult to find out before hand. {b Do not}
access [m] in that function.}
{- [k], if specified a function invoked once the spawn has succesfully
executed with the exit code.}
{- [stamp] is used for caching if two spawns diff only in their
stamp they will cache to different keys. This can be used to
memoize tool whose outputs may not entirely depend on the environment,
the cli stamp and the the content of read files.}}
{b Note.} If the tool spawn acts on a sort of "main" file
(e.g. a source file) it should be specified as the first element
of [reads], this is interpreted specially by certain build
tracer. *)
val spawn' :
t -> ?stamp:string -> ?reads:Fpath.t list -> writes_root:Fpath.t ->
?writes:(B000.Op.t -> Fpath.t list) ->
?env:Os.Env.t -> ?cwd:Fpath.t -> ?stdin:Fpath.t ->
?stdout:B000.Op.Spawn.stdo -> ?stderr:B000.Op.Spawn.stdo ->
?success_exits:B000.Op.Spawn.success_exits ->
?k:(int -> unit) -> cmd -> unit
* [ spawn ' ] is like { ! - spawn } except the actual file paths
written by the spawn need not be determined before the
spawn . Only the root directory of writes need to be specified
via [ writes_root ] . After the spawn executes the writes can be
determined via the [ writes ] function , the returned paths must be
absolute and be prefixed by [ writes_root ] ( defaults to
recursively list all the files rootet in [ writes_root ] ) .
written by the spawn need not be determined before the
spawn. Only the root directory of writes need to be specified
via [writes_root]. After the spawn executes the writes can be
determined via the [writes] function, the returned paths must be
absolute and be prefixed by [writes_root] (defaults to
recursively list all the files rootet in [writes_root]). *)
end
* Lazy immutable stores .
These stores provide access to immutable , lazily determined , typed
key - value bindings .
The value of a key in a store is defined either :
{ ul
{ - Explicitly when the store is { { ! Store.create}created } . }
{ - Lazily on the first key { { ! Store.get}access } via a key determination
function
specified at { { ! Store.val - key}key creation time } . } }
Once determined the value of a key in the store never changes .
{ b XXX . } Maybe move that at the level .
These stores provide access to immutable, lazily determined, typed
key-value bindings.
The value of a key in a store is defined either:
{ul
{- Explicitly when the store is {{!Store.create}created}.}
{- Lazily on the first key {{!Store.get}access} via a key determination
function
specified at {{!Store.val-key}key creation time}.}}
Once determined the value of a key in the store never changes.
{b XXX.} Maybe move that at the B0 level. *)
module Store : sig
* { 1 : stores Stores }
type 'a key
type t
val create : Memo.t -> dir:Fpath.t -> binding list -> t
* [ create memo bs ] is a store with predefined bindings [ bs ] .
If a key is mentioned more than once in [ bs ] the last binding
takes over . The store uses [ memo ] to determine other keys as
{ { ! get}needed } . [ dir ] is a scratch directory used by key determination
functions to write memoized file outputs .
If a key is mentioned more than once in [bs] the last binding
takes over. The store uses [memo] to determine other keys as
{{!get}needed}. [dir] is a scratch directory used by key determination
functions to write memoized file outputs. *)
val memo : t -> Memo.t
val dir : t -> Fpath.t
val key : ?mark:string -> (t -> Memo.t -> 'a Fut.t) -> 'a key
* [ key ~mark det ] is a new key whose value is determined on
{ { ! get}access } by the future :
{ [
det s ( Memo.with_mark mark ( Store.memo s ) )
] }
[ mark ] defaults to [ " " ] .
{{!get}access} by the future:
{[
det s (Memo.with_mark mark (Store.memo s))
]}
[mark] defaults to [""]. *)
val get : t -> 'a key -> 'a Fut.t
* [ get s k ] is a future that dermines with the value of [ k ] in
[ s ] .
[s]. *)
val set : t -> 'a key -> 'a -> unit
end
---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
857ea64b7294ebfd26be2df0bfae9b950affa570e2c19d7c5d3f935d68c41d7a | retro/keechma-next-realworld-app | delete_article_button.cljs | (ns app.ui.components.delete-article-button
(:require [keechma.next.helix.core :refer [with-keechma dispatch]]
[keechma.next.helix.lib :refer [defnc]]
[helix.core :as hx :refer [$ <> suspense]]
[helix.dom :as d]
["react" :as react]
["react-dom" :as rdom]
[app.util :refer [format-date]]
[keechma.next.controllers.pipelines :refer [throw-promise!]]
[app.settings :as settings]))
(defnc DeleteButtonRenderer [{:keys [article] :as props}]
(d/button
{:class "btn btn-sm btn-outline-danger"
:on-click #(dispatch props :user-actions :delete-article article)}
(d/i {:class "ion-trash-a"})
" Delete Article"))
(def DeleteButton (with-keechma DeleteButtonRenderer)) | null | https://raw.githubusercontent.com/retro/keechma-next-realworld-app/47a14f4f3f6d56be229cd82f7806d7397e559ebe/src/app/ui/components/delete_article_button.cljs | clojure | (ns app.ui.components.delete-article-button
(:require [keechma.next.helix.core :refer [with-keechma dispatch]]
[keechma.next.helix.lib :refer [defnc]]
[helix.core :as hx :refer [$ <> suspense]]
[helix.dom :as d]
["react" :as react]
["react-dom" :as rdom]
[app.util :refer [format-date]]
[keechma.next.controllers.pipelines :refer [throw-promise!]]
[app.settings :as settings]))
(defnc DeleteButtonRenderer [{:keys [article] :as props}]
(d/button
{:class "btn btn-sm btn-outline-danger"
:on-click #(dispatch props :user-actions :delete-article article)}
(d/i {:class "ion-trash-a"})
" Delete Article"))
(def DeleteButton (with-keechma DeleteButtonRenderer)) |
|
f8e9e7261e687982e38f099f302193445d70d77062874b225a3ea416c9897b96 | Shirakumo/kandria | history.lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass history ()
())
(defgeneric commit (action history))
(defgeneric actions (history))
(defclass action ()
((description :initarg :description :initform "<unknown change>" :accessor description)
(index :initform 0 :accessor index)))
(defmethod print-object ((action action) stream)
(print-unreadable-object (action stream :type T)
(format stream "~a ~a" (index action) (description action))))
(defgeneric redo (action region))
(defgeneric undo (action region))
(defclass linear-history (history)
((actions :initform (make-array 0 :adjustable T :fill-pointer T) :accessor actions)
(history-pointer :initform 0 :accessor history-pointer)))
(defmethod commit ((action action) (history linear-history))
(setf (index action) (history-pointer history))
(setf (fill-pointer (actions history)) (history-pointer history))
(vector-push-extend action (actions history))
(incf (history-pointer history)))
(defmethod redo ((history linear-history) region)
(when (< (history-pointer history) (fill-pointer (actions history)))
(redo (aref (actions history) (history-pointer history)) region)
(incf (history-pointer history))))
(defmethod undo ((history linear-history) region)
(when (< 0 (history-pointer history))
(decf (history-pointer history))
(undo (aref (actions history) (history-pointer history)) region)))
(defmethod undo ((action action) (history linear-history))
(loop until (or (= 0 (history-pointer history))
(<= (history-pointer history) (index action)))
do (decf (history-pointer history))
(undo (aref (actions history) (history-pointer history)) T)))
(defmethod redo ((action action) (history linear-history))
(loop until (or (< (index action) (history-pointer history))
(null (aref (actions history) (history-pointer history))))
do (redo (aref (actions history) (history-pointer history)) T)
(incf (history-pointer history))))
(defmethod clear ((history linear-history))
(loop for i from 0 below (length (actions history))
do (setf (aref (actions history) i) NIL))
(setf (fill-pointer (actions history)) 0)
(setf (history-pointer history) 0))
(defclass closure-action (action)
((redo :initarg :redo)
(undo :initarg :undo)))
(defmethod redo ((action closure-action) (region (eql T)))
(funcall (slot-value action 'redo)))
(defmethod undo ((action closure-action) (region (eql T)))
(funcall (slot-value action 'undo)))
(defmacro make-action (redo undo &rest initargs)
(let ((redog (gensym "REDO"))
(undog (gensym "UNDO")))
`(flet ((,redog ()
,redo)
(,undog ()
,undo))
(make-instance 'closure-action :redo #',redog :undo #',undog ,@initargs))))
(defmacro capture-action (place value &rest initargs)
(let ((previous (gensym "PREVIOUS-VALUE")))
`(let ((,previous ,place))
(make-action
(setf ,place ,value)
(setf ,place ,previous)
,@initargs))))
(defmacro with-commit ((tool &optional description &rest format-args) (&body redo) (&body undo))
`(commit (make-action (progn ,@redo) (progn ,@undo)
:description ,(if description
`(format NIL ,description ,@format-args)
"<unknown change>"))
,tool))
(defclass history-button (alloy:direct-value-component alloy:button)
((history :initarg :history :accessor history)))
(presentations:define-realization (ui history-button)
((:number simple:text)
(alloy:extent 0 0 30 (alloy:ph))
(princ-to-string (index alloy:value))
:size (alloy:un 12)
:pattern colors:white
:halign :start
:valign :middle)
((:label simple:text)
(alloy:margins 30 0 0 0)
(description alloy:value)
:size (alloy:un 12)
:pattern colors:white
:halign :start))
(presentations:define-update (ui history-button)
(:number)
(:label
:text (description alloy:value)
:pattern (if (<= (history-pointer (history alloy:renderable))
(index alloy:value))
colors:gray
colors:white)))
(defmethod alloy:activate ((button history-button))
(if (<= (history-pointer (history button)) (index (alloy:value button)))
(redo (alloy:value button) (history button))
(undo (alloy:value button) (history button)))
(create-marker (find-panel 'editor)))
(defclass history-dialog (alloy:dialog)
()
(:default-initargs
:title "History"
:extent (alloy:size 400 500)))
(defmethod alloy:reject ((dialog history-dialog)))
(defmethod alloy:accept ((dialog history-dialog)))
(defmethod initialize-instance :after ((panel history-dialog) &key history)
(let* ((layout (make-instance 'alloy:grid-layout :col-sizes '(T) :row-sizes '(T 30) :layout-parent panel))
(focus (make-instance 'alloy:focus-list :focus-parent panel))
(entitylist (make-instance 'entitylist)))
(loop for action across (actions history)
do (alloy:enter (make-instance 'history-button :history history :value action) entitylist))
(make-instance 'alloy:scroll-view :scroll :y :focus entitylist :layout entitylist
:layout-parent layout :focus-parent focus)))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/0eafe60b5f50c18980a6acc977dc45987e8e26c1/editor/history.lisp | lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass history ()
())
(defgeneric commit (action history))
(defgeneric actions (history))
(defclass action ()
((description :initarg :description :initform "<unknown change>" :accessor description)
(index :initform 0 :accessor index)))
(defmethod print-object ((action action) stream)
(print-unreadable-object (action stream :type T)
(format stream "~a ~a" (index action) (description action))))
(defgeneric redo (action region))
(defgeneric undo (action region))
(defclass linear-history (history)
((actions :initform (make-array 0 :adjustable T :fill-pointer T) :accessor actions)
(history-pointer :initform 0 :accessor history-pointer)))
(defmethod commit ((action action) (history linear-history))
(setf (index action) (history-pointer history))
(setf (fill-pointer (actions history)) (history-pointer history))
(vector-push-extend action (actions history))
(incf (history-pointer history)))
(defmethod redo ((history linear-history) region)
(when (< (history-pointer history) (fill-pointer (actions history)))
(redo (aref (actions history) (history-pointer history)) region)
(incf (history-pointer history))))
(defmethod undo ((history linear-history) region)
(when (< 0 (history-pointer history))
(decf (history-pointer history))
(undo (aref (actions history) (history-pointer history)) region)))
(defmethod undo ((action action) (history linear-history))
(loop until (or (= 0 (history-pointer history))
(<= (history-pointer history) (index action)))
do (decf (history-pointer history))
(undo (aref (actions history) (history-pointer history)) T)))
(defmethod redo ((action action) (history linear-history))
(loop until (or (< (index action) (history-pointer history))
(null (aref (actions history) (history-pointer history))))
do (redo (aref (actions history) (history-pointer history)) T)
(incf (history-pointer history))))
(defmethod clear ((history linear-history))
(loop for i from 0 below (length (actions history))
do (setf (aref (actions history) i) NIL))
(setf (fill-pointer (actions history)) 0)
(setf (history-pointer history) 0))
(defclass closure-action (action)
((redo :initarg :redo)
(undo :initarg :undo)))
(defmethod redo ((action closure-action) (region (eql T)))
(funcall (slot-value action 'redo)))
(defmethod undo ((action closure-action) (region (eql T)))
(funcall (slot-value action 'undo)))
(defmacro make-action (redo undo &rest initargs)
(let ((redog (gensym "REDO"))
(undog (gensym "UNDO")))
`(flet ((,redog ()
,redo)
(,undog ()
,undo))
(make-instance 'closure-action :redo #',redog :undo #',undog ,@initargs))))
(defmacro capture-action (place value &rest initargs)
(let ((previous (gensym "PREVIOUS-VALUE")))
`(let ((,previous ,place))
(make-action
(setf ,place ,value)
(setf ,place ,previous)
,@initargs))))
(defmacro with-commit ((tool &optional description &rest format-args) (&body redo) (&body undo))
`(commit (make-action (progn ,@redo) (progn ,@undo)
:description ,(if description
`(format NIL ,description ,@format-args)
"<unknown change>"))
,tool))
(defclass history-button (alloy:direct-value-component alloy:button)
((history :initarg :history :accessor history)))
(presentations:define-realization (ui history-button)
((:number simple:text)
(alloy:extent 0 0 30 (alloy:ph))
(princ-to-string (index alloy:value))
:size (alloy:un 12)
:pattern colors:white
:halign :start
:valign :middle)
((:label simple:text)
(alloy:margins 30 0 0 0)
(description alloy:value)
:size (alloy:un 12)
:pattern colors:white
:halign :start))
(presentations:define-update (ui history-button)
(:number)
(:label
:text (description alloy:value)
:pattern (if (<= (history-pointer (history alloy:renderable))
(index alloy:value))
colors:gray
colors:white)))
(defmethod alloy:activate ((button history-button))
(if (<= (history-pointer (history button)) (index (alloy:value button)))
(redo (alloy:value button) (history button))
(undo (alloy:value button) (history button)))
(create-marker (find-panel 'editor)))
(defclass history-dialog (alloy:dialog)
()
(:default-initargs
:title "History"
:extent (alloy:size 400 500)))
(defmethod alloy:reject ((dialog history-dialog)))
(defmethod alloy:accept ((dialog history-dialog)))
(defmethod initialize-instance :after ((panel history-dialog) &key history)
(let* ((layout (make-instance 'alloy:grid-layout :col-sizes '(T) :row-sizes '(T 30) :layout-parent panel))
(focus (make-instance 'alloy:focus-list :focus-parent panel))
(entitylist (make-instance 'entitylist)))
(loop for action across (actions history)
do (alloy:enter (make-instance 'history-button :history history :value action) entitylist))
(make-instance 'alloy:scroll-view :scroll :y :focus entitylist :layout entitylist
:layout-parent layout :focus-parent focus)))
|
|
96dedb786c956948375b45984549c40c2f60e0bbbdcb37cea2ca1b805ea00dca | leftaroundabout/beamonad | Redundancy.hs | -- |
Module : Data . . Redundancy
Copyright : ( c ) 2017
-- License : GPL v3
--
-- Maintainer : (@) jsag $ hvl.no
-- Stability : experimental
-- Portability : portable
--
module Data.Traversable.Redundancy where
import Data.Foldable (toList)
import Data.Traversable
import Data.Vector (Vector)
import qualified Data.Vector as Arr
import qualified Data.Map as Map
import Data.List (sortBy)
import Data.Ord (comparing)
import Control.Monad.Trans.State
rmRedundancy :: (Ord a, Traversable t) => t a -> (t Int, Vector a)
rmRedundancy q = ( (`evalState`indices) . forM q . const . state $ \((_,j):js) -> (j, js)
, resource )
where backIxed = fmap ($ []) . Map.fromListWith (.) . zip (toList q) $ (:)<$>[0..]
histogram = sortBy (comparing $ negate . length . snd)
$ Map.toList backIxed
indices = sortBy (comparing fst)
[ (j,i)
| (i,js) <- zip [0..] $ snd<$>histogram
, j <- js ]
resource = Arr.fromList $ fst<$>histogram
| null | https://raw.githubusercontent.com/leftaroundabout/beamonad/67cb0f34b38dc31944ff9c360051face3f7760d5/Data/Traversable/Redundancy.hs | haskell | |
License : GPL v3
Maintainer : (@) jsag $ hvl.no
Stability : experimental
Portability : portable
| Module : Data . . Redundancy
Copyright : ( c ) 2017
module Data.Traversable.Redundancy where
import Data.Foldable (toList)
import Data.Traversable
import Data.Vector (Vector)
import qualified Data.Vector as Arr
import qualified Data.Map as Map
import Data.List (sortBy)
import Data.Ord (comparing)
import Control.Monad.Trans.State
rmRedundancy :: (Ord a, Traversable t) => t a -> (t Int, Vector a)
rmRedundancy q = ( (`evalState`indices) . forM q . const . state $ \((_,j):js) -> (j, js)
, resource )
where backIxed = fmap ($ []) . Map.fromListWith (.) . zip (toList q) $ (:)<$>[0..]
histogram = sortBy (comparing $ negate . length . snd)
$ Map.toList backIxed
indices = sortBy (comparing fst)
[ (j,i)
| (i,js) <- zip [0..] $ snd<$>histogram
, j <- js ]
resource = Arr.fromList $ fst<$>histogram
|
506468e10d507c88c7086d0bccbae5485bf6126aff8fc3f37cd96ebfcb2379f8 | macourtney/Dark-Exchange | confirm_trade.clj | (ns darkexchange.model.actions.confirm-trade
(:require [darkexchange.interchange-map-util :as interchange-map-util]
[darkexchange.model.actions.action-keys :as action-keys]
[darkexchange.model.trade :as trade-model]))
(def action-key action-keys/confirm-trade-action-key)
(defn confirm-trade [foreign-trade-id trade-partner-identity]
{ :id (trade-model/confirm-trade foreign-trade-id trade-partner-identity) })
(defn action [request-map]
{ :data (confirm-trade (:trade-id (:data request-map)) (interchange-map-util/from-identity request-map)) }) | null | https://raw.githubusercontent.com/macourtney/Dark-Exchange/1654d05cda0c81585da7b8e64f9ea3e2944b27f1/src/darkexchange/model/actions/confirm_trade.clj | clojure | (ns darkexchange.model.actions.confirm-trade
(:require [darkexchange.interchange-map-util :as interchange-map-util]
[darkexchange.model.actions.action-keys :as action-keys]
[darkexchange.model.trade :as trade-model]))
(def action-key action-keys/confirm-trade-action-key)
(defn confirm-trade [foreign-trade-id trade-partner-identity]
{ :id (trade-model/confirm-trade foreign-trade-id trade-partner-identity) })
(defn action [request-map]
{ :data (confirm-trade (:trade-id (:data request-map)) (interchange-map-util/from-identity request-map)) }) |
|
b3da73209f253e2e465548d0463171d45fd9c5daef5aa3a85e5de7f9e7f6ab11 | B-Lang-org/bsc | YicesFFI.hs | {-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE EmptyDataDecls #-}
module YicesFFI (
-- * C types
YExpr,
YType,
YContext,
YStatus,
YModel,
YContextConfig,
YParams,
YErrorCode,
-- YErrorReport,
-- * Version numbers
yices_version,
yices_build_arch,
yices_build_mode,
yices_build_date,
-- yices_has_mcsat,
-- yices_is_thread_safe,
-- * Global initialization and cleanup
yices_init,
yices_exit,
yices_reset,
-- yices_free_string,
-- * Out-of-memory callback
-- yices_set_out_ot_mem_callback,
-- * Error reporting
yices_error_code,
-- yices_error_report,
yices_clear_error ,
-- yices_print_error,
-- yices_print_error_fd,
-- yices_error_string,
-- * Vectors of terms and types
-- yices_init_term_vector,
-- yices_init_type_vector,
-- yices_delete_term_vector,
-- yices_delete_type_vector,
-- yices_reset_term_vector,
-- yices_reset_type_vector,
-- * Type constructors
yices_bool_type,
yices_bv_type,
yices_int_type,
-- yices_real_type,
yices_new_scalar_type ,
yices_new_uninterpreted_type ,
-- yices_tuple_type,
-- yices_tuple_type1,
-- yices_tuple_type2,
yices_tuple_type3 ,
-- yices_function_type,
-- yices_function_type1,
-- yices_function_type2,
-- yices_function_type3,
-- * Type exploration
-- yices_type_is_bool,
-- yices_type_is_int,
-- yices_type_is_real,
-- yices_type_is_arithmetic,
-- yices_type_is_bitvector,
-- yices_type_is_tuple,
-- yices_type_is_function,
-- yices_type_is_scalar,
-- yices_type_is_uninterpreted,
-- yices_test_subtype,
-- yices_compatible_types,
-- yices_bvtype_size,
-- yices_scalar_type_card,
-- yices_type_num_children,
,
-- yices_type_children,
-- * Term constructors
yices_true,
yices_false,
yices_constant,
yices_new_uninterpreted_term,
yices_new_variable,
-- yices_application,
-- yices_application1,
-- yices_application2,
-- yices_application3,
yices_ite,
yices_eq,
yices_neq,
yices_not,
yices_or,
yices_and,
yices_xor,
yices_or2,
yices_and2,
yices_xor2,
-- yices_or3,
-- yices_and3,
-- yices_xor3,
yices_iff,
yices_implies,
-- yices_tuple,
yices_pair ,
-- yices_triple,
-- yices_select,
yices_tuple_update
-- yices_update,
-- yices_update1,
-- yices_update2,
-- yices_update3,
yices_distinct,
yices_forall,
yices_exists,
-- yices_lambda,
-- * Arithmetic term constructors
yices_zero,
yices_int32,
yices_int64,
-- yices_rational32,
yices_rational64 ,
-- yices_mpz,
-- yices_mpq,
-- yices_parse_rational,
-- yices_parse_float,
yices_add,
yices_sub,
yices_neg,
yices_mul,
yices_square,
yices_power,
-- yices_abs,
-- yices_floor,
-- yices_ceil,
yices_poly_int32 ,
-- yices_poly_int64,
-- yices_poly_rational32,
-- yices_poly_rational64
-- yices_poly_mpz,
-- yices_poly_mpq,
yices_arith_eq_atom,
yices_arith_neq_atom,
yices_arith_geq_atom,
yices_arith_leq_atom,
yices_arith_gt_atom,
yices_arith_lt_atom,
yices_arith_eq0_atom,
yices_arith_neq0_atom,
yices_arith_geq0_atom,
yices_arith_leq0_atom,
yices_arith_gt0_atom,
yices_arith_lt0_atom,
-- * Bit vector term constructors
yices_bvconst_uint32,
yices_bvconst_uint64,
-- yices_bvconst_int32,
-- yices_bvconst_int64,
-- yices_bvconst_mpz,
yices_bvconst_zero,
yices_bvconst_one,
yices_bvconst_minus_one,
-- yices_bvconst_from_array,
yices_parse_bvbin,
yices_parse_bvhex,
yices_bvadd,
yices_bvsub,
yices_bvneg,
yices_bvmul,
-- yices_bvsquare,
-- yices_bvpower,
yices_bvdiv,
yices_bvrem,
-- yices_bvsdiv,
-- yices_bvsrem,
-- yices_bvsmod,
yices_bvnot,
yices_bvnand,
yices_bvnor,
yices_bvxnor,
yices_bvshl,
yices_bvlshr,
yices_bvashr,
-- yices_bvand,
-- yices_bvor,
-- yices_bvxor,
yices_bvand2,
yices_bvor2,
yices_bvxor2,
-- yices_bvand3,
-- yices_bvor3,
-- yices_bvxor3,
-- yices_bvsum,
-- yices_bvproduct,
-- yices_shift_left0,
-- yices_shift_left1,
-- yices_shift_right0,
-- yices_shift_right1,
-- yices_ashift_right,
-- yices_rotate_left,
yices_rotate_right ,
yices_bvextract,
yices_bvconcat2,
-- yices_bvconcat,
-- yices_bvrepeat,
yices_sign_extend,
yices_zero_extend,
yices_redand,
yices_redor,
yices_redcomp,
convert Bools to an array
yices_bitextract, -- get a Bool from an array
yices_bveq_atom,
yices_bvneq_atom,
yices_bvge_atom,
yices_bvgt_atom,
yices_bvle_atom,
yices_bvlt_atom,
yices_bvsge_atom,
yices_bvsgt_atom,
yices_bvsle_atom,
yices_bvslt_atom,
{-
-- * Parsing
yices_parse_type,
yices_parse_term,
-- * Substitutions
yices_subst_term,
yices_subst_term_array,
-- * Names
yices_set_type_name,
yices_set_term_name,
yices_remove_type_name,
yices_remove_term_name,
yices_get_type_by_name,
yices_get_term_by_name,
yices_clear_type_name,
yices_clear_term_name,
yices_get_type_name,
yices_get_term_name,
-}
-- * Checks on terms
yices_type_of_term,
yices_term_is_bool,
yices_term_is_bitvector,
-- yices_term_is_int,
-- yices_term_is_real,
-- yices_term_is_arithmetic,
-- yices_term_is_tuple,
-- yices_term_is_function,
-- yices_term_is_scalar,
yices_term_bitsize,
-- yices_term_is_ground,
-- yices_term_is_atomic,
-- yices_term_is_composite,
-- yices_term_is_projection,
-- yices_term_is_sum,
-- yices_term_is_bvsum,
-- yices_term_is_product,
-- yices_term_constructor,
-- yices_term_num_children,
-- yices_term_child,
-- yices_proj_index,
-- yices_proj_arg,
-- yices_bool_const_value,
-- yices_bv_const_value,
-- yices_scalar_const_value,
-- yices_rational_const_value,
-- yices_sum_component,
-- yices_bvsum_component,
-- yices_product_component,
-- * Garbage collection
-- yices_num_terms,
-- yices_num_types,
-- yices_incref_term,
-- yices_decref_term,
-- yices_incref_type,
-- yices_decref_type,
-- yices_num_posref_terms,
-- yices_num_posref_types,
-- yices_garbage_collect,
-- * Context configuration
yices_new_config,
yices_free_config,
yices_set_config,
yices_default_config_for_logic,
-- * Contexts
yices_new_context,
yices_free_context,
yices_context_status,
yices_reset_context,
yices_push,
yices_pop,
-- yices_context_enable_option,
-- yices_context_disable_option,
yices_assert_formula,
yices_assert_formulas,
yices_check_context,
-- yices_check_context_with_assumptions,
-- yices_assert_blocking_clause,
-- yices_stop_search,
-- * Search parameters
yices_new_param_record,
-- yices_default_params_for_context,
yices_set_param,
yices_free_param_record,
* Unsat core
-- yices_get_unsat_core
-- * Models
yices_get_model,
yices_free_model,
-- yices_model_from_map,
-- yices_model_collect_defined_terms,
-- * Values in a model
yices_get_bool_value,
-- yices_get_int32_value,
yices_get_int64_value ,
-- yices_get_rational32_value,
-- yices_get_rational64_value,
-- yices_get_double_value,
-- yices_get_mpz_value,
-- yices_get_mpq_value,
-- yices_get_algebraic_number_value,
yices_get_bv_value,
yices_get_scalar_value ,
-- * Generic form: Value descriptors and nodes
-- ...
-- * Check the value of boolean formulas
-- ...
-- * Conversion of values to constant terms
-- ...
-- * Implicants
-- ...
-- * Model generalization
-- ...
-- * Pretty printing
yices_pp_type,
yices_pp_term,
-- yices_pp_term_array,
yices_print_model
-- yices_pp_model
-- yices_pp_type_fd,
-- yices_pp_term_fd,
-- yices_pp_term_array_fd,
-- yices_print_model_fd,
-- yices_pp_model_fd
-- yices_type_to_string,
-- yices_term_to_string,
-- yices_model_to_string
) where
import Foreign
import Foreign.C.Types
import Foreign.C.String
------------------------------------------------------------------------
-- C Types
Abstract type representing a Yices term ( term_t )
type YExpr = Int32
Abstract type representing a Yices type ( type_t )
type YType = Int32
Abstract type representing a Yices context ( context_t )
data YContext
-- Low level type for context status code (smt_status_t)
type YStatus = CInt
Abstract type representing a Yices model ( )
data YModel
Abstract type representing a Yices context configuration ( ctx_config_t )
data YContextConfig
Abstract type representing a Yices search parameters ( param_t )
data YParams
Type for Yices error codes
type YErrorCode = CInt
------------------------------------------------------------------------
-- Version numbers
-- versions are (const char *), not a C function call
foreign import ccall "yices.h &yices_version"
yices_version :: Ptr CString
foreign import ccall unsafe "yices.h &yices_build_arch"
yices_build_arch :: Ptr CString
foreign import ccall unsafe "yices.h &yices_build_mode"
yices_build_mode :: Ptr CString
foreign import ccall unsafe "yices.h &yices_build_date"
yices_build_date :: Ptr CString
------------------------------------------------------------------------
-- Global initialization and cleanup
foreign import ccall unsafe "yices.h"
yices_init :: IO ()
foreign import ccall unsafe "yices.h"
yices_exit :: IO ()
foreign import ccall unsafe "yices.h"
yices_reset :: IO ()
-- ...
------------------------------------------------------------------------
-- Error reporting
foreign import ccall unsafe "yices.h"
yices_error_code :: IO YErrorCode
-- ...
------------------------------------------------------------------------
-- Type constructors
foreign import ccall unsafe "yices.h"
yices_bool_type :: IO YType
foreign import ccall unsafe "yices.h"
yices_bv_type :: Word32 -> IO YType
foreign import ccall unsafe "yices.h"
yices_int_type :: IO YType
-- ...
------------------------------------------------------------------------
-- Term constructors
foreign import ccall unsafe "yices.h"
yices_true :: IO YExpr
foreign import ccall unsafe "yices.h"
yices_false :: IO YExpr
foreign import ccall unsafe "yices.h"
yices_constant :: YType -> Int32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_new_uninterpreted_term :: YType -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_new_variable :: YType -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_ite :: YExpr -> YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_eq :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_neq :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_not :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_or :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_and :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_xor :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_or2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_and2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_xor2 :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_iff :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_implies :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_distinct :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_forall :: Word32 -> Ptr YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_exists :: Word32 -> Ptr YExpr -> YExpr -> IO YExpr
-- ...
------------------------------------------------------------------------
-- Arithmetic term constructors
foreign import ccall unsafe "yices.h"
yices_zero :: IO YExpr
foreign import ccall unsafe "yices.h"
yices_int32 :: Int32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_int64 :: Int64 -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_add :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_sub :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_neg :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_mul :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_square :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_power :: YExpr -> Word32 -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_arith_eq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_neq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_geq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_leq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_gt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_lt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_eq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_neq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_geq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_leq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_gt0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_lt0_atom :: YExpr -> IO YExpr
------------------------------------------------------------------------
-- Bit vector term constructors
foreign import ccall unsafe "yices.h"
yices_bvconst_uint32 :: Word32 -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_uint64 :: Word32 -> Word64 -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_bvconst_zero :: Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_one :: Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_minus_one :: Word32 -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_parse_bvbin :: CString -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_parse_bvhex :: CString -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvadd :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsub :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvneg :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvmul :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_bvdiv :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvrem :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_bvnot :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvnand :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvnor :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvxnor :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvshl :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvlshr :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvashr :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_bvand2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvor2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvxor2 :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_bvextract :: YExpr -> Word32 -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconcat2 :: YExpr -> YExpr -> IO YExpr
-- ...
foreign import ccall unsafe "yices.h"
yices_sign_extend :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_zero_extend :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_redand :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_redor :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_redcomp :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvarray :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bitextract :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bveq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvneq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvge_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvgt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvle_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvlt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsge_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsgt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsle_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvslt_atom :: YExpr -> YExpr -> IO YExpr
------------------------------------------------------------------------
-- Parsing
-- ...
------------------------------------------------------------------------
-- Substitutions
-- ...
------------------------------------------------------------------------
-- Names
-- ...
------------------------------------------------------------------------
-- Checks on terms
foreign import ccall unsafe "yices.h"
yices_type_of_term :: YExpr -> IO YType
foreign import ccall unsafe "yices.h"
yices_term_is_bool :: YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_term_is_bitvector :: YExpr -> IO Int32
-- ...
foreign import ccall unsafe "yices.h"
yices_term_bitsize :: YExpr -> IO Word32
-- ...
------------------------------------------------------------------------
-- Garbage collection
-- ...
------------------------------------------------------------------------
-- Context configuration
foreign import ccall unsafe "yices.h"
yices_new_config :: IO (Ptr YContextConfig)
foreign import ccall unsafe "yices.h"
yices_free_config :: Ptr YContextConfig -> IO ()
foreign import ccall unsafe "yices.h"
yices_set_config :: Ptr YContextConfig -> CString -> CString -> IO Int32
foreign import ccall unsafe "yices.h"
yices_default_config_for_logic :: Ptr YContextConfig -> CString -> IO Int32
------------------------------------------------------------------------
-- Contexts
foreign import ccall unsafe "yices.h"
yices_new_context :: Ptr YContextConfig -> IO (Ptr YContext)
foreign import ccall unsafe "yices.h"
yices_free_context :: Ptr YContext -> IO ()
foreign import ccall unsafe "yices.h"
yices_context_status :: Ptr YContext -> IO YStatus
foreign import ccall unsafe "yices.h"
yices_reset_context :: Ptr YContext -> IO ()
foreign import ccall unsafe "yices.h"
yices_push :: Ptr YContext -> IO Int32
foreign import ccall unsafe "yices.h"
yices_pop :: Ptr YContext -> IO Int32
-- ...
foreign import ccall unsafe "yices.h"
yices_assert_formula :: Ptr YContext -> YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_assert_formulas :: Ptr YContext -> CUInt -> Ptr YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_check_context :: Ptr YContext -> Ptr YParams -> IO YStatus
------------------------------------------------------------------------
-- Search parameters
foreign import ccall unsafe "yices.h"
yices_new_param_record :: IO (Ptr YParams)
-- ...
foreign import ccall unsafe "yices.h"
yices_set_param :: Ptr YParams -> CString -> CString -> IO Int32
foreign import ccall unsafe "yices.h"
yices_free_param_record :: Ptr YParams -> IO ()
------------------------------------------------------------------------
Unsat core
-- ...
------------------------------------------------------------------------
Models
foreign import ccall unsafe "yices.h"
yices_get_model :: Ptr YContext -> Int32 -> IO (Ptr YModel)
foreign import ccall unsafe "yices.h"
yices_free_model :: Ptr YModel -> IO ()
-- ...
------------------------------------------------------------------------
-- Values in a model
foreign import ccall unsafe "yices.h"
yices_get_bool_value :: Ptr YModel -> YExpr -> Ptr Int32 -> IO Int32
-- ...
foreign import ccall unsafe "yices.h"
yices_get_bv_value :: Ptr YModel -> YExpr -> Ptr Int32 -> IO Int32
-- ...
------------------------------------------------------------------------
Generic form : Value descriptors and nodes
-- ...
------------------------------------------------------------------------
-- Check the value of boolean formulas
-- ...
------------------------------------------------------------------------
-- Conversion of values to constant terms
-- ...
------------------------------------------------------------------------
-- Implicants
-- ...
------------------------------------------------------------------------
-- Model generalization
-- ...
------------------------------------------------------------------------
-- Pretty printing
foreign import ccall unsafe "yices.h"
yices_pp_type :: Ptr CFile -> YType -> Word32 -> Word32 -> Word32 -> IO Int32
foreign import ccall unsafe "yices.h"
yices_pp_term :: Ptr CFile -> YExpr -> Word32 -> Word32 -> Word32 -> IO Int32
-- ...
foreign import ccall unsafe "yices.h"
yices_print_model :: Ptr CFile -> Ptr YModel -> IO ()
-- ...
------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/vendor/yices/v2.6/HaskellIfc/YicesFFI.hs | haskell | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE EmptyDataDecls #
* C types
YErrorReport,
* Version numbers
yices_has_mcsat,
yices_is_thread_safe,
* Global initialization and cleanup
yices_free_string,
* Out-of-memory callback
yices_set_out_ot_mem_callback,
* Error reporting
yices_error_report,
yices_print_error,
yices_print_error_fd,
yices_error_string,
* Vectors of terms and types
yices_init_term_vector,
yices_init_type_vector,
yices_delete_term_vector,
yices_delete_type_vector,
yices_reset_term_vector,
yices_reset_type_vector,
* Type constructors
yices_real_type,
yices_tuple_type,
yices_tuple_type1,
yices_tuple_type2,
yices_function_type,
yices_function_type1,
yices_function_type2,
yices_function_type3,
* Type exploration
yices_type_is_bool,
yices_type_is_int,
yices_type_is_real,
yices_type_is_arithmetic,
yices_type_is_bitvector,
yices_type_is_tuple,
yices_type_is_function,
yices_type_is_scalar,
yices_type_is_uninterpreted,
yices_test_subtype,
yices_compatible_types,
yices_bvtype_size,
yices_scalar_type_card,
yices_type_num_children,
yices_type_children,
* Term constructors
yices_application,
yices_application1,
yices_application2,
yices_application3,
yices_or3,
yices_and3,
yices_xor3,
yices_tuple,
yices_triple,
yices_select,
yices_update,
yices_update1,
yices_update2,
yices_update3,
yices_lambda,
* Arithmetic term constructors
yices_rational32,
yices_mpz,
yices_mpq,
yices_parse_rational,
yices_parse_float,
yices_abs,
yices_floor,
yices_ceil,
yices_poly_int64,
yices_poly_rational32,
yices_poly_rational64
yices_poly_mpz,
yices_poly_mpq,
* Bit vector term constructors
yices_bvconst_int32,
yices_bvconst_int64,
yices_bvconst_mpz,
yices_bvconst_from_array,
yices_bvsquare,
yices_bvpower,
yices_bvsdiv,
yices_bvsrem,
yices_bvsmod,
yices_bvand,
yices_bvor,
yices_bvxor,
yices_bvand3,
yices_bvor3,
yices_bvxor3,
yices_bvsum,
yices_bvproduct,
yices_shift_left0,
yices_shift_left1,
yices_shift_right0,
yices_shift_right1,
yices_ashift_right,
yices_rotate_left,
yices_bvconcat,
yices_bvrepeat,
get a Bool from an array
-- * Parsing
yices_parse_type,
yices_parse_term,
-- * Substitutions
yices_subst_term,
yices_subst_term_array,
-- * Names
yices_set_type_name,
yices_set_term_name,
yices_remove_type_name,
yices_remove_term_name,
yices_get_type_by_name,
yices_get_term_by_name,
yices_clear_type_name,
yices_clear_term_name,
yices_get_type_name,
yices_get_term_name,
* Checks on terms
yices_term_is_int,
yices_term_is_real,
yices_term_is_arithmetic,
yices_term_is_tuple,
yices_term_is_function,
yices_term_is_scalar,
yices_term_is_ground,
yices_term_is_atomic,
yices_term_is_composite,
yices_term_is_projection,
yices_term_is_sum,
yices_term_is_bvsum,
yices_term_is_product,
yices_term_constructor,
yices_term_num_children,
yices_term_child,
yices_proj_index,
yices_proj_arg,
yices_bool_const_value,
yices_bv_const_value,
yices_scalar_const_value,
yices_rational_const_value,
yices_sum_component,
yices_bvsum_component,
yices_product_component,
* Garbage collection
yices_num_terms,
yices_num_types,
yices_incref_term,
yices_decref_term,
yices_incref_type,
yices_decref_type,
yices_num_posref_terms,
yices_num_posref_types,
yices_garbage_collect,
* Context configuration
* Contexts
yices_context_enable_option,
yices_context_disable_option,
yices_check_context_with_assumptions,
yices_assert_blocking_clause,
yices_stop_search,
* Search parameters
yices_default_params_for_context,
yices_get_unsat_core
* Models
yices_model_from_map,
yices_model_collect_defined_terms,
* Values in a model
yices_get_int32_value,
yices_get_rational32_value,
yices_get_rational64_value,
yices_get_double_value,
yices_get_mpz_value,
yices_get_mpq_value,
yices_get_algebraic_number_value,
* Generic form: Value descriptors and nodes
...
* Check the value of boolean formulas
...
* Conversion of values to constant terms
...
* Implicants
...
* Model generalization
...
* Pretty printing
yices_pp_term_array,
yices_pp_model
yices_pp_type_fd,
yices_pp_term_fd,
yices_pp_term_array_fd,
yices_print_model_fd,
yices_pp_model_fd
yices_type_to_string,
yices_term_to_string,
yices_model_to_string
----------------------------------------------------------------------
C Types
Low level type for context status code (smt_status_t)
----------------------------------------------------------------------
Version numbers
versions are (const char *), not a C function call
----------------------------------------------------------------------
Global initialization and cleanup
...
----------------------------------------------------------------------
Error reporting
...
----------------------------------------------------------------------
Type constructors
...
----------------------------------------------------------------------
Term constructors
...
...
...
...
----------------------------------------------------------------------
Arithmetic term constructors
...
...
----------------------------------------------------------------------
Bit vector term constructors
...
...
...
...
...
...
...
----------------------------------------------------------------------
Parsing
...
----------------------------------------------------------------------
Substitutions
...
----------------------------------------------------------------------
Names
...
----------------------------------------------------------------------
Checks on terms
...
...
----------------------------------------------------------------------
Garbage collection
...
----------------------------------------------------------------------
Context configuration
----------------------------------------------------------------------
Contexts
...
----------------------------------------------------------------------
Search parameters
...
----------------------------------------------------------------------
...
----------------------------------------------------------------------
...
----------------------------------------------------------------------
Values in a model
...
...
----------------------------------------------------------------------
...
----------------------------------------------------------------------
Check the value of boolean formulas
...
----------------------------------------------------------------------
Conversion of values to constant terms
...
----------------------------------------------------------------------
Implicants
...
----------------------------------------------------------------------
Model generalization
...
----------------------------------------------------------------------
Pretty printing
...
...
---------------------------------------------------------------------- |
module YicesFFI (
YExpr,
YType,
YContext,
YStatus,
YModel,
YContextConfig,
YParams,
YErrorCode,
yices_version,
yices_build_arch,
yices_build_mode,
yices_build_date,
yices_init,
yices_exit,
yices_reset,
yices_error_code,
yices_clear_error ,
yices_bool_type,
yices_bv_type,
yices_int_type,
yices_new_scalar_type ,
yices_new_uninterpreted_type ,
yices_tuple_type3 ,
,
yices_true,
yices_false,
yices_constant,
yices_new_uninterpreted_term,
yices_new_variable,
yices_ite,
yices_eq,
yices_neq,
yices_not,
yices_or,
yices_and,
yices_xor,
yices_or2,
yices_and2,
yices_xor2,
yices_iff,
yices_implies,
yices_pair ,
yices_tuple_update
yices_distinct,
yices_forall,
yices_exists,
yices_zero,
yices_int32,
yices_int64,
yices_rational64 ,
yices_add,
yices_sub,
yices_neg,
yices_mul,
yices_square,
yices_power,
yices_poly_int32 ,
yices_arith_eq_atom,
yices_arith_neq_atom,
yices_arith_geq_atom,
yices_arith_leq_atom,
yices_arith_gt_atom,
yices_arith_lt_atom,
yices_arith_eq0_atom,
yices_arith_neq0_atom,
yices_arith_geq0_atom,
yices_arith_leq0_atom,
yices_arith_gt0_atom,
yices_arith_lt0_atom,
yices_bvconst_uint32,
yices_bvconst_uint64,
yices_bvconst_zero,
yices_bvconst_one,
yices_bvconst_minus_one,
yices_parse_bvbin,
yices_parse_bvhex,
yices_bvadd,
yices_bvsub,
yices_bvneg,
yices_bvmul,
yices_bvdiv,
yices_bvrem,
yices_bvnot,
yices_bvnand,
yices_bvnor,
yices_bvxnor,
yices_bvshl,
yices_bvlshr,
yices_bvashr,
yices_bvand2,
yices_bvor2,
yices_bvxor2,
yices_rotate_right ,
yices_bvextract,
yices_bvconcat2,
yices_sign_extend,
yices_zero_extend,
yices_redand,
yices_redor,
yices_redcomp,
convert Bools to an array
yices_bveq_atom,
yices_bvneq_atom,
yices_bvge_atom,
yices_bvgt_atom,
yices_bvle_atom,
yices_bvlt_atom,
yices_bvsge_atom,
yices_bvsgt_atom,
yices_bvsle_atom,
yices_bvslt_atom,
yices_type_of_term,
yices_term_is_bool,
yices_term_is_bitvector,
yices_term_bitsize,
yices_new_config,
yices_free_config,
yices_set_config,
yices_default_config_for_logic,
yices_new_context,
yices_free_context,
yices_context_status,
yices_reset_context,
yices_push,
yices_pop,
yices_assert_formula,
yices_assert_formulas,
yices_check_context,
yices_new_param_record,
yices_set_param,
yices_free_param_record,
* Unsat core
yices_get_model,
yices_free_model,
yices_get_bool_value,
yices_get_int64_value ,
yices_get_bv_value,
yices_get_scalar_value ,
yices_pp_type,
yices_pp_term,
yices_print_model
) where
import Foreign
import Foreign.C.Types
import Foreign.C.String
Abstract type representing a Yices term ( term_t )
type YExpr = Int32
Abstract type representing a Yices type ( type_t )
type YType = Int32
Abstract type representing a Yices context ( context_t )
data YContext
type YStatus = CInt
Abstract type representing a Yices model ( )
data YModel
Abstract type representing a Yices context configuration ( ctx_config_t )
data YContextConfig
Abstract type representing a Yices search parameters ( param_t )
data YParams
Type for Yices error codes
type YErrorCode = CInt
foreign import ccall "yices.h &yices_version"
yices_version :: Ptr CString
foreign import ccall unsafe "yices.h &yices_build_arch"
yices_build_arch :: Ptr CString
foreign import ccall unsafe "yices.h &yices_build_mode"
yices_build_mode :: Ptr CString
foreign import ccall unsafe "yices.h &yices_build_date"
yices_build_date :: Ptr CString
foreign import ccall unsafe "yices.h"
yices_init :: IO ()
foreign import ccall unsafe "yices.h"
yices_exit :: IO ()
foreign import ccall unsafe "yices.h"
yices_reset :: IO ()
foreign import ccall unsafe "yices.h"
yices_error_code :: IO YErrorCode
foreign import ccall unsafe "yices.h"
yices_bool_type :: IO YType
foreign import ccall unsafe "yices.h"
yices_bv_type :: Word32 -> IO YType
foreign import ccall unsafe "yices.h"
yices_int_type :: IO YType
foreign import ccall unsafe "yices.h"
yices_true :: IO YExpr
foreign import ccall unsafe "yices.h"
yices_false :: IO YExpr
foreign import ccall unsafe "yices.h"
yices_constant :: YType -> Int32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_new_uninterpreted_term :: YType -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_new_variable :: YType -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_ite :: YExpr -> YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_eq :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_neq :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_not :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_or :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_and :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_xor :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_or2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_and2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_xor2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_iff :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_implies :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_distinct :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_forall :: Word32 -> Ptr YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_exists :: Word32 -> Ptr YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_zero :: IO YExpr
foreign import ccall unsafe "yices.h"
yices_int32 :: Int32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_int64 :: Int64 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_add :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_sub :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_neg :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_mul :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_square :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_power :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_eq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_neq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_geq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_leq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_gt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_lt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_eq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_neq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_geq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_leq0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_gt0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_arith_lt0_atom :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_uint32 :: Word32 -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_uint64 :: Word32 -> Word64 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_zero :: Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_one :: Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconst_minus_one :: Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_parse_bvbin :: CString -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_parse_bvhex :: CString -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvadd :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsub :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvneg :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvmul :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvdiv :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvrem :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvnot :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvnand :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvnor :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvxnor :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvshl :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvlshr :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvashr :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvand2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvor2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvxor2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvextract :: YExpr -> Word32 -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvconcat2 :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_sign_extend :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_zero_extend :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_redand :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_redor :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_redcomp :: YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvarray :: Word32 -> Ptr YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bitextract :: YExpr -> Word32 -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bveq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvneq_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvge_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvgt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvle_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvlt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsge_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsgt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvsle_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_bvslt_atom :: YExpr -> YExpr -> IO YExpr
foreign import ccall unsafe "yices.h"
yices_type_of_term :: YExpr -> IO YType
foreign import ccall unsafe "yices.h"
yices_term_is_bool :: YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_term_is_bitvector :: YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_term_bitsize :: YExpr -> IO Word32
foreign import ccall unsafe "yices.h"
yices_new_config :: IO (Ptr YContextConfig)
foreign import ccall unsafe "yices.h"
yices_free_config :: Ptr YContextConfig -> IO ()
foreign import ccall unsafe "yices.h"
yices_set_config :: Ptr YContextConfig -> CString -> CString -> IO Int32
foreign import ccall unsafe "yices.h"
yices_default_config_for_logic :: Ptr YContextConfig -> CString -> IO Int32
foreign import ccall unsafe "yices.h"
yices_new_context :: Ptr YContextConfig -> IO (Ptr YContext)
foreign import ccall unsafe "yices.h"
yices_free_context :: Ptr YContext -> IO ()
foreign import ccall unsafe "yices.h"
yices_context_status :: Ptr YContext -> IO YStatus
foreign import ccall unsafe "yices.h"
yices_reset_context :: Ptr YContext -> IO ()
foreign import ccall unsafe "yices.h"
yices_push :: Ptr YContext -> IO Int32
foreign import ccall unsafe "yices.h"
yices_pop :: Ptr YContext -> IO Int32
foreign import ccall unsafe "yices.h"
yices_assert_formula :: Ptr YContext -> YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_assert_formulas :: Ptr YContext -> CUInt -> Ptr YExpr -> IO Int32
foreign import ccall unsafe "yices.h"
yices_check_context :: Ptr YContext -> Ptr YParams -> IO YStatus
foreign import ccall unsafe "yices.h"
yices_new_param_record :: IO (Ptr YParams)
foreign import ccall unsafe "yices.h"
yices_set_param :: Ptr YParams -> CString -> CString -> IO Int32
foreign import ccall unsafe "yices.h"
yices_free_param_record :: Ptr YParams -> IO ()
Unsat core
Models
foreign import ccall unsafe "yices.h"
yices_get_model :: Ptr YContext -> Int32 -> IO (Ptr YModel)
foreign import ccall unsafe "yices.h"
yices_free_model :: Ptr YModel -> IO ()
foreign import ccall unsafe "yices.h"
yices_get_bool_value :: Ptr YModel -> YExpr -> Ptr Int32 -> IO Int32
foreign import ccall unsafe "yices.h"
yices_get_bv_value :: Ptr YModel -> YExpr -> Ptr Int32 -> IO Int32
Generic form : Value descriptors and nodes
foreign import ccall unsafe "yices.h"
yices_pp_type :: Ptr CFile -> YType -> Word32 -> Word32 -> Word32 -> IO Int32
foreign import ccall unsafe "yices.h"
yices_pp_term :: Ptr CFile -> YExpr -> Word32 -> Word32 -> Word32 -> IO Int32
foreign import ccall unsafe "yices.h"
yices_print_model :: Ptr CFile -> Ptr YModel -> IO ()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.