_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
|
---|---|---|---|---|---|---|---|---|
be698f8df0af33310ee7b6c2a9f911002e11fe8f1ba02b639a693bafd5a1eba1 | returntocorp/semgrep | Exit_code.mli | (*
Exit codes of the semgrep executable (not just 'semgrep scan').
Some of those exit codes are also (ab)used to represent some error code
for errors reported in the semgrep CLI JSON output.
*)
(* This ensures that exit codes are declared and documented here. *)
type t = private int
(* 'to_int x' is the same as '(x :> int)'. *)
val to_int : t -> int
val of_int : int -> t
Standard exit codes .
All calls to exit must use one of these .
Standard exit codes.
All calls to exit must use one of these.
*)
val ok : t
val findings : t
val fatal : t
val invalid_code : t
val invalid_pattern : t
val unparseable_yaml : t
val missing_config : t
val invalid_language : t
val invalid_api_key : t
val scan_fail : t
(* to remove at some point *)
val not_implemented_in_osemgrep : t
| null | https://raw.githubusercontent.com/returntocorp/semgrep/855abad9ada6ea5fd72d437fd69ff2e5fa42c1f1/src/osemgrep/core/Exit_code.mli | ocaml |
Exit codes of the semgrep executable (not just 'semgrep scan').
Some of those exit codes are also (ab)used to represent some error code
for errors reported in the semgrep CLI JSON output.
This ensures that exit codes are declared and documented here.
'to_int x' is the same as '(x :> int)'.
to remove at some point |
type t = private int
val to_int : t -> int
val of_int : int -> t
Standard exit codes .
All calls to exit must use one of these .
Standard exit codes.
All calls to exit must use one of these.
*)
val ok : t
val findings : t
val fatal : t
val invalid_code : t
val invalid_pattern : t
val unparseable_yaml : t
val missing_config : t
val invalid_language : t
val invalid_api_key : t
val scan_fail : t
val not_implemented_in_osemgrep : t
|
df9c5e8738720402c0444a21aecc4be9e05e342ffcb6aba1b8672873247f2910 | 0install/0install | windows_api.disabled.ml | Copyright ( C ) 2019 ,
See the README file for details , or visit .
See the README file for details, or visit . *)
let v ~wow64:_ = failwith "Not a Windows build!"
| null | https://raw.githubusercontent.com/0install/0install/22eebdbe51a9f46cda29eed3e9e02e37e36b2d18/src/support/windows_api.disabled.ml | ocaml | Copyright ( C ) 2019 ,
See the README file for details , or visit .
See the README file for details, or visit . *)
let v ~wow64:_ = failwith "Not a Windows build!"
|
|
59b365786ebd9fed4f0a208d9400112d50ef56d4e9beb05edafa6b7e48226d7f | TrustInSoft/tis-kernel | ast.mli | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* 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 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(** Utilities for [Syntax]. *)
(* -------------------------------------------------------------------------- *)
open Syntax
val range : e -> position
val raise_at : e -> exn -> 'b
val error_at : e -> ('a,Format.formatter,unit,'b) format4 -> 'a
val reset : unit -> unit
val fresh : unit -> int
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/qed/top/ast.mli | 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.
************************************************************************
--------------------------------------------------------------------------
* Utilities for [Syntax].
-------------------------------------------------------------------------- | This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Syntax
val range : e -> position
val raise_at : e -> exn -> 'b
val error_at : e -> ('a,Format.formatter,unit,'b) format4 -> 'a
val reset : unit -> unit
val fresh : unit -> int
|
6a0c99d866cff5717b5a53a9e1233c2c2126802500f0041b3d89d87b775f08dc | edbutler/nonograms-rule-synthesis | compile.rkt | #lang rosette/safe
(provide
program-map-expressions-postorder
features-used-by-program
program-limited-to-features?
strip-unused-patterns
same-pattern?)
(require
(only-in racket error set=? mutable-seteq mutable-set set-add! set-member? set->list struct-copy exit set-subtract set-empty? for)
rosette/lib/match
"rules.rkt"
"action.rkt"
"ast.rkt"
"dsl-pretty.rkt"
"../core/core.rkt")
list of all expressions ( ? ) part of this program , including non - terminal expressions
; (so subexpressions appear both in the list and as part of other elements of the list).
(define (program-for-each-expr f prog)
(define (rec p) (program-for-each-expr f p))
(match prog [(Expr) (f prog)] [_ (void)])
(match prog
[(Program _ cnd act)
(rec cnd)
(rec act)]
[(Fill _ offset start end)
(rec offset)
(rec start)
(rec end)]
[(Filled? e _) (rec e)]
[(HighestStartCell e) (rec e)]
[(LowestEndCell e) (rec e)]
[(And l r)
(rec l)
(rec r)]
[(Apply _ args) (for-each rec args)]
[(Unique? i e) (rec e)]
[(TerminalExpr) (void)]))
(define (program-map-expressions f prog)
(match prog
[(Program pat cnd act)
(Program pat (f cnd) (f act))]
[(Fill v offset start end)
(Fill v (f offset) (f start) (f end))]
[(Filled? e v)
(Filled? (f e) v)]
[(HighestStartCell e)
(HighestStartCell (f e))]
[(LowestEndCell e)
(LowestEndCell (f e))]
[(And l r)
(And (f l) (f r))]
[(Apply op args)
(Apply op (map f args))]
[(Unique? i e)
(Unique? i (f e))]
[(TerminalExpr)
prog]))
Recurses over the structure of the given program , invoking f on each subexpression .
; Will recurse on the subexpresions, replacing the sub-expressions with any new value.
; Then will invoke f on the resulting new expression.
; If f returns a non-false value, the expression will be replaced with that return value.
; Otherwise it will be the result of the recursive call.
(define (program-map-expressions-postorder f prog)
(define v (program-map-expressions (curry program-map-expressions-postorder f) prog))
(f v))
Program ? - > ( symbol ? )
(define (features-used-by-program prog)
(define used (mutable-seteq))
; Apply has to be handled in a special manner because it overloads several features
(define (visit s)
(match s
[(Apply op _)
(set-add! used (feature-of-operator op))]
[_ (set-add! used (feature-of-ast-element s))]))
(program-for-each-expr visit prog)
; have to add pattern features specially
(for ([p (Program-pattern prog)])
(match p
; assumes the type name is the same as the feature name (which is true)
[(ListPattern t) (set-add! used t)]
[(NoPattern) (void)]))
(set->list used))
(define (program-limited-to-features? features prog)
(set-empty? (set-subtract (features-used-by-program prog) features)))
; Program? -> Program?
replaces any unferenced pattern with ( )
(define (strip-unused-patterns prog)
(define used-bindings (mutable-set))
(define (get e)
(match e
[(BindingIndex i) i]
[(BindingValue i) i]
[(Unique? i _) i]
[_ #f]))
(program-for-each-expr
(λ (e)
(define x (get e))
(when x (set-add! used-bindings x)))
prog)
(define new-patterns
(mapi
(λ (i b)
(if (set-member? used-bindings i)
b
(NoPattern)))
(Program-pattern prog)))
(struct-copy Program prog [pattern new-patterns]))
Program ? , Program ? - > boolean ?
; not rosette safe
(define (same-pattern? p1 p2)
(set=? (Program-pattern p1) (Program-pattern p2)))
| null | https://raw.githubusercontent.com/edbutler/nonograms-rule-synthesis/16f8dacb17bd77c9d927ab9fa0b8c1678dc68088/src/nonograms/compile.rkt | racket | (so subexpressions appear both in the list and as part of other elements of the list).
Will recurse on the subexpresions, replacing the sub-expressions with any new value.
Then will invoke f on the resulting new expression.
If f returns a non-false value, the expression will be replaced with that return value.
Otherwise it will be the result of the recursive call.
Apply has to be handled in a special manner because it overloads several features
have to add pattern features specially
assumes the type name is the same as the feature name (which is true)
Program? -> Program?
not rosette safe | #lang rosette/safe
(provide
program-map-expressions-postorder
features-used-by-program
program-limited-to-features?
strip-unused-patterns
same-pattern?)
(require
(only-in racket error set=? mutable-seteq mutable-set set-add! set-member? set->list struct-copy exit set-subtract set-empty? for)
rosette/lib/match
"rules.rkt"
"action.rkt"
"ast.rkt"
"dsl-pretty.rkt"
"../core/core.rkt")
list of all expressions ( ? ) part of this program , including non - terminal expressions
(define (program-for-each-expr f prog)
(define (rec p) (program-for-each-expr f p))
(match prog [(Expr) (f prog)] [_ (void)])
(match prog
[(Program _ cnd act)
(rec cnd)
(rec act)]
[(Fill _ offset start end)
(rec offset)
(rec start)
(rec end)]
[(Filled? e _) (rec e)]
[(HighestStartCell e) (rec e)]
[(LowestEndCell e) (rec e)]
[(And l r)
(rec l)
(rec r)]
[(Apply _ args) (for-each rec args)]
[(Unique? i e) (rec e)]
[(TerminalExpr) (void)]))
(define (program-map-expressions f prog)
(match prog
[(Program pat cnd act)
(Program pat (f cnd) (f act))]
[(Fill v offset start end)
(Fill v (f offset) (f start) (f end))]
[(Filled? e v)
(Filled? (f e) v)]
[(HighestStartCell e)
(HighestStartCell (f e))]
[(LowestEndCell e)
(LowestEndCell (f e))]
[(And l r)
(And (f l) (f r))]
[(Apply op args)
(Apply op (map f args))]
[(Unique? i e)
(Unique? i (f e))]
[(TerminalExpr)
prog]))
Recurses over the structure of the given program , invoking f on each subexpression .
(define (program-map-expressions-postorder f prog)
(define v (program-map-expressions (curry program-map-expressions-postorder f) prog))
(f v))
Program ? - > ( symbol ? )
(define (features-used-by-program prog)
(define used (mutable-seteq))
(define (visit s)
(match s
[(Apply op _)
(set-add! used (feature-of-operator op))]
[_ (set-add! used (feature-of-ast-element s))]))
(program-for-each-expr visit prog)
(for ([p (Program-pattern prog)])
(match p
[(ListPattern t) (set-add! used t)]
[(NoPattern) (void)]))
(set->list used))
(define (program-limited-to-features? features prog)
(set-empty? (set-subtract (features-used-by-program prog) features)))
replaces any unferenced pattern with ( )
(define (strip-unused-patterns prog)
(define used-bindings (mutable-set))
(define (get e)
(match e
[(BindingIndex i) i]
[(BindingValue i) i]
[(Unique? i _) i]
[_ #f]))
(program-for-each-expr
(λ (e)
(define x (get e))
(when x (set-add! used-bindings x)))
prog)
(define new-patterns
(mapi
(λ (i b)
(if (set-member? used-bindings i)
b
(NoPattern)))
(Program-pattern prog)))
(struct-copy Program prog [pattern new-patterns]))
Program ? , Program ? - > boolean ?
(define (same-pattern? p1 p2)
(set=? (Program-pattern p1) (Program-pattern p2)))
|
ae7248cf58e99d615a9bcb0ce58d9fb18ddda68abb776216ade35b4df73236b8 | OCamlPro/scilint | interpWebLib.ml | open InterpLib
let help_lines = [
"SciWeb is a simple online interpreter for the Scilab language developed by OCamlPro. ";
"It was developed as part of the Richelieu FUI R&D project, as an online demonstrator for OCaml parsers and interpreters for Scilab.";
"";
"SciWeb operations are executed in your browser only, there are no interactions with any server,";
"so the available operations are much more limited and slower than the standard Scilab interpreter.";
"All functions are implemented in OCaml, translated to Javascript.";
"";
"The following standard functions are available: argn, clear, disp, error, execstr, eye, global, inttype,";
" list, mlist, null, poly, quit, size, string, tlist, type, typeof, zeros";
"The following math functions are available: abs, binomial, binomial_coefficient, ceil, cos, cumsum, double, exp, factorial, floor, int, log,";
" mean, mean_vector, median_vector, ones, quartiles, rand_float, rand_int, sin, sqrt, sum, tan, tirage_entier, tirage_real, variance.";
^ ( String.concat " , " ( List.sort compare [
" cos " ; " sin " ; " tan " ; " exp " ; " int " ; " log " ; " sqrt " ; " floor " ; " abs " ; " ceil " ;
" mean " ; " ones " ; " factorial " ; " " ; " binomial";"sum " ; " cumsum " ; " median_vector";"mean_vector " ; " variance " ; " quartiles " ; " rand_int " ; " rand_float " ; " tirage_entier " ; " tirage_real " ; " double " ;
] ) ) ;
"cos"; "sin"; "tan"; "exp"; "int"; "log"; "sqrt"; "floor"; "abs"; "ceil";
"mean"; "ones"; "factorial"; "binomial_coefficient"; "binomial";"sum"; "cumsum" ; "median_vector";"mean_vector"; "variance"; "quartiles"; "rand_int"; "rand_float"; "tirage_entier"; "tirage_real"; "double";
])); *)
"The following plotting functions are available: bar, clf, grid, plot, xtitle";
"";
"Contact information:";
" OCamlPro SAS, Gif-sur-Yvette, France";
" Mail: <>";
" Web: /";
"";
"SciWeb code is open-source and available: /";
"";
"Basic help:";
" - Use the arrow buttons to create boxes above or below a box.";
" - Click out of box that you just modified or hit tab to update the results.";
" - Use the cross button to remove a box.";
]
open InterpCore.Values
let () =
register_library (fun state lib ->
(*--------------------- prompt ------------------------------------*)
register_function lib state "prompt" (string @-> string)
(fun msg ->
Js.Opt.case
(Dom_html.window##prompt (Js.string msg, Js.string ""))
(fun () -> "")
(fun s -> Js.to_string s)) ;
register_function lib state "alert" (string @-> void)
(fun msg -> Dom_html.window##alert (Js.string msg)) ;
(*--------------------- help --------------------------------------*)
let help l =
Printf.printf "%s\n%!" (String.concat "\n" help_lines);
in
register_function lib state "help" (void @-> null) help;
--------------------- -------------------------------------
let eval state lib name s =
Interp.treat_source ~set_ans:false
state lib (ScilabParserAst.String (name, s))
in
register_function lib state "execstr" (string @-> null) (fun content ->
eval state lib content content
);
register_function lib state "execstr" (Arg (Matrix String) @-> null)
(fun m ->
let w, h = matrix_size m in
let b = Buffer.create 100 in
for i = 1 to h do
for j = 1 to w do
Buffer.add_string b (matrix_get m j i);
Buffer.add_char b '\n'
done;
done;
let s = Buffer.contents b in
eval state lib s s
);
register_function lib state "lycee" (void @-> null) (fun filename ->
let rec iter = function
| OCamlRes.Res.File (filename, content) ->
eval state lib filename content
| OCamlRes.Res.Dir (dirname, content) ->
List.iter iter content
| OCamlRes.Res.Error _ -> ()
in
List.iter iter InterpLycee.root;
()
);
);
| null | https://raw.githubusercontent.com/OCamlPro/scilint/9d9ddd8e1630ddeae7f4f875bce62b2f65ec17d8/src/interp/interpWebLib.ml | ocaml | --------------------- prompt ------------------------------------
--------------------- help -------------------------------------- | open InterpLib
let help_lines = [
"SciWeb is a simple online interpreter for the Scilab language developed by OCamlPro. ";
"It was developed as part of the Richelieu FUI R&D project, as an online demonstrator for OCaml parsers and interpreters for Scilab.";
"";
"SciWeb operations are executed in your browser only, there are no interactions with any server,";
"so the available operations are much more limited and slower than the standard Scilab interpreter.";
"All functions are implemented in OCaml, translated to Javascript.";
"";
"The following standard functions are available: argn, clear, disp, error, execstr, eye, global, inttype,";
" list, mlist, null, poly, quit, size, string, tlist, type, typeof, zeros";
"The following math functions are available: abs, binomial, binomial_coefficient, ceil, cos, cumsum, double, exp, factorial, floor, int, log,";
" mean, mean_vector, median_vector, ones, quartiles, rand_float, rand_int, sin, sqrt, sum, tan, tirage_entier, tirage_real, variance.";
^ ( String.concat " , " ( List.sort compare [
" cos " ; " sin " ; " tan " ; " exp " ; " int " ; " log " ; " sqrt " ; " floor " ; " abs " ; " ceil " ;
" mean " ; " ones " ; " factorial " ; " " ; " binomial";"sum " ; " cumsum " ; " median_vector";"mean_vector " ; " variance " ; " quartiles " ; " rand_int " ; " rand_float " ; " tirage_entier " ; " tirage_real " ; " double " ;
] ) ) ;
"cos"; "sin"; "tan"; "exp"; "int"; "log"; "sqrt"; "floor"; "abs"; "ceil";
"mean"; "ones"; "factorial"; "binomial_coefficient"; "binomial";"sum"; "cumsum" ; "median_vector";"mean_vector"; "variance"; "quartiles"; "rand_int"; "rand_float"; "tirage_entier"; "tirage_real"; "double";
])); *)
"The following plotting functions are available: bar, clf, grid, plot, xtitle";
"";
"Contact information:";
" OCamlPro SAS, Gif-sur-Yvette, France";
" Mail: <>";
" Web: /";
"";
"SciWeb code is open-source and available: /";
"";
"Basic help:";
" - Use the arrow buttons to create boxes above or below a box.";
" - Click out of box that you just modified or hit tab to update the results.";
" - Use the cross button to remove a box.";
]
open InterpCore.Values
let () =
register_library (fun state lib ->
register_function lib state "prompt" (string @-> string)
(fun msg ->
Js.Opt.case
(Dom_html.window##prompt (Js.string msg, Js.string ""))
(fun () -> "")
(fun s -> Js.to_string s)) ;
register_function lib state "alert" (string @-> void)
(fun msg -> Dom_html.window##alert (Js.string msg)) ;
let help l =
Printf.printf "%s\n%!" (String.concat "\n" help_lines);
in
register_function lib state "help" (void @-> null) help;
--------------------- -------------------------------------
let eval state lib name s =
Interp.treat_source ~set_ans:false
state lib (ScilabParserAst.String (name, s))
in
register_function lib state "execstr" (string @-> null) (fun content ->
eval state lib content content
);
register_function lib state "execstr" (Arg (Matrix String) @-> null)
(fun m ->
let w, h = matrix_size m in
let b = Buffer.create 100 in
for i = 1 to h do
for j = 1 to w do
Buffer.add_string b (matrix_get m j i);
Buffer.add_char b '\n'
done;
done;
let s = Buffer.contents b in
eval state lib s s
);
register_function lib state "lycee" (void @-> null) (fun filename ->
let rec iter = function
| OCamlRes.Res.File (filename, content) ->
eval state lib filename content
| OCamlRes.Res.Dir (dirname, content) ->
List.iter iter content
| OCamlRes.Res.Error _ -> ()
in
List.iter iter InterpLycee.root;
()
);
);
|
23a7df1f95d9821dd5b72fe818e15dac0cc06dc42f6abc2caad580f842a9f938 | paurkedal/ocaml-prime | test_map.ml | Copyright ( C ) 2014 - -2022 Petter A. Urkedal < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the LGPL-3.0 Linking Exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library . If not , see
* < / > and < > , respectively .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the LGPL-3.0 Linking Exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library. If not, see
* </> and <>, respectively.
*)
module Int_map = Prime_map.Make (struct type t = int let compare = compare end)
let run () =
let m = Prime_int.fold_to (fun k -> Int_map.add k (-k)) 100 Int_map.empty in
let m2 = Int_map.filter (fun k _ -> k mod 2 = 0) m in
let m3 = Int_map.filter (fun k _ -> k mod 3 = 0) m in
let a, b, ab = Int_map.split_union (fun _ i j -> (i, j)) m2 m3 in
let a' = Int_map.compl m3 m2 in
let b' = Int_map.compl m2 m3 in
let ab' = Int_map.map2t (fun i j -> (i, j)) m2 m3 in
assert (Int_map.equal (=) a a');
assert (Int_map.equal (=) b b');
assert (Int_map.equal (=) ab ab')
| null | https://raw.githubusercontent.com/paurkedal/ocaml-prime/42efa85317069d726e8e3989e51c24ba03c56b47/tests/test_map.ml | ocaml | Copyright ( C ) 2014 - -2022 Petter A. Urkedal < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the LGPL-3.0 Linking Exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library . If not , see
* < / > and < > , respectively .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the LGPL-3.0 Linking Exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library. If not, see
* </> and <>, respectively.
*)
module Int_map = Prime_map.Make (struct type t = int let compare = compare end)
let run () =
let m = Prime_int.fold_to (fun k -> Int_map.add k (-k)) 100 Int_map.empty in
let m2 = Int_map.filter (fun k _ -> k mod 2 = 0) m in
let m3 = Int_map.filter (fun k _ -> k mod 3 = 0) m in
let a, b, ab = Int_map.split_union (fun _ i j -> (i, j)) m2 m3 in
let a' = Int_map.compl m3 m2 in
let b' = Int_map.compl m2 m3 in
let ab' = Int_map.map2t (fun i j -> (i, j)) m2 m3 in
assert (Int_map.equal (=) a a');
assert (Int_map.equal (=) b b');
assert (Int_map.equal (=) ab ab')
|
|
4057a878f523c3a7f125ad707d622ff21c354f7adf852deef94e9d97efd60ef2 | chrisdone/bdo | Main.hs | # LANGUAGE ViewPatterns #
{-# LANGUAGE OverloadedStrings #-}
-- | Main bdo server.
module Main where
import Bdo
import Control.Concurrent
import Control.Exception
import Control.Monad
import Data.Aeson
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import Http
import Network
import Network.URL
import Paths_bdo
import Prelude hiding (catch)
import System.Environment
import System.IO
-- | Main entry point.
main :: IO ()
main = do
(listenPort:_) <- getArgs
hSetBuffering stdout NoBuffering
startServer (read listenPort)
| null | https://raw.githubusercontent.com/chrisdone/bdo/c96cb6aa9e97fa3491185c50dee0f77a13241010/src/Main.hs | haskell | # LANGUAGE OverloadedStrings #
| Main bdo server.
| Main entry point. | # LANGUAGE ViewPatterns #
module Main where
import Bdo
import Control.Concurrent
import Control.Exception
import Control.Monad
import Data.Aeson
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import Http
import Network
import Network.URL
import Paths_bdo
import Prelude hiding (catch)
import System.Environment
import System.IO
main :: IO ()
main = do
(listenPort:_) <- getArgs
hSetBuffering stdout NoBuffering
startServer (read listenPort)
|
51d5dcde5c68ed035161c7196f67beac9391168d18e60670f7e4f43e5db41b9b | racket/scribble | reader.rkt | #lang s-exp syntax/module-reader
scribble/text/lang
#:read scribble:read-inside
#:read-syntax scribble:read-syntax-inside
#:whole-body-readers? #t
#:info (scribble-base-reader-info)
(require (prefix-in scribble: scribble/reader)
(only-in scribble/base/reader scribble-base-reader-info))
| null | https://raw.githubusercontent.com/racket/scribble/beb2d9834169665121d34b5f3195ddf252c3c998/scribble-text-lib/scribble/text/lang/reader.rkt | racket | #lang s-exp syntax/module-reader
scribble/text/lang
#:read scribble:read-inside
#:read-syntax scribble:read-syntax-inside
#:whole-body-readers? #t
#:info (scribble-base-reader-info)
(require (prefix-in scribble: scribble/reader)
(only-in scribble/base/reader scribble-base-reader-info))
|
|
e4f11299c07eea473d03a986a7272974d9e6e182ef99dd64ba94fa45a9d333f9 | bobeff/playground | 026.rkt | Exercise 26 . What do you expect as the value of this program :
;
; (define (string-insert s i)
; (string-append (substring s 0 i)
; "_"
; (substring s i)))
;
( string - insert " helloworld " 6 )
;
Confirm your expectation with and its stepper .
#lang racket
(require rackunit)
(define (string-insert s i)
(string-append (substring s 0 i)
"_"
(substring s i)))
(check-equal? (string-insert "helloworld" 6) "hellow_orld")
- > ( string - insert " helloworld " 6 )
- > ( string - append ( substring " helloworld 0 6 ) " _ " ( substring " helloworld " 6 ) )
- > ( string - append " hellow " " _ " ( substring " helloworld " 6 ) )
- > ( string append " hellow " " _ " " orld " )
; -> "hellow_orld"
| null | https://raw.githubusercontent.com/bobeff/playground/7072dbd7e0acd690749abe1498dd5f247cc21637/htdp-second-edition/exercises/026.rkt | racket |
(define (string-insert s i)
(string-append (substring s 0 i)
"_"
(substring s i)))
-> "hellow_orld" | Exercise 26 . What do you expect as the value of this program :
( string - insert " helloworld " 6 )
Confirm your expectation with and its stepper .
#lang racket
(require rackunit)
(define (string-insert s i)
(string-append (substring s 0 i)
"_"
(substring s i)))
(check-equal? (string-insert "helloworld" 6) "hellow_orld")
- > ( string - insert " helloworld " 6 )
- > ( string - append ( substring " helloworld 0 6 ) " _ " ( substring " helloworld " 6 ) )
- > ( string - append " hellow " " _ " ( substring " helloworld " 6 ) )
- > ( string append " hellow " " _ " " orld " )
|
4037ebc81dc57552d60bdc6f9b9b0b8c75a1707299c562ea137ce915071cd45c | ocaml/ocaml | polyvars.ml | (* TEST
* expect
*)
type ab = [ `A | `B ];;
let f (x : [`A]) = match x with #ab -> 1;;
[%%expect{|
type ab = [ `A | `B ]
Line 2, characters 32-35:
2 | let f (x : [`A]) = match x with #ab -> 1;;
^^^
Error: This pattern matches values of type [? `A | `B ]
but a pattern was expected which matches values of type [ `A ]
The second variant type does not allow tag(s) `B
|}];;
let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
[%%expect{|
Line 1, characters 31-34:
1 | let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
^^^
Error: This pattern matches values of type [? `B ]
but a pattern was expected which matches values of type [ `A ]
The second variant type does not allow tag(s) `B
|}];;
let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
[%%expect{|
Line 1, characters 34-36:
1 | let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
^^
Error: This pattern matches values of type [? `B ]
but a pattern was expected which matches values of type [ `A ]
The second variant type does not allow tag(s) `B
|}];;
let f (x : [< `A | `B]) = match x with `A | `B | `C -> 0;; (* warn *)
[%%expect{|
Line 1, characters 49-51:
1 | let f (x : [< `A | `B]) = match x with `A | `B | `C -> 0;; (* warn *)
^^
Warning 12 [redundant-subpat]: this sub-pattern is unused.
val f : [< `A | `B ] -> int = <fun>
|}];;
let f (x : [`A | `B]) = match x with `A | `B | `C -> 0;; (* fail *)
[%%expect{|
Line 1, characters 47-49:
1 | let f (x : [`A | `B]) = match x with `A | `B | `C -> 0;; (* fail *)
^^
Error: This pattern matches values of type [? `C ]
but a pattern was expected which matches values of type [ `A | `B ]
The second variant type does not allow tag(s) `C
|}];;
(* imported from in poly.ml *)
type t = A | B;;
function `A,_ -> 1 | _,A -> 2 | _,B -> 3;;
function `A,_ -> 1 | _,(A|B) -> 2;;
function Some `A, _ -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;;
function Some `A, A -> 1 | Some `A, B -> 1
| Some _, A -> 2 | None, A -> 3 | _, B -> 4;;
function A, `A -> 1 | A, `B -> 2 | B, _ -> 3;;
function `A, A -> 1 | `B, A -> 2 | _, B -> 3;;
function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
function `B,1 -> 1 | _,1 -> 2;;
function 1,`B -> 1 | 1,_ -> 2;;
[%%expect {|
type t = A | B
- : [> `A ] * t -> int = <fun>
- : [> `A ] * t -> int = <fun>
- : [> `A ] option * t -> int = <fun>
- : [> `A ] option * t -> int = <fun>
- : t * [< `A | `B ] -> int = <fun>
- : [< `A | `B ] * t -> int = <fun>
Line 9, characters 0-41:
9 | function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(`AnyOtherTag, `AnyOtherTag)
- : [> `A | `B ] * [> `A | `B ] -> int = <fun>
Line 10, characters 0-29:
10 | function `B,1 -> 1 | _,1 -> 2;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(_, 0)
Line 10, characters 21-24:
10 | function `B,1 -> 1 | _,1 -> 2;;
^^^
Warning 11 [redundant-case]: this match case is unused.
- : [< `B ] * int -> int = <fun>
Line 11, characters 0-29:
11 | function 1,`B -> 1 | 1,_ -> 2;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(0, _)
Line 11, characters 21-24:
11 | function 1,`B -> 1 | 1,_ -> 2;;
^^^
Warning 11 [redundant-case]: this match case is unused.
- : int * [< `B ] -> int = <fun>
|}];;
(* PR#6787 *)
let revapply x f = f x;;
let f x (g : [< `Foo]) =
let y = `Bar x, g in
revapply y (fun ((`Bar i), _) -> i);;
(* f : 'a -> [< `Foo ] -> 'a *)
[%%expect{|
val revapply : 'a -> ('a -> 'b) -> 'b = <fun>
val f : 'a -> [< `Foo ] -> 'a = <fun>
|}];;
(* PR#6124 *)
let f : ([`A | `B ] as 'a) -> [> 'a] -> unit = fun x (y : [> 'a]) -> ();;
let f (x : [`A | `B] as 'a) (y : [> 'a]) = ();;
[%%expect{|
Line 1, characters 61-63:
1 | let f : ([`A | `B ] as 'a) -> [> 'a] -> unit = fun x (y : [> 'a]) -> ();;
^^
Error: The type 'a does not expand to a polymorphic variant type
Hint: Did you mean `a?
|}]
(* PR#5927 *)
type 'a foo = 'a constraint 'a = [< `Tag of & int];;
[%%expect{|
type 'a foo = 'a constraint 'a = [< `Tag of & int ]
|}]
PR#7704
type t = private [> `A of string ];;
function (`A x : t) -> x;;
[%%expect{|
type t = private [> `A of string ]
Line 2, characters 0-24:
2 | function (`A x : t) -> x;;
^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
`<some private tag>
- : t -> string = <fun>
|}]
let f = function `AnyOtherTag, _ -> 1 | _, (`AnyOtherTag|`AnyOtherTag') -> 2;;
[%%expect{|
Line 1, characters 8-76:
1 | let f = function `AnyOtherTag, _ -> 1 | _, (`AnyOtherTag|`AnyOtherTag') -> 2;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(`AnyOtherTag', `AnyOtherTag'')
val f : [> `AnyOtherTag ] * [> `AnyOtherTag | `AnyOtherTag' ] -> int = <fun>
|}]
let x:(([`A] as 'a)* ([`B] as 'a)) = [`A]
[%%expect {|
Line 1, characters 22-32:
1 | let x:(([`A] as 'a)* ([`B] as 'a)) = [`A]
^^^^^^^^^^
Error: This alias is bound to type [ `B ] but is used as an instance of type
[ `A ]
These two variant types have no intersection
|}]
type t = private [< `A]
let f: t -> [ `A ] = fun x -> x
[%%expect {|
type t = private [< `A ]
Line 2, characters 30-31:
2 | let f: t -> [ `A ] = fun x -> x
^
Error: This expression has type t but an expression was expected of type
[ `A ]
The first variant type is private, it may not allow the tag(s) `A
|}]
(** Check that the non-regularity error message is robust to permutation *)
type ('a,'b,'c,'d,'e) a = [ `A of ('d,'a,'e,'c,'b) b ]
and ('a,'b,'c,'d,'e) b = [ `B of ('c,'d,'e,'a,'b) c ]
and ('a,'b,'c,'d,'e) c = [ `C of ('a,'b,'c,'d,'e) a ]
[%%expect {|
Line 3, characters 0-54:
3 | type ('a,'b,'c,'d,'e) a = [ `A of ('d,'a,'e,'c,'b) b ]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This recursive type is not regular.
The type constructor a is defined as
type ('a, 'b, 'c, 'd, 'e) a
but it is used as
('e, 'c, 'b, 'd, 'a) a
after the following expansion(s):
[ `A of ('d, 'a, 'e, 'c, 'b) b ] contains ('d, 'a, 'e, 'c, 'b) b,
('d, 'a, 'e, 'c, 'b) b = [ `B of ('e, 'c, 'b, 'd, 'a) c ],
[ `B of ('e, 'c, 'b, 'd, 'a) c ] contains ('e, 'c, 'b, 'd, 'a) c,
('e, 'c, 'b, 'd, 'a) c = [ `C of ('e, 'c, 'b, 'd, 'a) a ],
[ `C of ('e, 'c, 'b, 'd, 'a) a ] contains ('e, 'c, 'b, 'd, 'a) a
All uses need to match the definition for the recursive type to be regular.
|}]
PR 10762
type a = int
type t = [ `A of a ]
let inspect: [< t ] -> unit = function
| `A 0 -> ()
| `A _ -> ()
[%%expect {|
type a = int
type t = [ `A of a ]
val inspect : [< `A of a & int ] -> unit = <fun>
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-misc/polyvars.ml | ocaml | TEST
* expect
warn
warn
fail
fail
imported from in poly.ml
PR#6787
f : 'a -> [< `Foo ] -> 'a
PR#6124
PR#5927
* Check that the non-regularity error message is robust to permutation |
type ab = [ `A | `B ];;
let f (x : [`A]) = match x with #ab -> 1;;
[%%expect{|
type ab = [ `A | `B ]
Line 2, characters 32-35:
2 | let f (x : [`A]) = match x with #ab -> 1;;
^^^
Error: This pattern matches values of type [? `A | `B ]
but a pattern was expected which matches values of type [ `A ]
The second variant type does not allow tag(s) `B
|}];;
let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
[%%expect{|
Line 1, characters 31-34:
1 | let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
^^^
Error: This pattern matches values of type [? `B ]
but a pattern was expected which matches values of type [ `A ]
The second variant type does not allow tag(s) `B
|}];;
let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
[%%expect{|
Line 1, characters 34-36:
1 | let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
^^
Error: This pattern matches values of type [? `B ]
but a pattern was expected which matches values of type [ `A ]
The second variant type does not allow tag(s) `B
|}];;
[%%expect{|
Line 1, characters 49-51:
^^
Warning 12 [redundant-subpat]: this sub-pattern is unused.
val f : [< `A | `B ] -> int = <fun>
|}];;
[%%expect{|
Line 1, characters 47-49:
^^
Error: This pattern matches values of type [? `C ]
but a pattern was expected which matches values of type [ `A | `B ]
The second variant type does not allow tag(s) `C
|}];;
type t = A | B;;
function `A,_ -> 1 | _,A -> 2 | _,B -> 3;;
function `A,_ -> 1 | _,(A|B) -> 2;;
function Some `A, _ -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;;
function Some `A, A -> 1 | Some `A, B -> 1
| Some _, A -> 2 | None, A -> 3 | _, B -> 4;;
function A, `A -> 1 | A, `B -> 2 | B, _ -> 3;;
function `A, A -> 1 | `B, A -> 2 | _, B -> 3;;
function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
function `B,1 -> 1 | _,1 -> 2;;
function 1,`B -> 1 | 1,_ -> 2;;
[%%expect {|
type t = A | B
- : [> `A ] * t -> int = <fun>
- : [> `A ] * t -> int = <fun>
- : [> `A ] option * t -> int = <fun>
- : [> `A ] option * t -> int = <fun>
- : t * [< `A | `B ] -> int = <fun>
- : [< `A | `B ] * t -> int = <fun>
Line 9, characters 0-41:
9 | function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(`AnyOtherTag, `AnyOtherTag)
- : [> `A | `B ] * [> `A | `B ] -> int = <fun>
Line 10, characters 0-29:
10 | function `B,1 -> 1 | _,1 -> 2;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(_, 0)
Line 10, characters 21-24:
10 | function `B,1 -> 1 | _,1 -> 2;;
^^^
Warning 11 [redundant-case]: this match case is unused.
- : [< `B ] * int -> int = <fun>
Line 11, characters 0-29:
11 | function 1,`B -> 1 | 1,_ -> 2;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(0, _)
Line 11, characters 21-24:
11 | function 1,`B -> 1 | 1,_ -> 2;;
^^^
Warning 11 [redundant-case]: this match case is unused.
- : int * [< `B ] -> int = <fun>
|}];;
let revapply x f = f x;;
let f x (g : [< `Foo]) =
let y = `Bar x, g in
revapply y (fun ((`Bar i), _) -> i);;
[%%expect{|
val revapply : 'a -> ('a -> 'b) -> 'b = <fun>
val f : 'a -> [< `Foo ] -> 'a = <fun>
|}];;
let f : ([`A | `B ] as 'a) -> [> 'a] -> unit = fun x (y : [> 'a]) -> ();;
let f (x : [`A | `B] as 'a) (y : [> 'a]) = ();;
[%%expect{|
Line 1, characters 61-63:
1 | let f : ([`A | `B ] as 'a) -> [> 'a] -> unit = fun x (y : [> 'a]) -> ();;
^^
Error: The type 'a does not expand to a polymorphic variant type
Hint: Did you mean `a?
|}]
type 'a foo = 'a constraint 'a = [< `Tag of & int];;
[%%expect{|
type 'a foo = 'a constraint 'a = [< `Tag of & int ]
|}]
PR#7704
type t = private [> `A of string ];;
function (`A x : t) -> x;;
[%%expect{|
type t = private [> `A of string ]
Line 2, characters 0-24:
2 | function (`A x : t) -> x;;
^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
`<some private tag>
- : t -> string = <fun>
|}]
let f = function `AnyOtherTag, _ -> 1 | _, (`AnyOtherTag|`AnyOtherTag') -> 2;;
[%%expect{|
Line 1, characters 8-76:
1 | let f = function `AnyOtherTag, _ -> 1 | _, (`AnyOtherTag|`AnyOtherTag') -> 2;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(`AnyOtherTag', `AnyOtherTag'')
val f : [> `AnyOtherTag ] * [> `AnyOtherTag | `AnyOtherTag' ] -> int = <fun>
|}]
let x:(([`A] as 'a)* ([`B] as 'a)) = [`A]
[%%expect {|
Line 1, characters 22-32:
1 | let x:(([`A] as 'a)* ([`B] as 'a)) = [`A]
^^^^^^^^^^
Error: This alias is bound to type [ `B ] but is used as an instance of type
[ `A ]
These two variant types have no intersection
|}]
type t = private [< `A]
let f: t -> [ `A ] = fun x -> x
[%%expect {|
type t = private [< `A ]
Line 2, characters 30-31:
2 | let f: t -> [ `A ] = fun x -> x
^
Error: This expression has type t but an expression was expected of type
[ `A ]
The first variant type is private, it may not allow the tag(s) `A
|}]
type ('a,'b,'c,'d,'e) a = [ `A of ('d,'a,'e,'c,'b) b ]
and ('a,'b,'c,'d,'e) b = [ `B of ('c,'d,'e,'a,'b) c ]
and ('a,'b,'c,'d,'e) c = [ `C of ('a,'b,'c,'d,'e) a ]
[%%expect {|
Line 3, characters 0-54:
3 | type ('a,'b,'c,'d,'e) a = [ `A of ('d,'a,'e,'c,'b) b ]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This recursive type is not regular.
The type constructor a is defined as
type ('a, 'b, 'c, 'd, 'e) a
but it is used as
('e, 'c, 'b, 'd, 'a) a
after the following expansion(s):
[ `A of ('d, 'a, 'e, 'c, 'b) b ] contains ('d, 'a, 'e, 'c, 'b) b,
('d, 'a, 'e, 'c, 'b) b = [ `B of ('e, 'c, 'b, 'd, 'a) c ],
[ `B of ('e, 'c, 'b, 'd, 'a) c ] contains ('e, 'c, 'b, 'd, 'a) c,
('e, 'c, 'b, 'd, 'a) c = [ `C of ('e, 'c, 'b, 'd, 'a) a ],
[ `C of ('e, 'c, 'b, 'd, 'a) a ] contains ('e, 'c, 'b, 'd, 'a) a
All uses need to match the definition for the recursive type to be regular.
|}]
PR 10762
type a = int
type t = [ `A of a ]
let inspect: [< t ] -> unit = function
| `A 0 -> ()
| `A _ -> ()
[%%expect {|
type a = int
type t = [ `A of a ]
val inspect : [< `A of a & int ] -> unit = <fun>
|}]
|
27d0eb6f9452322b8ca22e701beeda9b2d68b09ec4a5ca9d19600f49b0cf83a7 | pnf/girder | grid.clj | (ns acyclic.girder.testutils.grid
(:require [acyclic.utils.cli :as cli]
[clojure.core.async :as async :refer [<! >! <!! >!! timeout chan alt!! go close!]]
[acyclic.girder.grid :as grid]
[taoensso.timbre :as timbre]
acyclic.girder.grid.redis)
(:import (java.util UUID))
(:gen-class))
(timbre/refer-timbre)
(def cli-options
[[nil "--worker WS" "Launch one or more workers, with comma-delimited names"]
[nil "--distributor DIST" "Launch a distributor"]
[nil "--host HOST" "Redis host" :default "localhost"]
[nil "--port PORT" "Redis port" :default 6379 :parse-fn #(Integer/parseInt %)]
[nil "--jobmsecs MSECS" "Amount of time for the job to take" :parse-fn #(Integer/parseInt %) :default 2]
[nil "--pool POOLID" "Pool ID" :default nil]
[ nil " --helper MSECS " " Launch helper for the designated pool ( or distributor , also specified ) " : parse - fn # ( Integer / parseInt % ) : default nil ]
[nil "--jobs N" :default 0 :parse-fn #(Integer/parseInt %)]
[nil "--jobtimeout SECS" "Time to wait." :parse-fn #(Integer/parseInt %) :default 10]
[nil "--reclevel N" "Number of recursions" :parse-fn #(Integer/parseInt %) :default 0]
[nil "--numrecjobs N" "Number of jobs to launch at each level of recursion" :parse-fn #(Integer/parseInt %) :default 2]
[nil "--cleanup"]
["-i" "--id NUM" "Some id number" :default 0 :parse-fn #(Integer/parseInt %)]
["-o" "--opts OPTS" "EDN string" :default nil :parse-fn read-string]
[nil "--cmt COMMENT" "Some comment to stick into job request ids" :default (str (rand))]])
(grid/cdefn recbog [msec jobnum reclevel numrecjobs args]
(debug "here we are in recbog" grid/*nodeid* msec jobnum reclevel numrecjobs args)
(if-not (pos? reclevel)
(let [res (str jobnum)]
(Thread/sleep msec)
(debug "recbog" msec jobnum reclevel numrecjobs args "returning" res)
res)
(let [reqs (map #(vector recbog msec % (dec reclevel) numrecjobs args) (range numrecjobs))
vs (grid/requests reqs)
res (str "RecBog:" grid/*nodeid* ":" jobnum ":" msec ":" reclevel ":" args ":[" (clojure.string/join "," (map str vs)) "]")]
(debug "recbog" msec jobnum reclevel numrecjobs args "returning" res)
(Thread/sleep msec)
res
)))
(defn doit [opts]
(acyclic.girder.grid.redis/init! (:host opts) (:port opts))
(let [{:keys [numrecjobs reclevel cmt help pool worker distributor host port jobmsecs jobs jobtimeout cleanup]} opts]
{:cleanup ;; --cleanup
(when cleanup (grid/cleanup))
:distributor ;; --distributor POOLID1[,POOLID2,...]
(when distributor
(let [ds (clojure.string/split distributor #",")]
(for [d ds]
(grid/launch-distributor d pool))))
: helper ; ; --helper MSECS --pool POOLID
#_(when helper
(grid/launch-helper (or distributor pool) helper))
--worker ( N - WORKERS | WID1[,WID2 , ... ] )
(when worker
(let [u (java.util.UUID/randomUUID)
n (try (Integer/parseInt worker) (catch Exception e nil))
ws (if n
(map #(str "w" % "-" u) (range n))
(clojure.string/split worker #","))]
(for [w ws]
(grid/launch-worker w pool))))
:jobs ;; --jobs N
(when (and pool jobs (pos? jobs))
(let [f (fn [i] (grid/enqueue pool [recbog jobmsecs i reclevel numrecjobs cmt] false "cli"))
c (async/map vector (map f (range jobs)))
t (async/timeout (* 1000 jobtimeout))]
(let [[v ch] (async/alts!! [c t])]
(or v "timeout"))))}
))
(defn -main [& args] (cli/edn-app args cli-options doit))
| null | https://raw.githubusercontent.com/pnf/girder/25517e39227a28f10b0940908c57b95ac19dc3ce/src/acyclic/girder/testutils/grid.clj | clojure | --cleanup
--distributor POOLID1[,POOLID2,...]
; --helper MSECS --pool POOLID
--jobs N | (ns acyclic.girder.testutils.grid
(:require [acyclic.utils.cli :as cli]
[clojure.core.async :as async :refer [<! >! <!! >!! timeout chan alt!! go close!]]
[acyclic.girder.grid :as grid]
[taoensso.timbre :as timbre]
acyclic.girder.grid.redis)
(:import (java.util UUID))
(:gen-class))
(timbre/refer-timbre)
(def cli-options
[[nil "--worker WS" "Launch one or more workers, with comma-delimited names"]
[nil "--distributor DIST" "Launch a distributor"]
[nil "--host HOST" "Redis host" :default "localhost"]
[nil "--port PORT" "Redis port" :default 6379 :parse-fn #(Integer/parseInt %)]
[nil "--jobmsecs MSECS" "Amount of time for the job to take" :parse-fn #(Integer/parseInt %) :default 2]
[nil "--pool POOLID" "Pool ID" :default nil]
[ nil " --helper MSECS " " Launch helper for the designated pool ( or distributor , also specified ) " : parse - fn # ( Integer / parseInt % ) : default nil ]
[nil "--jobs N" :default 0 :parse-fn #(Integer/parseInt %)]
[nil "--jobtimeout SECS" "Time to wait." :parse-fn #(Integer/parseInt %) :default 10]
[nil "--reclevel N" "Number of recursions" :parse-fn #(Integer/parseInt %) :default 0]
[nil "--numrecjobs N" "Number of jobs to launch at each level of recursion" :parse-fn #(Integer/parseInt %) :default 2]
[nil "--cleanup"]
["-i" "--id NUM" "Some id number" :default 0 :parse-fn #(Integer/parseInt %)]
["-o" "--opts OPTS" "EDN string" :default nil :parse-fn read-string]
[nil "--cmt COMMENT" "Some comment to stick into job request ids" :default (str (rand))]])
(grid/cdefn recbog [msec jobnum reclevel numrecjobs args]
(debug "here we are in recbog" grid/*nodeid* msec jobnum reclevel numrecjobs args)
(if-not (pos? reclevel)
(let [res (str jobnum)]
(Thread/sleep msec)
(debug "recbog" msec jobnum reclevel numrecjobs args "returning" res)
res)
(let [reqs (map #(vector recbog msec % (dec reclevel) numrecjobs args) (range numrecjobs))
vs (grid/requests reqs)
res (str "RecBog:" grid/*nodeid* ":" jobnum ":" msec ":" reclevel ":" args ":[" (clojure.string/join "," (map str vs)) "]")]
(debug "recbog" msec jobnum reclevel numrecjobs args "returning" res)
(Thread/sleep msec)
res
)))
(defn doit [opts]
(acyclic.girder.grid.redis/init! (:host opts) (:port opts))
(let [{:keys [numrecjobs reclevel cmt help pool worker distributor host port jobmsecs jobs jobtimeout cleanup]} opts]
(when cleanup (grid/cleanup))
(when distributor
(let [ds (clojure.string/split distributor #",")]
(for [d ds]
(grid/launch-distributor d pool))))
#_(when helper
(grid/launch-helper (or distributor pool) helper))
--worker ( N - WORKERS | WID1[,WID2 , ... ] )
(when worker
(let [u (java.util.UUID/randomUUID)
n (try (Integer/parseInt worker) (catch Exception e nil))
ws (if n
(map #(str "w" % "-" u) (range n))
(clojure.string/split worker #","))]
(for [w ws]
(grid/launch-worker w pool))))
(when (and pool jobs (pos? jobs))
(let [f (fn [i] (grid/enqueue pool [recbog jobmsecs i reclevel numrecjobs cmt] false "cli"))
c (async/map vector (map f (range jobs)))
t (async/timeout (* 1000 jobtimeout))]
(let [[v ch] (async/alts!! [c t])]
(or v "timeout"))))}
))
(defn -main [& args] (cli/edn-app args cli-options doit))
|
13250eb36fa2d60d9c19b7cd6aa47cdf564522e0094481fa67d0e3fd870edadd | lspitzner/brittany | Test326.hs | spanKey p q = case minViewWithKey q of
Just ((k, _), q') | p k ->
let (kas, q'') = spanKey p q' in ((k, a) : kas, q'')
_ -> ([], q)
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test326.hs | haskell | spanKey p q = case minViewWithKey q of
Just ((k, _), q') | p k ->
let (kas, q'') = spanKey p q' in ((k, a) : kas, q'')
_ -> ([], q)
|
|
000adc30f6c3e4d9fcd591ef3b9aca5856506844b2f4c1f1f1bd525d0cfc08fb | defunkydrummer/abcl-jazz | inspector.lisp |
(defun get-class (class-or-name)
"Obtain the class designed by the name, if it's a string,
otherwise return the java object"
(etypecase class-or-name
(string (jclass class-or-name))
(java-object class-or-name))) ;TODO: how to specialize?
(defun get-constructors (class-name)
"Obtain list of constructors defined by the class itself."
(loop with x = (get-class class-name)
for c across (java:jclass-constructors x)
when (equal (#"getName" (#"getDeclaringClass" c))
(java:jclass-name x))
collect (to-list c)))
(defun get-methods (class-name &key (only-local T))
"Obtain list of methods defined by the class itself.
Unless only-local = NIL, in which case gets all available methods."
(loop with x = (get-class class-name)
for c across (java:jclass-methods x)
when (if only-local (equal (#"getName" (#"getDeclaringClass" c))
(java:jclass-name x))
T)
collect (to-list c)))
;; pretty print classes and other java objects
(defgeneric to-list (c))
(defmethod to-list ((c (java:jclass "java.lang.Class")))
(list :name (#"getName" c)
:interfaces (#"getInterfaces" c)
:classes (#"getClasses" c)
:genericsuperclass (#"getGenericSuperclass" c)
:methods (get-methods c)
:constructors (get-methods c)
))
(defmethod to-list ((c (java:jclass "java.lang.reflect.Method")))
(list :name (#"getName" c)
:parameter-types (#"getParameterTypes" c)
:return-type (#"getReturnType" c)
:parameters (#"getParameters" c)))
(defmethod to-list ((c (java:jclass "java.lang.reflect.Constructor")))
(list :parameter-types (#"getParameterTypes" c)
:parameters (#"getParameters" c)))
;; list to swing List
;; can only show String values...
(defun k-v-to-string (param value)
(format nil "~40A: ~80A" param value))
(defun plist-to-listmodel (plist)
(let ((lm (defaultlistmodel)))
(alexandria:doplist (key val plist)
(defaultlistmodel-add lm (k-v-to-string key val)))
lm))
(defmacro list-listener (list jl f)
`(listselectionlistener (lambda (e)
(declare (ignore e))
(let* ((selected-i
(#"getSelectedIndex" ,jl))
(selected-list
(elt ,list selected-i)))
;; show inspector for list or plist or etc.
(cond
((typep selected-list 'cons)
(if (keywordp (car selected-list))
(display-plist selected-list)
(display-list selected-list)))
((typep selected-list 'string)
(show-message-dialog
,f
(format nil "String: ~A" selected-list)))
(t
(show-warning-message ,f "Can't inspect!")))
))))
(defun display-list (list)
(let* ((lm (defaultlistmodel))
(f (frame "Inspecting list" 640 480))
(jl (jlist lm)))
(#"addListSelectionListener"
jl
(list-listener list jl f))
(loop for item in list
do (defaultlistmodel-add lm (format nil "~80A" item)))
(add-using-borderlayout f
:center (scrollpane jl))))
(defun plist-to-jarray (plist)
"Convert PLIST into jarray of jarray<string>"
(let (x)
(alexandria:doplist (key val plist)
(push
(list (format nil "~A" key)
(format nil "~A" val))
x))
(java:jnew-array-from-list "java.lang.String" (nreverse x))))
(defun display-plist (plist)
"As JTable"
(let* ((dtm (defaulttablemodel '("Key" "Value")))
(jt (jtable dtm))
(f (frame "Inspecting plist" 640 480)))
;; add data...
(alexandria:doplist
(key val plist)
(#"addRow" dtm (list-to-jarray (list
(format nil "~A" key)
(format nil "~A" val)))))
(add-using-borderlayout f
:center (scrollpane jt))))
(defun display-table (list &key (title ""))
"Display table (list of plists with same length)"
(let ((column-names nil)
;(width nil)
)
(alexandria:doplist (k v (car list))
(push (format nil "~10A" k) column-names))
(nreverse column-names)
( setf width ( length column - names ) )
(let* ((dtm (defaulttablemodel column-names))
(jt (jtable dtm))
(f (frame title 640 480)))
(loop for row in list ;for each row
do
(let ((row2))
(alexandria:doplist (k v row)
(push (format nil "~10A" v) row2))
(nreverse row2)
(#"addRow" dtm (list-to-jarray row2))))
(add-using-borderlayout f
:center (scrollpane jt)))))
(defun display-methods (class-name &optional (only-local T))
(display-table (get-methods class-name :only-local only-local)
:title (format nil "Methods of ~A" class-name)
))
| null | https://raw.githubusercontent.com/defunkydrummer/abcl-jazz/b5a2b72892d344bfc539769eca449a63243148bc/inspector.lisp | lisp | TODO: how to specialize?
pretty print classes and other java objects
list to swing List
can only show String values...
show inspector for list or plist or etc.
add data...
(width nil)
for each row |
(defun get-class (class-or-name)
"Obtain the class designed by the name, if it's a string,
otherwise return the java object"
(etypecase class-or-name
(string (jclass class-or-name))
(defun get-constructors (class-name)
"Obtain list of constructors defined by the class itself."
(loop with x = (get-class class-name)
for c across (java:jclass-constructors x)
when (equal (#"getName" (#"getDeclaringClass" c))
(java:jclass-name x))
collect (to-list c)))
(defun get-methods (class-name &key (only-local T))
"Obtain list of methods defined by the class itself.
Unless only-local = NIL, in which case gets all available methods."
(loop with x = (get-class class-name)
for c across (java:jclass-methods x)
when (if only-local (equal (#"getName" (#"getDeclaringClass" c))
(java:jclass-name x))
T)
collect (to-list c)))
(defgeneric to-list (c))
(defmethod to-list ((c (java:jclass "java.lang.Class")))
(list :name (#"getName" c)
:interfaces (#"getInterfaces" c)
:classes (#"getClasses" c)
:genericsuperclass (#"getGenericSuperclass" c)
:methods (get-methods c)
:constructors (get-methods c)
))
(defmethod to-list ((c (java:jclass "java.lang.reflect.Method")))
(list :name (#"getName" c)
:parameter-types (#"getParameterTypes" c)
:return-type (#"getReturnType" c)
:parameters (#"getParameters" c)))
(defmethod to-list ((c (java:jclass "java.lang.reflect.Constructor")))
(list :parameter-types (#"getParameterTypes" c)
:parameters (#"getParameters" c)))
(defun k-v-to-string (param value)
(format nil "~40A: ~80A" param value))
(defun plist-to-listmodel (plist)
(let ((lm (defaultlistmodel)))
(alexandria:doplist (key val plist)
(defaultlistmodel-add lm (k-v-to-string key val)))
lm))
(defmacro list-listener (list jl f)
`(listselectionlistener (lambda (e)
(declare (ignore e))
(let* ((selected-i
(#"getSelectedIndex" ,jl))
(selected-list
(elt ,list selected-i)))
(cond
((typep selected-list 'cons)
(if (keywordp (car selected-list))
(display-plist selected-list)
(display-list selected-list)))
((typep selected-list 'string)
(show-message-dialog
,f
(format nil "String: ~A" selected-list)))
(t
(show-warning-message ,f "Can't inspect!")))
))))
(defun display-list (list)
(let* ((lm (defaultlistmodel))
(f (frame "Inspecting list" 640 480))
(jl (jlist lm)))
(#"addListSelectionListener"
jl
(list-listener list jl f))
(loop for item in list
do (defaultlistmodel-add lm (format nil "~80A" item)))
(add-using-borderlayout f
:center (scrollpane jl))))
(defun plist-to-jarray (plist)
"Convert PLIST into jarray of jarray<string>"
(let (x)
(alexandria:doplist (key val plist)
(push
(list (format nil "~A" key)
(format nil "~A" val))
x))
(java:jnew-array-from-list "java.lang.String" (nreverse x))))
(defun display-plist (plist)
"As JTable"
(let* ((dtm (defaulttablemodel '("Key" "Value")))
(jt (jtable dtm))
(f (frame "Inspecting plist" 640 480)))
(alexandria:doplist
(key val plist)
(#"addRow" dtm (list-to-jarray (list
(format nil "~A" key)
(format nil "~A" val)))))
(add-using-borderlayout f
:center (scrollpane jt))))
(defun display-table (list &key (title ""))
"Display table (list of plists with same length)"
(let ((column-names nil)
)
(alexandria:doplist (k v (car list))
(push (format nil "~10A" k) column-names))
(nreverse column-names)
( setf width ( length column - names ) )
(let* ((dtm (defaulttablemodel column-names))
(jt (jtable dtm))
(f (frame title 640 480)))
do
(let ((row2))
(alexandria:doplist (k v row)
(push (format nil "~10A" v) row2))
(nreverse row2)
(#"addRow" dtm (list-to-jarray row2))))
(add-using-borderlayout f
:center (scrollpane jt)))))
(defun display-methods (class-name &optional (only-local T))
(display-table (get-methods class-name :only-local only-local)
:title (format nil "Methods of ~A" class-name)
))
|
a9c15e4aa41d4324563b96393851646560c4dfe51400ec76a5846657ea0a9341 | brendanhay/gogol | List.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . WebSecurityScanner . Projects . ScanConfigs . ScanRuns . Findings . List
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- List Findings under a given ScanRun.
--
-- /See:/ <-command-center/docs/concepts-web-security-scanner-overview/ Web Security Scanner API Reference> for @websecurityscanner.projects.scanConfigs.scanRuns.findings.list@.
module Gogol.WebSecurityScanner.Projects.ScanConfigs.ScanRuns.Findings.List
( -- * Resource
WebSecurityScannerProjectsScanConfigsScanRunsFindingsListResource,
-- ** Constructing a Request
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList (..),
newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList,
)
where
import qualified Gogol.Prelude as Core
import Gogol.WebSecurityScanner.Types
-- | A resource alias for @websecurityscanner.projects.scanConfigs.scanRuns.findings.list@ method which the
' WebSecurityScannerProjectsScanConfigsScanRunsFindingsList ' request conforms to .
type WebSecurityScannerProjectsScanConfigsScanRunsFindingsListResource =
"v1"
Core.:> Core.Capture "parent" Core.Text
Core.:> "findings"
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "filter" Core.Text
Core.:> Core.QueryParam "pageSize" Core.Int32
Core.:> Core.QueryParam "pageToken" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Get '[Core.JSON] ListFindingsResponse
-- | List Findings under a given ScanRun.
--
-- /See:/ 'newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList' smart constructor.
data WebSecurityScannerProjectsScanConfigsScanRunsFindingsList = WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | The filter expression. The expression must be in the format: . Supported field: \'finding_type\'. Supported operator: \'=\'.
filter :: (Core.Maybe Core.Text),
-- | The maximum number of Findings to return, can be limited by server. If not specified or not positive, the implementation will select a reasonable value.
pageSize :: (Core.Maybe Core.Int32),
| A token identifying a page of results to be returned . This should be a @next_page_token@ value returned from a previous List request . If unspecified , the first page of results is returned .
pageToken :: (Core.Maybe Core.Text),
-- | Required. The parent resource name, which should be a scan run resource name in the format \'projects\/{projectId}\/scanConfigs\/{scanConfigId}\/scanRuns\/{scanRunId}\'.
parent :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' WebSecurityScannerProjectsScanConfigsScanRunsFindingsList ' with the minimum fields required to make a request .
newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList ::
-- | Required. The parent resource name, which should be a scan run resource name in the format \'projects\/{projectId}\/scanConfigs\/{scanConfigId}\/scanRuns\/{scanRunId}\'. See 'parent'.
Core.Text ->
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList parent =
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
filter = Core.Nothing,
pageSize = Core.Nothing,
pageToken = Core.Nothing,
parent = parent,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
where
type
Rs
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList =
ListFindingsResponse
type
Scopes
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList =
'[CloudPlatform'FullControl]
requestClient
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList {..} =
go
parent
xgafv
accessToken
callback
filter
pageSize
pageToken
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
webSecurityScannerService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
WebSecurityScannerProjectsScanConfigsScanRunsFindingsListResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-websecurityscanner/gen/Gogol/WebSecurityScanner/Projects/ScanConfigs/ScanRuns/Findings/List.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
List Findings under a given ScanRun.
/See:/ <-command-center/docs/concepts-web-security-scanner-overview/ Web Security Scanner API Reference> for @websecurityscanner.projects.scanConfigs.scanRuns.findings.list@.
* Resource
** Constructing a Request
| A resource alias for @websecurityscanner.projects.scanConfigs.scanRuns.findings.list@ method which the
| List Findings under a given ScanRun.
/See:/ 'newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList' smart constructor.
| V1 error format.
| OAuth access token.
| The filter expression. The expression must be in the format: . Supported field: \'finding_type\'. Supported operator: \'=\'.
| The maximum number of Findings to return, can be limited by server. If not specified or not positive, the implementation will select a reasonable value.
| Required. The parent resource name, which should be a scan run resource name in the format \'projects\/{projectId}\/scanConfigs\/{scanConfigId}\/scanRuns\/{scanRunId}\'.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Required. The parent resource name, which should be a scan run resource name in the format \'projects\/{projectId}\/scanConfigs\/{scanConfigId}\/scanRuns\/{scanRunId}\'. See 'parent'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . WebSecurityScanner . Projects . ScanConfigs . ScanRuns . Findings . List
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.WebSecurityScanner.Projects.ScanConfigs.ScanRuns.Findings.List
WebSecurityScannerProjectsScanConfigsScanRunsFindingsListResource,
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList (..),
newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList,
)
where
import qualified Gogol.Prelude as Core
import Gogol.WebSecurityScanner.Types
' WebSecurityScannerProjectsScanConfigsScanRunsFindingsList ' request conforms to .
type WebSecurityScannerProjectsScanConfigsScanRunsFindingsListResource =
"v1"
Core.:> Core.Capture "parent" Core.Text
Core.:> "findings"
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "filter" Core.Text
Core.:> Core.QueryParam "pageSize" Core.Int32
Core.:> Core.QueryParam "pageToken" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Get '[Core.JSON] ListFindingsResponse
data WebSecurityScannerProjectsScanConfigsScanRunsFindingsList = WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
filter :: (Core.Maybe Core.Text),
pageSize :: (Core.Maybe Core.Int32),
| A token identifying a page of results to be returned . This should be a @next_page_token@ value returned from a previous List request . If unspecified , the first page of results is returned .
pageToken :: (Core.Maybe Core.Text),
parent :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' WebSecurityScannerProjectsScanConfigsScanRunsFindingsList ' with the minimum fields required to make a request .
newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList ::
Core.Text ->
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
newWebSecurityScannerProjectsScanConfigsScanRunsFindingsList parent =
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
filter = Core.Nothing,
pageSize = Core.Nothing,
pageToken = Core.Nothing,
parent = parent,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList
where
type
Rs
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList =
ListFindingsResponse
type
Scopes
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList =
'[CloudPlatform'FullControl]
requestClient
WebSecurityScannerProjectsScanConfigsScanRunsFindingsList {..} =
go
parent
xgafv
accessToken
callback
filter
pageSize
pageToken
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
webSecurityScannerService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
WebSecurityScannerProjectsScanConfigsScanRunsFindingsListResource
)
Core.mempty
|
3e5e0769f8205ec2f2121928489c522db66e15aace9ce22e7191730fb801c7b0 | jakemcc/sicp-study | ex4_23.clj | Exercise 4.23
's version does more work at runtime , whereas the version
; in the text book does much of the work when it analyzes the code. | null | https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section4.1/src/ex4_23.clj | clojure | in the text book does much of the work when it analyzes the code. | Exercise 4.23
's version does more work at runtime , whereas the version |
f539ad4b6c3f2e4f1f90bb34eac00421775c5acd3dbdb2929c9e62bbc36cb44c | haskell-gi/gi-gtk-examples | ComboDemo.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.List (elemIndex)
import Data.GI.Base.ManagedPtr ( unsafeCastTo )
import qualified Data.Text as T
import qualified GI.Gtk as Gtk (main, init)
import GI.Gtk
(widgetShowAll, containerAdd, binGetChild, comboBoxSetActive,
comboBoxNewWithEntry, mainQuit, onWidgetDestroy, windowNew,
Entry(..), onEntryActivate, entryGetText)
import GI.Gtk.Enums (WindowType(..))
import Data.GI.Gtk.ComboBox (comboBoxSetModelText, comboBoxAppendText, comboBoxGetModelText)
import Data.GI.Gtk.ModelView.SeqStore (seqStoreToList, seqStoreAppend)
main = do
Gtk.init Nothing
win <- windowNew WindowTypeToplevel
onWidgetDestroy win mainQuit
combo <- comboBoxNewWithEntry
comboBoxSetModelText combo
mapM_ (comboBoxAppendText combo)
(T.words "ice-cream turkey pasta sandwich steak")
select the first item
comboBoxSetActive combo 0
-- Get the entry widget that the ComboBoxEntry uses.
w <- binGetChild combo
entry <- maybe (error "Could not get child") (unsafeCastTo Entry) w
-- Whenever the user has completed editing the text, append the new
-- text to the store unless it's already in there.
onEntryActivate entry $ do
str <- entryGetText entry
store <- comboBoxGetModelText combo
elems <- seqStoreToList store
comboBoxSetActive combo (-1)
idx <- case elemIndex str elems of
Just idx -> return $ fromIntegral idx
Nothing -> seqStoreAppend store str
comboBoxSetActive combo idx
return ()
containerAdd win combo
widgetShowAll win
Gtk.main
| null | https://raw.githubusercontent.com/haskell-gi/gi-gtk-examples/4c4f06dc91fbb9b9f50cdad295c8afe782e0bdec/menu/ComboDemo.hs | haskell | # LANGUAGE OverloadedStrings #
Get the entry widget that the ComboBoxEntry uses.
Whenever the user has completed editing the text, append the new
text to the store unless it's already in there. | module Main where
import Data.List (elemIndex)
import Data.GI.Base.ManagedPtr ( unsafeCastTo )
import qualified Data.Text as T
import qualified GI.Gtk as Gtk (main, init)
import GI.Gtk
(widgetShowAll, containerAdd, binGetChild, comboBoxSetActive,
comboBoxNewWithEntry, mainQuit, onWidgetDestroy, windowNew,
Entry(..), onEntryActivate, entryGetText)
import GI.Gtk.Enums (WindowType(..))
import Data.GI.Gtk.ComboBox (comboBoxSetModelText, comboBoxAppendText, comboBoxGetModelText)
import Data.GI.Gtk.ModelView.SeqStore (seqStoreToList, seqStoreAppend)
main = do
Gtk.init Nothing
win <- windowNew WindowTypeToplevel
onWidgetDestroy win mainQuit
combo <- comboBoxNewWithEntry
comboBoxSetModelText combo
mapM_ (comboBoxAppendText combo)
(T.words "ice-cream turkey pasta sandwich steak")
select the first item
comboBoxSetActive combo 0
w <- binGetChild combo
entry <- maybe (error "Could not get child") (unsafeCastTo Entry) w
onEntryActivate entry $ do
str <- entryGetText entry
store <- comboBoxGetModelText combo
elems <- seqStoreToList store
comboBoxSetActive combo (-1)
idx <- case elemIndex str elems of
Just idx -> return $ fromIntegral idx
Nothing -> seqStoreAppend store str
comboBoxSetActive combo idx
return ()
containerAdd win combo
widgetShowAll win
Gtk.main
|
e450f72af044f51baeb10c058126aab1684e196451c3189a9e81629c26b388f2 | ayazhafiz/plts | eval.ml | module T = Typecheck
open Cast_ir
open Cast_ir.Expr
open Cast_ir.Builtin
open Util
type error = CastError of elaborated_expr | TypeError of elaborated_expr
let type_error e = Error (TypeError e)
let cast_error e = Error (CastError e)
let rec unbox = function
| Elab (Cast (Ty (TUnknown, _), e), _) -> unbox e
| e -> e
let ( >>= ) = Result.bind
let subst x (Elab (v, _) as velab) =
let rec go subs (Elab (e, t)) =
let e' =
match e with
| Nat _ | Bool _ | Loc _ | Builtin _ -> e
| Var (`Local y) -> (
match List.assoc_opt y subs with Some e' -> e' | None -> e)
| Var (`Global _) -> e
| App (e1, e2) -> App (go subs e1, go subs e2)
| If (c, t, e) -> If (go subs c, go subs t, go subs e)
| Ref e -> Ref (go subs e)
| Deref e -> Deref (go subs e)
| RefAssign (e1, e2) -> RefAssign (go subs e1, go subs e2)
| Cast (t', e') -> Cast (t', go subs e')
| Lam (y, t', e') ->
if x = y then e
else
let y' = freshen y (S.union (freevars velab) (freevars e')) in
Lam (y', t', go ((y, Var (`Local y')) :: subs) e')
in
Elab (e', t)
in
go [ (x, v) ]
let bad_arg () = failwith "bad_arg"
class add_captured n : builtin =
object
method name = Printf.sprintf "__builtin_add_captured(%d)" n
method eval =
function
| Elab (Nat m, _) -> Elab (Nat (n + m), ft TNat) | _ -> bad_arg ()
end
class mult_captured n : builtin =
object
method name = Printf.sprintf "__builtin_mult_captured(%d)" n
method eval =
function
| Elab (Nat m, _) -> Elab (Nat (n * m), ft TNat) | _ -> bad_arg ()
end
class eqn_captured n : builtin =
object
method name = Printf.sprintf "__builtin_eqn_captured(%d)" n
method eval =
function
| Elab (Nat m, _) -> Elab (Bool (n = m), ft TBool) | _ -> bad_arg ()
end
class eqb_captured b : builtin =
object
method name = Printf.sprintf "__builtin_eqb_captured(%b)" b
method eval =
function
| Elab (Bool c, _) -> Elab (Bool (b = c), ft TBool) | _ -> bad_arg ()
end
let builtin_eval = function
| "succ" -> (
function Nat n -> Elab (Nat (n + 1), ft TNat) | _ -> bad_arg ())
| "pred" -> (
function Nat n -> Elab (Nat (n - 1), ft TNat) | _ -> bad_arg ())
| "add" -> (
function
| Nat n ->
Elab (Builtin (new add_captured n), ft (TArrow (ft TNat, ft TNat)))
| _ -> bad_arg ())
| "mult" -> (
function
| Nat n ->
Elab (Builtin (new mult_captured n), ft (TArrow (ft TNat, ft TNat)))
| _ -> bad_arg ())
| "eqn" -> (
function
| Nat n ->
Elab (Builtin (new eqn_captured n), ft (TArrow (ft TNat, ft TBool)))
| _ -> bad_arg ())
| "eqb" -> (
function
| Bool b ->
Elab (Builtin (new eqb_captured b), ft (TArrow (ft TBool, ft TBool)))
| _ -> bad_arg ())
| _ -> bad_arg ()
let eval e =
let freshname = fresh_generator () in
let freshloc =
let i = ref 0 in
fun () ->
incr i;
!i
in
let heap = Hashtbl.create 32 in
let rec eval (Elab (e, te) as input) : (elaborated_expr, error) result =
match e with
ELam
| Lam (s, t, e) -> Ok (Elab (Lam (s, t, e), te))
EApp
| App (e1, e2) -> (
eval e1 >>= fun (Elab (e1, _)) ->
match e1 with
| Lam (x, _, e3) ->
eval e2 >>= fun e2 ->
let e3' = subst x e2 e3 in
eval e3'
EDelta
| Var (`Global fn) ->
eval e2 >>= fun (Elab (e2, _)) -> Ok (builtin_eval fn e2)
| Builtin builtin -> eval e2 >>= fun e2 -> Ok (builtin#eval e2)
| _ -> type_error input)
(* EIf (new) *)
| If (c, thn, els) -> (
eval c >>= fun (Elab (c, _)) ->
match c with
| Bool true -> eval thn
| Bool false -> eval els
| _ -> type_error input)
(* EConst *)
| Nat n -> Ok (Elab (Nat n, ft TNat))
| Bool b -> Ok (Elab (Bool b, ft TBool))
(* ECstG *)
| Cast (Ty (TNat, _), e) -> (
eval e >>= fun v ->
let uv = unbox v in
match uv with Elab (_, Ty (TNat, _)) -> Ok uv | _ -> cast_error input)
| Cast (Ty (TBool, _), e) -> (
eval e >>= fun v ->
let uv = unbox v in
match uv with Elab (_, Ty (TBool, _)) -> Ok uv | _ -> cast_error input)
(* ECstF *)
| Cast (Ty (TArrow (s, s'), _), e) -> (
eval e >>= fun v ->
let uv = unbox v in
match uv with
| Elab (_, Ty (TArrow (t, t'), _))
when T.consistent (ft (TArrow (s, s'))) (ft (TArrow (t, t'))) ->
λ z : σ . ( ⟨σ′⟩ ( unbox v ( ⟨τ⟩ z ) ) )
let z = freshname "z" in
let inner_app =
Elab (App (uv, Elab (Cast (t, Elab (Var (`Local z), s)), t)), t')
in
let body = Elab (Cast (s', inner_app), s') in
let res = Lam (z, s, body) in
Ok (Elab (res, ft (TArrow (s, s'))))
| _ -> cast_error input)
(* ECstU *)
| Cast (Ty (TUnknown, _), e) ->
eval e >>= fun v -> Ok (Elab (Cast (ft TUnknown, unbox v), ft TUnknown))
(* ECstR *)
| Cast (Ty (TRef t, _), e) -> (
eval e >>= fun v ->
match unbox v with
| Elab (_, Ty (TRef t', _)) when t = t' -> Ok v
| _ -> cast_error input)
(* ERef *)
| Ref e ->
eval e >>= fun v ->
let l = freshloc () in
Hashtbl.add heap l v;
Ok (Elab (Loc l, ft (TRef te)))
EDeref
| Deref e -> (
eval e >>= function
| Elab (Loc l, _) -> Ok (Hashtbl.find heap l)
| _ -> type_error input)
(* EAssign *)
| RefAssign (e1, e2) -> (
eval e1 >>= function
| Elab (Loc l, t) ->
eval e2 >>= fun e2 ->
Hashtbl.add heap l e2;
Ok (Elab (Loc l, t))
| _ -> type_error input)
| Var _ | Loc _ | Builtin _ -> Ok input
| Cast (Ty (TInfer _, _), _) ->
failwith "unreachable: inference type variable is unresolved"
in
eval e |> Result.map unbox
| null | https://raw.githubusercontent.com/ayazhafiz/plts/2971814f57c25d3d665126e70b717dc18e6d3dd4/gtlc/eval.ml | ocaml | EIf (new)
EConst
ECstG
ECstF
ECstU
ECstR
ERef
EAssign | module T = Typecheck
open Cast_ir
open Cast_ir.Expr
open Cast_ir.Builtin
open Util
type error = CastError of elaborated_expr | TypeError of elaborated_expr
let type_error e = Error (TypeError e)
let cast_error e = Error (CastError e)
let rec unbox = function
| Elab (Cast (Ty (TUnknown, _), e), _) -> unbox e
| e -> e
let ( >>= ) = Result.bind
let subst x (Elab (v, _) as velab) =
let rec go subs (Elab (e, t)) =
let e' =
match e with
| Nat _ | Bool _ | Loc _ | Builtin _ -> e
| Var (`Local y) -> (
match List.assoc_opt y subs with Some e' -> e' | None -> e)
| Var (`Global _) -> e
| App (e1, e2) -> App (go subs e1, go subs e2)
| If (c, t, e) -> If (go subs c, go subs t, go subs e)
| Ref e -> Ref (go subs e)
| Deref e -> Deref (go subs e)
| RefAssign (e1, e2) -> RefAssign (go subs e1, go subs e2)
| Cast (t', e') -> Cast (t', go subs e')
| Lam (y, t', e') ->
if x = y then e
else
let y' = freshen y (S.union (freevars velab) (freevars e')) in
Lam (y', t', go ((y, Var (`Local y')) :: subs) e')
in
Elab (e', t)
in
go [ (x, v) ]
let bad_arg () = failwith "bad_arg"
class add_captured n : builtin =
object
method name = Printf.sprintf "__builtin_add_captured(%d)" n
method eval =
function
| Elab (Nat m, _) -> Elab (Nat (n + m), ft TNat) | _ -> bad_arg ()
end
class mult_captured n : builtin =
object
method name = Printf.sprintf "__builtin_mult_captured(%d)" n
method eval =
function
| Elab (Nat m, _) -> Elab (Nat (n * m), ft TNat) | _ -> bad_arg ()
end
class eqn_captured n : builtin =
object
method name = Printf.sprintf "__builtin_eqn_captured(%d)" n
method eval =
function
| Elab (Nat m, _) -> Elab (Bool (n = m), ft TBool) | _ -> bad_arg ()
end
class eqb_captured b : builtin =
object
method name = Printf.sprintf "__builtin_eqb_captured(%b)" b
method eval =
function
| Elab (Bool c, _) -> Elab (Bool (b = c), ft TBool) | _ -> bad_arg ()
end
let builtin_eval = function
| "succ" -> (
function Nat n -> Elab (Nat (n + 1), ft TNat) | _ -> bad_arg ())
| "pred" -> (
function Nat n -> Elab (Nat (n - 1), ft TNat) | _ -> bad_arg ())
| "add" -> (
function
| Nat n ->
Elab (Builtin (new add_captured n), ft (TArrow (ft TNat, ft TNat)))
| _ -> bad_arg ())
| "mult" -> (
function
| Nat n ->
Elab (Builtin (new mult_captured n), ft (TArrow (ft TNat, ft TNat)))
| _ -> bad_arg ())
| "eqn" -> (
function
| Nat n ->
Elab (Builtin (new eqn_captured n), ft (TArrow (ft TNat, ft TBool)))
| _ -> bad_arg ())
| "eqb" -> (
function
| Bool b ->
Elab (Builtin (new eqb_captured b), ft (TArrow (ft TBool, ft TBool)))
| _ -> bad_arg ())
| _ -> bad_arg ()
let eval e =
let freshname = fresh_generator () in
let freshloc =
let i = ref 0 in
fun () ->
incr i;
!i
in
let heap = Hashtbl.create 32 in
let rec eval (Elab (e, te) as input) : (elaborated_expr, error) result =
match e with
ELam
| Lam (s, t, e) -> Ok (Elab (Lam (s, t, e), te))
EApp
| App (e1, e2) -> (
eval e1 >>= fun (Elab (e1, _)) ->
match e1 with
| Lam (x, _, e3) ->
eval e2 >>= fun e2 ->
let e3' = subst x e2 e3 in
eval e3'
EDelta
| Var (`Global fn) ->
eval e2 >>= fun (Elab (e2, _)) -> Ok (builtin_eval fn e2)
| Builtin builtin -> eval e2 >>= fun e2 -> Ok (builtin#eval e2)
| _ -> type_error input)
| If (c, thn, els) -> (
eval c >>= fun (Elab (c, _)) ->
match c with
| Bool true -> eval thn
| Bool false -> eval els
| _ -> type_error input)
| Nat n -> Ok (Elab (Nat n, ft TNat))
| Bool b -> Ok (Elab (Bool b, ft TBool))
| Cast (Ty (TNat, _), e) -> (
eval e >>= fun v ->
let uv = unbox v in
match uv with Elab (_, Ty (TNat, _)) -> Ok uv | _ -> cast_error input)
| Cast (Ty (TBool, _), e) -> (
eval e >>= fun v ->
let uv = unbox v in
match uv with Elab (_, Ty (TBool, _)) -> Ok uv | _ -> cast_error input)
| Cast (Ty (TArrow (s, s'), _), e) -> (
eval e >>= fun v ->
let uv = unbox v in
match uv with
| Elab (_, Ty (TArrow (t, t'), _))
when T.consistent (ft (TArrow (s, s'))) (ft (TArrow (t, t'))) ->
λ z : σ . ( ⟨σ′⟩ ( unbox v ( ⟨τ⟩ z ) ) )
let z = freshname "z" in
let inner_app =
Elab (App (uv, Elab (Cast (t, Elab (Var (`Local z), s)), t)), t')
in
let body = Elab (Cast (s', inner_app), s') in
let res = Lam (z, s, body) in
Ok (Elab (res, ft (TArrow (s, s'))))
| _ -> cast_error input)
| Cast (Ty (TUnknown, _), e) ->
eval e >>= fun v -> Ok (Elab (Cast (ft TUnknown, unbox v), ft TUnknown))
| Cast (Ty (TRef t, _), e) -> (
eval e >>= fun v ->
match unbox v with
| Elab (_, Ty (TRef t', _)) when t = t' -> Ok v
| _ -> cast_error input)
| Ref e ->
eval e >>= fun v ->
let l = freshloc () in
Hashtbl.add heap l v;
Ok (Elab (Loc l, ft (TRef te)))
EDeref
| Deref e -> (
eval e >>= function
| Elab (Loc l, _) -> Ok (Hashtbl.find heap l)
| _ -> type_error input)
| RefAssign (e1, e2) -> (
eval e1 >>= function
| Elab (Loc l, t) ->
eval e2 >>= fun e2 ->
Hashtbl.add heap l e2;
Ok (Elab (Loc l, t))
| _ -> type_error input)
| Var _ | Loc _ | Builtin _ -> Ok input
| Cast (Ty (TInfer _, _), _) ->
failwith "unreachable: inference type variable is unresolved"
in
eval e |> Result.map unbox
|
ce80aca0ca303415816cc4166a6e347794f34d706bc825d7b4d5039e0207d86b | ku-fpg/hermit | Rev.hs | # LANGUAGE CPP #
module Main where
import HList
rev :: [a] -> [a]
rev [] = []
rev (y:ys) = rev ys ++ [y]
main :: IO ()
main = print $ rev [1..10]
-- Should be in the "List" module
{-# RULES "++ []" forall xs . xs ++ [] = xs #-}
{-# RULES "++ strict" (++) undefined = undefined #-}
The " Algebra " for repH
{-# RULES "repH ++" forall xs ys . repH (xs ++ ys) = repH xs . repH ys #-}
{-# RULES "repH []" repH [] = id #-}
{-# RULES "repH (:)" forall x xs . repH (x:xs) = ((:) x) . repH xs #-}
| null | https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/examples/concatVanishes/Rev.hs | haskell | Should be in the "List" module
# RULES "++ []" forall xs . xs ++ [] = xs #
# RULES "++ strict" (++) undefined = undefined #
# RULES "repH ++" forall xs ys . repH (xs ++ ys) = repH xs . repH ys #
# RULES "repH []" repH [] = id #
# RULES "repH (:)" forall x xs . repH (x:xs) = ((:) x) . repH xs # | # LANGUAGE CPP #
module Main where
import HList
rev :: [a] -> [a]
rev [] = []
rev (y:ys) = rev ys ++ [y]
main :: IO ()
main = print $ rev [1..10]
The " Algebra " for repH
|
e32e9ad3ac3e57b68dc55803a47818982b6779dce91c6bd8d740d2fc89b69451 | artyom-poptsov/guile-smc | char-context.scm | ;;; char-context.scm -- Guile-SMC finite state machine character context.
Copyright ( C ) 2021 < >
;;
;; 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 3 of the License , or
;; (at your option) any later version.
;;
;; The program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with the program. If not, see </>.
;;; Commentary:
;; This file contains an implementation of a character context based on a
;; generic context. The character context can be used to handle a stream of
;; characters.
;;; Code:
(define-module (smc context char-context)
#:use-module (ice-9 textual-ports)
#:use-module (oop goops)
#:use-module (smc context context)
#:use-module (smc core log)
From ( smc context context )
<context>
context?
context-debug-mode?
context-debug-mode-set!
context-stanza
context-stanza-set!
context-stanza-clear!
context-buffer
context-buffer-set!
context-buffer-clear!
context-clear!
guard:#t
action:no-op
action:store
action:clear-buffer
action:update-stanza)
#:export (<char-context>
char-context-port
char-context-counter
char-context-row
char-context-col
char-context-update-counters!
event-source
;; Actions.
action:syntax-error
;; All guards that are exported with 'define-public' below.
;; Logging procedures
context-log-error
context-log-warning
context-log-info
context-log-debug
make-char-guard
make-charset-guard))
(define-class <char-context> (<context>)
;; A port from which data is read.
;;
;; <port>
(port
#:init-value (current-input-port)
#:init-keyword #:port
#:getter char-context-port)
;; Total number of characters consumed.
;;
;; <number>
(counter
#:init-value 0
#:getter char-context-counter
#:setter char-context-counter-set!)
;; Current text column number.
;;
;; <number>
(col-number
#:init-value 0
#:getter char-context-col
#:setter char-context-col-set!)
;; Current text row number.
;;
;; <number>
(row-number
#:init-value 0
#:getter char-context-row
#:setter char-context-row-set!))
(define-method (%counter++! (ctx <char-context>))
(char-context-counter-set! ctx (+ (char-context-counter ctx) 1)))
;; Increment the current text column.
(define-method (%col++! (ctx <char-context>))
(char-context-col-set! ctx (+ (char-context-col ctx) 1)))
;; Reset the current text column.
(define-method (%col-reset! (ctx <char-context>))
(char-context-col-set! ctx 0))
Increment the current row number . Resets the current column number to zero .
(define-method (%row++! (ctx <char-context>))
(char-context-row-set! ctx (+ (char-context-row ctx) 1))
(%col-reset! ctx))
Update counters in a character context CTX based on an incoming character
;; CH. These counters are thrown when a syntax error occurred.
(define-method (char-context-update-counters! (ctx <char-context>) ch)
(unless (eof-object? ch)
(%counter++! ctx)
(%col++! ctx)
(when (char=? ch #\newline)
(%row++! ctx))))
;;; Event source.
;; Get the next character from a CONTEXT port.
(define-method (event-source (context <char-context>))
(let ((ch (get-char (char-context-port context))))
(char-context-update-counters! context ch)
ch))
;;; Guards.
;; Make a procedure that checks if a CH1 equals to CH2.
(define-syntax-rule (make-char-guard name ch1)
(define-public (name ctx ch2)
(char=? ch1 ch2)))
Make a procedure that checks if a CH is in a CHARSET .
(define-syntax-rule (make-charset-guard name charset)
(define-public (name ctx ch)
(char-set-contains? charset ch)))
;;; The procedures below are predicates for symbols of the ASCII table, in the
;;; same order.
(make-char-guard guard:nul? #\nul)
(make-char-guard guard:soh? #\soh)
(make-char-guard guard:stx? #\stx)
(make-char-guard guard:etx? #\etx)
(make-char-guard guard:eot? #\eot)
(make-char-guard guard:enq? #\enq)
(make-char-guard guard:ack? #\ack)
(make-char-guard guard:bel? #\bel)
(make-char-guard guard:bs? #\bs)
(make-char-guard guard:tab? #\tab)
(make-char-guard guard:lf? #\linefeed)
(make-char-guard guard:vt? #\vtab)
(make-char-guard guard:ff? #\ff)
(make-char-guard guard:cr? #\cr)
(make-char-guard guard:so? #\so)
(make-char-guard guard:si? #\si)
(make-char-guard guard:dle? #\dle)
(make-char-guard guard:dc1? #\dc1)
(make-char-guard guard:dc2? #\dc2)
(make-char-guard guard:dc3? #\dc3)
(make-char-guard guard:dc4? #\dc4)
(make-char-guard guard:nak? #\nak)
(make-char-guard guard:syn? #\syn)
(make-char-guard guard:etb? #\etb)
(make-char-guard guard:can? #\can)
(make-char-guard guard:em? #\em)
(make-char-guard guard:sub? #\sub)
(make-char-guard guard:esc? #\esc)
(make-char-guard guard:fs? #\fs)
(make-char-guard guard:gs? #\gs)
(make-char-guard guard:rs? #\rs)
(make-char-guard guard:us? #\us)
(make-char-guard guard:space? #\space)
(make-char-guard guard:exclamation-mark? #\!)
(make-char-guard guard:double-quote? #\")
(make-char-guard guard:number-sign? #\#)
(make-char-guard guard:dollar-sign? #\$)
(make-char-guard guard:percent-sign? #\%)
(make-char-guard guard:ampersand? #\&)
(make-char-guard guard:single-quote? #\')
(make-char-guard guard:left-parenthesis? #\()
(make-char-guard guard:right-parenthesis? #\))
(make-char-guard guard:asterisk? #\*)
(make-char-guard guard:plus-sign? #\+)
(make-char-guard guard:comma? #\,)
(make-char-guard guard:hyphen-minus? #\-)
(make-char-guard guard:full-stop? #\.)
(make-char-guard guard:solidus? #\/)
;; BEGIN: Digits.
(make-char-guard guard:digit-zero? #\0)
(make-char-guard guard:digit-one? #\1)
(make-char-guard guard:digit-two? #\2)
(make-char-guard guard:digit-three? #\3)
(make-char-guard guard:digit-four? #\4)
(make-char-guard guard:digit-five? #\5)
(make-char-guard guard:digit-six? #\6)
(make-char-guard guard:digit-seven? #\7)
(make-char-guard guard:digit-eight? #\8)
(make-char-guard guard:digit-nine? #\9)
;; END: Digits.
(make-char-guard guard:colon? #\:)
(make-char-guard guard:semicolon? #\;)
(make-char-guard guard:less-than-sign? #\<)
(make-char-guard guard:equals-sign? #\=)
(make-char-guard guard:more-than-sign? #\>)
(make-char-guard guard:question-mark? #\?)
(make-char-guard guard:at-symbol? #\@)
;; BEGIN: Uppercase letters.
(make-char-guard guard:letter-A? #\A)
(make-char-guard guard:letter-B? #\B)
(make-char-guard guard:letter-C? #\C)
(make-char-guard guard:letter-D? #\D)
(make-char-guard guard:letter-E? #\E)
(make-char-guard guard:letter-F? #\F)
(make-char-guard guard:letter-G? #\G)
(make-char-guard guard:letter-H? #\H)
(make-char-guard guard:letter-I? #\I)
(make-char-guard guard:letter-J? #\J)
(make-char-guard guard:letter-K? #\K)
(make-char-guard guard:letter-L? #\L)
(make-char-guard guard:letter-M? #\M)
(make-char-guard guard:letter-N? #\N)
(make-char-guard guard:letter-O? #\O)
(make-char-guard guard:letter-P? #\P)
(make-char-guard guard:letter-Q? #\Q)
(make-char-guard guard:letter-R? #\R)
(make-char-guard guard:letter-S? #\S)
(make-char-guard guard:letter-T? #\T)
(make-char-guard guard:letter-U? #\U)
(make-char-guard guard:letter-V? #\V)
(make-char-guard guard:letter-W? #\W)
(make-char-guard guard:letter-X? #\X)
(make-char-guard guard:letter-Y? #\Y)
(make-char-guard guard:letter-Z? #\Z)
;; END: Uppercase letter.
(make-char-guard guard:left-square-bracket? #\[)
(make-char-guard guard:reverse-solidus? #\\)
(make-char-guard guard:right-square-bracket? #\])
(make-char-guard guard:circumflex-accent? #\^)
(make-char-guard guard:low-line? #\_)
(make-char-guard guard:grave-accent? #\`)
;; BEGIN: Lowercase letters.
(make-char-guard guard:letter-a? #\a)
(make-char-guard guard:letter-b? #\b)
(make-char-guard guard:letter-c? #\c)
(make-char-guard guard:letter-d? #\d)
(make-char-guard guard:letter-e? #\e)
(make-char-guard guard:letter-f? #\f)
(make-char-guard guard:letter-g? #\g)
(make-char-guard guard:letter-h? #\h)
(make-char-guard guard:letter-i? #\i)
(make-char-guard guard:letter-j? #\j)
(make-char-guard guard:letter-k? #\k)
(make-char-guard guard:letter-l? #\l)
(make-char-guard guard:letter-m? #\m)
(make-char-guard guard:letter-n? #\n)
(make-char-guard guard:letter-o? #\o)
(make-char-guard guard:letter-p? #\p)
(make-char-guard guard:letter-q? #\q)
(make-char-guard guard:letter-r? #\r)
(make-char-guard guard:letter-s? #\s)
(make-char-guard guard:letter-t? #\t)
(make-char-guard guard:letter-u? #\u)
(make-char-guard guard:letter-v? #\v)
(make-char-guard guard:letter-w? #\w)
(make-char-guard guard:letter-x? #\x)
(make-char-guard guard:letter-y? #\y)
(make-char-guard guard:letter-z? #\z)
;; END: Lowercase letters.
(make-char-guard guard:left-curly-bracket? #\{)
(make-char-guard guard:vertical-line? #\|)
(make-char-guard guard:right-curly-bracket? #\})
(make-char-guard guard:tilde? #\~)
(make-char-guard guard:del? (integer->char 127))
Charset predicates .
(make-charset-guard guard:letter? char-set:letter)
(make-charset-guard guard:lower-case? char-set:lower-case)
(make-charset-guard guard:upper-case? char-set:upper-case)
(make-charset-guard guard:digit? char-set:digit)
(make-charset-guard guard:letter+digit? char-set:letter+digit)
(make-charset-guard guard:graphic? char-set:graphic)
(make-charset-guard guard:printing? char-set:printing)
(make-charset-guard guard:whitespace? char-set:whitespace)
(make-charset-guard guard:blank? char-set:blank)
(make-charset-guard guard:punctuation? char-set:punctuation)
(make-charset-guard guard:symbol? char-set:symbol)
(make-charset-guard guard:hex-digit? char-set:hex-digit)
(make-charset-guard guard:ascii? char-set:ascii)
;; Misc. procedures.
(make-char-guard guard:newline? #\newline)
(define-public (guard:eof-object? ctx ch)
(eof-object? ch))
(define (action:syntax-error ctx ch)
(error "Syntax error"
(char-context-port ctx)
(char-context-row ctx)
(char-context-col ctx)
ch
ctx))
(define (%current-position-prefix ctx)
(format #f "~a:~a:~a: "
(char-context-port ctx)
(char-context-row ctx)
(char-context-col ctx)))
(define (context-log-error ctx fmt . rest)
(apply log-error
(string-append (%current-position-prefix ctx) fmt)
rest))
(define (context-log-warning ctx fmt . rest)
(apply log-warning
(string-append (%current-position-prefix ctx) fmt)
rest))
(define (context-log-info ctx fmt . rest)
(apply log-info
(string-append (%current-position-prefix ctx) fmt)
rest))
(define (context-log-debug ctx fmt . rest)
(apply log-debug
(string-append (%current-position-prefix ctx) fmt)
rest))
;;; char-context.scm ends here.
| null | https://raw.githubusercontent.com/artyom-poptsov/guile-smc/fa299b43e65a9a30679865201d5ce02d0da7b5b5/modules/smc/context/char-context.scm | scheme | char-context.scm -- Guile-SMC finite state machine character context.
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
The program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with the program. If not, see </>.
Commentary:
This file contains an implementation of a character context based on a
generic context. The character context can be used to handle a stream of
characters.
Code:
Actions.
All guards that are exported with 'define-public' below.
Logging procedures
A port from which data is read.
<port>
Total number of characters consumed.
<number>
Current text column number.
<number>
Current text row number.
<number>
Increment the current text column.
Reset the current text column.
CH. These counters are thrown when a syntax error occurred.
Event source.
Get the next character from a CONTEXT port.
Guards.
Make a procedure that checks if a CH1 equals to CH2.
The procedures below are predicates for symbols of the ASCII table, in the
same order.
BEGIN: Digits.
END: Digits.
)
BEGIN: Uppercase letters.
END: Uppercase letter.
BEGIN: Lowercase letters.
END: Lowercase letters.
Misc. procedures.
char-context.scm ends here. |
Copyright ( C ) 2021 < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(define-module (smc context char-context)
#:use-module (ice-9 textual-ports)
#:use-module (oop goops)
#:use-module (smc context context)
#:use-module (smc core log)
From ( smc context context )
<context>
context?
context-debug-mode?
context-debug-mode-set!
context-stanza
context-stanza-set!
context-stanza-clear!
context-buffer
context-buffer-set!
context-buffer-clear!
context-clear!
guard:#t
action:no-op
action:store
action:clear-buffer
action:update-stanza)
#:export (<char-context>
char-context-port
char-context-counter
char-context-row
char-context-col
char-context-update-counters!
event-source
action:syntax-error
context-log-error
context-log-warning
context-log-info
context-log-debug
make-char-guard
make-charset-guard))
(define-class <char-context> (<context>)
(port
#:init-value (current-input-port)
#:init-keyword #:port
#:getter char-context-port)
(counter
#:init-value 0
#:getter char-context-counter
#:setter char-context-counter-set!)
(col-number
#:init-value 0
#:getter char-context-col
#:setter char-context-col-set!)
(row-number
#:init-value 0
#:getter char-context-row
#:setter char-context-row-set!))
(define-method (%counter++! (ctx <char-context>))
(char-context-counter-set! ctx (+ (char-context-counter ctx) 1)))
(define-method (%col++! (ctx <char-context>))
(char-context-col-set! ctx (+ (char-context-col ctx) 1)))
(define-method (%col-reset! (ctx <char-context>))
(char-context-col-set! ctx 0))
Increment the current row number . Resets the current column number to zero .
(define-method (%row++! (ctx <char-context>))
(char-context-row-set! ctx (+ (char-context-row ctx) 1))
(%col-reset! ctx))
Update counters in a character context CTX based on an incoming character
(define-method (char-context-update-counters! (ctx <char-context>) ch)
(unless (eof-object? ch)
(%counter++! ctx)
(%col++! ctx)
(when (char=? ch #\newline)
(%row++! ctx))))
(define-method (event-source (context <char-context>))
(let ((ch (get-char (char-context-port context))))
(char-context-update-counters! context ch)
ch))
(define-syntax-rule (make-char-guard name ch1)
(define-public (name ctx ch2)
(char=? ch1 ch2)))
Make a procedure that checks if a CH is in a CHARSET .
(define-syntax-rule (make-charset-guard name charset)
(define-public (name ctx ch)
(char-set-contains? charset ch)))
(make-char-guard guard:nul? #\nul)
(make-char-guard guard:soh? #\soh)
(make-char-guard guard:stx? #\stx)
(make-char-guard guard:etx? #\etx)
(make-char-guard guard:eot? #\eot)
(make-char-guard guard:enq? #\enq)
(make-char-guard guard:ack? #\ack)
(make-char-guard guard:bel? #\bel)
(make-char-guard guard:bs? #\bs)
(make-char-guard guard:tab? #\tab)
(make-char-guard guard:lf? #\linefeed)
(make-char-guard guard:vt? #\vtab)
(make-char-guard guard:ff? #\ff)
(make-char-guard guard:cr? #\cr)
(make-char-guard guard:so? #\so)
(make-char-guard guard:si? #\si)
(make-char-guard guard:dle? #\dle)
(make-char-guard guard:dc1? #\dc1)
(make-char-guard guard:dc2? #\dc2)
(make-char-guard guard:dc3? #\dc3)
(make-char-guard guard:dc4? #\dc4)
(make-char-guard guard:nak? #\nak)
(make-char-guard guard:syn? #\syn)
(make-char-guard guard:etb? #\etb)
(make-char-guard guard:can? #\can)
(make-char-guard guard:em? #\em)
(make-char-guard guard:sub? #\sub)
(make-char-guard guard:esc? #\esc)
(make-char-guard guard:fs? #\fs)
(make-char-guard guard:gs? #\gs)
(make-char-guard guard:rs? #\rs)
(make-char-guard guard:us? #\us)
(make-char-guard guard:space? #\space)
(make-char-guard guard:exclamation-mark? #\!)
(make-char-guard guard:double-quote? #\")
(make-char-guard guard:number-sign? #\#)
(make-char-guard guard:dollar-sign? #\$)
(make-char-guard guard:percent-sign? #\%)
(make-char-guard guard:ampersand? #\&)
(make-char-guard guard:single-quote? #\')
(make-char-guard guard:left-parenthesis? #\()
(make-char-guard guard:right-parenthesis? #\))
(make-char-guard guard:asterisk? #\*)
(make-char-guard guard:plus-sign? #\+)
(make-char-guard guard:comma? #\,)
(make-char-guard guard:hyphen-minus? #\-)
(make-char-guard guard:full-stop? #\.)
(make-char-guard guard:solidus? #\/)
(make-char-guard guard:digit-zero? #\0)
(make-char-guard guard:digit-one? #\1)
(make-char-guard guard:digit-two? #\2)
(make-char-guard guard:digit-three? #\3)
(make-char-guard guard:digit-four? #\4)
(make-char-guard guard:digit-five? #\5)
(make-char-guard guard:digit-six? #\6)
(make-char-guard guard:digit-seven? #\7)
(make-char-guard guard:digit-eight? #\8)
(make-char-guard guard:digit-nine? #\9)
(make-char-guard guard:colon? #\:)
(make-char-guard guard:less-than-sign? #\<)
(make-char-guard guard:equals-sign? #\=)
(make-char-guard guard:more-than-sign? #\>)
(make-char-guard guard:question-mark? #\?)
(make-char-guard guard:at-symbol? #\@)
(make-char-guard guard:letter-A? #\A)
(make-char-guard guard:letter-B? #\B)
(make-char-guard guard:letter-C? #\C)
(make-char-guard guard:letter-D? #\D)
(make-char-guard guard:letter-E? #\E)
(make-char-guard guard:letter-F? #\F)
(make-char-guard guard:letter-G? #\G)
(make-char-guard guard:letter-H? #\H)
(make-char-guard guard:letter-I? #\I)
(make-char-guard guard:letter-J? #\J)
(make-char-guard guard:letter-K? #\K)
(make-char-guard guard:letter-L? #\L)
(make-char-guard guard:letter-M? #\M)
(make-char-guard guard:letter-N? #\N)
(make-char-guard guard:letter-O? #\O)
(make-char-guard guard:letter-P? #\P)
(make-char-guard guard:letter-Q? #\Q)
(make-char-guard guard:letter-R? #\R)
(make-char-guard guard:letter-S? #\S)
(make-char-guard guard:letter-T? #\T)
(make-char-guard guard:letter-U? #\U)
(make-char-guard guard:letter-V? #\V)
(make-char-guard guard:letter-W? #\W)
(make-char-guard guard:letter-X? #\X)
(make-char-guard guard:letter-Y? #\Y)
(make-char-guard guard:letter-Z? #\Z)
(make-char-guard guard:left-square-bracket? #\[)
(make-char-guard guard:reverse-solidus? #\\)
(make-char-guard guard:right-square-bracket? #\])
(make-char-guard guard:circumflex-accent? #\^)
(make-char-guard guard:low-line? #\_)
(make-char-guard guard:grave-accent? #\`)
(make-char-guard guard:letter-a? #\a)
(make-char-guard guard:letter-b? #\b)
(make-char-guard guard:letter-c? #\c)
(make-char-guard guard:letter-d? #\d)
(make-char-guard guard:letter-e? #\e)
(make-char-guard guard:letter-f? #\f)
(make-char-guard guard:letter-g? #\g)
(make-char-guard guard:letter-h? #\h)
(make-char-guard guard:letter-i? #\i)
(make-char-guard guard:letter-j? #\j)
(make-char-guard guard:letter-k? #\k)
(make-char-guard guard:letter-l? #\l)
(make-char-guard guard:letter-m? #\m)
(make-char-guard guard:letter-n? #\n)
(make-char-guard guard:letter-o? #\o)
(make-char-guard guard:letter-p? #\p)
(make-char-guard guard:letter-q? #\q)
(make-char-guard guard:letter-r? #\r)
(make-char-guard guard:letter-s? #\s)
(make-char-guard guard:letter-t? #\t)
(make-char-guard guard:letter-u? #\u)
(make-char-guard guard:letter-v? #\v)
(make-char-guard guard:letter-w? #\w)
(make-char-guard guard:letter-x? #\x)
(make-char-guard guard:letter-y? #\y)
(make-char-guard guard:letter-z? #\z)
(make-char-guard guard:left-curly-bracket? #\{)
(make-char-guard guard:vertical-line? #\|)
(make-char-guard guard:right-curly-bracket? #\})
(make-char-guard guard:tilde? #\~)
(make-char-guard guard:del? (integer->char 127))
Charset predicates .
(make-charset-guard guard:letter? char-set:letter)
(make-charset-guard guard:lower-case? char-set:lower-case)
(make-charset-guard guard:upper-case? char-set:upper-case)
(make-charset-guard guard:digit? char-set:digit)
(make-charset-guard guard:letter+digit? char-set:letter+digit)
(make-charset-guard guard:graphic? char-set:graphic)
(make-charset-guard guard:printing? char-set:printing)
(make-charset-guard guard:whitespace? char-set:whitespace)
(make-charset-guard guard:blank? char-set:blank)
(make-charset-guard guard:punctuation? char-set:punctuation)
(make-charset-guard guard:symbol? char-set:symbol)
(make-charset-guard guard:hex-digit? char-set:hex-digit)
(make-charset-guard guard:ascii? char-set:ascii)
(make-char-guard guard:newline? #\newline)
(define-public (guard:eof-object? ctx ch)
(eof-object? ch))
(define (action:syntax-error ctx ch)
(error "Syntax error"
(char-context-port ctx)
(char-context-row ctx)
(char-context-col ctx)
ch
ctx))
(define (%current-position-prefix ctx)
(format #f "~a:~a:~a: "
(char-context-port ctx)
(char-context-row ctx)
(char-context-col ctx)))
(define (context-log-error ctx fmt . rest)
(apply log-error
(string-append (%current-position-prefix ctx) fmt)
rest))
(define (context-log-warning ctx fmt . rest)
(apply log-warning
(string-append (%current-position-prefix ctx) fmt)
rest))
(define (context-log-info ctx fmt . rest)
(apply log-info
(string-append (%current-position-prefix ctx) fmt)
rest))
(define (context-log-debug ctx fmt . rest)
(apply log-debug
(string-append (%current-position-prefix ctx) fmt)
rest))
|
ba44aa04aee794305c6cbb871da05eb591c154cb5d98460381825cfd9c054c5d | thattommyhall/offline-4clojure | p26.clj | ;; Fibonacci Sequence - Easy
Write a function which returns the first X fibonacci numbers .
tags - Fibonacci : seqs
;; restricted -
(ns offline-4clojure.p26
(:use clojure.test))
(def __
;; your solution here
)
(defn -main []
(are [soln] soln
(= (__ 3) '(1 1 2))
(= (__ 6) '(1 1 2 3 5 8))
(= (__ 8) '(1 1 2 3 5 8 13 21))
))
| null | https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p26.clj | clojure | Fibonacci Sequence - Easy
restricted -
your solution here | Write a function which returns the first X fibonacci numbers .
tags - Fibonacci : seqs
(ns offline-4clojure.p26
(:use clojure.test))
(def __
)
(defn -main []
(are [soln] soln
(= (__ 3) '(1 1 2))
(= (__ 6) '(1 1 2 3 5 8))
(= (__ 8) '(1 1 2 3 5 8 13 21))
))
|
5f75551c1d7df0dc599a850f73889ebc950d5de3acdb519d92d661803a4aadbe | ygmpkk/house | Exception.hs | -----------------------------------------------------------------------------
-- |
-- Module : Control.Exception
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- This module provides support for raising and catching both built-in
-- and user-defined exceptions.
--
-----------------------------------------------------------------------------
module Control.Exception (
-- * The Exception type
instance , Ord , Show ,
instance , Ord , Show ,
instance , Ord , Show ,
instance , Ord , Show ,
instance , Ord , Show ,
-- * Throwing exceptions
throwIO, -- :: Exception -> IO a
throw, -- :: Exception -> a
: : IOError - > IO a
#ifdef __GLASGOW_HASKELL__
throwTo, -- :: ThreadId -> Exception -> a
#endif
-- * Catching Exceptions
-- |There are several functions for catching and examining
-- exceptions; all of them may only be used from within the
-- 'IO' monad.
-- ** The @catch@ functions
catch, -- :: IO a -> (Exception -> IO a) -> IO a
catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
-- ** The @handle@ functions
handle, -- :: (Exception -> IO a) -> IO a -> IO a
handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
-- ** The @try@ functions
try, -- :: IO a -> IO (Either Exception a)
tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
-- ** The @evaluate@ function
evaluate, -- :: a -> IO a
-- ** The @mapException@ function
mapException, -- :: (Exception -> Exception) -> a -> a
-- ** Exception predicates
$ preds
: : Exception - > Maybe IOError
: : Exception - > Maybe ArithException
errorCalls, -- :: Exception -> Maybe String
dynExceptions, -- :: Exception -> Maybe Dynamic
assertions, -- :: Exception -> Maybe String
: : Exception - > Maybe AsyncException
#ifndef STANDALONE
userErrors, -- :: Exception -> Maybe String
#endif
-- * Dynamic exceptions
-- $dynamic
: : ex = > ex - > b
#ifdef __GLASGOW_HASKELL__
: : ex = > ThreadId - > ex - > b
#endif
: : ex = > IO a - > ( ex - > IO a ) - > IO a
-- * Asynchronous Exceptions
-- $async
-- ** Asynchronous exception control
|The following two functions allow a thread to control delivery of
-- asynchronous exceptions during a critical region.
block, -- :: IO a -> IO a
unblock, -- :: IO a -> IO a
-- *** Applying @block@ to an exception handler
-- $block_handler
-- *** Interruptible operations
-- $interruptible
-- * Assertions
assert, -- :: Bool -> a -> a
-- * Utilities
bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
bracket_, -- :: IO a -> IO b -> IO c -> IO ()
finally, -- :: IO a -> IO b -> IO a
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base ( assert )
import GHC.Exception as ExceptionBase hiding (catch)
import GHC.Conc ( throwTo, ThreadId )
import GHC.IOBase ( IO(..) )
#endif
#ifdef __HUGS__
import Hugs.Exception as ExceptionBase
#endif
import Prelude hiding ( catch )
#ifdef __GLASGOW_HASKELL__
import GHC.IOBase ( unsafePerformIO )
#else
import System.IO.Error hiding ( catch, try )
import System.IO.Unsafe ( unsafePerformIO )
#endif
import Data.Dynamic
#include "Typeable.h"
INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
-----------------------------------------------------------------------------
-- Catching exceptions
-- |This is the simplest of the exception-catching functions. It
-- takes a single argument, runs it, and if an exception is raised
-- the \"handler\" is executed, with the value of the exception passed as an
-- argument. Otherwise, the result is returned as normal. For example:
--
-- > catch (openFile f ReadMode)
-- > (\e -> hPutStr stderr (\"Couldn\'t open \"++f++\": \" ++ show e))
--
-- For catching exceptions in pure (non-'IO') expressions, see the
-- function 'evaluate'.
--
Note that due to Haskell\ 's unspecified evaluation order , an
expression may return one of several possible exceptions : consider
the expression @error \"urk\ " + 1 ` 0@. Does
-- 'catch' execute the handler passing
@ErrorCall \"urk\"@ , or @ArithError DivideByZero@ ?
--
The answer is \"either\ " : ' catch ' makes a
-- non-deterministic choice about which exception to catch. If you
-- call it again, you might get a different exception back. This is
-- ok, because 'catch' is an 'IO' computation.
--
-- Note that 'catch' catches all types of exceptions, and is generally
-- used for \"cleaning up\" before passing on the exception using
-- 'throwIO'. It is not good practice to discard the exception and
continue , without first checking the type of the exception ( it
-- might be a 'ThreadKilled', for example). In this case it is usually better
-- to use 'catchJust' and select the kinds of exceptions to catch.
--
Also note that The " Prelude " also exports a
-- function called 'catch' which has the same type as
-- 'Control.Exception.catch', the difference being that the
" Prelude " version only catches the IO and user
families of exceptions ( as required by 98 ) . We recommend
either hiding the " Prelude " version of
-- 'catch' when importing
-- "Control.Exception", or importing
-- "Control.Exception" qualified, to avoid name-clashes.
catch :: IO a -- ^ The computation to run
-> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
-> IO a
catch = ExceptionBase.catchException
-- | The function 'catchJust' is like 'catch', but it takes an extra
-- argument which is an /exception predicate/, a function which
-- selects which type of exceptions we\'re interested in. There are
-- some predefined exception predicates for useful subsets of
-- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
-- to catch just calls to the 'error' function, we could use
--
> result < - catchJust errorCalls thing_to_try handler
--
-- Any other exceptions which are not matched by the predicate
-- are re-raised, and may be caught by an enclosing
-- 'catch' or 'catchJust'.
catchJust
:: (Exception -> Maybe b) -- ^ Predicate to select exceptions
-> IO a -- ^ Computation to run
-> (b -> IO a) -- ^ Handler
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throw e
Just b -> handler b
-- | A version of 'catch' with the arguments swapped around; useful in
-- situations where the code for the handler is shorter. For example:
--
> do handle ( \e - > exitWith ( ExitFailure 1 ) ) $
-- > ...
handle :: (Exception -> IO a) -> IO a -> IO a
handle = flip catch
-- | A version of 'catchJust' with the arguments swapped around (see
-- 'handle').
handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
-----------------------------------------------------------------------------
-- evaluate
-- | Forces its argument to be evaluated, and returns the result in
-- the 'IO' monad. It can be used to order evaluation with respect to
-- other 'IO' operations; its semantics are given by
--
-- > evaluate undefined `seq` return () ==> return ()
-- > catch (evaluate undefined) (\e -> return ()) ==> return ()
--
NOTE : @(evaluate a)@ is /not/ the same as @(a \`seq\ ` return a)@.
#ifdef __GLASGOW_HASKELL__
evaluate :: a -> IO a
evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
NB . ca n't write
-- a `seq` (# s, a #)
-- because we can't have an unboxed tuple as a function argument
#endif
-----------------------------------------------------------------------------
' mapException '
| This function maps one exception into another as proposed in the
-- paper \"A semantics for imprecise exceptions\".
-- Notice that the usage of 'unsafePerformIO' is safe here.
mapException :: (Exception -> Exception) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throw (f x)))
-----------------------------------------------------------------------------
-- 'try' and variations.
-- | Similar to 'catch', but returns an 'Either' result which is
-- @(Right a)@ if no exception was raised, or @(Left e)@ if an
-- exception was raised and its value is @e@.
--
-- > try a = catch (Right \`liftM\` a) (return . Left)
--
-- Note: as with 'catch', it is only polite to use this variant if you intend
-- to re-throw the exception after performing whatever cleanup is needed.
-- Otherwise, 'tryJust' is generally considered to be better.
--
try :: IO a -> IO (Either Exception a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
-- | A variant of 'try' that takes an exception predicate to select
which exceptions are caught ( c.f . ' catchJust ' ) . If the exception
-- does not match the predicate, it is re-thrown.
tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throw e
Just b -> return (Left b)
-----------------------------------------------------------------------------
-- Dynamic exceptions
-- $dynamic
-- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
-- interface for throwing and catching exceptions of type 'Dynamic'
-- (see "Data.Dynamic") which allows exception values of any type in
the ' ' class to be thrown and caught .
-- | Raise any value as an exception, provided it is in the
' ' class .
throwDyn :: Typeable exception => exception -> b
throwDyn exception = throw (DynException (toDyn exception))
#ifdef __GLASGOW_HASKELL__
| A variant of ' ' that throws the dynamic exception to an
arbitrary thread ( GHC only : c.f . ' throwTo ' ) .
throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
throwDynTo t exception = throwTo t (DynException (toDyn exception))
#endif /* __GLASGOW_HASKELL__ */
-- | Catch dynamic exceptions of the required type. All other
-- exceptions are re-thrown, including dynamic exceptions of the wrong
-- type.
--
-- When using dynamic exceptions it is advisable to define a new
-- datatype to use for your exception type, to avoid possible clashes
-- with dynamic exceptions used in other libraries.
--
catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
catchDyn m k = catchException m handle
where handle ex = case ex of
(DynException dyn) ->
case fromDynamic dyn of
Just exception -> k exception
Nothing -> throw ex
_ -> throw ex
-----------------------------------------------------------------------------
Exception Predicates
$ preds
These pre - defined predicates may be used as the first argument to
-- 'catchJust', 'tryJust', or 'handleJust' to select certain common
-- classes of exceptions.
ioErrors :: Exception -> Maybe IOError
arithExceptions :: Exception -> Maybe ArithException
errorCalls :: Exception -> Maybe String
assertions :: Exception -> Maybe String
dynExceptions :: Exception -> Maybe Dynamic
asyncExceptions :: Exception -> Maybe AsyncException
ioErrors (IOException e) = Just e
ioErrors _ = Nothing
arithExceptions (ArithException e) = Just e
arithExceptions _ = Nothing
errorCalls (ErrorCall e) = Just e
errorCalls _ = Nothing
assertions (AssertionFailed e) = Just e
assertions _ = Nothing
dynExceptions (DynException e) = Just e
dynExceptions _ = Nothing
asyncExceptions (AsyncException e) = Just e
asyncExceptions _ = Nothing
#ifndef STANDALONE
userErrors :: Exception -> Maybe String
userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
userErrors _ = Nothing
#endif
-----------------------------------------------------------------------------
-- Some Useful Functions
-- | When you want to acquire a resource, do some work with it, and
-- then release the resource, it is a good idea to use 'bracket',
-- because 'bracket' will install the necessary exception handler to
-- release the resource in the event that an exception is raised
-- during the computation. If an exception is raised, then 'bracket' will
-- re-raise the exception (after performing the release).
--
-- A common example is opening a file:
--
-- > bracket
-- > (openFile "filename" ReadMode)
> ( )
-- > (\handle -> do { ... })
--
-- The arguments to 'bracket' are in this order so that we can partially apply
-- it, e.g.:
--
> withFile name = bracket ( openFile name )
--
bracket
^ computation to run first ( \"acquire resource\ " )
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracket before after thing =
block (do
a <- before
r <- catch
(unblock (thing a))
(\e -> do { after a; throw e })
after a
return r
)
-- | A specialised variant of 'bracket' with just a computation to run
-- afterward.
--
^ computation to run first
-> IO b -- ^ computation to run afterward (even if an exception
-- was raised)
returns the value from the first computation
a `finally` sequel =
block (do
r <- catch
(unblock a)
(\e -> do { sequel; throw e })
sequel
return r
)
| A variant of ' bracket ' where the return value from the first computation
-- is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
-- -----------------------------------------------------------------------------
-- Asynchronous exceptions
$ async
# AsynchronousExceptions # Asynchronous exceptions are so - called because they arise due to
external influences , and can be raised at any point during execution .
' StackOverflow ' and ' HeapOverflow ' are two examples of
system - generated asynchronous exceptions .
The primary source of asynchronous exceptions , however , is
' throwTo ' :
> throwTo : : ThreadId - > Exception - > IO ( )
' throwTo ' ( also ' throwDynTo ' and ' Control . Concurrent.killThread ' ) allows one
running thread to raise an arbitrary exception in another thread . The
exception is therefore asynchronous with respect to the target thread ,
which could be doing anything at the time it receives the exception .
Great care should be taken with asynchronous exceptions ; it is all too
easy to introduce race conditions by the over zealous use of
' throwTo ' .
#AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
external influences, and can be raised at any point during execution.
'StackOverflow' and 'HeapOverflow' are two examples of
system-generated asynchronous exceptions.
The primary source of asynchronous exceptions, however, is
'throwTo':
> throwTo :: ThreadId -> Exception -> IO ()
'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
running thread to raise an arbitrary exception in another thread. The
exception is therefore asynchronous with respect to the target thread,
which could be doing anything at the time it receives the exception.
Great care should be taken with asynchronous exceptions; it is all too
easy to introduce race conditions by the over zealous use of
'throwTo'.
-}
$ block_handler
There\ 's an implied ' block ' around every exception handler in a call
to one of the ' catch ' family of functions . This is because that is
what you want most of the time - it eliminates a common race condition
in starting an exception handler , because there may be no exception
handler on the stack to handle another exception if one arrives
immediately . If asynchronous exceptions are blocked on entering the
handler , though , we have time to install a new exception handler
before being interrupted . If this weren\'t the default , one would have
to write something like
> block (
> catch ( unblock ( ... ) )
> ( \e - > handler )
> )
If you need to unblock asynchronous exceptions again in the exception
handler , just use ' unblock ' as normal .
Note that ' try ' and friends /do not/ have a similar default , because
there is no exception handler in this case . If you want to use ' try '
in an asynchronous - exception - safe way , you will need to use
' block ' .
There\'s an implied 'block' around every exception handler in a call
to one of the 'catch' family of functions. This is because that is
what you want most of the time - it eliminates a common race condition
in starting an exception handler, because there may be no exception
handler on the stack to handle another exception if one arrives
immediately. If asynchronous exceptions are blocked on entering the
handler, though, we have time to install a new exception handler
before being interrupted. If this weren\'t the default, one would have
to write something like
> block (
> catch (unblock (...))
> (\e -> handler)
> )
If you need to unblock asynchronous exceptions again in the exception
handler, just use 'unblock' as normal.
Note that 'try' and friends /do not/ have a similar default, because
there is no exception handler in this case. If you want to use 'try'
in an asynchronous-exception-safe way, you will need to use
'block'.
-}
$ interruptible
Some operations are /interruptible/ , which means that they can receive
asynchronous exceptions even in the scope of a ' block ' . Any function
which may itself block is defined as interruptible ; this includes
' Control . Concurrent . MVar.takeMVar '
( but not ' Control . Concurrent . ' ) ,
and most operations which perform
some I\/O with the outside world . The reason for having
interruptible operations is so that we can write things like
> block (
> a < - takeMVar m
> catch ( unblock ( ... ) )
> ( \e - > ... )
> )
if the ' Control . Concurrent . MVar.takeMVar ' was not interruptible ,
then this particular
combination could lead to deadlock , because the thread itself would be
blocked in a state where it can\'t receive any asynchronous exceptions .
With ' Control . Concurrent . MVar.takeMVar ' interruptible , however , we can be
safe in the knowledge that the thread can receive exceptions right up
until the point when the ' Control . Concurrent . MVar.takeMVar ' succeeds .
Similar arguments apply for other interruptible operations like
' System . IO.openFile ' .
Some operations are /interruptible/, which means that they can receive
asynchronous exceptions even in the scope of a 'block'. Any function
which may itself block is defined as interruptible; this includes
'Control.Concurrent.MVar.takeMVar'
(but not 'Control.Concurrent.MVar.tryTakeMVar'),
and most operations which perform
some I\/O with the outside world. The reason for having
interruptible operations is so that we can write things like
> block (
> a <- takeMVar m
> catch (unblock (...))
> (\e -> ...)
> )
if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
then this particular
combination could lead to deadlock, because the thread itself would be
blocked in a state where it can\'t receive any asynchronous exceptions.
With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
safe in the knowledge that the thread can receive exceptions right up
until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
Similar arguments apply for other interruptible operations like
'System.IO.openFile'.
-}
-- -----------------------------------------------------------------------------
Assert
#ifdef __HADDOCK__
| If the first argument evaluates to ' True ' , then the result is the
second argument . Otherwise an ' AssertionFailed ' exception is raised ,
-- containing a 'String' with the source file and line number of the
-- call to assert.
--
-- Assertions can normally be turned on or off with a compiler flag
( for GHC , assertions are normally on unless the @-fignore - asserts@
option is give ) . When assertions are turned off , the first
argument to ' assert ' is ignored , and the second argument is
-- returned as the result.
assert :: Bool -> a -> a
#endif
#ifndef __GLASGOW_HASKELL__
assert :: Bool -> a -> a
assert True x = x
assert False _ = throw (AssertionFailed "")
#endif
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/base/Control/Exception.hs | haskell | ---------------------------------------------------------------------------
|
Module : Control.Exception
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
This module provides support for raising and catching both built-in
and user-defined exceptions.
---------------------------------------------------------------------------
* The Exception type
* Throwing exceptions
:: Exception -> IO a
:: Exception -> a
:: ThreadId -> Exception -> a
* Catching Exceptions
|There are several functions for catching and examining
exceptions; all of them may only be used from within the
'IO' monad.
** The @catch@ functions
:: IO a -> (Exception -> IO a) -> IO a
:: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
** The @handle@ functions
:: (Exception -> IO a) -> IO a -> IO a
:: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
** The @try@ functions
:: IO a -> IO (Either Exception a)
:: (Exception -> Maybe b) -> a -> IO (Either b a)
** The @evaluate@ function
:: a -> IO a
** The @mapException@ function
:: (Exception -> Exception) -> a -> a
** Exception predicates
:: Exception -> Maybe String
:: Exception -> Maybe Dynamic
:: Exception -> Maybe String
:: Exception -> Maybe String
* Dynamic exceptions
$dynamic
* Asynchronous Exceptions
$async
** Asynchronous exception control
asynchronous exceptions during a critical region.
:: IO a -> IO a
:: IO a -> IO a
*** Applying @block@ to an exception handler
$block_handler
*** Interruptible operations
$interruptible
* Assertions
:: Bool -> a -> a
* Utilities
:: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
:: IO a -> IO b -> IO c -> IO ()
:: IO a -> IO b -> IO a
---------------------------------------------------------------------------
Catching exceptions
|This is the simplest of the exception-catching functions. It
takes a single argument, runs it, and if an exception is raised
the \"handler\" is executed, with the value of the exception passed as an
argument. Otherwise, the result is returned as normal. For example:
> catch (openFile f ReadMode)
> (\e -> hPutStr stderr (\"Couldn\'t open \"++f++\": \" ++ show e))
For catching exceptions in pure (non-'IO') expressions, see the
function 'evaluate'.
'catch' execute the handler passing
non-deterministic choice about which exception to catch. If you
call it again, you might get a different exception back. This is
ok, because 'catch' is an 'IO' computation.
Note that 'catch' catches all types of exceptions, and is generally
used for \"cleaning up\" before passing on the exception using
'throwIO'. It is not good practice to discard the exception and
might be a 'ThreadKilled', for example). In this case it is usually better
to use 'catchJust' and select the kinds of exceptions to catch.
function called 'catch' which has the same type as
'Control.Exception.catch', the difference being that the
'catch' when importing
"Control.Exception", or importing
"Control.Exception" qualified, to avoid name-clashes.
^ The computation to run
^ Handler to invoke if an exception is raised
| The function 'catchJust' is like 'catch', but it takes an extra
argument which is an /exception predicate/, a function which
selects which type of exceptions we\'re interested in. There are
some predefined exception predicates for useful subsets of
exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
to catch just calls to the 'error' function, we could use
Any other exceptions which are not matched by the predicate
are re-raised, and may be caught by an enclosing
'catch' or 'catchJust'.
^ Predicate to select exceptions
^ Computation to run
^ Handler
| A version of 'catch' with the arguments swapped around; useful in
situations where the code for the handler is shorter. For example:
> ...
| A version of 'catchJust' with the arguments swapped around (see
'handle').
---------------------------------------------------------------------------
evaluate
| Forces its argument to be evaluated, and returns the result in
the 'IO' monad. It can be used to order evaluation with respect to
other 'IO' operations; its semantics are given by
> evaluate undefined `seq` return () ==> return ()
> catch (evaluate undefined) (\e -> return ()) ==> return ()
a `seq` (# s, a #)
because we can't have an unboxed tuple as a function argument
---------------------------------------------------------------------------
paper \"A semantics for imprecise exceptions\".
Notice that the usage of 'unsafePerformIO' is safe here.
---------------------------------------------------------------------------
'try' and variations.
| Similar to 'catch', but returns an 'Either' result which is
@(Right a)@ if no exception was raised, or @(Left e)@ if an
exception was raised and its value is @e@.
> try a = catch (Right \`liftM\` a) (return . Left)
Note: as with 'catch', it is only polite to use this variant if you intend
to re-throw the exception after performing whatever cleanup is needed.
Otherwise, 'tryJust' is generally considered to be better.
| A variant of 'try' that takes an exception predicate to select
does not match the predicate, it is re-thrown.
---------------------------------------------------------------------------
Dynamic exceptions
$dynamic
#DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
interface for throwing and catching exceptions of type 'Dynamic'
(see "Data.Dynamic") which allows exception values of any type in
| Raise any value as an exception, provided it is in the
| Catch dynamic exceptions of the required type. All other
exceptions are re-thrown, including dynamic exceptions of the wrong
type.
When using dynamic exceptions it is advisable to define a new
datatype to use for your exception type, to avoid possible clashes
with dynamic exceptions used in other libraries.
---------------------------------------------------------------------------
'catchJust', 'tryJust', or 'handleJust' to select certain common
classes of exceptions.
---------------------------------------------------------------------------
Some Useful Functions
| When you want to acquire a resource, do some work with it, and
then release the resource, it is a good idea to use 'bracket',
because 'bracket' will install the necessary exception handler to
release the resource in the event that an exception is raised
during the computation. If an exception is raised, then 'bracket' will
re-raise the exception (after performing the release).
A common example is opening a file:
> bracket
> (openFile "filename" ReadMode)
> (\handle -> do { ... })
The arguments to 'bracket' are in this order so that we can partially apply
it, e.g.:
^ computation to run last (\"release resource\")
^ computation to run in-between
returns the value from the in-between computation
| A specialised variant of 'bracket' with just a computation to run
afterward.
^ computation to run afterward (even if an exception
was raised)
is not required.
-----------------------------------------------------------------------------
Asynchronous exceptions
-----------------------------------------------------------------------------
containing a 'String' with the source file and line number of the
call to assert.
Assertions can normally be turned on or off with a compiler flag
returned as the result. | Copyright : ( c ) The University of Glasgow 2001
module Control.Exception (
instance , Ord , Show ,
instance , Ord , Show ,
instance , Ord , Show ,
instance , Ord , Show ,
instance , Ord , Show ,
: : IOError - > IO a
#ifdef __GLASGOW_HASKELL__
#endif
$ preds
: : Exception - > Maybe IOError
: : Exception - > Maybe ArithException
: : Exception - > Maybe AsyncException
#ifndef STANDALONE
#endif
: : ex = > ex - > b
#ifdef __GLASGOW_HASKELL__
: : ex = > ThreadId - > ex - > b
#endif
: : ex = > IO a - > ( ex - > IO a ) - > IO a
|The following two functions allow a thread to control delivery of
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base ( assert )
import GHC.Exception as ExceptionBase hiding (catch)
import GHC.Conc ( throwTo, ThreadId )
import GHC.IOBase ( IO(..) )
#endif
#ifdef __HUGS__
import Hugs.Exception as ExceptionBase
#endif
import Prelude hiding ( catch )
#ifdef __GLASGOW_HASKELL__
import GHC.IOBase ( unsafePerformIO )
#else
import System.IO.Error hiding ( catch, try )
import System.IO.Unsafe ( unsafePerformIO )
#endif
import Data.Dynamic
#include "Typeable.h"
INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
Note that due to Haskell\ 's unspecified evaluation order , an
expression may return one of several possible exceptions : consider
the expression @error \"urk\ " + 1 ` 0@. Does
@ErrorCall \"urk\"@ , or @ArithError DivideByZero@ ?
The answer is \"either\ " : ' catch ' makes a
continue , without first checking the type of the exception ( it
Also note that The " Prelude " also exports a
" Prelude " version only catches the IO and user
families of exceptions ( as required by 98 ) . We recommend
either hiding the " Prelude " version of
-> IO a
catch = ExceptionBase.catchException
> result < - catchJust errorCalls thing_to_try handler
catchJust
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throw e
Just b -> handler b
> do handle ( \e - > exitWith ( ExitFailure 1 ) ) $
handle :: (Exception -> IO a) -> IO a -> IO a
handle = flip catch
handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
NOTE : @(evaluate a)@ is /not/ the same as @(a \`seq\ ` return a)@.
#ifdef __GLASGOW_HASKELL__
evaluate :: a -> IO a
evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
NB . ca n't write
#endif
' mapException '
| This function maps one exception into another as proposed in the
mapException :: (Exception -> Exception) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throw (f x)))
try :: IO a -> IO (Either Exception a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
which exceptions are caught ( c.f . ' catchJust ' ) . If the exception
tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throw e
Just b -> return (Left b)
the ' ' class to be thrown and caught .
' ' class .
throwDyn :: Typeable exception => exception -> b
throwDyn exception = throw (DynException (toDyn exception))
#ifdef __GLASGOW_HASKELL__
| A variant of ' ' that throws the dynamic exception to an
arbitrary thread ( GHC only : c.f . ' throwTo ' ) .
throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
throwDynTo t exception = throwTo t (DynException (toDyn exception))
#endif /* __GLASGOW_HASKELL__ */
catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
catchDyn m k = catchException m handle
where handle ex = case ex of
(DynException dyn) ->
case fromDynamic dyn of
Just exception -> k exception
Nothing -> throw ex
_ -> throw ex
Exception Predicates
$ preds
These pre - defined predicates may be used as the first argument to
ioErrors :: Exception -> Maybe IOError
arithExceptions :: Exception -> Maybe ArithException
errorCalls :: Exception -> Maybe String
assertions :: Exception -> Maybe String
dynExceptions :: Exception -> Maybe Dynamic
asyncExceptions :: Exception -> Maybe AsyncException
ioErrors (IOException e) = Just e
ioErrors _ = Nothing
arithExceptions (ArithException e) = Just e
arithExceptions _ = Nothing
errorCalls (ErrorCall e) = Just e
errorCalls _ = Nothing
assertions (AssertionFailed e) = Just e
assertions _ = Nothing
dynExceptions (DynException e) = Just e
dynExceptions _ = Nothing
asyncExceptions (AsyncException e) = Just e
asyncExceptions _ = Nothing
#ifndef STANDALONE
userErrors :: Exception -> Maybe String
userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
userErrors _ = Nothing
#endif
> ( )
> withFile name = bracket ( openFile name )
bracket
^ computation to run first ( \"acquire resource\ " )
bracket before after thing =
block (do
a <- before
r <- catch
(unblock (thing a))
(\e -> do { after a; throw e })
after a
return r
)
^ computation to run first
returns the value from the first computation
a `finally` sequel =
block (do
r <- catch
(unblock a)
(\e -> do { sequel; throw e })
sequel
return r
)
| A variant of ' bracket ' where the return value from the first computation
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
$ async
# AsynchronousExceptions # Asynchronous exceptions are so - called because they arise due to
external influences , and can be raised at any point during execution .
' StackOverflow ' and ' HeapOverflow ' are two examples of
system - generated asynchronous exceptions .
The primary source of asynchronous exceptions , however , is
' throwTo ' :
> throwTo : : ThreadId - > Exception - > IO ( )
' throwTo ' ( also ' throwDynTo ' and ' Control . Concurrent.killThread ' ) allows one
running thread to raise an arbitrary exception in another thread . The
exception is therefore asynchronous with respect to the target thread ,
which could be doing anything at the time it receives the exception .
Great care should be taken with asynchronous exceptions ; it is all too
easy to introduce race conditions by the over zealous use of
' throwTo ' .
#AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
external influences, and can be raised at any point during execution.
'StackOverflow' and 'HeapOverflow' are two examples of
system-generated asynchronous exceptions.
The primary source of asynchronous exceptions, however, is
'throwTo':
> throwTo :: ThreadId -> Exception -> IO ()
'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
running thread to raise an arbitrary exception in another thread. The
exception is therefore asynchronous with respect to the target thread,
which could be doing anything at the time it receives the exception.
Great care should be taken with asynchronous exceptions; it is all too
easy to introduce race conditions by the over zealous use of
'throwTo'.
-}
$ block_handler
There\ 's an implied ' block ' around every exception handler in a call
to one of the ' catch ' family of functions . This is because that is
what you want most of the time - it eliminates a common race condition
in starting an exception handler , because there may be no exception
handler on the stack to handle another exception if one arrives
immediately . If asynchronous exceptions are blocked on entering the
handler , though , we have time to install a new exception handler
before being interrupted . If this weren\'t the default , one would have
to write something like
> block (
> catch ( unblock ( ... ) )
> ( \e - > handler )
> )
If you need to unblock asynchronous exceptions again in the exception
handler , just use ' unblock ' as normal .
Note that ' try ' and friends /do not/ have a similar default , because
there is no exception handler in this case . If you want to use ' try '
in an asynchronous - exception - safe way , you will need to use
' block ' .
There\'s an implied 'block' around every exception handler in a call
to one of the 'catch' family of functions. This is because that is
what you want most of the time - it eliminates a common race condition
in starting an exception handler, because there may be no exception
handler on the stack to handle another exception if one arrives
immediately. If asynchronous exceptions are blocked on entering the
handler, though, we have time to install a new exception handler
before being interrupted. If this weren\'t the default, one would have
to write something like
> block (
> catch (unblock (...))
> (\e -> handler)
> )
If you need to unblock asynchronous exceptions again in the exception
handler, just use 'unblock' as normal.
Note that 'try' and friends /do not/ have a similar default, because
there is no exception handler in this case. If you want to use 'try'
in an asynchronous-exception-safe way, you will need to use
'block'.
-}
$ interruptible
Some operations are /interruptible/ , which means that they can receive
asynchronous exceptions even in the scope of a ' block ' . Any function
which may itself block is defined as interruptible ; this includes
' Control . Concurrent . MVar.takeMVar '
( but not ' Control . Concurrent . ' ) ,
and most operations which perform
some I\/O with the outside world . The reason for having
interruptible operations is so that we can write things like
> block (
> a < - takeMVar m
> catch ( unblock ( ... ) )
> ( \e - > ... )
> )
if the ' Control . Concurrent . MVar.takeMVar ' was not interruptible ,
then this particular
combination could lead to deadlock , because the thread itself would be
blocked in a state where it can\'t receive any asynchronous exceptions .
With ' Control . Concurrent . MVar.takeMVar ' interruptible , however , we can be
safe in the knowledge that the thread can receive exceptions right up
until the point when the ' Control . Concurrent . MVar.takeMVar ' succeeds .
Similar arguments apply for other interruptible operations like
' System . IO.openFile ' .
Some operations are /interruptible/, which means that they can receive
asynchronous exceptions even in the scope of a 'block'. Any function
which may itself block is defined as interruptible; this includes
'Control.Concurrent.MVar.takeMVar'
(but not 'Control.Concurrent.MVar.tryTakeMVar'),
and most operations which perform
some I\/O with the outside world. The reason for having
interruptible operations is so that we can write things like
> block (
> a <- takeMVar m
> catch (unblock (...))
> (\e -> ...)
> )
if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
then this particular
combination could lead to deadlock, because the thread itself would be
blocked in a state where it can\'t receive any asynchronous exceptions.
With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
safe in the knowledge that the thread can receive exceptions right up
until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
Similar arguments apply for other interruptible operations like
'System.IO.openFile'.
-}
Assert
#ifdef __HADDOCK__
| If the first argument evaluates to ' True ' , then the result is the
second argument . Otherwise an ' AssertionFailed ' exception is raised ,
( for GHC , assertions are normally on unless the @-fignore - asserts@
option is give ) . When assertions are turned off , the first
argument to ' assert ' is ignored , and the second argument is
assert :: Bool -> a -> a
#endif
#ifndef __GLASGOW_HASKELL__
assert :: Bool -> a -> a
assert True x = x
assert False _ = throw (AssertionFailed "")
#endif
|
44bbf14da37c2a7416ef9d7d100494ca1be5fec64f1ea20f98d2a213c5c0e464 | arttuka/reagent-material-ui | toolbar.cljs | (ns reagent-mui.material.toolbar
"Imports @mui/material/Toolbar as a Reagent component.
Original documentation is at -ui/api/toolbar/ ."
(:require [reagent.core :as r]
["@mui/material/Toolbar" :as MuiToolbar]))
(def toolbar (r/adapt-react-class (.-default MuiToolbar)))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/core/reagent_mui/material/toolbar.cljs | clojure | (ns reagent-mui.material.toolbar
"Imports @mui/material/Toolbar as a Reagent component.
Original documentation is at -ui/api/toolbar/ ."
(:require [reagent.core :as r]
["@mui/material/Toolbar" :as MuiToolbar]))
(def toolbar (r/adapt-react-class (.-default MuiToolbar)))
|
|
75e82aa07c583e57bc04eee3ea9243b1764dc0791eb7eddb5cfde383c0a18974 | ralph-schleicher/rs-colors | rs-colors.lisp | ;;; rs-colors.lisp --- a color data type for Common Lisp.
Copyright ( C ) 2014
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; * Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR 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.
;;; Code:
(in-package :common-lisp-user)
(defpackage :rs-colors
(:use :common-lisp
:iterate
:rs-colors-internal)
(:import-from :alexandria
#:clamp)
(:import-from :read-number
#:read-integer
#:read-float)
(:export ;; types
#:color-object
#:colorp
#:color-coordinates
#:white-point
#:copy-color
#:coerce-color
#:rgb-color-object
#:hsv-color-object
#:hsl-color-object
#:cmy-color-object
#:cmyk-color-object
#:generic-color-object
#:normalize-color
#:absolute-color
;; generic-rgb
#:generic-rgb-color
#:make-generic-rgb-color
#:make-generic-rgb-color-from-number
#:generic-hsv-color
#:make-generic-hsv-color
#:generic-hsl-color
#:make-generic-hsl-color
#:generic-rgb-color-coordinates
#:generic-hsv-color-coordinates
#:generic-hsl-color-coordinates
;; generic-cmy
#:generic-cmy-color
#:make-generic-cmy-color
#:make-generic-cmy-color-from-number
#:generic-cmy-color-coordinates
;; generic-cmyk
#:generic-cmyk-color
#:make-generic-cmyk-color
#:make-generic-cmyk-color-from-number
#:generic-cmyk-color-coordinates
;; ciergb
#:ciergb-color
#:make-ciergb-color
#:ciergb-color-coordinates
;; ciexyz
#:ciexyz-color
#:make-ciexyz-color
#:ciexyz-color-coordinates
;; ciexyy
#:ciexyy-color
#:make-ciexyy-color
#:ciexyy-color-coordinates
;; cieluv
#:*cieluv-default-white-point*
#:cieluv-color
#:make-cieluv-color
#:cieluv-color-coordinates
;; cielab
#:*cielab-default-white-point*
#:cielab-color
#:make-cielab-color
#:cielab-color-coordinates
;; cielch
#:*cielch-default-white-point*
#:cielch-color
#:make-cielch-color
#:cielch-color-coordinates
;; srgb
#:srgb-color
#:make-srgb-color
#:make-srgb-color-from-number
#:srgb-white-point
#:srgb-color-coordinates
;; adobe-rgb
#:adobe-rgb-color
#:make-adobe-rgb-color
#:make-adobe-rgb-color-from-number
#:adobe-rgb-white-point
#:adobe-rgb-color-coordinates
;; wide-gamut-rgb
#:wide-gamut-rgb-color
#:make-wide-gamut-rgb-color
#:make-wide-gamut-rgb-color-from-number
#:wide-gamut-rgb-white-point
#:wide-gamut-rgb-color-coordinates
;; cie-white-points
#:cie-1931-white-point-a
#:cie-1931-white-point-b
#:cie-1931-white-point-c
#:cie-1931-white-point-d50
#:cie-1931-white-point-d55
#:cie-1931-white-point-d65
#:cie-1931-white-point-d75
#:cie-1931-white-point-e
#:cie-1931-white-point-f1
#:cie-1931-white-point-f2
#:cie-1931-white-point-f3
#:cie-1931-white-point-f4
#:cie-1931-white-point-f5
#:cie-1931-white-point-f6
#:cie-1931-white-point-f7
#:cie-1931-white-point-f8
#:cie-1931-white-point-f9
#:cie-1931-white-point-f10
#:cie-1931-white-point-f11
#:cie-1931-white-point-f12
#:cie-1964-white-point-a
#:cie-1964-white-point-b
#:cie-1964-white-point-c
#:cie-1964-white-point-d50
#:cie-1964-white-point-d55
#:cie-1964-white-point-d65
#:cie-1964-white-point-d75
#:cie-1964-white-point-e
#:cie-1964-white-point-f1
#:cie-1964-white-point-f2
#:cie-1964-white-point-f3
#:cie-1964-white-point-f4
#:cie-1964-white-point-f5
#:cie-1964-white-point-f6
#:cie-1964-white-point-f7
#:cie-1964-white-point-f8
#:cie-1964-white-point-f9
#:cie-1964-white-point-f10
#:cie-1964-white-point-f11
#:cie-1964-white-point-f12
;; io
#:define-color-printer
#:define-color-reader
#:print-color-xcms-ciergb
#:color-formatter-xcms-ciergb
#:read-color-xcms-ciergb
#:print-color-xcms-ciexyz
#:color-formatter-xcms-ciexyz
#:read-color-xcms-ciexyz
#:print-color-xcms-ciexyy
#:color-formatter-xcms-ciexyy
#:read-color-xcms-ciexyy
#:print-color-xcms-cieluv
#:color-formatter-xcms-cieluv
#:read-color-xcms-cieluv
#:print-color-xcms-cielab
#:color-formatter-xcms-cielab
#:read-color-xcms-cielab
#:print-color-xcms-cielch
#:color-formatter-xcms-cielch
#:read-color-xcms-cielch
#:print-color-xcms-rgbi
#:color-formatter-xcms-rgbi
#:read-color-xcms-rgbi
#:print-color-xcms-rgb
#:color-formatter-xcms-rgb
#:read-color-xcms-rgb
#:read-color-xcms
#:print-color-html
#:color-formatter-html
#:read-color-html
#:print-color-css3-rgb
#:color-formatter-css3-rgb
#:read-color-css3-rgb
#:print-color-css3-hsl
#:color-formatter-css3-hsl
#:read-color-css3-hsl
#:read-color-css3
;; color-matching-functions
#:cie-1931-standard-observer
#:cie-1964-standard-observer
#:*color-matching-functions*
#:color-matching-functions
#:cie-1931-second-radiation-constant
#:*second-radiation-constant*
#:cie-xy-chromaticity-of-light
#:cie-xy-chromaticity-of-black-body
;; black-body
#:codata-2018-first-radiation-constant-for-spectral-radiance
#:codata-2018-first-radiation-constant
#:codata-2018-second-radiation-constant
#:black-body-spectral-radiant-exitance
#:black-body-spectral-radiance
;; color-difference
#:cie76
#:cie94)
(:documentation "A color data type for Common Lisp."))
;;; rs-colors.lisp ends here
| null | https://raw.githubusercontent.com/ralph-schleicher/rs-colors/0604867895fab0ea9b8a6bb0ac4a08d452c53c59/rs-colors.lisp | lisp | rs-colors.lisp --- a color data type for Common Lisp.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
OR BUSINESS INTERRUPTION ) HOWEVER
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.
Code:
types
generic-rgb
generic-cmy
generic-cmyk
ciergb
ciexyz
ciexyy
cieluv
cielab
cielch
srgb
adobe-rgb
wide-gamut-rgb
cie-white-points
io
color-matching-functions
black-body
color-difference
rs-colors.lisp ends here |
Copyright ( C ) 2014
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(in-package :common-lisp-user)
(defpackage :rs-colors
(:use :common-lisp
:iterate
:rs-colors-internal)
(:import-from :alexandria
#:clamp)
(:import-from :read-number
#:read-integer
#:read-float)
#:color-object
#:colorp
#:color-coordinates
#:white-point
#:copy-color
#:coerce-color
#:rgb-color-object
#:hsv-color-object
#:hsl-color-object
#:cmy-color-object
#:cmyk-color-object
#:generic-color-object
#:normalize-color
#:absolute-color
#:generic-rgb-color
#:make-generic-rgb-color
#:make-generic-rgb-color-from-number
#:generic-hsv-color
#:make-generic-hsv-color
#:generic-hsl-color
#:make-generic-hsl-color
#:generic-rgb-color-coordinates
#:generic-hsv-color-coordinates
#:generic-hsl-color-coordinates
#:generic-cmy-color
#:make-generic-cmy-color
#:make-generic-cmy-color-from-number
#:generic-cmy-color-coordinates
#:generic-cmyk-color
#:make-generic-cmyk-color
#:make-generic-cmyk-color-from-number
#:generic-cmyk-color-coordinates
#:ciergb-color
#:make-ciergb-color
#:ciergb-color-coordinates
#:ciexyz-color
#:make-ciexyz-color
#:ciexyz-color-coordinates
#:ciexyy-color
#:make-ciexyy-color
#:ciexyy-color-coordinates
#:*cieluv-default-white-point*
#:cieluv-color
#:make-cieluv-color
#:cieluv-color-coordinates
#:*cielab-default-white-point*
#:cielab-color
#:make-cielab-color
#:cielab-color-coordinates
#:*cielch-default-white-point*
#:cielch-color
#:make-cielch-color
#:cielch-color-coordinates
#:srgb-color
#:make-srgb-color
#:make-srgb-color-from-number
#:srgb-white-point
#:srgb-color-coordinates
#:adobe-rgb-color
#:make-adobe-rgb-color
#:make-adobe-rgb-color-from-number
#:adobe-rgb-white-point
#:adobe-rgb-color-coordinates
#:wide-gamut-rgb-color
#:make-wide-gamut-rgb-color
#:make-wide-gamut-rgb-color-from-number
#:wide-gamut-rgb-white-point
#:wide-gamut-rgb-color-coordinates
#:cie-1931-white-point-a
#:cie-1931-white-point-b
#:cie-1931-white-point-c
#:cie-1931-white-point-d50
#:cie-1931-white-point-d55
#:cie-1931-white-point-d65
#:cie-1931-white-point-d75
#:cie-1931-white-point-e
#:cie-1931-white-point-f1
#:cie-1931-white-point-f2
#:cie-1931-white-point-f3
#:cie-1931-white-point-f4
#:cie-1931-white-point-f5
#:cie-1931-white-point-f6
#:cie-1931-white-point-f7
#:cie-1931-white-point-f8
#:cie-1931-white-point-f9
#:cie-1931-white-point-f10
#:cie-1931-white-point-f11
#:cie-1931-white-point-f12
#:cie-1964-white-point-a
#:cie-1964-white-point-b
#:cie-1964-white-point-c
#:cie-1964-white-point-d50
#:cie-1964-white-point-d55
#:cie-1964-white-point-d65
#:cie-1964-white-point-d75
#:cie-1964-white-point-e
#:cie-1964-white-point-f1
#:cie-1964-white-point-f2
#:cie-1964-white-point-f3
#:cie-1964-white-point-f4
#:cie-1964-white-point-f5
#:cie-1964-white-point-f6
#:cie-1964-white-point-f7
#:cie-1964-white-point-f8
#:cie-1964-white-point-f9
#:cie-1964-white-point-f10
#:cie-1964-white-point-f11
#:cie-1964-white-point-f12
#:define-color-printer
#:define-color-reader
#:print-color-xcms-ciergb
#:color-formatter-xcms-ciergb
#:read-color-xcms-ciergb
#:print-color-xcms-ciexyz
#:color-formatter-xcms-ciexyz
#:read-color-xcms-ciexyz
#:print-color-xcms-ciexyy
#:color-formatter-xcms-ciexyy
#:read-color-xcms-ciexyy
#:print-color-xcms-cieluv
#:color-formatter-xcms-cieluv
#:read-color-xcms-cieluv
#:print-color-xcms-cielab
#:color-formatter-xcms-cielab
#:read-color-xcms-cielab
#:print-color-xcms-cielch
#:color-formatter-xcms-cielch
#:read-color-xcms-cielch
#:print-color-xcms-rgbi
#:color-formatter-xcms-rgbi
#:read-color-xcms-rgbi
#:print-color-xcms-rgb
#:color-formatter-xcms-rgb
#:read-color-xcms-rgb
#:read-color-xcms
#:print-color-html
#:color-formatter-html
#:read-color-html
#:print-color-css3-rgb
#:color-formatter-css3-rgb
#:read-color-css3-rgb
#:print-color-css3-hsl
#:color-formatter-css3-hsl
#:read-color-css3-hsl
#:read-color-css3
#:cie-1931-standard-observer
#:cie-1964-standard-observer
#:*color-matching-functions*
#:color-matching-functions
#:cie-1931-second-radiation-constant
#:*second-radiation-constant*
#:cie-xy-chromaticity-of-light
#:cie-xy-chromaticity-of-black-body
#:codata-2018-first-radiation-constant-for-spectral-radiance
#:codata-2018-first-radiation-constant
#:codata-2018-second-radiation-constant
#:black-body-spectral-radiant-exitance
#:black-body-spectral-radiance
#:cie76
#:cie94)
(:documentation "A color data type for Common Lisp."))
|
dd57e157786937f6ad2202d54f6148d3b50a3f37ca2d24b0d621bbc0371f0abb | kdltr/chicken-core | batch-driver.scm | ;;;; batch-driver.scm - Driver procedure for the compiler
;
Copyright ( c ) 2008 - 2021 , The CHICKEN Team
Copyright ( c ) 2000 - 2007 ,
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
; conditions are met:
;
; Redistributions of source code must retain the above copyright notice, this list of conditions and the following
; disclaimer.
; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
; disclaimer in the documentation and/or other materials provided with the distribution.
; Neither the name of the author nor the names of its contributors may be used to endorse or promote
; products derived from this software without specific prior written permission.
;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS
; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(declare
(unit batch-driver)
(uses extras data-structures pathname
support compiler-syntax compiler optimizer internal
;; TODO: Backend should be configurable
scrutinizer lfa2 c-platform c-backend user-pass))
(module chicken.compiler.batch-driver
(compile-source-file)
(import scheme
chicken.base
chicken.fixnum
chicken.format
chicken.gc
chicken.internal
chicken.load
chicken.pathname
chicken.platform
chicken.pretty-print
chicken.process-context
chicken.string
chicken.time
chicken.compiler.support
chicken.compiler.compiler-syntax
chicken.compiler.core
chicken.compiler.optimizer
chicken.compiler.scrutinizer
chicken.compiler.lfa2
chicken.compiler.c-platform
chicken.compiler.c-backend
chicken.compiler.user-pass)
(include "tweaks")
(include "mini-srfi-1.scm")
(define-constant funny-message-timeout 60000)
;;; Emit collected information from various statistics about the program
(define (print-program-statistics db)
(receive
(size osize kvars kprocs globs sites entries) (compute-database-statistics db)
(when (debugging 's "program statistics:")
(printf "; program size: \t~s \toriginal program size: \t~s\n" size osize)
(printf "; variables with known values: \t~s\n" kvars)
(printf "; known procedures: \t~s\n" kprocs)
(printf "; global variables: \t~s\n" globs)
(printf "; known call sites: \t~s\n" sites)
(printf "; database entries: \t~s\n" entries) ) ) )
Initialize analysis database :
;;
;; - Simply marks the symbols directly in the plist.
- Does nothing after the first invocation , but we leave it this way to
;; have the option to add default entries for each new db.
(define initialize-analysis-database
(let ((initial #t))
(lambda ()
(when initial
(for-each
(lambda (s)
(mark-variable s '##compiler#intrinsic 'standard))
standard-bindings)
(for-each
(lambda (s)
(mark-variable s '##compiler#intrinsic 'extended))
extended-bindings)
(for-each
(lambda (s)
(mark-variable s '##compiler#intrinsic 'internal))
internal-bindings))
(set! initial #f))))
;;; Display analysis database:
(define display-analysis-database
(let ((names '((captured . cpt) (assigned . set) (boxed . box) (global . glo)
(assigned-locally . stl)
(contractable . con) (standard-binding . stb) (simple . sim)
(inlinable . inl)
(collapsable . col) (removable . rem) (constant . con)
(inline-target . ilt) (inline-transient . itr)
(undefined . und) (replacing . rpg) (unused . uud) (extended-binding . xtb)
(inline-export . ilx) (hidden-refs . hrf)
(value-ref . vvf)
(customizable . cst) (has-unused-parameters . hup) (boxed-rest . bxr) ) )
(omit #f))
(lambda (db)
(unless omit
(set! omit
(append default-standard-bindings
default-extended-bindings
internal-bindings) ) )
(hash-table-for-each
(lambda (sym plist)
(let ((val #f)
(lval #f)
(pvals #f)
(csites '())
(refs '())
(derived-rvars '()))
(unless (memq sym omit)
(write sym)
(let loop ((es plist))
(if (pair? es)
(begin
(case (caar es)
((captured assigned boxed global contractable standard-binding assigned-locally
collapsable removable undefined replacing unused simple inlinable inline-export
has-unused-parameters extended-binding customizable constant boxed-rest hidden-refs)
(printf "\t~a" (cdr (assq (caar es) names))) )
((unknown)
(set! val 'unknown) )
((value)
(unless (eq? val 'unknown) (set! val (cdar es))) )
((local-value)
(unless (eq? val 'unknown) (set! lval (cdar es))) )
((potential-values)
(set! pvals (cdar es)))
((replacable home contains contained-in use-expr closure-size rest-parameter
captured-variables explicit-rest rest-cdr rest-null?)
(printf "\t~a=~s" (caar es) (cdar es)) )
((derived-rest-vars)
(set! derived-rvars (cdar es)))
((references)
(set! refs (cdar es)) )
((call-sites)
(set! csites (cdar es)) )
(else (bomb "Illegal property" (car es))) )
(loop (cdr es)) ) ) )
(when (pair? refs) (printf "\trefs=~s" (length refs)))
(when (pair? derived-rvars) (printf "\tdrvars=~s" (length derived-rvars)))
(when (pair? csites) (printf "\tcss=~s" (length csites)))
(cond [(and val (not (eq? val 'unknown)))
(printf "\tval=~s" (cons (node-class val) (node-parameters val))) ]
[(and lval (not (eq? val 'unknown)))
(printf "\tlval=~s" (cons (node-class lval) (node-parameters lval)))])
(when (pair? pvals)
(for-each
(lambda (pval)
(printf "\tpval=~s" (cons (node-class pval) (node-parameters pval))))
pvals))
(newline) ) ) )
db) ) ) )
;;; Compile a complete source file:
(define (compile-source-file filename user-supplied-options . options)
(define (option-arg p)
(if (null? (cdr p))
(quit-compiling "missing argument to `-~A' option" (car p))
(let ([arg (cadr p)])
(if (symbol? arg)
(quit-compiling "invalid argument to `~A' option" arg)
arg) ) ) )
(initialize-compiler)
(set! explicit-use-flag (memq 'explicit-use options))
(set! emit-debug-info (memq 'debug-info options))
(when (memq 'module-registration options)
(set! compile-module-registration 'yes))
(when (memq 'no-module-registration options)
(set! compile-module-registration 'no))
(when (memq 'static options)
(set! static-extensions #t)
(register-feature! 'chicken-compile-static))
(let* ((dynamic (memq 'dynamic options))
(unit (memq 'unit options))
(init-forms `((##core#declare
,@(append
default-declarations
(if emit-debug-info
'((uses debugger-client))
'())
(if explicit-use-flag
'()
`((uses ,@default-units)))
(if (and static-extensions
(not dynamic)
(not unit)
(not explicit-use-flag)
(or (not compile-module-registration)
(eq? compile-module-registration 'yes)))
'((uses eval-modules))
'())))))
(import-forms `((import-for-syntax ,@default-syntax-imports)
,@(if explicit-use-flag
'()
`((import-syntax ,@default-imports)))))
(cleanup-forms '(((chicken.base#implicit-exit-handler))))
(outfile (cond ((memq 'output-file options)
=> (lambda (node)
(let ((oname (option-arg node)))
(if (symbol? oname)
(symbol->string oname)
oname) ) ) )
((memq 'to-stdout options) #f)
(else (make-pathname #f (if filename (pathname-file filename) "out") "c")) ) )
(ipath (map chop-separator
(##sys#split-path
(or (get-environment-variable "CHICKEN_INCLUDE_PATH") ""))))
(opasses (default-optimization-passes))
(time0 #f)
(time-breakdown #f)
(forms '())
(inline-output-file #f)
(type-output-file #f)
(profile (or (memq 'profile options)
(memq 'accumulate-profile options)
(memq 'profile-name options)))
(profile-name
(and-let* ((pn (memq 'profile-name options))) (cadr pn)))
(hsize (memq 'heap-size options))
(kwstyle (memq 'keyword-style options))
(loop/dispatch (memq 'clustering options))
(a-only (memq 'analyze-only options))
(do-scrutinize #t)
(do-lfa2 (memq 'lfa2 options))
(dumpnodes #f)
(start-time #f)
(upap #f)
(ssize (or (memq 'nursery options) (memq 'stack-size options)))
(module-name
(and-let* ((m (memq 'module options)))
(option-arg m))))
(define (cputime) (current-process-milliseconds))
(define (dribble fstr . args)
(debugging 'p (apply sprintf fstr args)))
(define (print-header mode dbgmode)
(debugging 'p "pass" mode)
(and (memq dbgmode debugging-chicken)
(begin
(printf "[~a]~%" mode)
#t) ) )
(define (print-node mode dbgmode n)
(when (print-header mode dbgmode)
(if dumpnodes
(dump-nodes n)
(pretty-print (build-expression-tree n)) ) ) )
(define (print-db mode dbgmode db pass)
(when (print-header mode dbgmode)
(printf "(iteration ~s)~%" pass)
(display-analysis-database db) ) )
(define (print-expr mode dbgmode xs)
(when (print-header mode dbgmode)
(for-each
(lambda (x)
(pretty-print x)
(newline))
xs) ) )
(define (arg-val str)
(let* ((len (string-length str))
(len1 (- len 1)) )
(or (if (< len 2)
(string->number str)
(case (string-ref str len1)
((#\m #\M) (* (string->number (substring str 0 len1)) (* 1024 1024)))
((#\k #\K) (* (string->number (substring str 0 len1)) 1024))
(else (string->number str)) ) )
(quit-compiling "invalid numeric argument ~S" str) ) ) )
(define (collect-options opt)
(let loop ([opts options])
(cond [(memq opt opts) => (lambda (p) (cons (option-arg p) (loop (cddr p))))]
[else '()] ) ) )
(define (begin-time)
(when time-breakdown (set! time0 (cputime))) )
(define (end-time pass)
(when time-breakdown
(printf "milliseconds needed for ~a: \t~s~%"
pass
(inexact->exact (round (- (cputime) time0)) ) )))
(define (analyze pass node . args)
(let-optionals args ((no 0) (contf #t))
(let ((db (analyze-expression node)))
(when upap
(upap pass db node
(cut db-get db <> <>)
(cut db-put! db <> <> <>)
no contf) )
db) ) )
(when unit
(set! unit-name (string->symbol (option-arg unit))))
(when (or unit-name dynamic)
(set! standalone-executable #f))
(when (memq 'ignore-repository options)
(set! ##sys#dload-disabled #t)
(repository-path #f))
(set! enable-specialization (memq 'specialize options))
(set! debugging-chicken
(append-map
(lambda (do)
(map (lambda (c) (string->symbol (string c)))
(string->list do) ) )
(collect-options 'debug) ) )
(when (memq 'h debugging-chicken)
(print-debug-options)
(exit))
(set! dumpnodes (memq '|D| debugging-chicken))
(set! import-libraries
(map (lambda (il)
(cons (string->symbol il)
(string-append il ".import.scm")))
(collect-options 'emit-import-library)))
(when (and (memq 'emit-all-import-libraries options)
(not a-only))
(set! all-import-libraries #t))
(when enable-specialization
(set! do-scrutinize #t))
(when (memq 't debugging-chicken) (##sys#start-timer))
(when (memq 'b debugging-chicken) (set! time-breakdown #t))
(when (memq 'raw options)
(set! explicit-use-flag #t)
(set! init-forms '())
(set! import-forms '())
(set! cleanup-forms '()))
(when (memq 'no-lambda-info options)
(set! emit-closure-info #f) )
(when (memq 'no-compiler-syntax options)
(set! compiler-syntax-enabled #f))
(when (memq 'local options)
(set! local-definitions #t))
(when (memq 'inline-global options)
(set! enable-inline-files #t)
(set! inline-locally #t))
(when (memq 'verbose options)
(set! verbose-mode #t)
(set! ##sys#notices-enabled #t))
(when (memq 'strict-types options)
(set! strict-variable-types #t)
(set! enable-specialization #t))
(when (memq 'no-warnings options)
(dribble "Warnings are disabled")
(set! ##sys#warnings-enabled #f)
(set! do-scrutinize #f)) ; saves some processing time
(when (memq 'optimize-leaf-routines options) (set! optimize-leaf-routines #t))
(when (memq 'unsafe options)
(set! unsafe #t) )
(when (memq 'setup-mode options)
(set! ##sys#setup-mode #t))
(when (memq 'regenerate-import-libraries options)
(set! preserve-unchanged-import-libraries #f))
(when (memq 'disable-interrupts options) (set! insert-timer-checks #f))
(when (memq 'fixnum-arithmetic options) (set! number-type 'fixnum))
(when (memq 'block options) (set! block-compilation #t))
(when (memq 'emit-external-prototypes-first options)
(set! external-protos-first #t))
(when (memq 'inline options) (set! inline-locally #t))
(and-let* ((elf (memq 'emit-link-file options)))
(set! emit-link-file (option-arg elf)))
(and-let* ((ifile (memq 'emit-inline-file options)))
(set! inline-locally #t) ; otherwise this option makes no sense
(set! local-definitions #t)
(set! inline-output-file (option-arg ifile)))
(and-let* ((tfile (memq 'emit-types-file options)))
(set! type-output-file (option-arg tfile)))
(and-let* ([inlimit (memq 'inline-limit options)])
(set! inline-max-size
(let ([arg (option-arg inlimit)])
(or (string->number arg)
(quit-compiling
"invalid argument to `-inline-limit' option: `~A'" arg) ) ) ) )
(and-let* ((ulimit (memq 'unroll-limit options)))
(set! unroll-limit
(let ((arg (option-arg ulimit)))
(or (string->number arg)
(quit-compiling
"invalid argument to `-unroll-limit' option: `~A'" arg) ) ) ) )
(when (memq 'case-insensitive options)
(dribble "Identifiers and symbols are case insensitive")
(register-feature! 'case-insensitive)
(case-sensitive #f) )
(when kwstyle
(let ([val (option-arg kwstyle)])
(cond [(string=? "prefix" val) (keyword-style #:prefix)]
[(string=? "none" val) (keyword-style #:none)]
[(string=? "suffix" val) (keyword-style #:suffix)]
[else (quit-compiling
"invalid argument to `-keyword-style' option")] ) ) )
(when (memq 'no-parentheses-synonyms options)
(dribble "Disabled support for parentheses synonyms")
(parentheses-synonyms #f) )
(when (memq 'no-symbol-escape options)
(dribble "Disabled support for escaped symbols")
(symbol-escape #f) )
(when (memq 'r5rs-syntax options)
(dribble "Disabled the CHICKEN extensions to R5RS syntax")
(case-sensitive #f)
(keyword-style #:none)
(parentheses-synonyms #f)
(symbol-escape #f) )
(set! ##sys#read-error-with-line-number #t)
(set! ##sys#include-pathnames
(append (map chop-separator (collect-options 'include-path))
##sys#include-pathnames
ipath) )
(when (and outfile filename (string=? outfile filename))
(quit-compiling "source- and output-filename are the same") )
(when (memq 'keep-shadowed-macros options)
(set! undefine-shadowed-macros #f) )
(when (memq 'no-argc-checks options)
(set! no-argc-checks #t) )
(when (memq 'no-bound-checks options)
(set! no-bound-checks #t) )
(when (memq 'no-procedure-checks options)
(set! no-procedure-checks #t) )
(when (memq 'no-procedure-checks-for-toplevel-bindings options)
(set! no-global-procedure-checks #t) )
(when (memq 'no-procedure-checks-for-usual-bindings options)
(for-each
(lambda (v)
(mark-variable v '##compiler#always-bound-to-procedure)
(mark-variable v '##compiler#always-bound) )
default-standard-bindings)
(for-each
(lambda (v)
(mark-variable v '##compiler#always-bound-to-procedure)
(mark-variable v '##compiler#always-bound) )
default-extended-bindings) )
(when (memq 'p debugging-chicken) (load-verbose #t))
;; Handle feature options:
(for-each
register-feature!
(append-map (cut string-split <> ", ") (collect-options 'feature)))
(for-each
unregister-feature!
(append-map (cut string-split <> ",") (collect-options 'no-feature)))
;; Load extensions:
(set! ##sys#features (cons #:compiler-extension ##sys#features))
(let ([extends (collect-options 'extend)])
(dribble "Loading compiler extensions...")
(for-each
(lambda (e)
(let ((f (##sys#resolve-include-filename e #f #t #f)))
(when (not f) (quit-compiling "cannot load extension: ~a" e))
(load f)))
extends) )
(set! ##sys#features (delete #:compiler-extension ##sys#features eq?))
(set! ##sys#features (cons '#:compiling ##sys#features))
(set! upap (user-post-analysis-pass))
;; Handle units added with the "-uses" flag.
(let ((uses (append-map
(lambda (u) (map string->symbol (string-split u ", ")))
(collect-options 'uses))))
(unless (null? uses)
(set! init-forms
(append init-forms `((##core#declare (uses . ,uses)))))))
;; Mark linked libraries so they will be compiled as unit dependencies.
(let ((link (append-map
(lambda (l) (map string->symbol (string-split l ", ")))
(collect-options 'link))))
(set! linked-libraries (lset-union/eq? linked-libraries link)))
;; Append required extensions to imports:
(set! import-forms
(append
import-forms
(map (lambda (r) `(import ,(string->symbol r)))
(collect-options 'require-extension))))
(when (memq 'compile-syntax options)
(set! ##sys#enable-runtime-macros #t) )
(set! target-heap-size
(and hsize
(arg-val (option-arg hsize))))
(set! target-stack-size
(and ssize
(arg-val (option-arg ssize))))
(set! emit-trace-info (not (memq 'no-trace options)))
(set! disable-stack-overflow-checking (memq 'disable-stack-overflow-checks options))
(set! bootstrap-mode (feature? #:chicken-bootstrap))
(when (memq 'm debugging-chicken) (set-gc-report! #t))
(cond ((memq 'no-usual-integrations options)
(set! do-scrutinize #f))
(else
(set! standard-bindings default-standard-bindings)
(set! extended-bindings default-extended-bindings) ))
(dribble "debugging info: ~A"
(if emit-trace-info
"calltrace"
"none") )
(when profile
(let ((acc (eq? 'accumulate-profile (car profile))))
(when (and acc (not profile-name))
(quit-compiling
"you need to specify -profile-name if using accumulated profiling runs"))
(set! emit-profile #t)
(set! profiled-procedures 'all)
(set! init-forms
(append
init-forms
default-profiling-declarations
(if acc
'((set! ##sys#profile-append-mode #t))
'() ) ) )
(dribble "generating ~aprofiled code" (if acc "accumulative " "")) ))
;;XXX hardcoded "modules.db" is bad (also used in chicken-install.scm)
(load-identifier-database "modules.db")
(cond ((memq 'version options)
(print-version #t)
(newline) )
((or (memq 'help options) (memq '-help options) (memq 'h options) (memq '-h options))
(print-usage))
((memq 'release options)
(display (chicken-version))
(newline) )
((not filename)
(print-version #t)
(display "\nEnter `chicken -help' for information on how to use the compiler,\n")
(display "or try `csc' for a more convenient interface.\n")
(display "\nRun `csi' to start the interactive interpreter.\n"))
(else
;; Display header:
(dribble "compiling `~a' ..." filename)
(debugging 'r "options" options)
(debugging 'r "debugging options" debugging-chicken)
(debugging 'r "target heap size" target-heap-size)
(debugging 'r "target stack size" target-stack-size)
(set! start-time (cputime))
;; Read toplevel expressions:
(set! ##sys#line-number-database (make-vector line-number-database-size '()))
(let ([prelude (collect-options 'prelude)]
[postlude (collect-options 'postlude)]
[files (append
(collect-options 'prologue)
(list filename)
(collect-options 'epilogue) ) ] )
(let ([proc (user-read-pass)])
(cond [proc
(dribble "User read pass...")
(set! forms (proc prelude files postlude)) ]
[else
(do ([files files (cdr files)])
((null? files)
(set! forms
(append (map string->expr prelude)
(reverse forms)
(map string->expr postlude) ) ) )
(let* ((f (car files))
(in (check-and-open-input-file f)) )
(fluid-let ((##sys#current-source-filename f))
(let loop ()
(let ((x (read/source-info in)))
(cond ((eof-object? x)
(close-checked-input-file in f) )
(else
(set! forms (cons x forms))
(loop)))))))) ] ) ) )
;; Start compilation passes:
(let ([proc (user-preprocessor-pass)])
(when proc
(dribble "User preprocessing pass...")
(set! forms (map proc forms))))
(print-expr "source" '|1| forms)
(begin-time)
s - expressions
(let* ((init0 (map canonicalize-expression init-forms))
(exps0 (map (lambda (x)
(fluid-let ((##sys#current-source-filename filename))
(canonicalize-expression x)))
(let ((forms (append import-forms forms)))
(if (not module-name)
forms
`((##core#module
,(string->symbol module-name) ()
,@forms))))))
(uses0 (map (lambda (u)
(canonicalize-expression `(##core#require ,u)))
(##sys#fast-reverse used-libraries)))
(exps (append
(map (lambda (ic) `(set! ,(cdr ic) ',(car ic))) immutable-constants)
init0
uses0
(if unit-name `((##core#provide ,unit-name)) '())
(if emit-profile
(profiling-prelude-exps (and (not unit-name)
(or profile-name #t)))
'() )
exps0
(if standalone-executable
cleanup-forms
'((##core#undefined))))))
(unless (null? import-libraries)
(quit-compiling
"No module definition found for import libraries to emit: ~A"
;; ~S would be confusing: separate with a comma
(string-intersperse
(map (lambda (il) (->string (car il)))
import-libraries) ", ")))
(when (pair? compiler-syntax-statistics)
(with-debugging-output
'S
(lambda ()
(print "applied compiler syntax:")
(for-each
(lambda (cs) (printf " ~a\t\t~a~%" (car cs) (cdr cs)))
compiler-syntax-statistics))))
(when (debugging '|N| "real name table:")
(display-real-name-table) )
(when (debugging 'n "line number database:")
(display-line-number-database) )
(set! ##sys#line-number-database line-number-database-2)
(set! line-number-database-2 #f)
(end-time "canonicalization")
(print-expr "canonicalized" '|2| exps)
(when (memq 'check-syntax options) (exit))
;; User-defined pass (s-expressions)
(let ([proc (user-pass)])
(when proc
(dribble "User pass...")
(begin-time)
(set! exps (map proc exps))
(end-time "user pass") ) )
Convert s - expressions to node tree
(let ((node0 (build-toplevel-procedure
(build-node-graph
(canonicalize-begin-body exps))))
(db #f))
(print-node "initial node tree" '|T| node0)
(initialize-analysis-database)
;; collect requirements and load inline files
(let ((extensions (remove chicken.load#core-unit? required-libraries)))
(when enable-inline-files
(for-each
(lambda (id)
(and-let* ((ifile (##sys#resolve-include-filename
(symbol->string id) '(".inline") #t #f)))
(dribble "Loading inline file ~a ..." ifile)
(load-inline-file ifile)))
extensions))
(let ((ifs (collect-options 'consult-inline-file)))
(unless (null? ifs)
(set! inline-locally #t)
(for-each
(lambda (ilf)
(dribble "Loading inline file ~a ..." ilf)
(load-inline-file ilf) )
ifs)))
;; Perform scrutiny and optionally specialization
(when (or do-scrutinize enable-specialization)
;;XXX hardcoded database file name
(unless (memq 'ignore-repository options)
(unless (load-type-database "types.db"
enable-specialization)
(quit-compiling
"default type-database `types.db' not found")))
(for-each
(lambda (fn)
(or (load-type-database fn enable-specialization #f)
(quit-compiling "type-database `~a' not found" fn)))
(collect-options 'consult-types-file))
(for-each
(lambda (id)
(load-type-database
(make-pathname #f (symbol->string id) "types")
enable-specialization))
extensions)
(begin-time)
(set! first-analysis #f)
(set! db (analyze 'scrutiny node0))
(print-db "analysis" '|0| db 0)
(end-time "pre-analysis (scrutiny)")
(begin-time)
(debugging 'p "performing scrutiny")
(scrutinize node0 db
do-scrutinize enable-specialization
strict-variable-types block-compilation)
(end-time "scrutiny")
(when enable-specialization
(print-node "specialization" '|P| node0))
(set! first-analysis #t) ) )
;; TODO: Move this so that we don't need to export these
(set! ##sys#line-number-database #f)
(set! constant-table #f)
(set! inline-table #f)
;; Analyze toplevel assignments
(unless unsafe
(scan-toplevel-assignments (first (node-subexpressions node0))) )
(begin-time)
Convert to CPS
(let ([node1 (perform-cps-conversion node0)])
(end-time "cps conversion")
(print-node "cps" '|3| node1)
;; Optimization loop:
(let loop ((i 1)
(node2 node1)
(progress #t)
(l/d #f)
(l/d-done #f))
(begin-time)
;; Analyze node tree for optimization
(let ([db (analyze 'opt node2 i progress)])
(when first-analysis
(when (memq 'u debugging-chicken)
(dump-undefined-globals db))
(when (memq 'd debugging-chicken)
(dump-defined-globals db))
(when (memq 'v debugging-chicken)
(dump-global-refs db))
;; do this here, because we must make sure we have a db
(when type-output-file
(dribble "generating type file `~a' ..." type-output-file)
(emit-types-file filename type-output-file db block-compilation)))
(set! first-analysis #f)
(end-time "analysis")
(print-db "analysis" '|4| db i)
(when (memq 's debugging-chicken)
(print-program-statistics db))
;; Optimize (once)
(cond (progress
(debugging 'p "optimization pass" i)
(begin-time)
(receive (node2 progress-flag)
(if l/d
(determine-loop-and-dispatch node2 db)
(perform-high-level-optimizations
node2 db block-compilation
inline-locally inline-max-size
unroll-limit
inline-substitutions-enabled))
(end-time "optimization")
(print-node "optimized-iteration" '|5| node2)
(cond (progress-flag
(loop (add1 i) node2 #t #f l/d))
((and (not l/d-done) loop/dispatch)
(debugging 'p "clustering enabled")
(loop (add1 i) node2 #t #t #t))
((not inline-substitutions-enabled)
(debugging 'p "rewritings enabled")
(set! inline-substitutions-enabled #t)
(loop (add1 i) node2 #t #f l/d-done) )
(optimize-leaf-routines
(begin-time)
(let ([db (analyze 'leaf node2)])
(end-time "analysis")
(begin-time)
(let ((progress
(transform-direct-lambdas! node2 db)))
(end-time "leaf routine optimization")
(loop (add1 i)
node2
progress
#f
l/d-done) ) ) )
(else
(loop (add1 i) node2 #f #f l/d-done)) ) ) )
(else
;; Secondary flow-analysis
(when do-lfa2
(begin-time)
(debugging 'p "doing lfa2")
(let ((floatvars (perform-secondary-flow-analysis node2 db)))
(end-time "secondary flow analysis")
(unless (null? floatvars)
(begin-time)
(debugging 'p "doing unboxing")
(set! node2 (perform-unboxing node2 floatvars)))
(end-time "unboxing")))
(print-node "optimized" '|7| node2)
;; inlining into a file with interrupts enabled would
;; change semantics
(when (and inline-output-file insert-timer-checks)
(let ((f inline-output-file))
(dribble "generating global inline file `~a' ..." f)
(emit-global-inline-file
filename f db block-compilation
inline-max-size
(map foreign-stub-id foreign-lambda-stubs)) ) )
(begin-time)
;; Closure conversion
(set! node2 (perform-closure-conversion node2 db))
(end-time "closure conversion")
(print-db "final-analysis" '|8| db i)
(when (and ##sys#warnings-enabled
(> (- (cputime) start-time) funny-message-timeout))
(display "(don't worry - still compiling...)\n") )
(print-node "closure-converted" '|9| node2)
(when a-only (exit 0))
(begin-time)
;; Preparation
(receive (node literals lliterals lambda-table dbg-info)
(prepare-for-code-generation node2 db)
(end-time "preparation")
(begin-time)
;; generate link file
(when emit-link-file
(let ((exts (remove chicken.load#core-unit? required-libraries)))
(dribble "generating link file `~a' ..." emit-link-file)
(with-output-to-file emit-link-file (cut pp exts))))
;; Code generation
(let ((out (if outfile (open-output-file outfile) (current-output-port))) )
(dribble "generating `~A' ..." outfile)
(generate-code literals lliterals lambda-table out filename
user-supplied-options dynamic db dbg-info)
(when outfile
(close-output-port out)))
(end-time "code generation")
(when (memq 't debugging-chicken)
(##sys#display-times (##sys#stop-timer)))
(compiler-cleanup-hook)
(dribble "compilation finished.") ) ) ) ) ) ) ) ) ) ) ) )
)
| null | https://raw.githubusercontent.com/kdltr/chicken-core/b2e6c5243dd469064bec947cb3b49dafaa1514e5/batch-driver.scm | scheme | batch-driver.scm - Driver procedure for the compiler
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
TODO: Backend should be configurable
Emit collected information from various statistics about the program
- Simply marks the symbols directly in the plist.
have the option to add default entries for each new db.
Display analysis database:
Compile a complete source file:
saves some processing time
otherwise this option makes no sense
Handle feature options:
Load extensions:
Handle units added with the "-uses" flag.
Mark linked libraries so they will be compiled as unit dependencies.
Append required extensions to imports:
XXX hardcoded "modules.db" is bad (also used in chicken-install.scm)
Display header:
Read toplevel expressions:
Start compilation passes:
~S would be confusing: separate with a comma
User-defined pass (s-expressions)
collect requirements and load inline files
Perform scrutiny and optionally specialization
XXX hardcoded database file name
TODO: Move this so that we don't need to export these
Analyze toplevel assignments
Optimization loop:
Analyze node tree for optimization
do this here, because we must make sure we have a db
Optimize (once)
Secondary flow-analysis
inlining into a file with interrupts enabled would
change semantics
Closure conversion
Preparation
generate link file
Code generation | Copyright ( c ) 2008 - 2021 , The CHICKEN Team
Copyright ( c ) 2000 - 2007 ,
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS
CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
(declare
(unit batch-driver)
(uses extras data-structures pathname
support compiler-syntax compiler optimizer internal
scrutinizer lfa2 c-platform c-backend user-pass))
(module chicken.compiler.batch-driver
(compile-source-file)
(import scheme
chicken.base
chicken.fixnum
chicken.format
chicken.gc
chicken.internal
chicken.load
chicken.pathname
chicken.platform
chicken.pretty-print
chicken.process-context
chicken.string
chicken.time
chicken.compiler.support
chicken.compiler.compiler-syntax
chicken.compiler.core
chicken.compiler.optimizer
chicken.compiler.scrutinizer
chicken.compiler.lfa2
chicken.compiler.c-platform
chicken.compiler.c-backend
chicken.compiler.user-pass)
(include "tweaks")
(include "mini-srfi-1.scm")
(define-constant funny-message-timeout 60000)
(define (print-program-statistics db)
(receive
(size osize kvars kprocs globs sites entries) (compute-database-statistics db)
(when (debugging 's "program statistics:")
(printf "; program size: \t~s \toriginal program size: \t~s\n" size osize)
(printf "; variables with known values: \t~s\n" kvars)
(printf "; known procedures: \t~s\n" kprocs)
(printf "; global variables: \t~s\n" globs)
(printf "; known call sites: \t~s\n" sites)
(printf "; database entries: \t~s\n" entries) ) ) )
Initialize analysis database :
- Does nothing after the first invocation , but we leave it this way to
(define initialize-analysis-database
(let ((initial #t))
(lambda ()
(when initial
(for-each
(lambda (s)
(mark-variable s '##compiler#intrinsic 'standard))
standard-bindings)
(for-each
(lambda (s)
(mark-variable s '##compiler#intrinsic 'extended))
extended-bindings)
(for-each
(lambda (s)
(mark-variable s '##compiler#intrinsic 'internal))
internal-bindings))
(set! initial #f))))
(define display-analysis-database
(let ((names '((captured . cpt) (assigned . set) (boxed . box) (global . glo)
(assigned-locally . stl)
(contractable . con) (standard-binding . stb) (simple . sim)
(inlinable . inl)
(collapsable . col) (removable . rem) (constant . con)
(inline-target . ilt) (inline-transient . itr)
(undefined . und) (replacing . rpg) (unused . uud) (extended-binding . xtb)
(inline-export . ilx) (hidden-refs . hrf)
(value-ref . vvf)
(customizable . cst) (has-unused-parameters . hup) (boxed-rest . bxr) ) )
(omit #f))
(lambda (db)
(unless omit
(set! omit
(append default-standard-bindings
default-extended-bindings
internal-bindings) ) )
(hash-table-for-each
(lambda (sym plist)
(let ((val #f)
(lval #f)
(pvals #f)
(csites '())
(refs '())
(derived-rvars '()))
(unless (memq sym omit)
(write sym)
(let loop ((es plist))
(if (pair? es)
(begin
(case (caar es)
((captured assigned boxed global contractable standard-binding assigned-locally
collapsable removable undefined replacing unused simple inlinable inline-export
has-unused-parameters extended-binding customizable constant boxed-rest hidden-refs)
(printf "\t~a" (cdr (assq (caar es) names))) )
((unknown)
(set! val 'unknown) )
((value)
(unless (eq? val 'unknown) (set! val (cdar es))) )
((local-value)
(unless (eq? val 'unknown) (set! lval (cdar es))) )
((potential-values)
(set! pvals (cdar es)))
((replacable home contains contained-in use-expr closure-size rest-parameter
captured-variables explicit-rest rest-cdr rest-null?)
(printf "\t~a=~s" (caar es) (cdar es)) )
((derived-rest-vars)
(set! derived-rvars (cdar es)))
((references)
(set! refs (cdar es)) )
((call-sites)
(set! csites (cdar es)) )
(else (bomb "Illegal property" (car es))) )
(loop (cdr es)) ) ) )
(when (pair? refs) (printf "\trefs=~s" (length refs)))
(when (pair? derived-rvars) (printf "\tdrvars=~s" (length derived-rvars)))
(when (pair? csites) (printf "\tcss=~s" (length csites)))
(cond [(and val (not (eq? val 'unknown)))
(printf "\tval=~s" (cons (node-class val) (node-parameters val))) ]
[(and lval (not (eq? val 'unknown)))
(printf "\tlval=~s" (cons (node-class lval) (node-parameters lval)))])
(when (pair? pvals)
(for-each
(lambda (pval)
(printf "\tpval=~s" (cons (node-class pval) (node-parameters pval))))
pvals))
(newline) ) ) )
db) ) ) )
(define (compile-source-file filename user-supplied-options . options)
(define (option-arg p)
(if (null? (cdr p))
(quit-compiling "missing argument to `-~A' option" (car p))
(let ([arg (cadr p)])
(if (symbol? arg)
(quit-compiling "invalid argument to `~A' option" arg)
arg) ) ) )
(initialize-compiler)
(set! explicit-use-flag (memq 'explicit-use options))
(set! emit-debug-info (memq 'debug-info options))
(when (memq 'module-registration options)
(set! compile-module-registration 'yes))
(when (memq 'no-module-registration options)
(set! compile-module-registration 'no))
(when (memq 'static options)
(set! static-extensions #t)
(register-feature! 'chicken-compile-static))
(let* ((dynamic (memq 'dynamic options))
(unit (memq 'unit options))
(init-forms `((##core#declare
,@(append
default-declarations
(if emit-debug-info
'((uses debugger-client))
'())
(if explicit-use-flag
'()
`((uses ,@default-units)))
(if (and static-extensions
(not dynamic)
(not unit)
(not explicit-use-flag)
(or (not compile-module-registration)
(eq? compile-module-registration 'yes)))
'((uses eval-modules))
'())))))
(import-forms `((import-for-syntax ,@default-syntax-imports)
,@(if explicit-use-flag
'()
`((import-syntax ,@default-imports)))))
(cleanup-forms '(((chicken.base#implicit-exit-handler))))
(outfile (cond ((memq 'output-file options)
=> (lambda (node)
(let ((oname (option-arg node)))
(if (symbol? oname)
(symbol->string oname)
oname) ) ) )
((memq 'to-stdout options) #f)
(else (make-pathname #f (if filename (pathname-file filename) "out") "c")) ) )
(ipath (map chop-separator
(##sys#split-path
(or (get-environment-variable "CHICKEN_INCLUDE_PATH") ""))))
(opasses (default-optimization-passes))
(time0 #f)
(time-breakdown #f)
(forms '())
(inline-output-file #f)
(type-output-file #f)
(profile (or (memq 'profile options)
(memq 'accumulate-profile options)
(memq 'profile-name options)))
(profile-name
(and-let* ((pn (memq 'profile-name options))) (cadr pn)))
(hsize (memq 'heap-size options))
(kwstyle (memq 'keyword-style options))
(loop/dispatch (memq 'clustering options))
(a-only (memq 'analyze-only options))
(do-scrutinize #t)
(do-lfa2 (memq 'lfa2 options))
(dumpnodes #f)
(start-time #f)
(upap #f)
(ssize (or (memq 'nursery options) (memq 'stack-size options)))
(module-name
(and-let* ((m (memq 'module options)))
(option-arg m))))
(define (cputime) (current-process-milliseconds))
(define (dribble fstr . args)
(debugging 'p (apply sprintf fstr args)))
(define (print-header mode dbgmode)
(debugging 'p "pass" mode)
(and (memq dbgmode debugging-chicken)
(begin
(printf "[~a]~%" mode)
#t) ) )
(define (print-node mode dbgmode n)
(when (print-header mode dbgmode)
(if dumpnodes
(dump-nodes n)
(pretty-print (build-expression-tree n)) ) ) )
(define (print-db mode dbgmode db pass)
(when (print-header mode dbgmode)
(printf "(iteration ~s)~%" pass)
(display-analysis-database db) ) )
(define (print-expr mode dbgmode xs)
(when (print-header mode dbgmode)
(for-each
(lambda (x)
(pretty-print x)
(newline))
xs) ) )
(define (arg-val str)
(let* ((len (string-length str))
(len1 (- len 1)) )
(or (if (< len 2)
(string->number str)
(case (string-ref str len1)
((#\m #\M) (* (string->number (substring str 0 len1)) (* 1024 1024)))
((#\k #\K) (* (string->number (substring str 0 len1)) 1024))
(else (string->number str)) ) )
(quit-compiling "invalid numeric argument ~S" str) ) ) )
(define (collect-options opt)
(let loop ([opts options])
(cond [(memq opt opts) => (lambda (p) (cons (option-arg p) (loop (cddr p))))]
[else '()] ) ) )
(define (begin-time)
(when time-breakdown (set! time0 (cputime))) )
(define (end-time pass)
(when time-breakdown
(printf "milliseconds needed for ~a: \t~s~%"
pass
(inexact->exact (round (- (cputime) time0)) ) )))
(define (analyze pass node . args)
(let-optionals args ((no 0) (contf #t))
(let ((db (analyze-expression node)))
(when upap
(upap pass db node
(cut db-get db <> <>)
(cut db-put! db <> <> <>)
no contf) )
db) ) )
(when unit
(set! unit-name (string->symbol (option-arg unit))))
(when (or unit-name dynamic)
(set! standalone-executable #f))
(when (memq 'ignore-repository options)
(set! ##sys#dload-disabled #t)
(repository-path #f))
(set! enable-specialization (memq 'specialize options))
(set! debugging-chicken
(append-map
(lambda (do)
(map (lambda (c) (string->symbol (string c)))
(string->list do) ) )
(collect-options 'debug) ) )
(when (memq 'h debugging-chicken)
(print-debug-options)
(exit))
(set! dumpnodes (memq '|D| debugging-chicken))
(set! import-libraries
(map (lambda (il)
(cons (string->symbol il)
(string-append il ".import.scm")))
(collect-options 'emit-import-library)))
(when (and (memq 'emit-all-import-libraries options)
(not a-only))
(set! all-import-libraries #t))
(when enable-specialization
(set! do-scrutinize #t))
(when (memq 't debugging-chicken) (##sys#start-timer))
(when (memq 'b debugging-chicken) (set! time-breakdown #t))
(when (memq 'raw options)
(set! explicit-use-flag #t)
(set! init-forms '())
(set! import-forms '())
(set! cleanup-forms '()))
(when (memq 'no-lambda-info options)
(set! emit-closure-info #f) )
(when (memq 'no-compiler-syntax options)
(set! compiler-syntax-enabled #f))
(when (memq 'local options)
(set! local-definitions #t))
(when (memq 'inline-global options)
(set! enable-inline-files #t)
(set! inline-locally #t))
(when (memq 'verbose options)
(set! verbose-mode #t)
(set! ##sys#notices-enabled #t))
(when (memq 'strict-types options)
(set! strict-variable-types #t)
(set! enable-specialization #t))
(when (memq 'no-warnings options)
(dribble "Warnings are disabled")
(set! ##sys#warnings-enabled #f)
(when (memq 'optimize-leaf-routines options) (set! optimize-leaf-routines #t))
(when (memq 'unsafe options)
(set! unsafe #t) )
(when (memq 'setup-mode options)
(set! ##sys#setup-mode #t))
(when (memq 'regenerate-import-libraries options)
(set! preserve-unchanged-import-libraries #f))
(when (memq 'disable-interrupts options) (set! insert-timer-checks #f))
(when (memq 'fixnum-arithmetic options) (set! number-type 'fixnum))
(when (memq 'block options) (set! block-compilation #t))
(when (memq 'emit-external-prototypes-first options)
(set! external-protos-first #t))
(when (memq 'inline options) (set! inline-locally #t))
(and-let* ((elf (memq 'emit-link-file options)))
(set! emit-link-file (option-arg elf)))
(and-let* ((ifile (memq 'emit-inline-file options)))
(set! local-definitions #t)
(set! inline-output-file (option-arg ifile)))
(and-let* ((tfile (memq 'emit-types-file options)))
(set! type-output-file (option-arg tfile)))
(and-let* ([inlimit (memq 'inline-limit options)])
(set! inline-max-size
(let ([arg (option-arg inlimit)])
(or (string->number arg)
(quit-compiling
"invalid argument to `-inline-limit' option: `~A'" arg) ) ) ) )
(and-let* ((ulimit (memq 'unroll-limit options)))
(set! unroll-limit
(let ((arg (option-arg ulimit)))
(or (string->number arg)
(quit-compiling
"invalid argument to `-unroll-limit' option: `~A'" arg) ) ) ) )
(when (memq 'case-insensitive options)
(dribble "Identifiers and symbols are case insensitive")
(register-feature! 'case-insensitive)
(case-sensitive #f) )
(when kwstyle
(let ([val (option-arg kwstyle)])
(cond [(string=? "prefix" val) (keyword-style #:prefix)]
[(string=? "none" val) (keyword-style #:none)]
[(string=? "suffix" val) (keyword-style #:suffix)]
[else (quit-compiling
"invalid argument to `-keyword-style' option")] ) ) )
(when (memq 'no-parentheses-synonyms options)
(dribble "Disabled support for parentheses synonyms")
(parentheses-synonyms #f) )
(when (memq 'no-symbol-escape options)
(dribble "Disabled support for escaped symbols")
(symbol-escape #f) )
(when (memq 'r5rs-syntax options)
(dribble "Disabled the CHICKEN extensions to R5RS syntax")
(case-sensitive #f)
(keyword-style #:none)
(parentheses-synonyms #f)
(symbol-escape #f) )
(set! ##sys#read-error-with-line-number #t)
(set! ##sys#include-pathnames
(append (map chop-separator (collect-options 'include-path))
##sys#include-pathnames
ipath) )
(when (and outfile filename (string=? outfile filename))
(quit-compiling "source- and output-filename are the same") )
(when (memq 'keep-shadowed-macros options)
(set! undefine-shadowed-macros #f) )
(when (memq 'no-argc-checks options)
(set! no-argc-checks #t) )
(when (memq 'no-bound-checks options)
(set! no-bound-checks #t) )
(when (memq 'no-procedure-checks options)
(set! no-procedure-checks #t) )
(when (memq 'no-procedure-checks-for-toplevel-bindings options)
(set! no-global-procedure-checks #t) )
(when (memq 'no-procedure-checks-for-usual-bindings options)
(for-each
(lambda (v)
(mark-variable v '##compiler#always-bound-to-procedure)
(mark-variable v '##compiler#always-bound) )
default-standard-bindings)
(for-each
(lambda (v)
(mark-variable v '##compiler#always-bound-to-procedure)
(mark-variable v '##compiler#always-bound) )
default-extended-bindings) )
(when (memq 'p debugging-chicken) (load-verbose #t))
(for-each
register-feature!
(append-map (cut string-split <> ", ") (collect-options 'feature)))
(for-each
unregister-feature!
(append-map (cut string-split <> ",") (collect-options 'no-feature)))
(set! ##sys#features (cons #:compiler-extension ##sys#features))
(let ([extends (collect-options 'extend)])
(dribble "Loading compiler extensions...")
(for-each
(lambda (e)
(let ((f (##sys#resolve-include-filename e #f #t #f)))
(when (not f) (quit-compiling "cannot load extension: ~a" e))
(load f)))
extends) )
(set! ##sys#features (delete #:compiler-extension ##sys#features eq?))
(set! ##sys#features (cons '#:compiling ##sys#features))
(set! upap (user-post-analysis-pass))
(let ((uses (append-map
(lambda (u) (map string->symbol (string-split u ", ")))
(collect-options 'uses))))
(unless (null? uses)
(set! init-forms
(append init-forms `((##core#declare (uses . ,uses)))))))
(let ((link (append-map
(lambda (l) (map string->symbol (string-split l ", ")))
(collect-options 'link))))
(set! linked-libraries (lset-union/eq? linked-libraries link)))
(set! import-forms
(append
import-forms
(map (lambda (r) `(import ,(string->symbol r)))
(collect-options 'require-extension))))
(when (memq 'compile-syntax options)
(set! ##sys#enable-runtime-macros #t) )
(set! target-heap-size
(and hsize
(arg-val (option-arg hsize))))
(set! target-stack-size
(and ssize
(arg-val (option-arg ssize))))
(set! emit-trace-info (not (memq 'no-trace options)))
(set! disable-stack-overflow-checking (memq 'disable-stack-overflow-checks options))
(set! bootstrap-mode (feature? #:chicken-bootstrap))
(when (memq 'm debugging-chicken) (set-gc-report! #t))
(cond ((memq 'no-usual-integrations options)
(set! do-scrutinize #f))
(else
(set! standard-bindings default-standard-bindings)
(set! extended-bindings default-extended-bindings) ))
(dribble "debugging info: ~A"
(if emit-trace-info
"calltrace"
"none") )
(when profile
(let ((acc (eq? 'accumulate-profile (car profile))))
(when (and acc (not profile-name))
(quit-compiling
"you need to specify -profile-name if using accumulated profiling runs"))
(set! emit-profile #t)
(set! profiled-procedures 'all)
(set! init-forms
(append
init-forms
default-profiling-declarations
(if acc
'((set! ##sys#profile-append-mode #t))
'() ) ) )
(dribble "generating ~aprofiled code" (if acc "accumulative " "")) ))
(load-identifier-database "modules.db")
(cond ((memq 'version options)
(print-version #t)
(newline) )
((or (memq 'help options) (memq '-help options) (memq 'h options) (memq '-h options))
(print-usage))
((memq 'release options)
(display (chicken-version))
(newline) )
((not filename)
(print-version #t)
(display "\nEnter `chicken -help' for information on how to use the compiler,\n")
(display "or try `csc' for a more convenient interface.\n")
(display "\nRun `csi' to start the interactive interpreter.\n"))
(else
(dribble "compiling `~a' ..." filename)
(debugging 'r "options" options)
(debugging 'r "debugging options" debugging-chicken)
(debugging 'r "target heap size" target-heap-size)
(debugging 'r "target stack size" target-stack-size)
(set! start-time (cputime))
(set! ##sys#line-number-database (make-vector line-number-database-size '()))
(let ([prelude (collect-options 'prelude)]
[postlude (collect-options 'postlude)]
[files (append
(collect-options 'prologue)
(list filename)
(collect-options 'epilogue) ) ] )
(let ([proc (user-read-pass)])
(cond [proc
(dribble "User read pass...")
(set! forms (proc prelude files postlude)) ]
[else
(do ([files files (cdr files)])
((null? files)
(set! forms
(append (map string->expr prelude)
(reverse forms)
(map string->expr postlude) ) ) )
(let* ((f (car files))
(in (check-and-open-input-file f)) )
(fluid-let ((##sys#current-source-filename f))
(let loop ()
(let ((x (read/source-info in)))
(cond ((eof-object? x)
(close-checked-input-file in f) )
(else
(set! forms (cons x forms))
(loop)))))))) ] ) ) )
(let ([proc (user-preprocessor-pass)])
(when proc
(dribble "User preprocessing pass...")
(set! forms (map proc forms))))
(print-expr "source" '|1| forms)
(begin-time)
s - expressions
(let* ((init0 (map canonicalize-expression init-forms))
(exps0 (map (lambda (x)
(fluid-let ((##sys#current-source-filename filename))
(canonicalize-expression x)))
(let ((forms (append import-forms forms)))
(if (not module-name)
forms
`((##core#module
,(string->symbol module-name) ()
,@forms))))))
(uses0 (map (lambda (u)
(canonicalize-expression `(##core#require ,u)))
(##sys#fast-reverse used-libraries)))
(exps (append
(map (lambda (ic) `(set! ,(cdr ic) ',(car ic))) immutable-constants)
init0
uses0
(if unit-name `((##core#provide ,unit-name)) '())
(if emit-profile
(profiling-prelude-exps (and (not unit-name)
(or profile-name #t)))
'() )
exps0
(if standalone-executable
cleanup-forms
'((##core#undefined))))))
(unless (null? import-libraries)
(quit-compiling
"No module definition found for import libraries to emit: ~A"
(string-intersperse
(map (lambda (il) (->string (car il)))
import-libraries) ", ")))
(when (pair? compiler-syntax-statistics)
(with-debugging-output
'S
(lambda ()
(print "applied compiler syntax:")
(for-each
(lambda (cs) (printf " ~a\t\t~a~%" (car cs) (cdr cs)))
compiler-syntax-statistics))))
(when (debugging '|N| "real name table:")
(display-real-name-table) )
(when (debugging 'n "line number database:")
(display-line-number-database) )
(set! ##sys#line-number-database line-number-database-2)
(set! line-number-database-2 #f)
(end-time "canonicalization")
(print-expr "canonicalized" '|2| exps)
(when (memq 'check-syntax options) (exit))
(let ([proc (user-pass)])
(when proc
(dribble "User pass...")
(begin-time)
(set! exps (map proc exps))
(end-time "user pass") ) )
Convert s - expressions to node tree
(let ((node0 (build-toplevel-procedure
(build-node-graph
(canonicalize-begin-body exps))))
(db #f))
(print-node "initial node tree" '|T| node0)
(initialize-analysis-database)
(let ((extensions (remove chicken.load#core-unit? required-libraries)))
(when enable-inline-files
(for-each
(lambda (id)
(and-let* ((ifile (##sys#resolve-include-filename
(symbol->string id) '(".inline") #t #f)))
(dribble "Loading inline file ~a ..." ifile)
(load-inline-file ifile)))
extensions))
(let ((ifs (collect-options 'consult-inline-file)))
(unless (null? ifs)
(set! inline-locally #t)
(for-each
(lambda (ilf)
(dribble "Loading inline file ~a ..." ilf)
(load-inline-file ilf) )
ifs)))
(when (or do-scrutinize enable-specialization)
(unless (memq 'ignore-repository options)
(unless (load-type-database "types.db"
enable-specialization)
(quit-compiling
"default type-database `types.db' not found")))
(for-each
(lambda (fn)
(or (load-type-database fn enable-specialization #f)
(quit-compiling "type-database `~a' not found" fn)))
(collect-options 'consult-types-file))
(for-each
(lambda (id)
(load-type-database
(make-pathname #f (symbol->string id) "types")
enable-specialization))
extensions)
(begin-time)
(set! first-analysis #f)
(set! db (analyze 'scrutiny node0))
(print-db "analysis" '|0| db 0)
(end-time "pre-analysis (scrutiny)")
(begin-time)
(debugging 'p "performing scrutiny")
(scrutinize node0 db
do-scrutinize enable-specialization
strict-variable-types block-compilation)
(end-time "scrutiny")
(when enable-specialization
(print-node "specialization" '|P| node0))
(set! first-analysis #t) ) )
(set! ##sys#line-number-database #f)
(set! constant-table #f)
(set! inline-table #f)
(unless unsafe
(scan-toplevel-assignments (first (node-subexpressions node0))) )
(begin-time)
Convert to CPS
(let ([node1 (perform-cps-conversion node0)])
(end-time "cps conversion")
(print-node "cps" '|3| node1)
(let loop ((i 1)
(node2 node1)
(progress #t)
(l/d #f)
(l/d-done #f))
(begin-time)
(let ([db (analyze 'opt node2 i progress)])
(when first-analysis
(when (memq 'u debugging-chicken)
(dump-undefined-globals db))
(when (memq 'd debugging-chicken)
(dump-defined-globals db))
(when (memq 'v debugging-chicken)
(dump-global-refs db))
(when type-output-file
(dribble "generating type file `~a' ..." type-output-file)
(emit-types-file filename type-output-file db block-compilation)))
(set! first-analysis #f)
(end-time "analysis")
(print-db "analysis" '|4| db i)
(when (memq 's debugging-chicken)
(print-program-statistics db))
(cond (progress
(debugging 'p "optimization pass" i)
(begin-time)
(receive (node2 progress-flag)
(if l/d
(determine-loop-and-dispatch node2 db)
(perform-high-level-optimizations
node2 db block-compilation
inline-locally inline-max-size
unroll-limit
inline-substitutions-enabled))
(end-time "optimization")
(print-node "optimized-iteration" '|5| node2)
(cond (progress-flag
(loop (add1 i) node2 #t #f l/d))
((and (not l/d-done) loop/dispatch)
(debugging 'p "clustering enabled")
(loop (add1 i) node2 #t #t #t))
((not inline-substitutions-enabled)
(debugging 'p "rewritings enabled")
(set! inline-substitutions-enabled #t)
(loop (add1 i) node2 #t #f l/d-done) )
(optimize-leaf-routines
(begin-time)
(let ([db (analyze 'leaf node2)])
(end-time "analysis")
(begin-time)
(let ((progress
(transform-direct-lambdas! node2 db)))
(end-time "leaf routine optimization")
(loop (add1 i)
node2
progress
#f
l/d-done) ) ) )
(else
(loop (add1 i) node2 #f #f l/d-done)) ) ) )
(else
(when do-lfa2
(begin-time)
(debugging 'p "doing lfa2")
(let ((floatvars (perform-secondary-flow-analysis node2 db)))
(end-time "secondary flow analysis")
(unless (null? floatvars)
(begin-time)
(debugging 'p "doing unboxing")
(set! node2 (perform-unboxing node2 floatvars)))
(end-time "unboxing")))
(print-node "optimized" '|7| node2)
(when (and inline-output-file insert-timer-checks)
(let ((f inline-output-file))
(dribble "generating global inline file `~a' ..." f)
(emit-global-inline-file
filename f db block-compilation
inline-max-size
(map foreign-stub-id foreign-lambda-stubs)) ) )
(begin-time)
(set! node2 (perform-closure-conversion node2 db))
(end-time "closure conversion")
(print-db "final-analysis" '|8| db i)
(when (and ##sys#warnings-enabled
(> (- (cputime) start-time) funny-message-timeout))
(display "(don't worry - still compiling...)\n") )
(print-node "closure-converted" '|9| node2)
(when a-only (exit 0))
(begin-time)
(receive (node literals lliterals lambda-table dbg-info)
(prepare-for-code-generation node2 db)
(end-time "preparation")
(begin-time)
(when emit-link-file
(let ((exts (remove chicken.load#core-unit? required-libraries)))
(dribble "generating link file `~a' ..." emit-link-file)
(with-output-to-file emit-link-file (cut pp exts))))
(let ((out (if outfile (open-output-file outfile) (current-output-port))) )
(dribble "generating `~A' ..." outfile)
(generate-code literals lliterals lambda-table out filename
user-supplied-options dynamic db dbg-info)
(when outfile
(close-output-port out)))
(end-time "code generation")
(when (memq 't debugging-chicken)
(##sys#display-times (##sys#stop-timer)))
(compiler-cleanup-hook)
(dribble "compilation finished.") ) ) ) ) ) ) ) ) ) ) ) )
)
|
f301836f503b117dc1a1b4ffdfe2d079b0a40a1ae37dfdadd75f7c8b26da074f | ku-fpg/sized-types | Unsigned.hs | # LANGUAGE ScopedTypeVariables , TypeFamilies , CPP , FlexibleContexts , DataKinds #
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE StandaloneDeriving, DeriveDataTypeable #-}
#endif
-- | Unsigned, fixed sized numbers.
--
Copyright : ( c ) 2009 - 2013 University of Kansas
-- License: BSD3
--
Maintainer : < >
-- Stability: unstable
Portability : ghc
module Data.Sized.Unsigned
( Unsigned
, toVector
, fromVector
, showBits
, U1, U2, U3, U4, U5, U6, U7, U8, U9
, U10, U11, U12, U13, U14, U15, U16, U17, U18, U19
, U20, U21, U22, U23, U24, U25, U26, U27, U28, U29
, U30, U31, U32
) where
import Data.Array.IArray(elems, (!))
import Data.Sized.Matrix as M
import Data.Sized.Fin
import Data.Bits
import Data.Ix
import GHC.TypeLits
import Data.Typeable
newtype Unsigned (ix :: Nat) = Unsigned Integer
deriving (Eq, Ord)
' toVector ' turns a sized ' Unsigned ' value into a ' Vector ' of ' 's .
toVector :: forall ix . (SingI ix) => Unsigned ix -> Vector ix Bool
toVector (Unsigned v) = matrix $ take (fromIntegral $ fromSing (sing :: Sing ix)) $ map odd $ iterate (`div` 2) v
' fromVector ' turns a ' Vector ' of ' 's into sized ' Unsigned ' value .
fromVector :: (SingI ix) => Vector ix Bool -> Unsigned ix
fromVector m = mkUnsigned $
sum [ n
| (n,b) <- zip (iterate (* 2) 1)
(elems m)
, b
]
mkUnsigned :: forall ix . (SingI ix) => Integer -> Unsigned ix
mkUnsigned x = Unsigned (x `mod` (2 ^ bitCount))
where bitCount = fromNat (sing :: Sing ix)
instance Show (Unsigned ix) where
show (Unsigned a) = show a
instance (SingI ix) => Read (Unsigned ix) where
readsPrec i str = [ (mkUnsigned a,r) | (a,r) <- readsPrec i str ]
instance (SingI ix) => Integral (Unsigned ix) where
toInteger (Unsigned m) = m
quotRem (Unsigned a) (Unsigned b) =
case quotRem a b of
(q,r) -> (mkUnsigned q,mkUnsigned r) -- TODO: check for size
instance (SingI ix) => Num (Unsigned ix) where
(Unsigned a) + (Unsigned b) = mkUnsigned $ a + b
(Unsigned a) - (Unsigned b) = mkUnsigned $ a - b
(Unsigned a) * (Unsigned b) = mkUnsigned $ a * b
abs (Unsigned n) = mkUnsigned $ abs n
signum (Unsigned n) = mkUnsigned $ signum n
fromInteger n = mkUnsigned n
instance (SingI ix) => Real (Unsigned ix) where
toRational (Unsigned n) = toRational n
instance (SingI ix) => Enum (Unsigned ix) where
fromEnum (Unsigned n) = fromEnum n
toEnum n = mkUnsigned (toInteger n)
instance (SingI ix) => Bits (Unsigned ix) where
bitSize _ = fromIntegral (fromNat (sing :: Sing ix))
complement (Unsigned v) = Unsigned (complement v)
isSigned _ = False
(Unsigned a) `xor` (Unsigned b) = Unsigned (a `xor` b)
(Unsigned a) .|. (Unsigned b) = Unsigned (a .|. b)
(Unsigned a) .&. (Unsigned b) = Unsigned (a .&. b)
shiftL (Unsigned v) i = mkUnsigned (shiftL v i)
shiftR (Unsigned v) i = mkUnsigned (shiftR v i)
-- TODO: fix
it might be possible to loosen the Integral requirement
rotate ( Ui i = fromVector ( forAll $ \ ix - > m ! ( fromIntegral ( ( fromIntegral ix - i ) ` mod ` M.population m ) ) )
-- where m = toVector v
rotate v i = fromVector (forAll $ \ ix -> m ! (fromIntegral ((fromIntegral ix - i) `mod` mLeng)))
where m = toVector v
mLeng = size $ M.zeroOf m
testBit (Unsigned u) idx = testBit u idx
bit i = fromVector (forAll $ \ ix -> if ix == fromIntegral i then True else False)
popCount n = sum $ fmap (\ b -> if b then 1 else 0) $ elems $ toVector n
showBits :: (SingI ix) => Unsigned ix -> String
showBits u = "0b" ++ reverse
[ if testBit u i then '1' else '0'
| i <- [0..(bitSize u - 1)]
]
#if __GLASGOW_HASKELL__ >= 707
deriving instance Typeable Unsigned
#else
instance SingI nat => Typeable (Unsigned (nat :: Nat)) where
typeOf _ = mkTyConApp (mkTyCon3 "sized-types" "Data.Sized.Unsigned" ("Unsigned#" ++ show (fromSing (sing :: Sing nat)))) []
#endif
instance (SingI ix) => Bounded (Unsigned ix) where
minBound = Unsigned 0
maxBound = Unsigned (2 ^ (fromNat (sing :: Sing ix)) - 1)
-- We do not address efficiency in this implementation.
instance (SingI ix) => Ix (Unsigned ix) where
range (l, u) = [l .. u]
inRange (l, u) v = (l <= v) && (v <= u)
index (l, u) v | inRange (l,u) v = fromIntegral (v - l)
| otherwise = error "Error in Ix array index"
rangeSize (l, u) | l <= u = fromIntegral $ (toInteger u) - (toInteger l) + 1
| otherwise = 0
-- | common; numerically boolean.
type U1 = Unsigned 1
type U2 = Unsigned 2
type U3 = Unsigned 3
type U4 = Unsigned 4
type U5 = Unsigned 5
type U6 = Unsigned 6
type U7 = Unsigned 7
type U8 = Unsigned 8
type U9 = Unsigned 9
type U10 = Unsigned 10
type U11 = Unsigned 11
type U12 = Unsigned 12
type U13 = Unsigned 13
type U14 = Unsigned 14
type U15 = Unsigned 15
type U16 = Unsigned 16
type U17 = Unsigned 17
type U18 = Unsigned 18
type U19 = Unsigned 19
type U20 = Unsigned 20
type U21 = Unsigned 21
type U22 = Unsigned 22
type U23 = Unsigned 23
type U24 = Unsigned 24
type U25 = Unsigned 25
type U26 = Unsigned 26
type U27 = Unsigned 27
type U28 = Unsigned 28
type U29 = Unsigned 29
type U30 = Unsigned 30
type U31 = Unsigned 31
type U32 = Unsigned 32
| null | https://raw.githubusercontent.com/ku-fpg/sized-types/77e8931d1758085ae76d67e9054549e8e75bd595/Data/Sized/Unsigned.hs | haskell | # LANGUAGE StandaloneDeriving, DeriveDataTypeable #
| Unsigned, fixed sized numbers.
License: BSD3
Stability: unstable
TODO: check for size
TODO: fix
where m = toVector v
We do not address efficiency in this implementation.
| common; numerically boolean. | # LANGUAGE ScopedTypeVariables , TypeFamilies , CPP , FlexibleContexts , DataKinds #
#if __GLASGOW_HASKELL__ >= 707
#endif
Copyright : ( c ) 2009 - 2013 University of Kansas
Maintainer : < >
Portability : ghc
module Data.Sized.Unsigned
( Unsigned
, toVector
, fromVector
, showBits
, U1, U2, U3, U4, U5, U6, U7, U8, U9
, U10, U11, U12, U13, U14, U15, U16, U17, U18, U19
, U20, U21, U22, U23, U24, U25, U26, U27, U28, U29
, U30, U31, U32
) where
import Data.Array.IArray(elems, (!))
import Data.Sized.Matrix as M
import Data.Sized.Fin
import Data.Bits
import Data.Ix
import GHC.TypeLits
import Data.Typeable
newtype Unsigned (ix :: Nat) = Unsigned Integer
deriving (Eq, Ord)
' toVector ' turns a sized ' Unsigned ' value into a ' Vector ' of ' 's .
toVector :: forall ix . (SingI ix) => Unsigned ix -> Vector ix Bool
toVector (Unsigned v) = matrix $ take (fromIntegral $ fromSing (sing :: Sing ix)) $ map odd $ iterate (`div` 2) v
' fromVector ' turns a ' Vector ' of ' 's into sized ' Unsigned ' value .
fromVector :: (SingI ix) => Vector ix Bool -> Unsigned ix
fromVector m = mkUnsigned $
sum [ n
| (n,b) <- zip (iterate (* 2) 1)
(elems m)
, b
]
mkUnsigned :: forall ix . (SingI ix) => Integer -> Unsigned ix
mkUnsigned x = Unsigned (x `mod` (2 ^ bitCount))
where bitCount = fromNat (sing :: Sing ix)
instance Show (Unsigned ix) where
show (Unsigned a) = show a
instance (SingI ix) => Read (Unsigned ix) where
readsPrec i str = [ (mkUnsigned a,r) | (a,r) <- readsPrec i str ]
instance (SingI ix) => Integral (Unsigned ix) where
toInteger (Unsigned m) = m
quotRem (Unsigned a) (Unsigned b) =
case quotRem a b of
instance (SingI ix) => Num (Unsigned ix) where
(Unsigned a) + (Unsigned b) = mkUnsigned $ a + b
(Unsigned a) - (Unsigned b) = mkUnsigned $ a - b
(Unsigned a) * (Unsigned b) = mkUnsigned $ a * b
abs (Unsigned n) = mkUnsigned $ abs n
signum (Unsigned n) = mkUnsigned $ signum n
fromInteger n = mkUnsigned n
instance (SingI ix) => Real (Unsigned ix) where
toRational (Unsigned n) = toRational n
instance (SingI ix) => Enum (Unsigned ix) where
fromEnum (Unsigned n) = fromEnum n
toEnum n = mkUnsigned (toInteger n)
instance (SingI ix) => Bits (Unsigned ix) where
bitSize _ = fromIntegral (fromNat (sing :: Sing ix))
complement (Unsigned v) = Unsigned (complement v)
isSigned _ = False
(Unsigned a) `xor` (Unsigned b) = Unsigned (a `xor` b)
(Unsigned a) .|. (Unsigned b) = Unsigned (a .|. b)
(Unsigned a) .&. (Unsigned b) = Unsigned (a .&. b)
shiftL (Unsigned v) i = mkUnsigned (shiftL v i)
shiftR (Unsigned v) i = mkUnsigned (shiftR v i)
it might be possible to loosen the Integral requirement
rotate ( Ui i = fromVector ( forAll $ \ ix - > m ! ( fromIntegral ( ( fromIntegral ix - i ) ` mod ` M.population m ) ) )
rotate v i = fromVector (forAll $ \ ix -> m ! (fromIntegral ((fromIntegral ix - i) `mod` mLeng)))
where m = toVector v
mLeng = size $ M.zeroOf m
testBit (Unsigned u) idx = testBit u idx
bit i = fromVector (forAll $ \ ix -> if ix == fromIntegral i then True else False)
popCount n = sum $ fmap (\ b -> if b then 1 else 0) $ elems $ toVector n
showBits :: (SingI ix) => Unsigned ix -> String
showBits u = "0b" ++ reverse
[ if testBit u i then '1' else '0'
| i <- [0..(bitSize u - 1)]
]
#if __GLASGOW_HASKELL__ >= 707
deriving instance Typeable Unsigned
#else
instance SingI nat => Typeable (Unsigned (nat :: Nat)) where
typeOf _ = mkTyConApp (mkTyCon3 "sized-types" "Data.Sized.Unsigned" ("Unsigned#" ++ show (fromSing (sing :: Sing nat)))) []
#endif
instance (SingI ix) => Bounded (Unsigned ix) where
minBound = Unsigned 0
maxBound = Unsigned (2 ^ (fromNat (sing :: Sing ix)) - 1)
instance (SingI ix) => Ix (Unsigned ix) where
range (l, u) = [l .. u]
inRange (l, u) v = (l <= v) && (v <= u)
index (l, u) v | inRange (l,u) v = fromIntegral (v - l)
| otherwise = error "Error in Ix array index"
rangeSize (l, u) | l <= u = fromIntegral $ (toInteger u) - (toInteger l) + 1
| otherwise = 0
type U1 = Unsigned 1
type U2 = Unsigned 2
type U3 = Unsigned 3
type U4 = Unsigned 4
type U5 = Unsigned 5
type U6 = Unsigned 6
type U7 = Unsigned 7
type U8 = Unsigned 8
type U9 = Unsigned 9
type U10 = Unsigned 10
type U11 = Unsigned 11
type U12 = Unsigned 12
type U13 = Unsigned 13
type U14 = Unsigned 14
type U15 = Unsigned 15
type U16 = Unsigned 16
type U17 = Unsigned 17
type U18 = Unsigned 18
type U19 = Unsigned 19
type U20 = Unsigned 20
type U21 = Unsigned 21
type U22 = Unsigned 22
type U23 = Unsigned 23
type U24 = Unsigned 24
type U25 = Unsigned 25
type U26 = Unsigned 26
type U27 = Unsigned 27
type U28 = Unsigned 28
type U29 = Unsigned 29
type U30 = Unsigned 30
type U31 = Unsigned 31
type U32 = Unsigned 32
|
fb48ee922e3164ff6bc600e6748d64993da4644def456257e8c46c7330e9c6a4 | deech/cabal-auto-expose | Benchmark.hs | {-# LANGUAGE BangPatterns #-}
module Main where
import Test.QuickCheck
import Criterion
import Criterion.Main
import Distribution.Simple.AutoExpose hiding (defaultMain)
main :: IO ()
main = do
let setupEnv = generate (vectorOf 1000 (arbitrary :: Gen String))
defaultMain [ env setupEnv $ \ ss ->
bgroup "main"
[ bench "whnf-indexWithNeighbors" $ whnf indexWithNeighbors ss
, bench "nf-indexWithNeighbors" $ nf indexWithNeighbors ss
]
]
| null | https://raw.githubusercontent.com/deech/cabal-auto-expose/0e642c66c143d45012b611b94796bbbe175cdf0f/cabal-auto-expose/Benchmark.hs | haskell | # LANGUAGE BangPatterns # | module Main where
import Test.QuickCheck
import Criterion
import Criterion.Main
import Distribution.Simple.AutoExpose hiding (defaultMain)
main :: IO ()
main = do
let setupEnv = generate (vectorOf 1000 (arbitrary :: Gen String))
defaultMain [ env setupEnv $ \ ss ->
bgroup "main"
[ bench "whnf-indexWithNeighbors" $ whnf indexWithNeighbors ss
, bench "nf-indexWithNeighbors" $ nf indexWithNeighbors ss
]
]
|
0fdaaba73c6b6d11108b5d83071469b1537575625b2aa0d9812c1e15e27d02c6 | mfikes/advent-of-code | day_19.cljc | (ns advent-2017.day-19
(:require
[advent.util :refer [count']]
#?(:cljs [planck.core :refer [slurp]])
[#?(:clj clojure.java.io :cljs planck.io) :as io]
[clojure.string :as str]))
(def input (-> "advent_2017/day_19/input" io/resource slurp))
(def matrix (mapv vec (str/split-lines input)))
(defn move [state]
(apply update-in state
(case (:dir state)
:down [[:loc 0] inc]
:up [[:loc 0] dec]
:left [[:loc 1] dec]
:right [[:loc 1] inc])))
(defn update-dir [state]
(let [adjacent (fn [idx] (get-in matrix (update (:loc state) idx dec)))]
(cond-> state (= (get-in matrix (:loc state)) \+)
(assoc :dir (case (:dir state)
(:down :up) (if (#{\space \|} (adjacent 1)) :right :left)
(:right :left) (if (#{\space \-} (adjacent 0)) :down :up))))))
(def path (eduction
(map :loc)
(take-while #(not= \space (get-in matrix %)))
(iterate (comp update-dir move)
{:dir :down :loc [0 (.indexOf (matrix 0) \|)]})))
(defn part-1 []
(let [letters (set "ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
(transduce (keep #(letters (get-in matrix %))) str path)))
(defn part-2 []
(count' path))
| null | https://raw.githubusercontent.com/mfikes/advent-of-code/72a015ac8fd9b1097efea69a0bb8acc26462665e/src/advent_2017/day_19.cljc | clojure | (ns advent-2017.day-19
(:require
[advent.util :refer [count']]
#?(:cljs [planck.core :refer [slurp]])
[#?(:clj clojure.java.io :cljs planck.io) :as io]
[clojure.string :as str]))
(def input (-> "advent_2017/day_19/input" io/resource slurp))
(def matrix (mapv vec (str/split-lines input)))
(defn move [state]
(apply update-in state
(case (:dir state)
:down [[:loc 0] inc]
:up [[:loc 0] dec]
:left [[:loc 1] dec]
:right [[:loc 1] inc])))
(defn update-dir [state]
(let [adjacent (fn [idx] (get-in matrix (update (:loc state) idx dec)))]
(cond-> state (= (get-in matrix (:loc state)) \+)
(assoc :dir (case (:dir state)
(:down :up) (if (#{\space \|} (adjacent 1)) :right :left)
(:right :left) (if (#{\space \-} (adjacent 0)) :down :up))))))
(def path (eduction
(map :loc)
(take-while #(not= \space (get-in matrix %)))
(iterate (comp update-dir move)
{:dir :down :loc [0 (.indexOf (matrix 0) \|)]})))
(defn part-1 []
(let [letters (set "ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
(transduce (keep #(letters (get-in matrix %))) str path)))
(defn part-2 []
(count' path))
|
|
979bd8ebf0e0f662bf6160f0da50717e9b3dbb210355b69efe8b4c389cccce2f | janestreet/bonsai | header_tree.mli | open! Core
open! Bonsai_web
type t = private
| Leaf of leaf
| Group of group
| Organizational_group of t list
| Spacer of t
and leaf = private
{ leaf_label : Vdom.Node.t
; initial_width : Css_gen.Length.t
; visible : bool
}
and group = private
{ children : t list
; group_label : Vdom.Node.t
}
[@@deriving sexp]
val leaf : label:Vdom.Node.t -> initial_width:Css_gen.Length.t -> visible:bool -> t
val group : label:Vdom.Node.t -> t list -> t
val org_group : t list -> t
val colspan : t -> int
val height : t -> int
val leaves : t -> leaf list
(** For each leaf, [column_names] returns a list like [group_label; group_label; ...;
leaf_label], where the group labels are that leaf's ancestors, ordered left to right
from most to least distant. Used for rendering column groups in tests. *)
val column_names : t -> Vdom.Node.t list list
| null | https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/web_ui/partial_render_table/src/header_tree.mli | ocaml | * For each leaf, [column_names] returns a list like [group_label; group_label; ...;
leaf_label], where the group labels are that leaf's ancestors, ordered left to right
from most to least distant. Used for rendering column groups in tests. | open! Core
open! Bonsai_web
type t = private
| Leaf of leaf
| Group of group
| Organizational_group of t list
| Spacer of t
and leaf = private
{ leaf_label : Vdom.Node.t
; initial_width : Css_gen.Length.t
; visible : bool
}
and group = private
{ children : t list
; group_label : Vdom.Node.t
}
[@@deriving sexp]
val leaf : label:Vdom.Node.t -> initial_width:Css_gen.Length.t -> visible:bool -> t
val group : label:Vdom.Node.t -> t list -> t
val org_group : t list -> t
val colspan : t -> int
val height : t -> int
val leaves : t -> leaf list
val column_names : t -> Vdom.Node.t list list
|
3f6a64b42788d04895c8dbe8083e972081f0146b161b8c56c81e4306386f485b | baffalop/aoc22-haskell | Day11.hs | # LANGUAGE TemplateHaskell , DeriveFunctor #
module Day11 (parse, solve1, solve2) where
import Prelude hiding (round)
import Data.Text (Text)
import qualified Data.Attoparsec.Text as P
import Data.Attoparsec.Text (Parser)
import Data.Map (Map, (!))
import qualified Data.Map as M
import Data.Sequence (Seq, (|>))
import qualified Data.Sequence as Seq
import Lens.Micro.Platform (makeLensesFor, (%~), (.~))
import Control.Monad.State (State, execState)
import qualified Control.Monad.State as State
import Control.Applicative ((<|>))
import Data.Functor (($>))
import Utils ((<.>), ffmap)
import Control.Monad (replicateM_, forM_, void)
import Data.Foldable (traverse_, Foldable (toList))
import Data.List (sortOn)
import Control.Arrow ((>>>))
type Monkeys = Map MonkeyId Monkey
type MonkeyState = State Monkeys ()
newtype MonkeyId = ID Int deriving (Show, Eq, Ord)
type Worry = IWorry Integer
newtype IWorry a = Worry { worry :: a } deriving (Show, Eq, Ord, Functor)
data Monkey = Monkey
{ items :: Seq Worry
, amplify :: Worry -> Worry
, divisor :: Integer
, throwTo :: Worry -> MonkeyId
, inspected :: Int
}
instance Show Monkey where
show Monkey{..} =
"[Monkey] Items: " <> show (worry <$> items)
<> " Worry 2 becomes " <> show (worry $ amplify $ Worry 2)
<> " - Inspected: " <> show inspected <> "\n"
makeLensesFor [("items", "_items"), ("inspected", "_inspected")] ''Monkey
parse :: Text -> Either String Monkeys
parse = P.parseOnly $ M.fromList <$> monkey `P.sepBy` P.skipSpace
where
monkey :: Parser (MonkeyId, Monkey)
monkey = do
monkeyId <- P.string "Monkey " >> ID <$> P.decimal <* P.char ':'
P.skipSpace <* P.string "Starting items: "
items <- Seq.fromList <$> (Worry <$> P.decimal) `P.sepBy` P.string ", "
amplify <- P.skipSpace *> operation
(divisor, throwTo) <- P.skipSpace *> logic
pure (monkeyId, Monkey { inspected = 0, .. })
operation :: Parser (Worry -> Worry)
operation = fmap <$> do
void $ P.string "Operation: new = old"
operator <- (*) <$ P.string " * " <|> (+) <$ P.string " + "
operator <$> P.decimal <|> P.string "old" $> \x -> x `operator` x
logic :: Integral n => Parser (n, IWorry n -> MonkeyId)
logic = do
divisor <- P.string "Test: divisible by " *> P.decimal <* P.skipSpace
ifTrue <- P.string "If true: throw to monkey " >> ID <$> P.decimal <* P.skipSpace
ifFalse <- P.string "If false: throw to monkey " >> ID <$> P.decimal
pure $ (divisor,) \(Worry w) -> if (w `mod` divisor) == 0 then ifTrue else ifFalse
solve1 :: Monkeys -> Int
solve1 = scoreMostInspected . execState (replicateM_ 20 $ round $ fmap (`div` 3))
solve2 :: Monkeys -> Int
solve2 monkeys = scoreMostInspected $ execState (replicateM_ 10000 roundModulo) monkeys
where
roundModulo :: State Monkeys ()
roundModulo = do
round id
State.modify $ fmap $ _items %~ ffmap (`mod` commonDivisor)
commonDivisor :: Integer
commonDivisor = product $ divisor <$> toList monkeys
round :: (Worry -> Worry) -> MonkeyState
round reduce =
State.gets M.keys >>= traverse_ \k -> do
Monkey{..} <- State.gets (! k)
forM_ items $ amplify >>> reduce >>> \worry ->
State.modify $ M.adjust (_items %~ (|> worry)) (throwTo worry)
State.modify $ flip M.adjust k $ (_items .~ Seq.empty) . (_inspected %~ (+ length items))
scoreMostInspected :: Monkeys -> Int
scoreMostInspected = product . take 2 . sortOn negate . (inspected <.> toList)
| null | https://raw.githubusercontent.com/baffalop/aoc22-haskell/45360a2109b91a63f70d00b51aebc911360be7e1/src/Day11.hs | haskell | # LANGUAGE TemplateHaskell , DeriveFunctor #
module Day11 (parse, solve1, solve2) where
import Prelude hiding (round)
import Data.Text (Text)
import qualified Data.Attoparsec.Text as P
import Data.Attoparsec.Text (Parser)
import Data.Map (Map, (!))
import qualified Data.Map as M
import Data.Sequence (Seq, (|>))
import qualified Data.Sequence as Seq
import Lens.Micro.Platform (makeLensesFor, (%~), (.~))
import Control.Monad.State (State, execState)
import qualified Control.Monad.State as State
import Control.Applicative ((<|>))
import Data.Functor (($>))
import Utils ((<.>), ffmap)
import Control.Monad (replicateM_, forM_, void)
import Data.Foldable (traverse_, Foldable (toList))
import Data.List (sortOn)
import Control.Arrow ((>>>))
type Monkeys = Map MonkeyId Monkey
type MonkeyState = State Monkeys ()
newtype MonkeyId = ID Int deriving (Show, Eq, Ord)
type Worry = IWorry Integer
newtype IWorry a = Worry { worry :: a } deriving (Show, Eq, Ord, Functor)
data Monkey = Monkey
{ items :: Seq Worry
, amplify :: Worry -> Worry
, divisor :: Integer
, throwTo :: Worry -> MonkeyId
, inspected :: Int
}
instance Show Monkey where
show Monkey{..} =
"[Monkey] Items: " <> show (worry <$> items)
<> " Worry 2 becomes " <> show (worry $ amplify $ Worry 2)
<> " - Inspected: " <> show inspected <> "\n"
makeLensesFor [("items", "_items"), ("inspected", "_inspected")] ''Monkey
parse :: Text -> Either String Monkeys
parse = P.parseOnly $ M.fromList <$> monkey `P.sepBy` P.skipSpace
where
monkey :: Parser (MonkeyId, Monkey)
monkey = do
monkeyId <- P.string "Monkey " >> ID <$> P.decimal <* P.char ':'
P.skipSpace <* P.string "Starting items: "
items <- Seq.fromList <$> (Worry <$> P.decimal) `P.sepBy` P.string ", "
amplify <- P.skipSpace *> operation
(divisor, throwTo) <- P.skipSpace *> logic
pure (monkeyId, Monkey { inspected = 0, .. })
operation :: Parser (Worry -> Worry)
operation = fmap <$> do
void $ P.string "Operation: new = old"
operator <- (*) <$ P.string " * " <|> (+) <$ P.string " + "
operator <$> P.decimal <|> P.string "old" $> \x -> x `operator` x
logic :: Integral n => Parser (n, IWorry n -> MonkeyId)
logic = do
divisor <- P.string "Test: divisible by " *> P.decimal <* P.skipSpace
ifTrue <- P.string "If true: throw to monkey " >> ID <$> P.decimal <* P.skipSpace
ifFalse <- P.string "If false: throw to monkey " >> ID <$> P.decimal
pure $ (divisor,) \(Worry w) -> if (w `mod` divisor) == 0 then ifTrue else ifFalse
solve1 :: Monkeys -> Int
solve1 = scoreMostInspected . execState (replicateM_ 20 $ round $ fmap (`div` 3))
solve2 :: Monkeys -> Int
solve2 monkeys = scoreMostInspected $ execState (replicateM_ 10000 roundModulo) monkeys
where
roundModulo :: State Monkeys ()
roundModulo = do
round id
State.modify $ fmap $ _items %~ ffmap (`mod` commonDivisor)
commonDivisor :: Integer
commonDivisor = product $ divisor <$> toList monkeys
round :: (Worry -> Worry) -> MonkeyState
round reduce =
State.gets M.keys >>= traverse_ \k -> do
Monkey{..} <- State.gets (! k)
forM_ items $ amplify >>> reduce >>> \worry ->
State.modify $ M.adjust (_items %~ (|> worry)) (throwTo worry)
State.modify $ flip M.adjust k $ (_items .~ Seq.empty) . (_inspected %~ (+ length items))
scoreMostInspected :: Monkeys -> Int
scoreMostInspected = product . take 2 . sortOn negate . (inspected <.> toList)
|
|
7aa15bbee88994c9969174d9899af056ebeceef617387382e45eb39a3348d4a5 | triffon/fp-2022-23 | 07.palindrome.rkt | #lang racket
(require rackunit)
(require rackunit/text-ui)
# # # зад 7
Дали числото е палиндром ?
(define (palindrome? n)
'tuk)
(run-tests
(test-suite
"palindrome? tests"
(check-false (palindrome? 1234))
(check-false (palindrome? 1231))
(check-true (palindrome? 9102019))
(check-true (palindrome? 10000001))
(check-true (palindrome? 0))
(check-true (palindrome? 5)))
'verbose)
| null | https://raw.githubusercontent.com/triffon/fp-2022-23/caf334dba494954cc7bd62b9f4fc5a1ff8315f2b/exercises/cs2/02.scheme.rec-iter/07.palindrome.rkt | racket | #lang racket
(require rackunit)
(require rackunit/text-ui)
# # # зад 7
Дали числото е палиндром ?
(define (palindrome? n)
'tuk)
(run-tests
(test-suite
"palindrome? tests"
(check-false (palindrome? 1234))
(check-false (palindrome? 1231))
(check-true (palindrome? 9102019))
(check-true (palindrome? 10000001))
(check-true (palindrome? 0))
(check-true (palindrome? 5)))
'verbose)
|
|
19d6401892996c371677aeaccb9b3b9a4b29ea8280d117003972d7fa812c1081 | unison-code/unison | HsGen.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 SpecsGen.HsGen
(
constantExtendedOperation,
extendRemats,
expand,
preProcess,
promote,
update,
makeBound,
dummySrcLoc,
name,
infoToIds,
opcOpsFunBind,
targetInstructionCon,
simpleOpcFunBind,
simpleFun,
constantFun,
simpleErrorRhs,
hsModule,
hsExportDataType,
hsExportVar,
unisonImport,
instructionDeclImport,
registerDeclImport,
itineraryDeclImport,
registerClassDeclImport,
hsFun,
hsDataDecl,
hsItinDecl,
hsRegClassDecl,
hsInstDecl,
opcPVar,
mkOpcRhs,
toHsStr,
toHsVar,
toHsInt,
toHsCon,
toHsPStr,
toHsPVar,
toHsList,
opToHsVar,
idToHsCon,
redefNameIfIn,
renameRedefs,
mkOperandMap,
toVarName,
toRedefName,
toVarList,
toOpType,
toConstantExtendedOp,
isConstantExtendedOp,
moduleName
)
where
import Data.List
import Data.Char
import qualified Data.Map as M
import Language.Haskell.Syntax
import qualified Data.Text as T
import Control.Arrow
import Data.Function
import SpecsGen.SimpleYaml
constantExtendedOperation i
| isConstantExtendable i =
let oldId = YString (oId i)
newId = YString $ toConstantExtendedOp $ yString oldId
i' = yApply (yReplaceString oldId newId) i
in Just i'
| otherwise = Nothing
isConstantExtendable i =
(iType i == "copy") ||
(any (isConstantExtendableOp . simplifyOperand) $ iOperands i)
isConstantExtendableOp (_, YBoundInfo) = True
isConstantExtendableOp (_, YBlockRefInfo) = True
isConstantExtendableOp _ = False
extendRemats is remat = concatMap (extendRemat (idMap is)) remat
extendRemat id2i r =
let id = yFetchStr "id" r
hc = yFetchStr "home-class" r
ic = yFetchStr "infinite-class" r
suf = case yFetch "suffix" r of
YString s -> s
YNil -> ""
i = case M.lookup id id2i of
Just i' -> i'
Nothing ->
error ("Rematerializable instruction \'" ++ id ++ "\' does not exist")
d = sourceVersion id suf (hc, ic) i
dc = dematVersion id suf (hc, ic)
rc = rematVersion id suf (hc, ic)
ris = map (maybeExpandInstr id2i) [d, dc, rc]
in case yFetch "versions" r of
(YSeq versions) -> [expandVersion ri v | ri <- ris, v <- versions]
YNil -> ris
expandVersion i (YString "base") = i
expandVersion i (YMap [(YString suf, YSeq [YMap fields])]) =
let id = oId i
v = YMap ([(YString "id", YString (id ++ suf))] ++
[(YString "parent", YString id)] ++
fields)
i' = maybeExpandInstr (idMap [i]) v
in i'
sourceVersion id suf (_, ic) i =
let (_, [d]) = iUseDefs i
u = [(YString "id", YString (id ++ "_source" ++ suf))] ++
[(YString "parent", YString id)] ++
noUsages ++ noEffects ++
[(YString "new-operands",
YSeq [YMap [(YString d, YSeq [YString "register", YString "def",
YString ic, YString "-1"])]])]
in YMap u
dematVersion id suf (hc, ic) =
YMap ([(YString "id", YString (id ++ "_demat" ++ suf))] ++
[(YString "parent", YString id)] ++
noUsages ++ noEffects ++ copy ++ copyOperands hc ic (Just "-1"))
rematVersion id suf (hc, ic) =
YMap ([(YString "id", YString (id ++ "_remat" ++ suf))] ++
[(YString "parent", YString id)] ++
copy ++ copyOperands ic hc Nothing)
noUsages = [(YString "itinerary", YString "NoItinerary"),
(YString "size", YString "0")]
noEffects = [(YString "affects", YNil),
(YString "affected-by", YNil)]
copy = [(YString "type", YString "copy")]
copyOperands s d dl =
[(YString "uses", YSeq [YString "src"]),
(YString "defines", YSeq [YString "dst"]),
(YString "operands", YSeq [regOperand "src" "use" s Nothing,
regOperand "dst" "def" d dl])]
regOperand name typ rclass deflat =
let lat = case deflat of
Just l -> [YString l]
Nothing -> []
in YMap [(YString name,
YSeq ([YString "register", YString typ, YString rclass] ++ lat))]
idMap is = M.fromList $ map (\i -> (oId i, i)) is
expand is = map (maybeExpandInstr (idMap is)) is
maybeExpandInstr id2i i =
case iParent i of
Nothing -> i
Just p ->
let i1 = case M.lookup p id2i of
Just i1' -> i1'
Nothing ->
error ("Parent instruction \'" ++ p ++ "\' does not exist")
i2 = foldl replaceField i1 (yMap i)
i3 = deleteField (YString "parent") i2
i4 = addField (YString "parent", YString p) i3
i5 = maybeExpandOperands (yLookup "new-operands" i) i4
in i5
maybeExpandOperands (Just (YSeq new)) i =
let operands = nubBy (equaling operandName) $ new ++ iOperands i
i1 = replaceField i (YString "operands", YSeq operands)
uses = nub $ iUses i ++
[YString (operandName o) | o <- new, isUse o]
i2 = replaceField i1 (YString "uses", YSeq uses)
defines = nub $ iDefines i ++
[YString (operandName o) | o <- new, isDef o]
i3 = replaceField i2 (YString "defines", YSeq defines)
in i3
maybeExpandOperands Nothing i = i
equaling = ((==) `on`)
operandName (YMap [(YString name, _)]) = name
isUse (YMap [(_,YSeq (_:YString ud:_:_))]) = ud `elem` ["use", "usedef"]
isUse _ = False
isDef (YMap [(_,YSeq (_:YString ud:_:_))]) = ud `elem` ["def", "usedef"]
isDef _ = False
replaceField i (YString "parent", _) = i
replaceField (YMap fs) f = YMap (map (replace f) fs)
replace (YString newk, newv) (YString oldk, oldv)
| newk == oldk = (YString newk, newv)
| otherwise = (YString oldk, oldv)
addField f (YMap fs) = YMap (fs ++ [f])
deleteField df (YMap fs) = YMap (filter (not . isField df) fs)
isField f (f', _) = f == f'
preProcess is pp = map (maybePreProcessInstr (idMap pp)) is
maybePreProcessInstr id2pp i =
case M.lookup (oId i) id2pp of
Just pp -> foldl replaceField i (yMap pp)
Nothing -> i
promote effs i =
let rs = sideEffects $ iAffectedBy i
ws = if iType i `elem` ["call", "branch"]
then [] -- calls and branches do not have definition operands
else sideEffects $ iAffects i
i1 = foldl (explicateEffect (rs, ws)) i effs
in i1
explicateEffect (rs, ws) i eff =
let (ef, rc) =
case break (\c -> c == ':') eff of
(ef', []) -> (ef', "Unknown")
(ef', _:rc') -> (ef', rc')
i1 = if ef `elem` rs then addEffectOperand (ef ++ "_use") "use" rc i else i
i2 = if ef `elem` ws then addEffectOperand (ef ++ "_def") "def" rc i1 else i1
i3 = if ef `elem` rs then addToOperands (ef ++ "_use") "uses" i2 else i2
i4 = if ef `elem` ws then addToOperands (ef ++ "_def") "defines" i3 else i3
in i4
addEffectOperand name typ rc i =
let ps = [YString "register", YString typ, YString rc]
in yApplyTo (YString "operands")
(yAddToSeq (YMap [(YString name, YSeq ps)])) i
addToOperands name list i = yApplyTo (YString list) (yAddToSeq (YString name)) i
update regClasses i = foldl updateRegClass i regClasses
updateRegClass i regClass =
let (operand,
rclass) = second tail $ break (\c -> c == ':') regClass
(us, ds) = iUseDefs i
in doUpdateRegClass (operand `elem` us, operand `elem` ds) (operand, rclass) i
doUpdateRegClass (False, False) _ i = i
doUpdateRegClass ud (operand, rclass) i =
let usedef = case ud of
(True, True) -> "usedef"
(True, False) -> "use"
(False, True) -> "def"
i' = updateOperandInInstr operand
(YSeq [YString "register",YString usedef,YString rclass]) i
in i'
updateOperandInInstr k v (YMap fs) =
let fs' = map (updateOperandInFields k v) fs
in (YMap fs')
updateOperandInFields k v (YString "operands", YSeq ops) =
(YString "operands", YSeq (map (updateOperand k v) ops))
updateOperandInFields _ _ f = f
updateOperand k v op @ (YMap [(YString k', _)])
| k == k' = (YMap [(YString k, v)])
| otherwise = op
makeBound regClasses i = foldl makeRegClassBound i regClasses
makeRegClassBound i regClass =
let operands = map (mkRegClassBound regClass) $ iOperands i
in replaceField i (YString "operands", YSeq operands)
mkRegClassBound regClass (YMap [(k, YSeq [YString "register", _, YString rc])])
| regClass == rc = YMap [(k, YString "bound")]
mkRegClassBound _ operand = operand
yApplyTo p f (YMap s) = YMap [(k, if k == p then f v else v) | (k, v) <- s]
yAddToSeq e (YSeq s) = YSeq (s ++ [e])
yAddToSeq e YNil = YSeq [e]
sideEffects affs = [e | (YOtherSideEffect e) <- toAffectsList affs]
dummySrcLoc = SrcLoc "" 1 1
name = UnQual . HsIdent
infoToIds iF is =
let infoId = [(iF i, [oId i]) | i <- is]
info2id = sort $ M.toList $ M.fromListWith (++) infoId
in info2id
opcOpsFunBind n ((us, ds), rhss) = funBind [opcPVar, HsPTuple [us, ds]] n rhss
hsModule n e i d = HsModule dummySrcLoc (Module n) e i d
hsExportDataType n = HsEThingAll (name n)
hsExportVar n = HsEVar (name n)
unisonImport = hsImport "Unison"
instructionDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ ".SpecsGen." ++
targetName ++ "InstructionDecl")
registerDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ "." ++
targetName ++ "RegisterDecl")
itineraryDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ ".SpecsGen." ++
targetName ++ "ItineraryDecl")
registerClassDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ ".SpecsGen." ++
targetName ++ "RegisterClassDecl")
hsImport n = HsImportDecl dummySrcLoc (Module n) False Nothing Nothing
funBind as n = hsFunBind n as
targetInstructionCon targetName = targetName ++ "Instruction"
simpleOpcFunBind n = hsFunBind n [opcPVar]
simpleFun op n = hsFun n [op]
constantFun n rhs = hsFun n [] rhs
hsFunBind n h rhss = mkHsFun n h (HsGuardedRhss rhss)
hsFun n h rhs = mkHsFun n h (HsUnGuardedRhs rhs)
mkHsFun n h g =
HsFunBind
[
HsMatch
dummySrcLoc
(HsIdent n)
h
g
[]
]
simpleErrorRhs n =
simpleFun (toHsPVar "a") n
(HsApp (toHsVar "error")
(HsParen
(HsInfixApp (toHsStr ("unmatched: " ++ n ++ " "))
(HsQVarOp (UnQual $ HsSymbol "++"))
(HsApp (toHsVar "show") (toHsVar "a")))))
hsDataDecl targetName cs =
HsDataDecl dummySrcLoc [] (HsIdent (targetInstructionCon targetName)) []
[HsConDecl dummySrcLoc (HsIdent (toOpType c)) [] | c <- cs]
[name "Eq", name "Ord"]
hsItinDecl targetName cs =
HsDataDecl dummySrcLoc [] (HsIdent (targetName ++ "Itinerary")) []
[HsConDecl dummySrcLoc (HsIdent (toOpType c)) [] | c <- cs]
[name "Eq", name "Ord", name "Read", name "Show"]
hsRegClassDecl targetName cs =
HsDataDecl dummySrcLoc [] (HsIdent (targetName ++ "RegisterClass")) []
[HsConDecl dummySrcLoc (HsIdent (toOpType c)) [] | c <- cs]
[name "Eq", name "Ord", name "Read", name "Show"]
hsInstDecl targetName ss =
HsInstDecl dummySrcLoc [] (name "Show")
[HsTyVar (HsIdent (targetInstructionCon targetName))] ss
opcPVar = toHsPVar "i"
mkOpcRhs f iF (info, ids) =
let sids = sort ids
idList = map f sids
hsInfo = iF info
i = toHsVar "i"
cond = HsInfixApp i (HsQVarOp (name "elem")) (HsList idList)
in HsGuardedRhs dummySrcLoc cond hsInfo
toHsStr = HsLit . HsString
toHsVar = HsVar . name
toHsInt = HsLit . HsInt
toHsCon = HsCon . name
toHsPStr = HsPLit . HsString
toHsPVar = HsPVar . HsIdent
toHsList = HsList
idToHsCon = toHsCon . toOpType
renameRedefs (l1, l2) = (l1, map (redefNameIfIn l1) l2)
redefNameIfIn l s = if s `elem` l then toRedefName s else s
toRedefName = (++ "'")
mkOperandMap a =
let o2info = map simplifyOperand a
o2info' = M.fromList o2info
in o2info'
toVarName "0" = "zero"
toVarName (c:l) = toLower c : l
toVarList = HsPList . map toHsPVar
toOpType (c:l) = stringReplace "." "" (toUpper c : l)
opToHsVar = toHsVar . toVarName
toConstantExtendedOp op = op ++ "_ce"
isConstantExtendedOp op = "_ce" `isSuffixOf` op
stringReplace s1 s2 = T.unpack . T.replace (T.pack s1) (T.pack s2) . T.pack
moduleName targetName suffix =
"Unison.Target." ++ targetName ++ ".SpecsGen." ++ suffix
| null | https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison-specsgen/src/SpecsGen/HsGen.hs | haskell | calls and branches do not have definition operands | |
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 SpecsGen.HsGen
(
constantExtendedOperation,
extendRemats,
expand,
preProcess,
promote,
update,
makeBound,
dummySrcLoc,
name,
infoToIds,
opcOpsFunBind,
targetInstructionCon,
simpleOpcFunBind,
simpleFun,
constantFun,
simpleErrorRhs,
hsModule,
hsExportDataType,
hsExportVar,
unisonImport,
instructionDeclImport,
registerDeclImport,
itineraryDeclImport,
registerClassDeclImport,
hsFun,
hsDataDecl,
hsItinDecl,
hsRegClassDecl,
hsInstDecl,
opcPVar,
mkOpcRhs,
toHsStr,
toHsVar,
toHsInt,
toHsCon,
toHsPStr,
toHsPVar,
toHsList,
opToHsVar,
idToHsCon,
redefNameIfIn,
renameRedefs,
mkOperandMap,
toVarName,
toRedefName,
toVarList,
toOpType,
toConstantExtendedOp,
isConstantExtendedOp,
moduleName
)
where
import Data.List
import Data.Char
import qualified Data.Map as M
import Language.Haskell.Syntax
import qualified Data.Text as T
import Control.Arrow
import Data.Function
import SpecsGen.SimpleYaml
constantExtendedOperation i
| isConstantExtendable i =
let oldId = YString (oId i)
newId = YString $ toConstantExtendedOp $ yString oldId
i' = yApply (yReplaceString oldId newId) i
in Just i'
| otherwise = Nothing
isConstantExtendable i =
(iType i == "copy") ||
(any (isConstantExtendableOp . simplifyOperand) $ iOperands i)
isConstantExtendableOp (_, YBoundInfo) = True
isConstantExtendableOp (_, YBlockRefInfo) = True
isConstantExtendableOp _ = False
extendRemats is remat = concatMap (extendRemat (idMap is)) remat
extendRemat id2i r =
let id = yFetchStr "id" r
hc = yFetchStr "home-class" r
ic = yFetchStr "infinite-class" r
suf = case yFetch "suffix" r of
YString s -> s
YNil -> ""
i = case M.lookup id id2i of
Just i' -> i'
Nothing ->
error ("Rematerializable instruction \'" ++ id ++ "\' does not exist")
d = sourceVersion id suf (hc, ic) i
dc = dematVersion id suf (hc, ic)
rc = rematVersion id suf (hc, ic)
ris = map (maybeExpandInstr id2i) [d, dc, rc]
in case yFetch "versions" r of
(YSeq versions) -> [expandVersion ri v | ri <- ris, v <- versions]
YNil -> ris
expandVersion i (YString "base") = i
expandVersion i (YMap [(YString suf, YSeq [YMap fields])]) =
let id = oId i
v = YMap ([(YString "id", YString (id ++ suf))] ++
[(YString "parent", YString id)] ++
fields)
i' = maybeExpandInstr (idMap [i]) v
in i'
sourceVersion id suf (_, ic) i =
let (_, [d]) = iUseDefs i
u = [(YString "id", YString (id ++ "_source" ++ suf))] ++
[(YString "parent", YString id)] ++
noUsages ++ noEffects ++
[(YString "new-operands",
YSeq [YMap [(YString d, YSeq [YString "register", YString "def",
YString ic, YString "-1"])]])]
in YMap u
dematVersion id suf (hc, ic) =
YMap ([(YString "id", YString (id ++ "_demat" ++ suf))] ++
[(YString "parent", YString id)] ++
noUsages ++ noEffects ++ copy ++ copyOperands hc ic (Just "-1"))
rematVersion id suf (hc, ic) =
YMap ([(YString "id", YString (id ++ "_remat" ++ suf))] ++
[(YString "parent", YString id)] ++
copy ++ copyOperands ic hc Nothing)
noUsages = [(YString "itinerary", YString "NoItinerary"),
(YString "size", YString "0")]
noEffects = [(YString "affects", YNil),
(YString "affected-by", YNil)]
copy = [(YString "type", YString "copy")]
copyOperands s d dl =
[(YString "uses", YSeq [YString "src"]),
(YString "defines", YSeq [YString "dst"]),
(YString "operands", YSeq [regOperand "src" "use" s Nothing,
regOperand "dst" "def" d dl])]
regOperand name typ rclass deflat =
let lat = case deflat of
Just l -> [YString l]
Nothing -> []
in YMap [(YString name,
YSeq ([YString "register", YString typ, YString rclass] ++ lat))]
idMap is = M.fromList $ map (\i -> (oId i, i)) is
expand is = map (maybeExpandInstr (idMap is)) is
maybeExpandInstr id2i i =
case iParent i of
Nothing -> i
Just p ->
let i1 = case M.lookup p id2i of
Just i1' -> i1'
Nothing ->
error ("Parent instruction \'" ++ p ++ "\' does not exist")
i2 = foldl replaceField i1 (yMap i)
i3 = deleteField (YString "parent") i2
i4 = addField (YString "parent", YString p) i3
i5 = maybeExpandOperands (yLookup "new-operands" i) i4
in i5
maybeExpandOperands (Just (YSeq new)) i =
let operands = nubBy (equaling operandName) $ new ++ iOperands i
i1 = replaceField i (YString "operands", YSeq operands)
uses = nub $ iUses i ++
[YString (operandName o) | o <- new, isUse o]
i2 = replaceField i1 (YString "uses", YSeq uses)
defines = nub $ iDefines i ++
[YString (operandName o) | o <- new, isDef o]
i3 = replaceField i2 (YString "defines", YSeq defines)
in i3
maybeExpandOperands Nothing i = i
equaling = ((==) `on`)
operandName (YMap [(YString name, _)]) = name
isUse (YMap [(_,YSeq (_:YString ud:_:_))]) = ud `elem` ["use", "usedef"]
isUse _ = False
isDef (YMap [(_,YSeq (_:YString ud:_:_))]) = ud `elem` ["def", "usedef"]
isDef _ = False
replaceField i (YString "parent", _) = i
replaceField (YMap fs) f = YMap (map (replace f) fs)
replace (YString newk, newv) (YString oldk, oldv)
| newk == oldk = (YString newk, newv)
| otherwise = (YString oldk, oldv)
addField f (YMap fs) = YMap (fs ++ [f])
deleteField df (YMap fs) = YMap (filter (not . isField df) fs)
isField f (f', _) = f == f'
preProcess is pp = map (maybePreProcessInstr (idMap pp)) is
maybePreProcessInstr id2pp i =
case M.lookup (oId i) id2pp of
Just pp -> foldl replaceField i (yMap pp)
Nothing -> i
promote effs i =
let rs = sideEffects $ iAffectedBy i
ws = if iType i `elem` ["call", "branch"]
else sideEffects $ iAffects i
i1 = foldl (explicateEffect (rs, ws)) i effs
in i1
explicateEffect (rs, ws) i eff =
let (ef, rc) =
case break (\c -> c == ':') eff of
(ef', []) -> (ef', "Unknown")
(ef', _:rc') -> (ef', rc')
i1 = if ef `elem` rs then addEffectOperand (ef ++ "_use") "use" rc i else i
i2 = if ef `elem` ws then addEffectOperand (ef ++ "_def") "def" rc i1 else i1
i3 = if ef `elem` rs then addToOperands (ef ++ "_use") "uses" i2 else i2
i4 = if ef `elem` ws then addToOperands (ef ++ "_def") "defines" i3 else i3
in i4
addEffectOperand name typ rc i =
let ps = [YString "register", YString typ, YString rc]
in yApplyTo (YString "operands")
(yAddToSeq (YMap [(YString name, YSeq ps)])) i
addToOperands name list i = yApplyTo (YString list) (yAddToSeq (YString name)) i
update regClasses i = foldl updateRegClass i regClasses
updateRegClass i regClass =
let (operand,
rclass) = second tail $ break (\c -> c == ':') regClass
(us, ds) = iUseDefs i
in doUpdateRegClass (operand `elem` us, operand `elem` ds) (operand, rclass) i
doUpdateRegClass (False, False) _ i = i
doUpdateRegClass ud (operand, rclass) i =
let usedef = case ud of
(True, True) -> "usedef"
(True, False) -> "use"
(False, True) -> "def"
i' = updateOperandInInstr operand
(YSeq [YString "register",YString usedef,YString rclass]) i
in i'
updateOperandInInstr k v (YMap fs) =
let fs' = map (updateOperandInFields k v) fs
in (YMap fs')
updateOperandInFields k v (YString "operands", YSeq ops) =
(YString "operands", YSeq (map (updateOperand k v) ops))
updateOperandInFields _ _ f = f
updateOperand k v op @ (YMap [(YString k', _)])
| k == k' = (YMap [(YString k, v)])
| otherwise = op
makeBound regClasses i = foldl makeRegClassBound i regClasses
makeRegClassBound i regClass =
let operands = map (mkRegClassBound regClass) $ iOperands i
in replaceField i (YString "operands", YSeq operands)
mkRegClassBound regClass (YMap [(k, YSeq [YString "register", _, YString rc])])
| regClass == rc = YMap [(k, YString "bound")]
mkRegClassBound _ operand = operand
yApplyTo p f (YMap s) = YMap [(k, if k == p then f v else v) | (k, v) <- s]
yAddToSeq e (YSeq s) = YSeq (s ++ [e])
yAddToSeq e YNil = YSeq [e]
sideEffects affs = [e | (YOtherSideEffect e) <- toAffectsList affs]
dummySrcLoc = SrcLoc "" 1 1
name = UnQual . HsIdent
infoToIds iF is =
let infoId = [(iF i, [oId i]) | i <- is]
info2id = sort $ M.toList $ M.fromListWith (++) infoId
in info2id
opcOpsFunBind n ((us, ds), rhss) = funBind [opcPVar, HsPTuple [us, ds]] n rhss
hsModule n e i d = HsModule dummySrcLoc (Module n) e i d
hsExportDataType n = HsEThingAll (name n)
hsExportVar n = HsEVar (name n)
unisonImport = hsImport "Unison"
instructionDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ ".SpecsGen." ++
targetName ++ "InstructionDecl")
registerDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ "." ++
targetName ++ "RegisterDecl")
itineraryDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ ".SpecsGen." ++
targetName ++ "ItineraryDecl")
registerClassDeclImport targetName =
hsImport ("Unison.Target." ++ targetName ++ ".SpecsGen." ++
targetName ++ "RegisterClassDecl")
hsImport n = HsImportDecl dummySrcLoc (Module n) False Nothing Nothing
funBind as n = hsFunBind n as
targetInstructionCon targetName = targetName ++ "Instruction"
simpleOpcFunBind n = hsFunBind n [opcPVar]
simpleFun op n = hsFun n [op]
constantFun n rhs = hsFun n [] rhs
hsFunBind n h rhss = mkHsFun n h (HsGuardedRhss rhss)
hsFun n h rhs = mkHsFun n h (HsUnGuardedRhs rhs)
mkHsFun n h g =
HsFunBind
[
HsMatch
dummySrcLoc
(HsIdent n)
h
g
[]
]
simpleErrorRhs n =
simpleFun (toHsPVar "a") n
(HsApp (toHsVar "error")
(HsParen
(HsInfixApp (toHsStr ("unmatched: " ++ n ++ " "))
(HsQVarOp (UnQual $ HsSymbol "++"))
(HsApp (toHsVar "show") (toHsVar "a")))))
hsDataDecl targetName cs =
HsDataDecl dummySrcLoc [] (HsIdent (targetInstructionCon targetName)) []
[HsConDecl dummySrcLoc (HsIdent (toOpType c)) [] | c <- cs]
[name "Eq", name "Ord"]
hsItinDecl targetName cs =
HsDataDecl dummySrcLoc [] (HsIdent (targetName ++ "Itinerary")) []
[HsConDecl dummySrcLoc (HsIdent (toOpType c)) [] | c <- cs]
[name "Eq", name "Ord", name "Read", name "Show"]
hsRegClassDecl targetName cs =
HsDataDecl dummySrcLoc [] (HsIdent (targetName ++ "RegisterClass")) []
[HsConDecl dummySrcLoc (HsIdent (toOpType c)) [] | c <- cs]
[name "Eq", name "Ord", name "Read", name "Show"]
hsInstDecl targetName ss =
HsInstDecl dummySrcLoc [] (name "Show")
[HsTyVar (HsIdent (targetInstructionCon targetName))] ss
opcPVar = toHsPVar "i"
mkOpcRhs f iF (info, ids) =
let sids = sort ids
idList = map f sids
hsInfo = iF info
i = toHsVar "i"
cond = HsInfixApp i (HsQVarOp (name "elem")) (HsList idList)
in HsGuardedRhs dummySrcLoc cond hsInfo
toHsStr = HsLit . HsString
toHsVar = HsVar . name
toHsInt = HsLit . HsInt
toHsCon = HsCon . name
toHsPStr = HsPLit . HsString
toHsPVar = HsPVar . HsIdent
toHsList = HsList
idToHsCon = toHsCon . toOpType
renameRedefs (l1, l2) = (l1, map (redefNameIfIn l1) l2)
redefNameIfIn l s = if s `elem` l then toRedefName s else s
toRedefName = (++ "'")
mkOperandMap a =
let o2info = map simplifyOperand a
o2info' = M.fromList o2info
in o2info'
toVarName "0" = "zero"
toVarName (c:l) = toLower c : l
toVarList = HsPList . map toHsPVar
toOpType (c:l) = stringReplace "." "" (toUpper c : l)
opToHsVar = toHsVar . toVarName
toConstantExtendedOp op = op ++ "_ce"
isConstantExtendedOp op = "_ce" `isSuffixOf` op
stringReplace s1 s2 = T.unpack . T.replace (T.pack s1) (T.pack s2) . T.pack
moduleName targetName suffix =
"Unison.Target." ++ targetName ++ ".SpecsGen." ++ suffix
|
cd34f6c824c41b91d9c72745432e96faed0b03a4a883c8a86bd49d2faf265af6 | TyOverby/mono | linux_ext.ml | open! Core
module Unix = Core_unix
module Thread = Core_thread
module Time_ns = Time_ns_unix
module File_descr = Unix.File_descr
module Syscall_result = Unix.Syscall_result
module Sysinfo0 = struct
type t =
{ uptime : Time.Span.t;
load1 : int;
load5 : int;
load15 : int;
total_ram : int;
free_ram : int;
shared_ram : int;
buffer_ram : int;
total_swap : int;
free_swap : int;
procs : int;
totalhigh : int;
freehigh : int;
mem_unit : int;
}
[@@deriving bin_io, sexp]
end
(* If you update this type, you also must update linux_tcpopt_bool, in the C stubs. (And
do make sure you get the order correct) *)
type tcp_bool_option = TCP_CORK | TCP_QUICKACK [@@deriving sexp, bin_io]
module Bound_to_interface = struct
type t = Any | Only of string [@@deriving sexp_of]
end
We use [ Int63 ] rather than [ Int ] because these flags use 32 bits .
module Epoll_flags (Flag_values : sig
val in_ : Int63.t
val out : Int63.t
(* val rdhup : Int63.t *)
val pri : Int63.t
val err : Int63.t
val hup : Int63.t
val et : Int63.t
val oneshot : Int63.t
end) = struct
let none = Int63.zero
include Flag_values
include Flags.Make (struct
let allow_intersecting = false
let should_print_error = true
let remove_zero_flags = false
let known =
[ in_, "in";
out, "out";
rdhup , " " ;
pri, "pri";
err, "err";
hup, "hup";
et, "et";
oneshot, "oneshot";
]
;;
end)
end
module Priority : sig
type t [@@deriving sexp]
val equal : t -> t -> bool
val of_int : int -> t
val to_int : t -> int
val incr : t -> t
val decr : t -> t
end = struct
type t = int [@@deriving sexp]
let of_int t = t
let to_int t = t
let incr t = t - 1
let decr t = t + 1
let equal (t : t) t' = t = t'
end
module Peer_credentials = struct
(* C code depends on the layout of the type *)
type t =
{ pid : Pid.t
; uid : int
; gid : int
}
[@@deriving sexp_of]
end
(* This expands a kernel command-line cpu-list string, which is a comma-separated list
with elements:
{|
N single value
N-M closed range
N-M:A/S groups of (A)mount in closed range with (S)tride
|}
See: -guide/kernel-parameters.html
*)
let cpu_list_of_string_exn str =
let parse_int_pair ~sep str =
try
(* NOTE: since we're dealing with CPUs, don't need to handle negatives. *)
String.lsplit2_exn str ~on:sep
|> Tuple2.map ~f:int_of_string
with
| _ ->
raise_s
[%message
"cpu_list_of_string_exn: expected separated integer pair"
(sep : char)
(str : string)]
in
let parse_range_pair str =
let first, last = parse_int_pair ~sep:'-' str in
if first > last
then
raise_s
[%message
"cpu_list_of_string_exn: range start is after end" (first : int) (last : int)]
else first, last
in
(* Empty cpu-list is represented as an empty string. *)
let parts = if String.(str = "") then [] else String.split ~on:',' str in
List.fold parts ~init:[] ~f:(fun acc part ->
(* first, see if we've got a ':' for a grouped range. *)
match String.lsplit2 part ~on:':', String.lsplit2 part ~on:'-' with
| None, None ->
(* Single value. *)
let cpu =
try int_of_string part with
| _ ->
raise_s
[%message "cpu_list_of_string_exn: expected integer" (part : string)]
in
acc @ [ cpu ]
| None, Some _range ->
(* Simple range. *)
let first, last = parse_range_pair part in
let rlist = List.init (last - first + 1) ~f:(Int.( + ) first) in
acc @ rlist
| Some (range, amt_stride), _ ->
let first, last = parse_range_pair range in
let amt, stride = parse_int_pair ~sep:'/' amt_stride in
if amt <= 0 || stride <= 0
then
(* A kernel won't treat these kindly, they're wrong and we'll
raise in this code. *)
raise_s
[%message
"cpu_list_of_string_exn: invalid grouped range stride or amount"
(amt : int)
(stride : int)]
else if amt >= stride
then (
(* odd, but valid: whole closed range. *)
let rlist = List.init (last - first + 1) ~f:(Int.( + ) first) in
acc @ rlist)
else (
(* This is probably simpler with procedural code, but
we'll do it functional-style :o). *)
let n_sublists =
Float.round_up ((last - first + 1) // stride) |> Float.to_int
in
let starts = List.init n_sublists ~f:(fun li -> first + (li * stride)) in
let rlist =
List.concat_map starts ~f:(fun start ->
let group_end = Int.min (start + (amt - 1)) last in
List.init (group_end - start + 1) ~f:(Int.( + ) start))
in
acc @ rlist))
|> List.dedup_and_sort ~compare:Int.compare
;;
let cpu_list_of_file_exn file =
match In_channel.with_file file ~f:In_channel.input_lines |> List.hd with
| None -> []
| Some cpu_list -> cpu_list_of_string_exn cpu_list
;;
let isolated_cpus =
Memo.unit (fun () -> cpu_list_of_file_exn "/sys/devices/system/cpu/isolated")
;;
let online_cpus =
Memo.unit (fun () -> cpu_list_of_file_exn "/sys/devices/system/cpu/online")
;;
let cpus_local_to_nic ~ifname =
cpu_list_of_file_exn (sprintf "/sys/class/net/%s/device/local_cpulist" ifname)
;;
(* These module contains definitions that get used when the necessary features are not
enabled. We put these somewhere where they'll always be compiled, to prevent them from
getting out of sync with the real implementations. *)
module Null_toplevel = struct
module Sysinfo = struct
include Sysinfo0
let sysinfo = Or_error.unimplemented "Linux_ext.Sysinfo.sysinfo"
end
let u = Or_error.unimplemented
let cores = u "Linux_ext.cores"
let cpu_list_of_string_exn = cpu_list_of_string_exn
let isolated_cpus = u "Linux_ext.isolated_cores"
let online_cpus = u "Linux_ext.online_cores"
let cpus_local_to_nic = u "Linux_ext.cpus_local_to_nic"
let file_descr_realpath = u "Linux_ext.file_descr_realpath"
let get_ipv4_address_for_interface = u "Linux_ext.get_ipv4_address_for_interface"
let get_mac_address = u "Linux_ext.get_mac_address"
let bind_to_interface = u "Linux_ext.bind_to_interface"
let get_bind_to_interface = u "Linux_ext.get_bind_to_interface"
let get_terminal_size = u "Linux_ext.get_terminal_size"
let gettcpopt_bool = u "Linux_ext.gettcpopt_bool"
let setpriority = u "Linux_ext.setpriority"
let getpriority = u "Linux_ext.getpriority"
let in_channel_realpath = u "Linux_ext.in_channel_realpath"
let out_channel_realpath = u "Linux_ext.out_channel_realpath"
let pr_get_name = u "Linux_ext.pr_get_name"
let pr_get_pdeathsig = u "Linux_ext.pr_get_pdeathsig"
let pr_set_name_first16 = u "Linux_ext.pr_set_name_first16"
let pr_set_pdeathsig = u "Linux_ext.pr_set_pdeathsig"
let sched_setaffinity = u "Linux_ext.sched_setaffinity"
let sched_getaffinity = u "Linux_ext.sched_getaffinity"
let sched_setaffinity_this_thread = u "Linux_ext.sched_setaffinity_this_thread"
let send_no_sigpipe = u "Linux_ext.send_no_sigpipe"
let send_nonblocking_no_sigpipe = u "Linux_ext.send_nonblocking_no_sigpipe"
let sendfile = u "Linux_ext.sendfile"
let sendmsg_nonblocking_no_sigpipe = u "Linux_ext.sendmsg_nonblocking_no_sigpipe"
let settcpopt_bool = u "Linux_ext.settcpopt_bool"
let peer_credentials = u "Linux_ext.peer_credentials"
module Epoll = struct
module Flags = Epoll_flags (struct
let in_ = Int63.of_int (1 lsl 0)
let out = Int63.of_int (1 lsl 1)
let = Int63.of_int ( 1 lsl 2 )
let pri = Int63.of_int (1 lsl 3)
let err = Int63.of_int (1 lsl 4)
let hup = Int63.of_int (1 lsl 5)
let et = Int63.of_int (1 lsl 6)
let oneshot = Int63.of_int (1 lsl 7)
end)
type t = [ `Epoll_is_not_implemented ] [@@deriving sexp_of]
let create = Or_error.unimplemented "Linux_ext.Epoll.create"
let close _ = assert false
let invariant _ = assert false
let find _ _ = assert false
let find_exn _ _ = assert false
let set _ _ _ = assert false
let remove _ _ = assert false
let iter _ ~f:_ = assert false
let fold _ ~init:_ ~f:_ = assert false
let wait _ ~timeout:_ = assert false
let wait_timeout_after _ _ = assert false
let iter_ready _ ~f:_ = assert false
let fold_ready _ ~init:_ ~f:_ = assert false
module Expert = struct
let clear_ready _ = assert false
end
(* let pwait _ ~timeout:_ _ = assert false *)
end
end
module Null : Linux_ext_intf.S = struct
type nonrec tcp_bool_option = tcp_bool_option =
TCP_CORK | TCP_QUICKACK
[@@deriving sexp, bin_io]
module Bound_to_interface = struct
type t = Bound_to_interface.t = Any | Only of string
[@@deriving sexp_of]
end
module Peer_credentials = Peer_credentials
module Priority = Priority
module Clock = struct
type t
let get = Or_error.unimplemented "Linux_ext.Clock.get"
let get_time = Or_error.unimplemented "Linux_ext.Clock.get_time"
let set_time = Or_error.unimplemented "Linux_ext.Clock.set_time"
let get_resolution = Or_error.unimplemented "Linux_ext.Clock.get_resolution"
let get_process_clock = Or_error.unimplemented "Linux_ext.Clock.get_process_clock"
let get_thread_clock = Or_error.unimplemented "Linux_ext.Clock.get_thread_clock"
end
module Eventfd = struct
type t = File_descr.t [@@deriving compare, sexp_of]
module Flags = struct
(* These (and flags below) are in octal to match the system header file
<bits/eventfd.h> *)
let nonblock = Int63.of_int 0o4000
let cloexec = Int63.of_int 0o2000000
let semaphore = Int63.of_int 0o1
include Flags.Make(struct
let allow_intersecting = true
let should_print_error = true
let remove_zero_flags = false
let known =
[ nonblock , "nonblock"
; cloexec , "cloexec"
; semaphore, "semaphore" ]
end)
end
let create = Or_error.unimplemented "Linux_ext.Eventfd.create"
let read _ = assert false
let write _ = assert false
let to_file_descr t = t
end
module Timerfd = struct
module Clock = struct
type t = unit [@@deriving bin_io, compare, sexp]
let realtime = ()
let monotonic = ()
end
module Flags = struct
let nonblock = Int63.of_int 0o4000
let cloexec = Int63.of_int 0o2000000
include Flags.Make (struct
let allow_intersecting = false
let should_print_error = true
let remove_zero_flags = false
let known =
List.rev
[ nonblock, "nonblock";
cloexec, "cloexec";
]
end)
end
type t = File_descr.t [@@deriving compare, sexp_of]
let to_file_descr t = t
type repeat =
{ fire_after : Time_ns.Span.t
; interval : Time_ns.Span.t
}
let create = Or_error.unimplemented "Linux_ext.Timerfd.create"
let set_at _ _ = assert false
let set_after _ _ = assert false
let set_repeating ?after:_ _ _ = assert false
let set_repeating_at _ _ _ = assert false
let clear _ = assert false
let get _ = assert false
module Private = struct
let unsafe_timerfd_settime _ = assert false
end
end
module Extended_file_attributes = struct
module Get_attr_result = struct
type t =
| Ok of string
| ENOATTR
| ERANGE
| ENOTSUP
[@@deriving sexp_of]
end
let getxattr = Or_error.unimplemented "Linux_ext.Extended_file_attributes.getxattr"
module Set_attr_result = struct
type t =
| Ok
| EEXIST
| ENOATTR
| ENOTSUP
[@@deriving sexp_of]
end
let setxattr = Or_error.unimplemented "Linux_ext.Extended_file_attributes.setxattr"
end
include Null_toplevel
end
module _ = Null
We leave a dummy reference to Null since it may trigger warning 60 ( unused - module )
depending on the conditional compilation below .
depending on the conditional compilation below. *)
[%%import "config.h"]
[%%ifdef JSC_POSIX_TIMERS]
module Clock = struct
type t
These functions should be in Unix , but due to the dependency on Time ,
this is not possible ( cyclic dependency ) .
this is not possible (cyclic dependency). *)
external get_time : t -> float = "core_unix_clock_gettime"
let get_time t = Time.Span.of_sec (get_time t)
external set_time : t -> float -> unit = "core_unix_clock_settime"
let set_time t s = set_time t (Time.Span.to_sec s)
external get_resolution : t -> float = "core_unix_clock_getres"
let get_resolution t = Time.Span.of_sec (get_resolution t)
external get_process_clock : unit -> t = "core_unix_clock_process_cputime_id_stub"
external get_thread_clock : unit -> t = "core_unix_clock_thread_cputime_id_stub"
[%%ifdef JSC_THREAD_CPUTIME]
external get : Thread.t -> t = "core_unix_pthread_getcpuclockid"
let get = Ok get
[%%else]
let get = Or_error.unimplemented "Linux_ext.Clock.get"
[%%endif]
let get_time = Ok get_time
let set_time = Ok set_time
let get_resolution = Ok get_resolution
let get_process_clock = Ok get_process_clock
let get_thread_clock = Ok get_thread_clock
end
[%%else]
module Clock = Null.Clock
[%%endif]
[%%ifdef JSC_TIMERFD]
module Timerfd = struct
module Clock : sig
type t [@@deriving bin_io, compare, sexp]
val realtime : t
val monotonic : t
end = struct
type t = Int63.t [@@deriving bin_io, compare, sexp]
external realtime : unit -> Int63.t = "core_linux_timerfd_CLOCK_REALTIME"
let realtime = realtime ()
external monotonic : unit -> Int63.t = "core_linux_timerfd_CLOCK_MONOTONIC"
let monotonic = monotonic ()
end
module Flags = struct
external nonblock : unit -> Int63.t = "core_linux_timerfd_TFD_NONBLOCK"
let nonblock = nonblock ()
external cloexec : unit -> Int63.t = "core_linux_timerfd_TFD_CLOEXEC"
let cloexec = cloexec ()
include Flags.Make (struct
let allow_intersecting = false
let should_print_error = true
let remove_zero_flags = false
let known =
List.rev
[ nonblock, "nonblock";
cloexec, "cloexec";
]
end)
end
type t = File_descr.t [@@deriving compare, sexp_of]
let to_file_descr t = t
external timerfd_create : Clock.t -> Flags.t -> int = "core_linux_timerfd_create"
At Jane Street , we link with [ --wrap timerfd_create ] so that we can use
our own wrapper around [ timerfd_create ] . This allows us to compile an executable on
a machine that has timerfd ( e.g. CentOS 6 ) but then run the executable on a machine
that does not ( e.g. CentOS 5 ) , but that has our wrapper library . We set up our
wrapper so that when running on a machine that does n't have it , [ timerfd_create ]
raises ENOSYS .
our own wrapper around [timerfd_create]. This allows us to compile an executable on
a machine that has timerfd (e.g. CentOS 6) but then run the executable on a machine
that does not (e.g. CentOS 5), but that has our wrapper library. We set up our
wrapper so that when running on a machine that doesn't have it, [timerfd_create]
raises ENOSYS. *)
let create =
let create ?(flags = Flags.empty) clock =
File_descr.of_int (timerfd_create clock flags)
in
match Result.try_with (fun () -> create Clock.realtime) with
| Ok t -> (Unix.close t; Ok create)
| Error (Unix.Unix_error (ENOSYS, _, _)) ->
Or_error.unimplemented "Linux_ext.Timerfd.create"
| Error _ ->
(* [timerfd_create] is implemented but fails with the arguments we used above.
[create] might still be usable with different arguments, so we expose it
here. *)
Ok create
;;
external unsafe_timerfd_settime
: t
-> bool
-> initial : Int63.t
-> interval : Int63.t
-> Syscall_result.Unit.t
= "core_linux_timerfd_settime" [@@noalloc]
let timerfd_settime t ~absolute ~initial ~interval =
(* We could accept [interval < 0] or [initial < 0 when absolute], but then the
conversions to timespecs in the C code become tedious and [timerfd_setttime] fails
when it gets anything negative anyway. *)
if Int63.O.( initial < zero || interval < zero )
then raise_s
[%sexp
"timerfd_settime got invalid parameters (initial < 0 or interval < 0).",
{ timerfd = (t : t)
; initial = (initial : Int63.t)
; interval = (interval : Int63.t)
}
];
unsafe_timerfd_settime t absolute ~initial ~interval
|> Syscall_result.Unit.ok_or_unix_error_exn ~syscall_name:"timerfd_settime"
;;
let initial_of_span span =
Time_ns.Span.to_int63_ns
(if Time_ns.Span.( <= ) span Time_ns.Span.zero
then Time_ns.Span.nanosecond
else span)
;;
let set_at t at =
if Time_ns.( <= ) at Time_ns.epoch
then failwiths ~here:[%here] "Timerfd.set_at got time before epoch" at [%sexp_of: Time_ns.t];
timerfd_settime t
~absolute:true
~initial:(Time_ns.to_int63_ns_since_epoch at)
~interval:Int63.zero
;;
let set_after t span =
timerfd_settime t
~absolute:false
~initial:(initial_of_span span)
~interval:Int63.zero
;;
let set_repeating ?after t interval =
if Time_ns.Span.( <= ) interval Time_ns.Span.zero
then failwiths ~here:[%here] "Timerfd.set_repeating got invalid interval" interval
[%sexp_of: Time_ns.Span.t];
let interval = Time_ns.Span.to_int63_ns interval in
timerfd_settime t
~absolute:false
~initial:(Option.value_map after ~f:initial_of_span ~default:interval)
~interval
;;
let set_repeating_at t at (interval : Time_ns.Span.t) =
if Time_ns.( <= ) at Time_ns.epoch
then failwiths ~here:[%here] "Timerfd.set_repeating_at got time before epoch" at [%sexp_of: Time_ns.t];
if Time_ns.Span.( <= ) interval Time_ns.Span.zero
then failwiths ~here:[%here] "Timerfd.set_repeating_at got invalid interval" interval
[%sexp_of: Time_ns.Span.t];
let interval = Time_ns.Span.to_int63_ns interval in
timerfd_settime t
~absolute:true
~initial:(Time_ns.to_int63_ns_since_epoch at)
~interval
;;
let clear t =
timerfd_settime t ~absolute:false ~initial:Int63.zero ~interval:Int63.zero
type repeat =
{ fire_after : Time_ns.Span.t
; interval : Time_ns.Span.t
}
external timerfd_gettime : t -> repeat = "core_linux_timerfd_gettime"
let get t =
let spec = timerfd_gettime t in
if Time_ns.Span.equal spec.interval Time_ns.Span.zero
then
if Time_ns.Span.equal spec.fire_after Time_ns.Span.zero
then `Not_armed
else `Fire_after spec.fire_after
else
`Repeat spec
;;
module Private = struct
let unsafe_timerfd_settime = unsafe_timerfd_settime
end
end
[%%else]
module Timerfd = Null.Timerfd
[%%endif]
[%%ifdef JSC_LINUX_EXT]
type file_descr = Unix.File_descr.t
module Eventfd = struct
module Flags = struct
external cloexec : unit -> Int63.t = "core_linux_eventfd_EFD_CLOEXEC"
external nonblock : unit -> Int63.t = "core_linux_eventfd_EFD_NONBLOCK"
external semaphore : unit -> Int63.t = "core_linux_eventfd_EFD_SEMAPHORE"
let cloexec = cloexec ()
let nonblock = nonblock ()
let semaphore = semaphore ()
let known =
[ cloexec , "cloexec"
; nonblock , "nonblock"
; semaphore, "semaphore" ]
include Flags.Make (struct
let allow_intersecting = true
let should_print_error = true
let known = known
let remove_zero_flags = false
end)
end
type t = File_descr.t [@@deriving compare, sexp_of]
external create : Int32.t -> Flags.t -> t = "core_linux_eventfd"
external read : t -> Int64.t = "core_linux_eventfd_read"
external write : t -> Int64.t -> unit = "core_linux_eventfd_write"
let create =
let create ?(flags=Flags.empty) init = create init flags in
Or_error.return create
let to_file_descr t = t
end
external sendfile
: sock : file_descr -> fd : file_descr -> pos : int -> len : int -> int
= "core_linux_sendfile_stub"
;;
let sendfile ?(pos = 0) ?len ~fd sock =
let len =
match len with
| Some len -> len
| None -> Int64.to_int_exn (Int64.( - ) (Unix.fstat fd).st_size (Int64.of_int pos))
in
sendfile ~sock ~fd ~pos ~len
(* Raw result of sysinfo syscall *)
module Raw_sysinfo = struct
type t = {
uptime : int;
load1 : int;
load5 : int;
load15 : int;
total_ram : int;
free_ram : int;
shared_ram : int;
buffer_ram : int;
total_swap : int;
free_swap : int;
procs : int;
totalhigh : int;
freehigh : int;
mem_unit : int;
}
end
module Sysinfo = struct
include Sysinfo0
external raw_sysinfo : unit -> Raw_sysinfo.t = "core_linux_sysinfo"
let sysinfo = Ok (fun () ->
let raw = raw_sysinfo () in
{
uptime = Time.Span.of_int_sec raw.Raw_sysinfo.uptime;
load1 = raw.Raw_sysinfo.load1;
load5 = raw.Raw_sysinfo.load5;
load15 = raw.Raw_sysinfo.load15;
total_ram = raw.Raw_sysinfo.total_ram;
free_ram = raw.Raw_sysinfo.free_ram;
shared_ram = raw.Raw_sysinfo.shared_ram;
buffer_ram = raw.Raw_sysinfo.buffer_ram;
total_swap = raw.Raw_sysinfo.total_swap;
free_swap = raw.Raw_sysinfo.free_swap;
procs = raw.Raw_sysinfo.procs;
totalhigh = raw.Raw_sysinfo.totalhigh;
freehigh = raw.Raw_sysinfo.freehigh;
mem_unit = raw.Raw_sysinfo.mem_unit;
})
end
external gettcpopt_bool
: file_descr -> tcp_bool_option -> bool = "core_linux_gettcpopt_bool_stub"
external settcpopt_bool
: file_descr -> tcp_bool_option -> bool -> unit = "core_linux_settcpopt_bool_stub"
external peer_credentials : file_descr -> Peer_credentials.t = "core_linux_peer_credentials"
external unsafe_send_nonblocking_no_sigpipe
: file_descr -> pos : int -> len : int -> Bytes.t -> int
= "core_linux_send_nonblocking_no_sigpipe_stub"
let unsafe_send_nonblocking_no_sigpipe fd ~pos ~len buf =
let res = unsafe_send_nonblocking_no_sigpipe fd ~pos ~len buf in
if res = -1 then None
else Some res
external unsafe_send_no_sigpipe
: file_descr -> pos : int -> len : int -> Bytes.t -> int
= "core_linux_send_no_sigpipe_stub"
let check_send_args ?pos ?len buf =
let str_len = Bytes.length buf in
let pos =
match pos with
| None -> 0
| Some pos ->
if pos < 0 then invalid_arg "send_nonblocking_no_sigpipe: pos < 0";
if pos > str_len then
invalid_arg "send_nonblocking_no_sigpipe: pos > str_len";
pos
in
let len =
match len with
| None -> str_len - pos
| Some len ->
if len < 0 then invalid_arg "send_nonblocking_no_sigpipe: pos < 0";
if pos + len > str_len then
invalid_arg "send_nonblocking_no_sigpipe: pos + len > str_len";
len
in
(pos, len)
let send_nonblocking_no_sigpipe sock ?pos ?len buf =
let (pos, len) = check_send_args ?pos ?len buf in
unsafe_send_nonblocking_no_sigpipe sock ~pos ~len buf
let send_no_sigpipe sock ?pos ?len buf =
let (pos, len) = check_send_args ?pos ?len buf in
unsafe_send_no_sigpipe sock ~pos ~len buf
external unsafe_sendmsg_nonblocking_no_sigpipe
: file_descr -> string Unix.IOVec.t array -> int -> int
= "core_linux_sendmsg_nonblocking_no_sigpipe_stub"
let unsafe_sendmsg_nonblocking_no_sigpipe fd iovecs count =
let res = unsafe_sendmsg_nonblocking_no_sigpipe fd iovecs count in
if res = -1 then None
else Some res
let sendmsg_nonblocking_no_sigpipe sock ?count iovecs =
let count =
match count with
| None -> Array.length iovecs
| Some count ->
if count < 0 then
invalid_arg "sendmsg_nonblocking_no_sigpipe: count < 0";
let n_iovecs = Array.length iovecs in
if count > n_iovecs then
invalid_arg "sendmsg_nonblocking_no_sigpipe: count > n_iovecs";
count
in
unsafe_sendmsg_nonblocking_no_sigpipe sock iovecs count
external pr_set_pdeathsig : Signal.t -> unit = "core_linux_pr_set_pdeathsig_stub"
external pr_get_pdeathsig : unit -> Signal.t = "core_linux_pr_get_pdeathsig_stub"
external pr_set_name_first16 : string -> unit = "core_linux_pr_set_name"
external pr_get_name : unit -> string = "core_linux_pr_get_name"
let file_descr_realpath fd =
Filename_unix.realpath ("/proc/self/fd/" ^ File_descr.to_string fd)
let out_channel_realpath oc = file_descr_realpath (Unix.descr_of_out_channel oc)
let in_channel_realpath ic = file_descr_realpath (Unix.descr_of_in_channel ic)
external raw_sched_setaffinity
: pid : int -> cpuset : int list -> unit = "core_linux_sched_setaffinity"
let sched_setaffinity ?pid ~cpuset () =
let pid = match pid with None -> 0 | Some pid -> Pid.to_int pid in
raw_sched_setaffinity ~pid ~cpuset
;;
external raw_sched_getaffinity
: pid : int -> int list = "core_linux_sched_getaffinity"
let sched_getaffinity ?pid () =
let pid = match pid with None -> 0 | Some pid -> Pid.to_int pid in
raw_sched_getaffinity ~pid
;;
(* defined in unix_stubs.c *)
external gettid : unit -> int = "core_unix_gettid"
external setpriority : Priority.t -> unit = "core_linux_setpriority"
external getpriority : unit -> Priority.t = "core_linux_getpriority"
let sched_setaffinity_this_thread ~cpuset =
sched_setaffinity ~pid:(Pid.of_int (gettid ())) ~cpuset ()
;;
let cores =
Memo.unit (fun () ->
let num_cores =
In_channel.with_file "/proc/cpuinfo" ~f:In_channel.input_lines
|> List.fold_left ~init:0 ~f:(fun count line ->
count +
(match String.lsplit2 ~on:':' line with
| None -> 0
| Some (label, _) ->
if String.(=) (String.rstrip label) "processor" then 1
else 0))
in
if num_cores > 0 then num_cores
else failwith "Linux_ext.cores: failed to parse /proc/cpuinfo")
external get_terminal_size : File_descr.t -> int * int = "core_linux_get_terminal_size"
let get_terminal_size = function
| `Fd fd -> get_terminal_size fd
| `Controlling ->
protectx
(Unix.openfile "/dev/tty" ~mode:[ O_RDWR ] ~perm:0)
~finally:Unix.close
~f:get_terminal_size
external get_ipv4_address_for_interface : string -> string =
"core_linux_get_ipv4_address_for_interface" ;;
external get_mac_address : ifname : string -> string =
"core_linux_get_mac_address" ;;
(* The C-stub is a simple pass-through of the linux SO_BINDTODEVICE semantics, wherein an
empty string removes any binding *)
external bind_to_interface' : File_descr.t -> string -> unit =
"core_linux_bind_to_interface" ;;
let bind_to_interface fd ifname =
let name =
match ifname with
| Bound_to_interface.Only name -> name
| Bound_to_interface.Any -> ""
in
bind_to_interface' fd name
;;
external get_bind_to_interface' : File_descr.t -> string =
"core_linux_get_bind_to_interface" ;;
let get_bind_to_interface fd =
match get_bind_to_interface' fd with
| "" -> Bound_to_interface.Any
| name -> Bound_to_interface.Only name
module Epoll = struct
external flag_epollin : unit -> Int63.t = "core_linux_epoll_EPOLLIN_flag"
external flag_epollout : unit -> Int63.t = "core_linux_epoll_EPOLLOUT_flag"
(* external flag_epollrdhup : unit -> Int63.t = "core_linux_epoll_EPOLLRDHUP_flag" *)
external flag_epollpri : unit -> Int63.t = "core_linux_epoll_EPOLLPRI_flag"
external flag_epollerr : unit -> Int63.t = "core_linux_epoll_EPOLLERR_flag"
external flag_epollhup : unit -> Int63.t = "core_linux_epoll_EPOLLHUP_flag"
external flag_epollet : unit -> Int63.t = "core_linux_epoll_EPOLLET_flag"
external flag_epolloneshot : unit -> Int63.t = "core_linux_epoll_EPOLLONESHOT_flag"
module Flags = Epoll_flags (struct
let in_ = flag_epollin ()
let out = flag_epollout ()
let = flag_epollrdhup ( )
let pri = flag_epollpri ()
let err = flag_epollerr ()
let hup = flag_epollhup ()
let et = flag_epollet ()
let oneshot = flag_epolloneshot ()
end)
external epoll_create : unit -> File_descr.t = "core_linux_epoll_create"
Some justification for the below interface : Unlike select ( ) and poll ( ) , epoll ( ) fills
in an array of ready events , analogous to a read ( ) call where you pass in a buffer to
be filled .
Since this is at the core of the I / O loop , we 'd like to avoid reallocating that
buffer on every call to poll . We 're allocating the array on the ocaml side ( as a
Bigstring ) , then iterating through it in - place , reducing allocation , copies , and any
intermediate lists . For very high message rates and many fds this could be a very
beneficial .
in an array of ready events, analogous to a read() call where you pass in a buffer to
be filled.
Since this is at the core of the I/O loop, we'd like to avoid reallocating that
buffer on every call to poll. We're allocating the array on the ocaml side (as a
Bigstring), then iterating through it in-place, reducing allocation, copies, and any
intermediate lists. For very high message rates and many fds this could be a very
beneficial. *)
type ready_events = Bigstring.t
external epoll_sizeof_epoll_event
: unit -> int = "core_linux_epoll_sizeof_epoll_event" [@@noalloc]
external epoll_offsetof_readyfd
: unit -> int = "core_linux_epoll_offsetof_readyfd" [@@noalloc]
external epoll_offsetof_readyflags
: unit -> int = "core_linux_epoll_offsetof_readyflags" [@@noalloc]
let sizeof_epoll_event = epoll_sizeof_epoll_event ()
let offsetof_readyfd = epoll_offsetof_readyfd ()
let offsetof_readyflags = epoll_offsetof_readyflags ()
external epoll_ctl_add
: File_descr.t -> File_descr.t -> Flags.t -> unit
= "core_linux_epoll_ctl_add"
external epoll_ctl_mod
: File_descr.t -> File_descr.t -> Flags.t -> unit
= "core_linux_epoll_ctl_mod"
external epoll_ctl_del
: File_descr.t -> File_descr.t -> unit
= "core_linux_epoll_ctl_del"
module Table = Bounded_int_table
module T = struct
type 'a t =
{ epollfd : File_descr.t;
[ flags_by_fd ] has one entry for each file - descr in the epoll set , and stores
the epoll flags that the kernel 's epoll set currently has for that
file - descr . Keeping our own representation of the kernel data structure is
useful for debugging , since the information appears in a human - readable way
in [ sexp_of_t ] 's output . It also allows us to hide the distinction between
[ epoll_ctl_add ] and [ epoll_ctl_mod ] , since we know which to use based on
whether the file descriptor is already being watched .
the epoll flags that the kernel's epoll set currently has for that
file-descr. Keeping our own representation of the kernel data structure is
useful for debugging, since the information appears in a human-readable way
in [sexp_of_t]'s output. It also allows us to hide the distinction between
[epoll_ctl_add] and [epoll_ctl_mod], since we know which to use based on
whether the file descriptor is already being watched. *)
flags_by_fd : (File_descr.t, Flags.t) Table.t;
max_ready_events : int;
(* [num_ready_events] holds the number of ready events in [ready_events], as
determined by the last call to [wait]. *)
mutable num_ready_events : int;
ready_events : 'a;
}
[@@deriving fields, sexp_of]
end
open T
let epoll_readyfd t i =
Bigstring.unsafe_get_int32_le
t
~pos:(i*sizeof_epoll_event + offsetof_readyfd)
|> File_descr.of_int
;;
let epoll_readyflags t i =
Bigstring.unsafe_get_int32_le
t
~pos:(i*sizeof_epoll_event + offsetof_readyflags)
|> Flags.of_int
;;
type in_use = ready_events T.t
module Pretty = struct
type ready_event =
{ file_descr : File_descr.t;
flags : Flags.t;
}
[@@deriving sexp_of]
type ready_events = ready_event array [@@deriving sexp_of]
type t = ready_events T.t [@@deriving sexp_of]
end
let to_pretty t =
{ t with
ready_events =
Array.init t.num_ready_events ~f:(fun i ->
{ Pretty.
file_descr = epoll_readyfd t.ready_events i;
flags = epoll_readyflags t.ready_events i;
});
}
;;
let sexp_of_in_use t = Pretty.sexp_of_t (to_pretty t)
type t = [ `Closed | `In_use of in_use ] ref [@@deriving sexp_of]
let close t =
match !t with
| `Closed -> ()
| `In_use { epollfd; _ } ->
t := `Closed;
Unix.close epollfd;
;;
let invariant t : unit =
match !t with
| `Closed -> ()
| `In_use t ->
try
let check f field = f (Field.get field t) in
Fields.iter
~epollfd:ignore
~flags_by_fd:(check (Table.invariant ignore ignore))
~max_ready_events:(check (fun max_ready_events -> assert (max_ready_events > 0)))
~num_ready_events:(check (fun num_ready -> assert (num_ready >= 0)))
~ready_events:ignore
with exn ->
failwiths ~here:[%here] "Epoll.invariant failed" (exn, t) [%sexp_of: exn * in_use]
;;
let create ~num_file_descrs ~max_ready_events =
if max_ready_events < 0 then
failwiths ~here:[%here] "Epoll.create got nonpositive max_ready_events" max_ready_events
([%sexp_of: int]);
ref (`In_use
{ epollfd = epoll_create ();
flags_by_fd =
Table.create
~num_keys:num_file_descrs
~key_to_int:File_descr.to_int
~sexp_of_key:File_descr.sexp_of_t
();
max_ready_events;
num_ready_events = 0;
ready_events = Bigstring.create (sizeof_epoll_event * max_ready_events);
})
;;
let in_use_exn t =
match !t with
| `Closed -> failwith "attempt to use closed epoll set"
| `In_use r -> r
;;
let find t file_descr =
let t = in_use_exn t in
Table.find t.flags_by_fd file_descr
;;
let find_exn t file_descr =
let t = in_use_exn t in
Table.find_exn t.flags_by_fd file_descr
;;
let iter t ~f =
let t = in_use_exn t in
Table.iteri t.flags_by_fd ~f:(fun ~key:file_descr ~data:flags ->
f file_descr flags)
;;
let fold t ~init ~f =
let t = in_use_exn t in
Table.fold t.flags_by_fd ~init ~f:(fun ~key ~data -> f key data)
let set t fd flags =
let t = in_use_exn t in
let already_present = Table.mem t.flags_by_fd fd in
Both [ epoll_ctl_add ] and [ epoll_ctl_mod ] may raise if the file descriptor does not
support polling . Perform these operations first and let them raise before modifying
the table to reflect the change in epoll state .
support polling. Perform these operations first and let them raise before modifying
the table to reflect the change in epoll state. *)
let () =
if already_present
then
epoll_ctl_mod t.epollfd fd flags
else
epoll_ctl_add t.epollfd fd flags
in
Table.set t.flags_by_fd ~key:fd ~data:flags
;;
let remove t fd =
let t = in_use_exn t in
if Table.mem t.flags_by_fd fd then epoll_ctl_del t.epollfd fd;
Table.remove t.flags_by_fd fd
;;
external epoll_wait : File_descr.t -> ready_events -> int -> int = "core_linux_epoll_wait"
let wait_internal t ~timeout_ms =
let t = in_use_exn t in
(* We clear [num_ready_events] because [epoll_wait] will invalidate [ready_events],
and we don't want another thread to observe [t] and see junk. *)
t.num_ready_events <- 0;
t.num_ready_events <- epoll_wait t.epollfd t.ready_events timeout_ms;
if t.num_ready_events = 0 then `Timeout else `Ok
;;
let wait_timeout_after t span =
let timeout_ms =
if Time_ns.Span.( <= ) span Time_ns.Span.zero
then 0
else
For positive timeouts , we use a minimum timeout of one millisecond , to ensure
that we are guaranteed that the timeout has passed when we wake up . If we
allowed a positive sub - millisecond timeout , we would round down and end up
using a timeout of zero , causing [ wait_internal ] to return immediately . Such
behaviour has been seen to cause Async to spin , repeatedly requesting slightly
smaller timeouts .
that we are guaranteed that the timeout has passed when we wake up. If we
allowed a positive sub-millisecond timeout, we would round down and end up
using a timeout of zero, causing [wait_internal] to return immediately. Such
behaviour has been seen to cause Async to spin, repeatedly requesting slightly
smaller timeouts. *)
let span = Time_ns.Span.max span Time_ns.Span.millisecond in
Int63.to_int_exn
Time_ns.Span.(div
(span + of_int63_ns (Int63.of_int 500_000))
(of_int63_ns (Int63.of_int 1_000_000)))
in
assert (timeout_ms >= 0);
wait_internal t ~timeout_ms
;;
let wait t ~timeout =
From the epoll man page :
| Specifying a timeout of -1 makes epoll_wait ( ) wait indefinitely , while
| specifying a timeout equal to zero makes epoll_wait ( ) to return immediately
| even if no events are available ( return code equal to zero ) .
| Specifying a timeout of -1 makes epoll_wait() wait indefinitely, while
| specifying a timeout equal to zero makes epoll_wait() to return immediately
| even if no events are available (return code equal to zero). *)
match timeout with
| `Never -> wait_internal t ~timeout_ms:(-1)
| `Immediately -> wait_internal t ~timeout_ms:0
| `After span -> wait_timeout_after t span
;;
let fold_ready t ~init ~f =
let t = in_use_exn t in
let ac = ref init in
for i = 0 to t.num_ready_events - 1 do
ac := f !ac (epoll_readyfd t.ready_events i) (epoll_readyflags t.ready_events i)
done;
!ac
;;
let iter_ready t ~f =
let t = in_use_exn t in
for i = 0 to t.num_ready_events - 1 do
f (epoll_readyfd t.ready_events i) (epoll_readyflags t.ready_events i)
done
;;
module Expert = struct
let clear_ready t =
let t = in_use_exn t in
t.num_ready_events <- 0
;;
end
external epoll_pwait
* : File_descr.t - > Events_buffer.raw - > int - > int list - > int
* = " core_linux_epoll_pwait "
*
* let pwait t ~timeout sigs =
* let millis = Float.iround_exn ~dir:`Zero ( Span.to_ms timeout ) in
* let num_ready = epoll_pwait t.epollfd t.events in
* if num_ready = 0 then ` Timeout
* else ` Ok { Ready_fds.num_ready ; events = t.events }
* ; ;
* : File_descr.t -> Events_buffer.raw -> int -> int list -> int
* = "core_linux_epoll_pwait"
*
* let pwait t ~timeout sigs =
* let millis = Float.iround_exn ~dir:`Zero ( Span.to_ms timeout ) in
* let num_ready = epoll_pwait t.epollfd t.events millis sigs in
* if num_ready = 0 then `Timeout
* else `Ok { Ready_fds.num_ready ; events = t.events }
* ;; *)
let create = Ok create
end
let cores = Ok cores
let isolated_cpus = Ok isolated_cpus
let online_cpus = Ok online_cpus
let cpus_local_to_nic = Ok cpus_local_to_nic
let file_descr_realpath = Ok file_descr_realpath
let get_ipv4_address_for_interface = Ok get_ipv4_address_for_interface
let get_mac_address = Ok get_mac_address
let bind_to_interface = Ok bind_to_interface
let get_bind_to_interface = Ok get_bind_to_interface
let get_terminal_size = Ok get_terminal_size
let gettcpopt_bool = Ok gettcpopt_bool
let setpriority = Ok setpriority
let getpriority = Ok getpriority
let in_channel_realpath = Ok in_channel_realpath
let out_channel_realpath = Ok out_channel_realpath
let pr_get_name = Ok pr_get_name
let pr_get_pdeathsig = Ok pr_get_pdeathsig
let pr_set_name_first16 = Ok pr_set_name_first16
let pr_set_pdeathsig = Ok pr_set_pdeathsig
let sched_setaffinity = Ok sched_setaffinity
let sched_getaffinity = Ok sched_getaffinity
let sched_setaffinity_this_thread = Ok sched_setaffinity_this_thread
let send_no_sigpipe = Ok send_no_sigpipe
let send_nonblocking_no_sigpipe = Ok send_nonblocking_no_sigpipe
let sendfile = Ok sendfile
let sendmsg_nonblocking_no_sigpipe = Ok sendmsg_nonblocking_no_sigpipe
let settcpopt_bool = Ok settcpopt_bool
let peer_credentials = Ok peer_credentials
module Extended_file_attributes = struct
module Flags = struct
external only_create : unit -> Int63.t = "core_linux_xattr_XATTR_CREATE_flag"
external only_replace : unit -> Int63.t = "core_linux_xattr_XATTR_REPLACE_flag"
let set = Int63.zero
end
module Get_attr_result = struct
type t =
| Ok of string
| ENOATTR
| ERANGE
| ENOTSUP
[@@deriving sexp_of]
end
module Set_attr_result = struct
type t =
| Ok
| EEXIST
| ENOATTR
| ENOTSUP
[@@deriving sexp_of]
end
external getxattr : string -> string -> Get_attr_result.t = "core_linux_getxattr"
external setxattr : string -> string -> string -> Int63.t -> Set_attr_result.t = "core_linux_setxattr"
let getxattr ~path ~name =
getxattr path name
;;
let setxattr ?(how = `Set) ~path ~name ~value () =
let flags =
match how with
| `Set -> Flags.set
| `Create -> Flags.only_create ()
| `Replace -> Flags.only_replace ()
in
setxattr path name value flags
;;
let getxattr = Ok getxattr
let setxattr = Ok setxattr
end
[%%else]
include Null_toplevel
module Eventfd = Null.Eventfd
module Extended_file_attributes = Null.Extended_file_attributes
[%%endif]
| null | https://raw.githubusercontent.com/TyOverby/mono/146b39835a8c2714d37a55d46cd7c7e43755c3b0/vendor/janestreet-core_unix/linux_ext/src/linux_ext.ml | ocaml | If you update this type, you also must update linux_tcpopt_bool, in the C stubs. (And
do make sure you get the order correct)
val rdhup : Int63.t
C code depends on the layout of the type
This expands a kernel command-line cpu-list string, which is a comma-separated list
with elements:
{|
N single value
N-M closed range
N-M:A/S groups of (A)mount in closed range with (S)tride
|}
See: -guide/kernel-parameters.html
NOTE: since we're dealing with CPUs, don't need to handle negatives.
Empty cpu-list is represented as an empty string.
first, see if we've got a ':' for a grouped range.
Single value.
Simple range.
A kernel won't treat these kindly, they're wrong and we'll
raise in this code.
odd, but valid: whole closed range.
This is probably simpler with procedural code, but
we'll do it functional-style :o).
These module contains definitions that get used when the necessary features are not
enabled. We put these somewhere where they'll always be compiled, to prevent them from
getting out of sync with the real implementations.
let pwait _ ~timeout:_ _ = assert false
These (and flags below) are in octal to match the system header file
<bits/eventfd.h>
[timerfd_create] is implemented but fails with the arguments we used above.
[create] might still be usable with different arguments, so we expose it
here.
We could accept [interval < 0] or [initial < 0 when absolute], but then the
conversions to timespecs in the C code become tedious and [timerfd_setttime] fails
when it gets anything negative anyway.
Raw result of sysinfo syscall
defined in unix_stubs.c
The C-stub is a simple pass-through of the linux SO_BINDTODEVICE semantics, wherein an
empty string removes any binding
external flag_epollrdhup : unit -> Int63.t = "core_linux_epoll_EPOLLRDHUP_flag"
[num_ready_events] holds the number of ready events in [ready_events], as
determined by the last call to [wait].
We clear [num_ready_events] because [epoll_wait] will invalidate [ready_events],
and we don't want another thread to observe [t] and see junk. | open! Core
module Unix = Core_unix
module Thread = Core_thread
module Time_ns = Time_ns_unix
module File_descr = Unix.File_descr
module Syscall_result = Unix.Syscall_result
module Sysinfo0 = struct
type t =
{ uptime : Time.Span.t;
load1 : int;
load5 : int;
load15 : int;
total_ram : int;
free_ram : int;
shared_ram : int;
buffer_ram : int;
total_swap : int;
free_swap : int;
procs : int;
totalhigh : int;
freehigh : int;
mem_unit : int;
}
[@@deriving bin_io, sexp]
end
type tcp_bool_option = TCP_CORK | TCP_QUICKACK [@@deriving sexp, bin_io]
module Bound_to_interface = struct
type t = Any | Only of string [@@deriving sexp_of]
end
We use [ Int63 ] rather than [ Int ] because these flags use 32 bits .
module Epoll_flags (Flag_values : sig
val in_ : Int63.t
val out : Int63.t
val pri : Int63.t
val err : Int63.t
val hup : Int63.t
val et : Int63.t
val oneshot : Int63.t
end) = struct
let none = Int63.zero
include Flag_values
include Flags.Make (struct
let allow_intersecting = false
let should_print_error = true
let remove_zero_flags = false
let known =
[ in_, "in";
out, "out";
rdhup , " " ;
pri, "pri";
err, "err";
hup, "hup";
et, "et";
oneshot, "oneshot";
]
;;
end)
end
module Priority : sig
type t [@@deriving sexp]
val equal : t -> t -> bool
val of_int : int -> t
val to_int : t -> int
val incr : t -> t
val decr : t -> t
end = struct
type t = int [@@deriving sexp]
let of_int t = t
let to_int t = t
let incr t = t - 1
let decr t = t + 1
let equal (t : t) t' = t = t'
end
module Peer_credentials = struct
type t =
{ pid : Pid.t
; uid : int
; gid : int
}
[@@deriving sexp_of]
end
let cpu_list_of_string_exn str =
let parse_int_pair ~sep str =
try
String.lsplit2_exn str ~on:sep
|> Tuple2.map ~f:int_of_string
with
| _ ->
raise_s
[%message
"cpu_list_of_string_exn: expected separated integer pair"
(sep : char)
(str : string)]
in
let parse_range_pair str =
let first, last = parse_int_pair ~sep:'-' str in
if first > last
then
raise_s
[%message
"cpu_list_of_string_exn: range start is after end" (first : int) (last : int)]
else first, last
in
let parts = if String.(str = "") then [] else String.split ~on:',' str in
List.fold parts ~init:[] ~f:(fun acc part ->
match String.lsplit2 part ~on:':', String.lsplit2 part ~on:'-' with
| None, None ->
let cpu =
try int_of_string part with
| _ ->
raise_s
[%message "cpu_list_of_string_exn: expected integer" (part : string)]
in
acc @ [ cpu ]
| None, Some _range ->
let first, last = parse_range_pair part in
let rlist = List.init (last - first + 1) ~f:(Int.( + ) first) in
acc @ rlist
| Some (range, amt_stride), _ ->
let first, last = parse_range_pair range in
let amt, stride = parse_int_pair ~sep:'/' amt_stride in
if amt <= 0 || stride <= 0
then
raise_s
[%message
"cpu_list_of_string_exn: invalid grouped range stride or amount"
(amt : int)
(stride : int)]
else if amt >= stride
then (
let rlist = List.init (last - first + 1) ~f:(Int.( + ) first) in
acc @ rlist)
else (
let n_sublists =
Float.round_up ((last - first + 1) // stride) |> Float.to_int
in
let starts = List.init n_sublists ~f:(fun li -> first + (li * stride)) in
let rlist =
List.concat_map starts ~f:(fun start ->
let group_end = Int.min (start + (amt - 1)) last in
List.init (group_end - start + 1) ~f:(Int.( + ) start))
in
acc @ rlist))
|> List.dedup_and_sort ~compare:Int.compare
;;
let cpu_list_of_file_exn file =
match In_channel.with_file file ~f:In_channel.input_lines |> List.hd with
| None -> []
| Some cpu_list -> cpu_list_of_string_exn cpu_list
;;
let isolated_cpus =
Memo.unit (fun () -> cpu_list_of_file_exn "/sys/devices/system/cpu/isolated")
;;
let online_cpus =
Memo.unit (fun () -> cpu_list_of_file_exn "/sys/devices/system/cpu/online")
;;
let cpus_local_to_nic ~ifname =
cpu_list_of_file_exn (sprintf "/sys/class/net/%s/device/local_cpulist" ifname)
;;
module Null_toplevel = struct
module Sysinfo = struct
include Sysinfo0
let sysinfo = Or_error.unimplemented "Linux_ext.Sysinfo.sysinfo"
end
let u = Or_error.unimplemented
let cores = u "Linux_ext.cores"
let cpu_list_of_string_exn = cpu_list_of_string_exn
let isolated_cpus = u "Linux_ext.isolated_cores"
let online_cpus = u "Linux_ext.online_cores"
let cpus_local_to_nic = u "Linux_ext.cpus_local_to_nic"
let file_descr_realpath = u "Linux_ext.file_descr_realpath"
let get_ipv4_address_for_interface = u "Linux_ext.get_ipv4_address_for_interface"
let get_mac_address = u "Linux_ext.get_mac_address"
let bind_to_interface = u "Linux_ext.bind_to_interface"
let get_bind_to_interface = u "Linux_ext.get_bind_to_interface"
let get_terminal_size = u "Linux_ext.get_terminal_size"
let gettcpopt_bool = u "Linux_ext.gettcpopt_bool"
let setpriority = u "Linux_ext.setpriority"
let getpriority = u "Linux_ext.getpriority"
let in_channel_realpath = u "Linux_ext.in_channel_realpath"
let out_channel_realpath = u "Linux_ext.out_channel_realpath"
let pr_get_name = u "Linux_ext.pr_get_name"
let pr_get_pdeathsig = u "Linux_ext.pr_get_pdeathsig"
let pr_set_name_first16 = u "Linux_ext.pr_set_name_first16"
let pr_set_pdeathsig = u "Linux_ext.pr_set_pdeathsig"
let sched_setaffinity = u "Linux_ext.sched_setaffinity"
let sched_getaffinity = u "Linux_ext.sched_getaffinity"
let sched_setaffinity_this_thread = u "Linux_ext.sched_setaffinity_this_thread"
let send_no_sigpipe = u "Linux_ext.send_no_sigpipe"
let send_nonblocking_no_sigpipe = u "Linux_ext.send_nonblocking_no_sigpipe"
let sendfile = u "Linux_ext.sendfile"
let sendmsg_nonblocking_no_sigpipe = u "Linux_ext.sendmsg_nonblocking_no_sigpipe"
let settcpopt_bool = u "Linux_ext.settcpopt_bool"
let peer_credentials = u "Linux_ext.peer_credentials"
module Epoll = struct
module Flags = Epoll_flags (struct
let in_ = Int63.of_int (1 lsl 0)
let out = Int63.of_int (1 lsl 1)
let = Int63.of_int ( 1 lsl 2 )
let pri = Int63.of_int (1 lsl 3)
let err = Int63.of_int (1 lsl 4)
let hup = Int63.of_int (1 lsl 5)
let et = Int63.of_int (1 lsl 6)
let oneshot = Int63.of_int (1 lsl 7)
end)
type t = [ `Epoll_is_not_implemented ] [@@deriving sexp_of]
let create = Or_error.unimplemented "Linux_ext.Epoll.create"
let close _ = assert false
let invariant _ = assert false
let find _ _ = assert false
let find_exn _ _ = assert false
let set _ _ _ = assert false
let remove _ _ = assert false
let iter _ ~f:_ = assert false
let fold _ ~init:_ ~f:_ = assert false
let wait _ ~timeout:_ = assert false
let wait_timeout_after _ _ = assert false
let iter_ready _ ~f:_ = assert false
let fold_ready _ ~init:_ ~f:_ = assert false
module Expert = struct
let clear_ready _ = assert false
end
end
end
module Null : Linux_ext_intf.S = struct
type nonrec tcp_bool_option = tcp_bool_option =
TCP_CORK | TCP_QUICKACK
[@@deriving sexp, bin_io]
module Bound_to_interface = struct
type t = Bound_to_interface.t = Any | Only of string
[@@deriving sexp_of]
end
module Peer_credentials = Peer_credentials
module Priority = Priority
module Clock = struct
type t
let get = Or_error.unimplemented "Linux_ext.Clock.get"
let get_time = Or_error.unimplemented "Linux_ext.Clock.get_time"
let set_time = Or_error.unimplemented "Linux_ext.Clock.set_time"
let get_resolution = Or_error.unimplemented "Linux_ext.Clock.get_resolution"
let get_process_clock = Or_error.unimplemented "Linux_ext.Clock.get_process_clock"
let get_thread_clock = Or_error.unimplemented "Linux_ext.Clock.get_thread_clock"
end
module Eventfd = struct
type t = File_descr.t [@@deriving compare, sexp_of]
module Flags = struct
let nonblock = Int63.of_int 0o4000
let cloexec = Int63.of_int 0o2000000
let semaphore = Int63.of_int 0o1
include Flags.Make(struct
let allow_intersecting = true
let should_print_error = true
let remove_zero_flags = false
let known =
[ nonblock , "nonblock"
; cloexec , "cloexec"
; semaphore, "semaphore" ]
end)
end
let create = Or_error.unimplemented "Linux_ext.Eventfd.create"
let read _ = assert false
let write _ = assert false
let to_file_descr t = t
end
module Timerfd = struct
module Clock = struct
type t = unit [@@deriving bin_io, compare, sexp]
let realtime = ()
let monotonic = ()
end
module Flags = struct
let nonblock = Int63.of_int 0o4000
let cloexec = Int63.of_int 0o2000000
include Flags.Make (struct
let allow_intersecting = false
let should_print_error = true
let remove_zero_flags = false
let known =
List.rev
[ nonblock, "nonblock";
cloexec, "cloexec";
]
end)
end
type t = File_descr.t [@@deriving compare, sexp_of]
let to_file_descr t = t
type repeat =
{ fire_after : Time_ns.Span.t
; interval : Time_ns.Span.t
}
let create = Or_error.unimplemented "Linux_ext.Timerfd.create"
let set_at _ _ = assert false
let set_after _ _ = assert false
let set_repeating ?after:_ _ _ = assert false
let set_repeating_at _ _ _ = assert false
let clear _ = assert false
let get _ = assert false
module Private = struct
let unsafe_timerfd_settime _ = assert false
end
end
module Extended_file_attributes = struct
module Get_attr_result = struct
type t =
| Ok of string
| ENOATTR
| ERANGE
| ENOTSUP
[@@deriving sexp_of]
end
let getxattr = Or_error.unimplemented "Linux_ext.Extended_file_attributes.getxattr"
module Set_attr_result = struct
type t =
| Ok
| EEXIST
| ENOATTR
| ENOTSUP
[@@deriving sexp_of]
end
let setxattr = Or_error.unimplemented "Linux_ext.Extended_file_attributes.setxattr"
end
include Null_toplevel
end
module _ = Null
We leave a dummy reference to Null since it may trigger warning 60 ( unused - module )
depending on the conditional compilation below .
depending on the conditional compilation below. *)
[%%import "config.h"]
[%%ifdef JSC_POSIX_TIMERS]
module Clock = struct
type t
These functions should be in Unix , but due to the dependency on Time ,
this is not possible ( cyclic dependency ) .
this is not possible (cyclic dependency). *)
external get_time : t -> float = "core_unix_clock_gettime"
let get_time t = Time.Span.of_sec (get_time t)
external set_time : t -> float -> unit = "core_unix_clock_settime"
let set_time t s = set_time t (Time.Span.to_sec s)
external get_resolution : t -> float = "core_unix_clock_getres"
let get_resolution t = Time.Span.of_sec (get_resolution t)
external get_process_clock : unit -> t = "core_unix_clock_process_cputime_id_stub"
external get_thread_clock : unit -> t = "core_unix_clock_thread_cputime_id_stub"
[%%ifdef JSC_THREAD_CPUTIME]
external get : Thread.t -> t = "core_unix_pthread_getcpuclockid"
let get = Ok get
[%%else]
let get = Or_error.unimplemented "Linux_ext.Clock.get"
[%%endif]
let get_time = Ok get_time
let set_time = Ok set_time
let get_resolution = Ok get_resolution
let get_process_clock = Ok get_process_clock
let get_thread_clock = Ok get_thread_clock
end
[%%else]
module Clock = Null.Clock
[%%endif]
[%%ifdef JSC_TIMERFD]
module Timerfd = struct
module Clock : sig
type t [@@deriving bin_io, compare, sexp]
val realtime : t
val monotonic : t
end = struct
type t = Int63.t [@@deriving bin_io, compare, sexp]
external realtime : unit -> Int63.t = "core_linux_timerfd_CLOCK_REALTIME"
let realtime = realtime ()
external monotonic : unit -> Int63.t = "core_linux_timerfd_CLOCK_MONOTONIC"
let monotonic = monotonic ()
end
module Flags = struct
external nonblock : unit -> Int63.t = "core_linux_timerfd_TFD_NONBLOCK"
let nonblock = nonblock ()
external cloexec : unit -> Int63.t = "core_linux_timerfd_TFD_CLOEXEC"
let cloexec = cloexec ()
include Flags.Make (struct
let allow_intersecting = false
let should_print_error = true
let remove_zero_flags = false
let known =
List.rev
[ nonblock, "nonblock";
cloexec, "cloexec";
]
end)
end
type t = File_descr.t [@@deriving compare, sexp_of]
let to_file_descr t = t
external timerfd_create : Clock.t -> Flags.t -> int = "core_linux_timerfd_create"
At Jane Street , we link with [ --wrap timerfd_create ] so that we can use
our own wrapper around [ timerfd_create ] . This allows us to compile an executable on
a machine that has timerfd ( e.g. CentOS 6 ) but then run the executable on a machine
that does not ( e.g. CentOS 5 ) , but that has our wrapper library . We set up our
wrapper so that when running on a machine that does n't have it , [ timerfd_create ]
raises ENOSYS .
our own wrapper around [timerfd_create]. This allows us to compile an executable on
a machine that has timerfd (e.g. CentOS 6) but then run the executable on a machine
that does not (e.g. CentOS 5), but that has our wrapper library. We set up our
wrapper so that when running on a machine that doesn't have it, [timerfd_create]
raises ENOSYS. *)
let create =
let create ?(flags = Flags.empty) clock =
File_descr.of_int (timerfd_create clock flags)
in
match Result.try_with (fun () -> create Clock.realtime) with
| Ok t -> (Unix.close t; Ok create)
| Error (Unix.Unix_error (ENOSYS, _, _)) ->
Or_error.unimplemented "Linux_ext.Timerfd.create"
| Error _ ->
Ok create
;;
external unsafe_timerfd_settime
: t
-> bool
-> initial : Int63.t
-> interval : Int63.t
-> Syscall_result.Unit.t
= "core_linux_timerfd_settime" [@@noalloc]
let timerfd_settime t ~absolute ~initial ~interval =
if Int63.O.( initial < zero || interval < zero )
then raise_s
[%sexp
"timerfd_settime got invalid parameters (initial < 0 or interval < 0).",
{ timerfd = (t : t)
; initial = (initial : Int63.t)
; interval = (interval : Int63.t)
}
];
unsafe_timerfd_settime t absolute ~initial ~interval
|> Syscall_result.Unit.ok_or_unix_error_exn ~syscall_name:"timerfd_settime"
;;
let initial_of_span span =
Time_ns.Span.to_int63_ns
(if Time_ns.Span.( <= ) span Time_ns.Span.zero
then Time_ns.Span.nanosecond
else span)
;;
let set_at t at =
if Time_ns.( <= ) at Time_ns.epoch
then failwiths ~here:[%here] "Timerfd.set_at got time before epoch" at [%sexp_of: Time_ns.t];
timerfd_settime t
~absolute:true
~initial:(Time_ns.to_int63_ns_since_epoch at)
~interval:Int63.zero
;;
let set_after t span =
timerfd_settime t
~absolute:false
~initial:(initial_of_span span)
~interval:Int63.zero
;;
let set_repeating ?after t interval =
if Time_ns.Span.( <= ) interval Time_ns.Span.zero
then failwiths ~here:[%here] "Timerfd.set_repeating got invalid interval" interval
[%sexp_of: Time_ns.Span.t];
let interval = Time_ns.Span.to_int63_ns interval in
timerfd_settime t
~absolute:false
~initial:(Option.value_map after ~f:initial_of_span ~default:interval)
~interval
;;
let set_repeating_at t at (interval : Time_ns.Span.t) =
if Time_ns.( <= ) at Time_ns.epoch
then failwiths ~here:[%here] "Timerfd.set_repeating_at got time before epoch" at [%sexp_of: Time_ns.t];
if Time_ns.Span.( <= ) interval Time_ns.Span.zero
then failwiths ~here:[%here] "Timerfd.set_repeating_at got invalid interval" interval
[%sexp_of: Time_ns.Span.t];
let interval = Time_ns.Span.to_int63_ns interval in
timerfd_settime t
~absolute:true
~initial:(Time_ns.to_int63_ns_since_epoch at)
~interval
;;
let clear t =
timerfd_settime t ~absolute:false ~initial:Int63.zero ~interval:Int63.zero
type repeat =
{ fire_after : Time_ns.Span.t
; interval : Time_ns.Span.t
}
external timerfd_gettime : t -> repeat = "core_linux_timerfd_gettime"
let get t =
let spec = timerfd_gettime t in
if Time_ns.Span.equal spec.interval Time_ns.Span.zero
then
if Time_ns.Span.equal spec.fire_after Time_ns.Span.zero
then `Not_armed
else `Fire_after spec.fire_after
else
`Repeat spec
;;
module Private = struct
let unsafe_timerfd_settime = unsafe_timerfd_settime
end
end
[%%else]
module Timerfd = Null.Timerfd
[%%endif]
[%%ifdef JSC_LINUX_EXT]
type file_descr = Unix.File_descr.t
module Eventfd = struct
module Flags = struct
external cloexec : unit -> Int63.t = "core_linux_eventfd_EFD_CLOEXEC"
external nonblock : unit -> Int63.t = "core_linux_eventfd_EFD_NONBLOCK"
external semaphore : unit -> Int63.t = "core_linux_eventfd_EFD_SEMAPHORE"
let cloexec = cloexec ()
let nonblock = nonblock ()
let semaphore = semaphore ()
let known =
[ cloexec , "cloexec"
; nonblock , "nonblock"
; semaphore, "semaphore" ]
include Flags.Make (struct
let allow_intersecting = true
let should_print_error = true
let known = known
let remove_zero_flags = false
end)
end
type t = File_descr.t [@@deriving compare, sexp_of]
external create : Int32.t -> Flags.t -> t = "core_linux_eventfd"
external read : t -> Int64.t = "core_linux_eventfd_read"
external write : t -> Int64.t -> unit = "core_linux_eventfd_write"
let create =
let create ?(flags=Flags.empty) init = create init flags in
Or_error.return create
let to_file_descr t = t
end
external sendfile
: sock : file_descr -> fd : file_descr -> pos : int -> len : int -> int
= "core_linux_sendfile_stub"
;;
let sendfile ?(pos = 0) ?len ~fd sock =
let len =
match len with
| Some len -> len
| None -> Int64.to_int_exn (Int64.( - ) (Unix.fstat fd).st_size (Int64.of_int pos))
in
sendfile ~sock ~fd ~pos ~len
module Raw_sysinfo = struct
type t = {
uptime : int;
load1 : int;
load5 : int;
load15 : int;
total_ram : int;
free_ram : int;
shared_ram : int;
buffer_ram : int;
total_swap : int;
free_swap : int;
procs : int;
totalhigh : int;
freehigh : int;
mem_unit : int;
}
end
module Sysinfo = struct
include Sysinfo0
external raw_sysinfo : unit -> Raw_sysinfo.t = "core_linux_sysinfo"
let sysinfo = Ok (fun () ->
let raw = raw_sysinfo () in
{
uptime = Time.Span.of_int_sec raw.Raw_sysinfo.uptime;
load1 = raw.Raw_sysinfo.load1;
load5 = raw.Raw_sysinfo.load5;
load15 = raw.Raw_sysinfo.load15;
total_ram = raw.Raw_sysinfo.total_ram;
free_ram = raw.Raw_sysinfo.free_ram;
shared_ram = raw.Raw_sysinfo.shared_ram;
buffer_ram = raw.Raw_sysinfo.buffer_ram;
total_swap = raw.Raw_sysinfo.total_swap;
free_swap = raw.Raw_sysinfo.free_swap;
procs = raw.Raw_sysinfo.procs;
totalhigh = raw.Raw_sysinfo.totalhigh;
freehigh = raw.Raw_sysinfo.freehigh;
mem_unit = raw.Raw_sysinfo.mem_unit;
})
end
external gettcpopt_bool
: file_descr -> tcp_bool_option -> bool = "core_linux_gettcpopt_bool_stub"
external settcpopt_bool
: file_descr -> tcp_bool_option -> bool -> unit = "core_linux_settcpopt_bool_stub"
external peer_credentials : file_descr -> Peer_credentials.t = "core_linux_peer_credentials"
external unsafe_send_nonblocking_no_sigpipe
: file_descr -> pos : int -> len : int -> Bytes.t -> int
= "core_linux_send_nonblocking_no_sigpipe_stub"
let unsafe_send_nonblocking_no_sigpipe fd ~pos ~len buf =
let res = unsafe_send_nonblocking_no_sigpipe fd ~pos ~len buf in
if res = -1 then None
else Some res
external unsafe_send_no_sigpipe
: file_descr -> pos : int -> len : int -> Bytes.t -> int
= "core_linux_send_no_sigpipe_stub"
let check_send_args ?pos ?len buf =
let str_len = Bytes.length buf in
let pos =
match pos with
| None -> 0
| Some pos ->
if pos < 0 then invalid_arg "send_nonblocking_no_sigpipe: pos < 0";
if pos > str_len then
invalid_arg "send_nonblocking_no_sigpipe: pos > str_len";
pos
in
let len =
match len with
| None -> str_len - pos
| Some len ->
if len < 0 then invalid_arg "send_nonblocking_no_sigpipe: pos < 0";
if pos + len > str_len then
invalid_arg "send_nonblocking_no_sigpipe: pos + len > str_len";
len
in
(pos, len)
let send_nonblocking_no_sigpipe sock ?pos ?len buf =
let (pos, len) = check_send_args ?pos ?len buf in
unsafe_send_nonblocking_no_sigpipe sock ~pos ~len buf
let send_no_sigpipe sock ?pos ?len buf =
let (pos, len) = check_send_args ?pos ?len buf in
unsafe_send_no_sigpipe sock ~pos ~len buf
external unsafe_sendmsg_nonblocking_no_sigpipe
: file_descr -> string Unix.IOVec.t array -> int -> int
= "core_linux_sendmsg_nonblocking_no_sigpipe_stub"
let unsafe_sendmsg_nonblocking_no_sigpipe fd iovecs count =
let res = unsafe_sendmsg_nonblocking_no_sigpipe fd iovecs count in
if res = -1 then None
else Some res
let sendmsg_nonblocking_no_sigpipe sock ?count iovecs =
let count =
match count with
| None -> Array.length iovecs
| Some count ->
if count < 0 then
invalid_arg "sendmsg_nonblocking_no_sigpipe: count < 0";
let n_iovecs = Array.length iovecs in
if count > n_iovecs then
invalid_arg "sendmsg_nonblocking_no_sigpipe: count > n_iovecs";
count
in
unsafe_sendmsg_nonblocking_no_sigpipe sock iovecs count
external pr_set_pdeathsig : Signal.t -> unit = "core_linux_pr_set_pdeathsig_stub"
external pr_get_pdeathsig : unit -> Signal.t = "core_linux_pr_get_pdeathsig_stub"
external pr_set_name_first16 : string -> unit = "core_linux_pr_set_name"
external pr_get_name : unit -> string = "core_linux_pr_get_name"
let file_descr_realpath fd =
Filename_unix.realpath ("/proc/self/fd/" ^ File_descr.to_string fd)
let out_channel_realpath oc = file_descr_realpath (Unix.descr_of_out_channel oc)
let in_channel_realpath ic = file_descr_realpath (Unix.descr_of_in_channel ic)
external raw_sched_setaffinity
: pid : int -> cpuset : int list -> unit = "core_linux_sched_setaffinity"
let sched_setaffinity ?pid ~cpuset () =
let pid = match pid with None -> 0 | Some pid -> Pid.to_int pid in
raw_sched_setaffinity ~pid ~cpuset
;;
external raw_sched_getaffinity
: pid : int -> int list = "core_linux_sched_getaffinity"
let sched_getaffinity ?pid () =
let pid = match pid with None -> 0 | Some pid -> Pid.to_int pid in
raw_sched_getaffinity ~pid
;;
external gettid : unit -> int = "core_unix_gettid"
external setpriority : Priority.t -> unit = "core_linux_setpriority"
external getpriority : unit -> Priority.t = "core_linux_getpriority"
let sched_setaffinity_this_thread ~cpuset =
sched_setaffinity ~pid:(Pid.of_int (gettid ())) ~cpuset ()
;;
let cores =
Memo.unit (fun () ->
let num_cores =
In_channel.with_file "/proc/cpuinfo" ~f:In_channel.input_lines
|> List.fold_left ~init:0 ~f:(fun count line ->
count +
(match String.lsplit2 ~on:':' line with
| None -> 0
| Some (label, _) ->
if String.(=) (String.rstrip label) "processor" then 1
else 0))
in
if num_cores > 0 then num_cores
else failwith "Linux_ext.cores: failed to parse /proc/cpuinfo")
external get_terminal_size : File_descr.t -> int * int = "core_linux_get_terminal_size"
let get_terminal_size = function
| `Fd fd -> get_terminal_size fd
| `Controlling ->
protectx
(Unix.openfile "/dev/tty" ~mode:[ O_RDWR ] ~perm:0)
~finally:Unix.close
~f:get_terminal_size
external get_ipv4_address_for_interface : string -> string =
"core_linux_get_ipv4_address_for_interface" ;;
external get_mac_address : ifname : string -> string =
"core_linux_get_mac_address" ;;
external bind_to_interface' : File_descr.t -> string -> unit =
"core_linux_bind_to_interface" ;;
let bind_to_interface fd ifname =
let name =
match ifname with
| Bound_to_interface.Only name -> name
| Bound_to_interface.Any -> ""
in
bind_to_interface' fd name
;;
external get_bind_to_interface' : File_descr.t -> string =
"core_linux_get_bind_to_interface" ;;
let get_bind_to_interface fd =
match get_bind_to_interface' fd with
| "" -> Bound_to_interface.Any
| name -> Bound_to_interface.Only name
module Epoll = struct
external flag_epollin : unit -> Int63.t = "core_linux_epoll_EPOLLIN_flag"
external flag_epollout : unit -> Int63.t = "core_linux_epoll_EPOLLOUT_flag"
external flag_epollpri : unit -> Int63.t = "core_linux_epoll_EPOLLPRI_flag"
external flag_epollerr : unit -> Int63.t = "core_linux_epoll_EPOLLERR_flag"
external flag_epollhup : unit -> Int63.t = "core_linux_epoll_EPOLLHUP_flag"
external flag_epollet : unit -> Int63.t = "core_linux_epoll_EPOLLET_flag"
external flag_epolloneshot : unit -> Int63.t = "core_linux_epoll_EPOLLONESHOT_flag"
module Flags = Epoll_flags (struct
let in_ = flag_epollin ()
let out = flag_epollout ()
let = flag_epollrdhup ( )
let pri = flag_epollpri ()
let err = flag_epollerr ()
let hup = flag_epollhup ()
let et = flag_epollet ()
let oneshot = flag_epolloneshot ()
end)
external epoll_create : unit -> File_descr.t = "core_linux_epoll_create"
Some justification for the below interface : Unlike select ( ) and poll ( ) , epoll ( ) fills
in an array of ready events , analogous to a read ( ) call where you pass in a buffer to
be filled .
Since this is at the core of the I / O loop , we 'd like to avoid reallocating that
buffer on every call to poll . We 're allocating the array on the ocaml side ( as a
Bigstring ) , then iterating through it in - place , reducing allocation , copies , and any
intermediate lists . For very high message rates and many fds this could be a very
beneficial .
in an array of ready events, analogous to a read() call where you pass in a buffer to
be filled.
Since this is at the core of the I/O loop, we'd like to avoid reallocating that
buffer on every call to poll. We're allocating the array on the ocaml side (as a
Bigstring), then iterating through it in-place, reducing allocation, copies, and any
intermediate lists. For very high message rates and many fds this could be a very
beneficial. *)
type ready_events = Bigstring.t
external epoll_sizeof_epoll_event
: unit -> int = "core_linux_epoll_sizeof_epoll_event" [@@noalloc]
external epoll_offsetof_readyfd
: unit -> int = "core_linux_epoll_offsetof_readyfd" [@@noalloc]
external epoll_offsetof_readyflags
: unit -> int = "core_linux_epoll_offsetof_readyflags" [@@noalloc]
let sizeof_epoll_event = epoll_sizeof_epoll_event ()
let offsetof_readyfd = epoll_offsetof_readyfd ()
let offsetof_readyflags = epoll_offsetof_readyflags ()
external epoll_ctl_add
: File_descr.t -> File_descr.t -> Flags.t -> unit
= "core_linux_epoll_ctl_add"
external epoll_ctl_mod
: File_descr.t -> File_descr.t -> Flags.t -> unit
= "core_linux_epoll_ctl_mod"
external epoll_ctl_del
: File_descr.t -> File_descr.t -> unit
= "core_linux_epoll_ctl_del"
module Table = Bounded_int_table
module T = struct
type 'a t =
{ epollfd : File_descr.t;
[ flags_by_fd ] has one entry for each file - descr in the epoll set , and stores
the epoll flags that the kernel 's epoll set currently has for that
file - descr . Keeping our own representation of the kernel data structure is
useful for debugging , since the information appears in a human - readable way
in [ sexp_of_t ] 's output . It also allows us to hide the distinction between
[ epoll_ctl_add ] and [ epoll_ctl_mod ] , since we know which to use based on
whether the file descriptor is already being watched .
the epoll flags that the kernel's epoll set currently has for that
file-descr. Keeping our own representation of the kernel data structure is
useful for debugging, since the information appears in a human-readable way
in [sexp_of_t]'s output. It also allows us to hide the distinction between
[epoll_ctl_add] and [epoll_ctl_mod], since we know which to use based on
whether the file descriptor is already being watched. *)
flags_by_fd : (File_descr.t, Flags.t) Table.t;
max_ready_events : int;
mutable num_ready_events : int;
ready_events : 'a;
}
[@@deriving fields, sexp_of]
end
open T
let epoll_readyfd t i =
Bigstring.unsafe_get_int32_le
t
~pos:(i*sizeof_epoll_event + offsetof_readyfd)
|> File_descr.of_int
;;
let epoll_readyflags t i =
Bigstring.unsafe_get_int32_le
t
~pos:(i*sizeof_epoll_event + offsetof_readyflags)
|> Flags.of_int
;;
type in_use = ready_events T.t
module Pretty = struct
type ready_event =
{ file_descr : File_descr.t;
flags : Flags.t;
}
[@@deriving sexp_of]
type ready_events = ready_event array [@@deriving sexp_of]
type t = ready_events T.t [@@deriving sexp_of]
end
let to_pretty t =
{ t with
ready_events =
Array.init t.num_ready_events ~f:(fun i ->
{ Pretty.
file_descr = epoll_readyfd t.ready_events i;
flags = epoll_readyflags t.ready_events i;
});
}
;;
let sexp_of_in_use t = Pretty.sexp_of_t (to_pretty t)
type t = [ `Closed | `In_use of in_use ] ref [@@deriving sexp_of]
let close t =
match !t with
| `Closed -> ()
| `In_use { epollfd; _ } ->
t := `Closed;
Unix.close epollfd;
;;
let invariant t : unit =
match !t with
| `Closed -> ()
| `In_use t ->
try
let check f field = f (Field.get field t) in
Fields.iter
~epollfd:ignore
~flags_by_fd:(check (Table.invariant ignore ignore))
~max_ready_events:(check (fun max_ready_events -> assert (max_ready_events > 0)))
~num_ready_events:(check (fun num_ready -> assert (num_ready >= 0)))
~ready_events:ignore
with exn ->
failwiths ~here:[%here] "Epoll.invariant failed" (exn, t) [%sexp_of: exn * in_use]
;;
let create ~num_file_descrs ~max_ready_events =
if max_ready_events < 0 then
failwiths ~here:[%here] "Epoll.create got nonpositive max_ready_events" max_ready_events
([%sexp_of: int]);
ref (`In_use
{ epollfd = epoll_create ();
flags_by_fd =
Table.create
~num_keys:num_file_descrs
~key_to_int:File_descr.to_int
~sexp_of_key:File_descr.sexp_of_t
();
max_ready_events;
num_ready_events = 0;
ready_events = Bigstring.create (sizeof_epoll_event * max_ready_events);
})
;;
let in_use_exn t =
match !t with
| `Closed -> failwith "attempt to use closed epoll set"
| `In_use r -> r
;;
let find t file_descr =
let t = in_use_exn t in
Table.find t.flags_by_fd file_descr
;;
let find_exn t file_descr =
let t = in_use_exn t in
Table.find_exn t.flags_by_fd file_descr
;;
let iter t ~f =
let t = in_use_exn t in
Table.iteri t.flags_by_fd ~f:(fun ~key:file_descr ~data:flags ->
f file_descr flags)
;;
let fold t ~init ~f =
let t = in_use_exn t in
Table.fold t.flags_by_fd ~init ~f:(fun ~key ~data -> f key data)
let set t fd flags =
let t = in_use_exn t in
let already_present = Table.mem t.flags_by_fd fd in
Both [ epoll_ctl_add ] and [ epoll_ctl_mod ] may raise if the file descriptor does not
support polling . Perform these operations first and let them raise before modifying
the table to reflect the change in epoll state .
support polling. Perform these operations first and let them raise before modifying
the table to reflect the change in epoll state. *)
let () =
if already_present
then
epoll_ctl_mod t.epollfd fd flags
else
epoll_ctl_add t.epollfd fd flags
in
Table.set t.flags_by_fd ~key:fd ~data:flags
;;
let remove t fd =
let t = in_use_exn t in
if Table.mem t.flags_by_fd fd then epoll_ctl_del t.epollfd fd;
Table.remove t.flags_by_fd fd
;;
external epoll_wait : File_descr.t -> ready_events -> int -> int = "core_linux_epoll_wait"
let wait_internal t ~timeout_ms =
let t = in_use_exn t in
t.num_ready_events <- 0;
t.num_ready_events <- epoll_wait t.epollfd t.ready_events timeout_ms;
if t.num_ready_events = 0 then `Timeout else `Ok
;;
let wait_timeout_after t span =
let timeout_ms =
if Time_ns.Span.( <= ) span Time_ns.Span.zero
then 0
else
For positive timeouts , we use a minimum timeout of one millisecond , to ensure
that we are guaranteed that the timeout has passed when we wake up . If we
allowed a positive sub - millisecond timeout , we would round down and end up
using a timeout of zero , causing [ wait_internal ] to return immediately . Such
behaviour has been seen to cause Async to spin , repeatedly requesting slightly
smaller timeouts .
that we are guaranteed that the timeout has passed when we wake up. If we
allowed a positive sub-millisecond timeout, we would round down and end up
using a timeout of zero, causing [wait_internal] to return immediately. Such
behaviour has been seen to cause Async to spin, repeatedly requesting slightly
smaller timeouts. *)
let span = Time_ns.Span.max span Time_ns.Span.millisecond in
Int63.to_int_exn
Time_ns.Span.(div
(span + of_int63_ns (Int63.of_int 500_000))
(of_int63_ns (Int63.of_int 1_000_000)))
in
assert (timeout_ms >= 0);
wait_internal t ~timeout_ms
;;
let wait t ~timeout =
From the epoll man page :
| Specifying a timeout of -1 makes epoll_wait ( ) wait indefinitely , while
| specifying a timeout equal to zero makes epoll_wait ( ) to return immediately
| even if no events are available ( return code equal to zero ) .
| Specifying a timeout of -1 makes epoll_wait() wait indefinitely, while
| specifying a timeout equal to zero makes epoll_wait() to return immediately
| even if no events are available (return code equal to zero). *)
match timeout with
| `Never -> wait_internal t ~timeout_ms:(-1)
| `Immediately -> wait_internal t ~timeout_ms:0
| `After span -> wait_timeout_after t span
;;
let fold_ready t ~init ~f =
let t = in_use_exn t in
let ac = ref init in
for i = 0 to t.num_ready_events - 1 do
ac := f !ac (epoll_readyfd t.ready_events i) (epoll_readyflags t.ready_events i)
done;
!ac
;;
let iter_ready t ~f =
let t = in_use_exn t in
for i = 0 to t.num_ready_events - 1 do
f (epoll_readyfd t.ready_events i) (epoll_readyflags t.ready_events i)
done
;;
module Expert = struct
let clear_ready t =
let t = in_use_exn t in
t.num_ready_events <- 0
;;
end
external epoll_pwait
* : File_descr.t - > Events_buffer.raw - > int - > int list - > int
* = " core_linux_epoll_pwait "
*
* let pwait t ~timeout sigs =
* let millis = Float.iround_exn ~dir:`Zero ( Span.to_ms timeout ) in
* let num_ready = epoll_pwait t.epollfd t.events in
* if num_ready = 0 then ` Timeout
* else ` Ok { Ready_fds.num_ready ; events = t.events }
* ; ;
* : File_descr.t -> Events_buffer.raw -> int -> int list -> int
* = "core_linux_epoll_pwait"
*
* let pwait t ~timeout sigs =
* let millis = Float.iround_exn ~dir:`Zero ( Span.to_ms timeout ) in
* let num_ready = epoll_pwait t.epollfd t.events millis sigs in
* if num_ready = 0 then `Timeout
* else `Ok { Ready_fds.num_ready ; events = t.events }
* ;; *)
let create = Ok create
end
let cores = Ok cores
let isolated_cpus = Ok isolated_cpus
let online_cpus = Ok online_cpus
let cpus_local_to_nic = Ok cpus_local_to_nic
let file_descr_realpath = Ok file_descr_realpath
let get_ipv4_address_for_interface = Ok get_ipv4_address_for_interface
let get_mac_address = Ok get_mac_address
let bind_to_interface = Ok bind_to_interface
let get_bind_to_interface = Ok get_bind_to_interface
let get_terminal_size = Ok get_terminal_size
let gettcpopt_bool = Ok gettcpopt_bool
let setpriority = Ok setpriority
let getpriority = Ok getpriority
let in_channel_realpath = Ok in_channel_realpath
let out_channel_realpath = Ok out_channel_realpath
let pr_get_name = Ok pr_get_name
let pr_get_pdeathsig = Ok pr_get_pdeathsig
let pr_set_name_first16 = Ok pr_set_name_first16
let pr_set_pdeathsig = Ok pr_set_pdeathsig
let sched_setaffinity = Ok sched_setaffinity
let sched_getaffinity = Ok sched_getaffinity
let sched_setaffinity_this_thread = Ok sched_setaffinity_this_thread
let send_no_sigpipe = Ok send_no_sigpipe
let send_nonblocking_no_sigpipe = Ok send_nonblocking_no_sigpipe
let sendfile = Ok sendfile
let sendmsg_nonblocking_no_sigpipe = Ok sendmsg_nonblocking_no_sigpipe
let settcpopt_bool = Ok settcpopt_bool
let peer_credentials = Ok peer_credentials
module Extended_file_attributes = struct
module Flags = struct
external only_create : unit -> Int63.t = "core_linux_xattr_XATTR_CREATE_flag"
external only_replace : unit -> Int63.t = "core_linux_xattr_XATTR_REPLACE_flag"
let set = Int63.zero
end
module Get_attr_result = struct
type t =
| Ok of string
| ENOATTR
| ERANGE
| ENOTSUP
[@@deriving sexp_of]
end
module Set_attr_result = struct
type t =
| Ok
| EEXIST
| ENOATTR
| ENOTSUP
[@@deriving sexp_of]
end
external getxattr : string -> string -> Get_attr_result.t = "core_linux_getxattr"
external setxattr : string -> string -> string -> Int63.t -> Set_attr_result.t = "core_linux_setxattr"
let getxattr ~path ~name =
getxattr path name
;;
let setxattr ?(how = `Set) ~path ~name ~value () =
let flags =
match how with
| `Set -> Flags.set
| `Create -> Flags.only_create ()
| `Replace -> Flags.only_replace ()
in
setxattr path name value flags
;;
let getxattr = Ok getxattr
let setxattr = Ok setxattr
end
[%%else]
include Null_toplevel
module Eventfd = Null.Eventfd
module Extended_file_attributes = Null.Extended_file_attributes
[%%endif]
|
9a53725cd981551e730d55e9b2f714587669834a5a9a2a0132f4ddd09b404aee | MarcFontaine/stm32hs | RealTimeClock.hs | ----------------------------------------------------------------------------
-- |
-- Module : App.RealTimeClock
-- License : BSD3
--
-- Stability : experimental
Portability : GHC - only
--
-- Read the real time clock.
-- This only works if the controller has a battery installed
and the RTC has been initialized .
module App.RealTimeClock
where
import STM32.API
import qualified STM32.RTC as RTC
printRTC :: IO ()
printRTC = runMI $ do
initMI
resetHalt
RTC.getCounter >>=print'
| null | https://raw.githubusercontent.com/MarcFontaine/stm32hs/d7afeb8f9d83e01c76003f4b199b45044bd4e383/STM32-Zombie/src/App/RealTimeClock.hs | haskell | --------------------------------------------------------------------------
|
Module : App.RealTimeClock
License : BSD3
Stability : experimental
Read the real time clock.
This only works if the controller has a battery installed | Portability : GHC - only
and the RTC has been initialized .
module App.RealTimeClock
where
import STM32.API
import qualified STM32.RTC as RTC
printRTC :: IO ()
printRTC = runMI $ do
initMI
resetHalt
RTC.getCounter >>=print'
|
73344ba0413f87cefe5b07fd1e73541097b3c01671acbe513b65ac498ca784c9 | ocaml-community/calendar | date_sig.mli | (**************************************************************************)
(* *)
(* This file is part of Calendar. *)
(* *)
Copyright ( C ) 2003 - 2011
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License version 2.1 as published by the
Free Software Foundation , with a special linking exception ( usual
(* for Objective Caml libraries). *)
(* *)
(* 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 *)
(* *)
See the GNU Lesser General Public Licence version 2.1 for more
(* details (enclosed in the file LGPL). *)
(* *)
(* The special linking exception is detailled in the enclosed file *)
(* LICENSE. *)
(**************************************************************************)
* Date interface . A date may be seen as a triple ( year , month , day ) .
All the dates should belong to
[ [ January , 1st 4713 BC ; January 22th , 3268 AC ] ] ( called the Julian period ) .
An [ Out_of_bounds ] exception is raised if you attempt to create a date
outside the Julian period .
If a date [ d ] does not exists and if [ d_bef ] ( resp . [ d_aft ] ) is
the last ( resp . first ) existing date before ( resp . after ) [ d ] ,
[ d ] is automatically coerced to [ d_aft + d - d_bef - 1 ] .
For example , both dates " February 29th , 2003 " and
" February 30th , 2003 " do not exist and they are coerced respectively to the
date " Mars 1st , 2003 " and " Mars 2nd , 2003 " .
This rule is called the coercion rule .
As an exception to the coercion rule , the date belonging to
[ [ October 5th , 1582 ; October 14th , 1582 ] ] do not exist and an [ Undefined ]
exception is raised if you attempt to create such a date .
Those dropped days correspond to the change from the Julian to the calendar .
All the dates should belong to
[[January, 1st 4713 BC; January 22th, 3268 AC]] (called the Julian period).
An [Out_of_bounds] exception is raised if you attempt to create a date
outside the Julian period.
If a date [d] does not exists and if [d_bef] (resp. [d_aft]) is
the last (resp. first) existing date before (resp. after) [d],
[d] is automatically coerced to [d_aft + d - d_bef - 1].
For example, both dates "February 29th, 2003" and
"February 30th, 2003" do not exist and they are coerced respectively to the
date "Mars 1st, 2003" and "Mars 2nd, 2003".
This rule is called the coercion rule.
As an exception to the coercion rule, the date belonging to
[[October 5th, 1582; October 14th, 1582]] do not exist and an [Undefined]
exception is raised if you attempt to create such a date.
Those dropped days correspond to the change from the Julian to the Gregorian
calendar. *)
(** Common operations for all date representations.
@since 2.0 (this signature was before inlined in interface of Date). *)
module type S = sig
* { 2 }
* The different fields of a date .
@since 2.02
@since 2.02 *)
type field = Period.date_field
* Type of a date , without specifying any precision level .
@since 2.02
@since 2.02 *)
type -'a date constraint 'a = [< field ]
(** Type of a date. *)
type t = field date
* Days of the week .
type day = Sun | Mon | Tue | Wed | Thu | Fri | Sat
* Months of the year .
type month =
Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
(** Year as an [int]. *)
type year = int
* { 2 Exceptions }
exception Out_of_bounds
* Raised when a date is outside the Julian period .
exception Undefined
* Raised when a date belongs to
[ [ October 5th , 1582 ; October 14th , 1582 ] ] .
[[October 5th, 1582; October 14th, 1582]]. *)
(** {2 Constructors} *)
val make : year -> int -> int -> t
* [ make year month day ] makes the date year - month - day . A BC year [ y ]
corresponds to the year [ -(y+1 ) ] .
@example years ( 5 BC ) and ( 1 BC ) respectively correspond to years
( -4 ) and 0 .
@raise Out_of_bounds when a date is outside the Julian period .
@raise Undefined when a date belongs to [ [ October 5th , 1582 ; October
14th , 1582 ] ] .
corresponds to the year [-(y+1)].
@example years (5 BC) and (1 BC) respectively correspond to years
(-4) and 0.
@raise Out_of_bounds when a date is outside the Julian period.
@raise Undefined when a date belongs to [[October 5th, 1582; October
14th, 1582]]. *)
val lmake : year:year -> ?month:int -> ?day:int -> unit -> t
* Labelled version of [ make ] .
The default value of [ month ] and [ day ] is [ 1 ] .
@raise Out_of_bounds when a date is outside the Julian period .
@raise Undefined when a date belongs to [ [ October 5th , 1582 ; October
14th , 1582 ] ] .
@since 1.05
The default value of [month] and [day] is [1].
@raise Out_of_bounds when a date is outside the Julian period.
@raise Undefined when a date belongs to [[October 5th, 1582; October
14th, 1582]].
@since 1.05 *)
val make_year: int -> [< `Year ] date
* [ make_year y ] makes a date only represented by its year [ y ] . The month
and the day of such a date are not relevant .
@since 2.02
and the day of such a date are not relevant.
@since 2.02 *)
val make_year_month: int -> int -> [< `Year | `Month ] date
* [ make_year_month y m ] makes a date only represented by its year [ y ] and
its month [ m ] . The day of such a date is not relevant .
@since 2.02
its month [m]. The day of such a date is not relevant.
@since 2.02 *)
val today : unit -> t
(** Date of the current day (based on [Time_Zone.current ()]). *)
val from_jd : int -> t
* Make a date from its Julian day .
@example [ from_jd 0 ] returns the date 4713 BC-1 - 1 .
@example [from_jd 0] returns the date 4713 BC-1-1. *)
val from_mjd : int -> t
* Make a date from its modified Julian day ( i.e. Julian day - 2 400 001 ) .
The Modified Julian day is more manageable than the Julian day .
@example [ from_mjd 0 ] returns the date 1858 - 11 - 17 .
The Modified Julian day is more manageable than the Julian day.
@example [from_mjd 0] returns the date 1858-11-17. *)
val from_day_of_year: year -> int -> t
* Make a date from a year and its day of the year .
@example [ from_day_of_year 2008 39 ] returns the date 2008 - 2 - 8 .
@since 2.0
@example [from_day_of_year 2008 39] returns the date 2008-2-8.
@since 2.0 *)
* { 2 Getters }
val days_in_month : [> `Year | `Month ] date -> int
* Number of days in the month of a date .
@example [ days_in_month ( make 2003 6 26 ) ] returns [ 30 ] .
@example [days_in_month (make 2003 6 26)] returns [30]. *)
val day_of_week : t -> day
* Day of the week .
@example [ ( make 2003 6 26 ) ] returns [ Thu ] .
@example [day_of_week (make 2003 6 26)] returns [Thu]. *)
val day_of_month : t -> int
* Day of the month .
@example [ day_of_month ( make 2003 6 26 ) ] returns [ 26 ] .
@example [day_of_month (make 2003 6 26)] returns [26]. *)
val day_of_year : t -> int
* Day of the year .
@example [ day_of_year ( make 2003 1 5 ) ] returns [ 5 ]
@example [ day_of_year ( make 2003 12 28 ) ] returns [ 362 ] .
@example [day_of_year (make 2003 1 5)] returns [5]
@example [day_of_year (make 2003 12 28)] returns [362]. *)
val week : t -> int
* Week .
@example [ week ( make 2000 1 3 ) ] returns [ 1 ] .
@example [ week ( make 2000 1 2 ) ] returns [ 52 ] .
@example [ week ( make 2003 12 28 ) ] returns [ 52 ] .
@example [ week ( make 2003 12 29 ) ] returns [ 1 ] .
@example [week (make 2000 1 3)] returns [1].
@example [week (make 2000 1 2)] returns [52].
@example [week (make 2003 12 28)] returns [52].
@example [week (make 2003 12 29)] returns [1]. *)
val month : [> `Month ] date -> month
* Month .
@example [ month ( make 2003 6 26 ) ] returns [ Jun ] .
@example [month (make 2003 6 26)] returns [Jun]. *)
val year : [> `Year ] date -> year
* Year .
@example [ year ( make 2003 6 26 ) ] returns [ 2003 ] .
@example [year (make 2003 6 26)] returns [2003]. *)
val to_jd : t -> int
* Julian day .
@example [ to_jd ( make ( -4712 ) 1 1 ) ] returns 0 .
@example [to_jd (make (-4712) 1 1)] returns 0. *)
val to_mjd : t -> int
* Modified Julian day ( i.e. Julian day - 2 400 001 ) .
The Modified Julian day is more manageable than the Julian day .
@example [ ( make 1858 11 17 ) ] returns 0 .
The Modified Julian day is more manageable than the Julian day.
@example [to_mjd (make 1858 11 17)] returns 0. *)
* { 2 Dates are comparable }
val equal: 'a date -> 'b date -> bool
* Equality function between two dates .
@see < Utils.Comparable.html#VALequal > Utils.Comparable.equal
@since 1.09.0
@see <Utils.Comparable.html#VALequal> Utils.Comparable.equal
@since 1.09.0 *)
val compare : 'a date -> 'b date -> int
* Comparison function between two dates .
@see < Utils.Comparable.html#VALcompare > Utils.Comparable.compare
@see <Utils.Comparable.html#VALcompare> Utils.Comparable.compare *)
val ( > ) : 'a date -> 'b date -> bool
* Check if the first date is later than the second
val ( >= ) : 'a date -> 'b date -> bool
* Check if the first date is later or equal to the second
val ( < ) : 'a date -> 'b date -> bool
* Check if the first date is earlier than the second
val ( <= ) : 'a date -> 'b date -> bool
* Check if the first date is earlier or equal to the second
val hash: 'a date -> int
(** Hash function for dates.
@see <Utils.Comparable.html#VALhash> Utils.Comparable.hash
@since 2.0 *)
* { 2 Boolean operations on dates }
val is_valid_date: year -> int -> int -> bool
* Check if a date is valid , that is the date has not been coerced to look
like a real date .
@example [ is_valid_date 2008 2 8 ] returns [ true ]
@example [ is_valid_date 2008 2 30 ] returns [ false ]
@since 2.0
like a real date.
@example [is_valid_date 2008 2 8] returns [true]
@example [is_valid_date 2008 2 30] returns [false]
@since 2.0 *)
val is_leap_day : t -> bool
* Return [ true ] if a date is a leap day
( i.e. February , 24th of a leap year ) ; [ false ] otherwise .
(i.e. February, 24th of a leap year); [false] otherwise. *)
val is_gregorian : t -> bool
(** Return [true] if a date belongs to the Gregorian calendar;
[false] otherwise. *)
val is_julian : t -> bool
* Return [ true ] iff a date belongs to the Julian calendar ;
[ false ] otherwise .
[false] otherwise. *)
* { 2 Coercions }
val to_unixtm : t -> Unix.tm
* Convert a date into the [ Unix.tm ] type .
The field [ is_isdst ] is always [ false ] . The fields [ Unix.tm_sec ] ,
[ Unix.tm_min ] and [ Unix.tm_hour ] are irrelevant .
@since 1.01
The field [is_isdst] is always [false]. The fields [Unix.tm_sec],
[Unix.tm_min] and [Unix.tm_hour] are irrelevant.
@since 1.01 *)
val from_unixtm : Unix.tm -> t
* Inverse of [ to_unixtm ] . Assume the current time zone .
@since 1.01
@since 1.01 *)
val to_unixfloat : t -> float
* Convert a date to a float such than [ to_unixfloat ( make 1970 1 1 ) ]
returns [ 0.0 ] . So such a float is convertible with those of the [ Unix ]
module . The fractional part of the result is always [ 0 ] .
@since 1.01
returns [0.0]. So such a float is convertible with those of the [Unix]
module. The fractional part of the result is always [0].
@since 1.01 *)
val from_unixfloat : float -> t
* Inverse of [ to_unixfloat ] . Ignore the fractional part of the argument .
Assume the current time zone .
@since 1.01
Assume the current time zone.
@since 1.01 *)
val to_business: t -> year * int * day
* Return the " business week " and the day in this week respecting ISO 8601 .
Notice that business weeks at the beginning and end of the year can
sometimes have year numbers which do n't match the real year .
@example [ to_business ( make 2000 1 3 ) ] returns [ 2000 , 1 , Mon ]
@example [ to_business ( make 2000 1 2 ) ] returns [ 1999 , 52 , Sun ]
@example [ to_business ( make 2003 12 28 ) ] returns [ 2003 , 52 , Sun ]
@example [ to_business ( make 2003 12 29 ) ] returns [ 2004 , 1 , Mon ] .
@since 1.09.0
Notice that business weeks at the beginning and end of the year can
sometimes have year numbers which don't match the real year.
@example [to_business (make 2000 1 3)] returns [2000, 1, Mon]
@example [to_business (make 2000 1 2)] returns [1999, 52, Sun]
@example [to_business (make 2003 12 28)] returns [2003, 52, Sun]
@example [to_business (make 2003 12 29)] returns [2004, 1, Mon].
@since 1.09.0 *)
val from_business: year -> int -> day -> t
* Inverse of [ to_business ] respecting ISO-8601 .
Notice that business weeks at the beginning and end of the year
can sometimes have year numbers which do n't match the real year .
@raise Invalid_argument if the date is bad .
@since 1.09.0
Notice that business weeks at the beginning and end of the year
can sometimes have year numbers which don't match the real year.
@raise Invalid_argument if the date is bad.
@since 1.09.0 *)
val int_of_day : day -> int
* Convert a day to an integer respecting ISO-8601 .
So , Monday is 1 , Tuesday is 2 , ... , and sunday is 7 .
So, Monday is 1, Tuesday is 2, ..., and sunday is 7. *)
val day_of_int : int -> day
* Inverse of [ int_of_day ] .
@raise Invalid_argument if the argument does not belong to [ 1 ; 7 ] .
@raise Invalid_argument if the argument does not belong to [1; 7]. *)
val int_of_month : month -> int
* Convert a month to an integer respecting ISO-8601 .
So , January is 1 , February is 2 and so on .
So, January is 1, February is 2 and so on. *)
val month_of_int : int -> month
* Inverse of [ int_of_month ] .
@raise Invalid_argument if the argument does not belong to [ 1 ; 12 ] .
@raise Invalid_argument if the argument does not belong to [1; 12]. *)
(** {2 Period} *)
* A period is the number of days between two dates .
module Period : sig
* { 3 Arithmetic operations }
type +'a p constraint 'a = [< field ]
include Period.S with type +'a period = 'a p
* { 3 Constructors }
val make: int -> int -> int -> t
* [ make year month day ] makes a period of the specified length .
val lmake: ?year:int -> ?month:int -> ?day:int -> unit -> t
(** Labelled version of [make].
The default value of each argument is [0]. *)
val year: int -> [> `Year ] period
(** [year n] makes a period of [n] years. *)
val month: int -> [> `Year | `Month ] period
* [ month n ] makes a period of [ n ] months .
val week: int -> [> `Week | `Day ] period
* [ week n ] makes a period of [ n ] weeks .
val day: int -> [> `Week | `Day ] period
(** [day n] makes a period of [n] days. *)
* { 3 Getters }
exception Not_computable
* @since 1.04
val nb_days: 'a period -> int
* Number of days in a period .
@raise Not_computable if the number of days is not computable .
@example [ nb_days ( day 6 ) ] returns [ 6 ]
@example [ nb_days ( year 1 ) ] raises [ Not_computable ] because a year is
not a constant number of days .
@since 1.04
@deprecated since 2.02 : use { ! safe_nb_days } instead
@raise Not_computable if the number of days is not computable.
@example [nb_days (day 6)] returns [6]
@example [nb_days (year 1)] raises [Not_computable] because a year is
not a constant number of days.
@since 1.04
@deprecated since 2.02: use {!safe_nb_days} instead *)
val safe_nb_days: [< `Week | `Day ] period -> int
* Equivalent to { ! nb_days } but never raises any exception .
@since 2.02
@since 2.02 *)
val ymd: 'a period -> int * int * int
* Number of years , months and days in a period .
@example [ ymd ( make 1 2 3 ) ] returns [ 1 , 2 , 3 ] .
@since 1.09.0
@example [ymd (make 1 2 3)] returns [1, 2, 3].
@since 1.09.0 *)
end
* { 2 Arithmetic operations on dates and periods }
val add : 'a date -> 'a Period.period -> 'a date
* [ add d p ] returns [ d + p ] .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@example [ add ( make 2003 12 31 ) ( Period.month 1 ) ] returns the date
2004 - 1 - 31
@example [ add ( make 2003 12 31 ) ( Period.month 2 ) ] returns the date
2004 - 3 - 2 ( following the coercion rule describes in the introduction ) .
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]].
@example [add (make 2003 12 31) (Period.month 1)] returns the date
2004-1-31
@example [add (make 2003 12 31) (Period.month 2)] returns the date
2004-3-2 (following the coercion rule describes in the introduction). *)
val sub : 'a date -> 'a date -> [> `Week | `Day ] Period.period
(** [sub d1 d2] returns the period between [d1] and [d2]. *)
val precise_sub : 'a date -> 'a date -> Period.t
* [ precise_sub d1 d2 ] returns the period between [ d1 ] and [ d2 ] .
It is equivalent to [ sub ] , but :
- the period is expressed with a number of years , months and days , not
only with a number of days ;
- it is less efficient .
@since 2.03
It is equivalent to [sub], but:
- the period is expressed with a number of years, months and days, not
only with a number of days;
- it is less efficient.
@since 2.03 *)
val rem : 'a date -> 'a Period.period -> 'a date
* [ rem d p ] is equivalent to [ add d ( Period.opp p ) ] .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]]. *)
val next : 'a date -> ([< field ] as 'a) -> 'a date
* [ next d f ] returns the date corresponding to the next specified field .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@example [ next ( make 2003 12 31 ) ` Month ] returns the date 2004 - 1 - 31
( i.e. one month later ) .
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]].
@example [next (make 2003 12 31) `Month] returns the date 2004-1-31
(i.e. one month later). *)
val prev : 'a date -> ([< field ] as 'a) -> 'a date
* [ prev d f ] returns the date corresponding to the previous specified
field .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@example [ prev ( make 2003 12 31 ) ` Year ] returns the date 2002 - 12 - 31
( i.e. one year ago ) .
field.
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]].
@example [prev (make 2003 12 31) `Year] returns the date 2002-12-31
(i.e. one year ago). *)
* { 2 Operations on years }
val is_leap_year : year -> bool
* Return [ true ] if a year is a leap year ; [ false ] otherwise .
val same_calendar : year -> year -> bool
* Return [ true ] if two years have the same calendar ; [ false ]
otherwise .
otherwise. *)
val days_in_year : ?month:month -> year -> int
* Number of days in a year .
[ days_in_year ~month y ] returns the number of days in the year [ y ] up
to the end of the given month . Thus [ days_in_year ~month : Dec y ] is the
same as [ days_in_year y ] .
[days_in_year ~month y] returns the number of days in the year [y] up
to the end of the given month. Thus [days_in_year ~month:Dec y] is the
same as [days_in_year y]. *)
val weeks_in_year: year -> int
* Number of weeks in a year .
val week_first_last: int -> year -> t * t
* Return the first and last days of a week in a year .
@since 1.08
@since 1.08 *)
val nth_weekday_of_month: year -> month -> day -> int -> t
* [ nth_weekday_of_month y m d n ] returns the [ n]-th day [ d ] in the month
[ m ] of the year [ y ] ( for instance the 3rd Thursday of the month ) .
@since 1.09.0
[m] of the year [y] (for instance the 3rd Thursday of the month).
@since 1.09.0 *)
val century : year -> int
* Century of a year .
@example [ century 2000 ] returns 20
@example [ century 2001 ] returns 21 .
@example [century 2000] returns 20
@example [century 2001] returns 21. *)
val millenium : year -> int
* Millenium of a year .
@example [ millenium 2000 ] returns 2
@example [ millenium 2001 ] returns 3 .
@example [millenium 2000] returns 2
@example [millenium 2001] returns 3. *)
val solar_number : year -> int
* Solar number .
In the Julian calendar there is a one - to - one relationship between the
Solar number and the day on which a particular date falls .
In the Julian calendar there is a one-to-one relationship between the
Solar number and the day on which a particular date falls. *)
val indiction : year -> int
* Indiction .
The Indiction was used in the middle ages to specify the position of a
year in a 15 year taxation cycle . It was introduced by emperor
1 September 312 and ceased to be used in
1806 .
The Indiction has no astronomical significance .
The Indiction was used in the middle ages to specify the position of a
year in a 15 year taxation cycle. It was introduced by emperor
Constantine the Great on 1 September 312 and ceased to be used in
1806.
The Indiction has no astronomical significance. *)
val golden_number : year -> int
* Golden number .
Considering that the relationship between the moon 's phases and the
days of the year repeats itself every 19 years , it is natural to
associate a number between 1 and 19 with each year .
This number is the so - called Golden number .
Considering that the relationship between the moon's phases and the
days of the year repeats itself every 19 years, it is natural to
associate a number between 1 and 19 with each year.
This number is the so-called Golden number. *)
val epact : year -> int
* Epact .
The Epact is a measure of the age of the moon ( i.e. the number of days
that have passed since an " official " new moon ) on a particular date .
The Epact is a measure of the age of the moon (i.e. the number of days
that have passed since an "official" new moon) on a particular date. *)
val easter : year -> t
* Easter Sunday .
In the Christian world , ( and the days immediately preceding it )
is the celebration of the death and resurrection of in
( approximately ) AD 30 .
In the Christian world, Easter (and the days immediately preceding it)
is the celebration of the death and resurrection of Jesus in
(approximately) AD 30. *)
val carnaval: year -> t
* Monday . [ carnaval y ] is [ easter y - 48 ] .
@since 1.09.0
@since 1.09.0 *)
val mardi_gras: year -> t
* Mardi Gras . [ mardi_gras y ] is [ easter y - 47 ] .
@since 1.09.0
@since 1.09.0 *)
val ash: year -> t
* Ash Wednesday . [ ash y ] is [ easter y - 46 ] .
@since 1.09.0
@since 1.09.0 *)
val palm: year -> t
* Palm Sunday . [ palm y ] is [ easter y - 7 ] .
@since 1.09.0
@since 1.09.0 *)
val easter_friday: year -> t
* Easter Friday . [ easter_friday y ] is [ easter y - 2 ] .
@since 1.09.0
@since 1.09.0 *)
val easter_saturday: year -> t
* Easter Saturday . [ easter_saturday y ] is [ easter y - 1 ] .
@since 1.09.0
@since 1.09.0 *)
val easter_monday: year -> t
* Easter Monday . [ easter_monday y ] is [ easter y + 1 ] .
@since 1.09.0
@since 1.09.0 *)
val ascension: year -> t
* Ascension . [ ascension y ] is [ easter y + 39 ] .
@since 1.09.0
@since 1.09.0 *)
val withsunday: year -> t
* Withsunday . [ withsunday y ] is [ easter y + 49 ] .
@since 1.09.0
@since 1.09.0 *)
val withmonday: year -> t
* Withmonday . [ withmonday y ] is [ easter y + 50 ] .
@since 1.09.0
@since 1.09.0 *)
val corpus_christi: year -> t
* Feast of Corpus Christi . [ corpus_christi y ] is [ easter + 60 ] .
@since 1.09.0
@since 1.09.0 *)
end
| null | https://raw.githubusercontent.com/ocaml-community/calendar/f119658010cc9045e1866eddadc4a776adbcc146/src/date_sig.mli | ocaml | ************************************************************************
This file is part of Calendar.
you can redistribute it and/or modify it under the terms of the GNU
for Objective Caml libraries).
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
details (enclosed in the file LGPL).
The special linking exception is detailled in the enclosed file
LICENSE.
************************************************************************
* Common operations for all date representations.
@since 2.0 (this signature was before inlined in interface of Date).
* Type of a date.
* Year as an [int].
* {2 Constructors}
* Date of the current day (based on [Time_Zone.current ()]).
* Hash function for dates.
@see <Utils.Comparable.html#VALhash> Utils.Comparable.hash
@since 2.0
* Return [true] if a date belongs to the Gregorian calendar;
[false] otherwise.
* {2 Period}
* Labelled version of [make].
The default value of each argument is [0].
* [year n] makes a period of [n] years.
* [day n] makes a period of [n] days.
* [sub d1 d2] returns the period between [d1] and [d2]. | Copyright ( C ) 2003 - 2011
Lesser General Public License version 2.1 as published by the
Free Software Foundation , with a special linking exception ( usual
See the GNU Lesser General Public Licence version 2.1 for more
* Date interface . A date may be seen as a triple ( year , month , day ) .
All the dates should belong to
[ [ January , 1st 4713 BC ; January 22th , 3268 AC ] ] ( called the Julian period ) .
An [ Out_of_bounds ] exception is raised if you attempt to create a date
outside the Julian period .
If a date [ d ] does not exists and if [ d_bef ] ( resp . [ d_aft ] ) is
the last ( resp . first ) existing date before ( resp . after ) [ d ] ,
[ d ] is automatically coerced to [ d_aft + d - d_bef - 1 ] .
For example , both dates " February 29th , 2003 " and
" February 30th , 2003 " do not exist and they are coerced respectively to the
date " Mars 1st , 2003 " and " Mars 2nd , 2003 " .
This rule is called the coercion rule .
As an exception to the coercion rule , the date belonging to
[ [ October 5th , 1582 ; October 14th , 1582 ] ] do not exist and an [ Undefined ]
exception is raised if you attempt to create such a date .
Those dropped days correspond to the change from the Julian to the calendar .
All the dates should belong to
[[January, 1st 4713 BC; January 22th, 3268 AC]] (called the Julian period).
An [Out_of_bounds] exception is raised if you attempt to create a date
outside the Julian period.
If a date [d] does not exists and if [d_bef] (resp. [d_aft]) is
the last (resp. first) existing date before (resp. after) [d],
[d] is automatically coerced to [d_aft + d - d_bef - 1].
For example, both dates "February 29th, 2003" and
"February 30th, 2003" do not exist and they are coerced respectively to the
date "Mars 1st, 2003" and "Mars 2nd, 2003".
This rule is called the coercion rule.
As an exception to the coercion rule, the date belonging to
[[October 5th, 1582; October 14th, 1582]] do not exist and an [Undefined]
exception is raised if you attempt to create such a date.
Those dropped days correspond to the change from the Julian to the Gregorian
calendar. *)
module type S = sig
* { 2 }
* The different fields of a date .
@since 2.02
@since 2.02 *)
type field = Period.date_field
* Type of a date , without specifying any precision level .
@since 2.02
@since 2.02 *)
type -'a date constraint 'a = [< field ]
type t = field date
* Days of the week .
type day = Sun | Mon | Tue | Wed | Thu | Fri | Sat
* Months of the year .
type month =
Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
type year = int
* { 2 Exceptions }
exception Out_of_bounds
* Raised when a date is outside the Julian period .
exception Undefined
* Raised when a date belongs to
[ [ October 5th , 1582 ; October 14th , 1582 ] ] .
[[October 5th, 1582; October 14th, 1582]]. *)
val make : year -> int -> int -> t
* [ make year month day ] makes the date year - month - day . A BC year [ y ]
corresponds to the year [ -(y+1 ) ] .
@example years ( 5 BC ) and ( 1 BC ) respectively correspond to years
( -4 ) and 0 .
@raise Out_of_bounds when a date is outside the Julian period .
@raise Undefined when a date belongs to [ [ October 5th , 1582 ; October
14th , 1582 ] ] .
corresponds to the year [-(y+1)].
@example years (5 BC) and (1 BC) respectively correspond to years
(-4) and 0.
@raise Out_of_bounds when a date is outside the Julian period.
@raise Undefined when a date belongs to [[October 5th, 1582; October
14th, 1582]]. *)
val lmake : year:year -> ?month:int -> ?day:int -> unit -> t
* Labelled version of [ make ] .
The default value of [ month ] and [ day ] is [ 1 ] .
@raise Out_of_bounds when a date is outside the Julian period .
@raise Undefined when a date belongs to [ [ October 5th , 1582 ; October
14th , 1582 ] ] .
@since 1.05
The default value of [month] and [day] is [1].
@raise Out_of_bounds when a date is outside the Julian period.
@raise Undefined when a date belongs to [[October 5th, 1582; October
14th, 1582]].
@since 1.05 *)
val make_year: int -> [< `Year ] date
* [ make_year y ] makes a date only represented by its year [ y ] . The month
and the day of such a date are not relevant .
@since 2.02
and the day of such a date are not relevant.
@since 2.02 *)
val make_year_month: int -> int -> [< `Year | `Month ] date
* [ make_year_month y m ] makes a date only represented by its year [ y ] and
its month [ m ] . The day of such a date is not relevant .
@since 2.02
its month [m]. The day of such a date is not relevant.
@since 2.02 *)
val today : unit -> t
val from_jd : int -> t
* Make a date from its Julian day .
@example [ from_jd 0 ] returns the date 4713 BC-1 - 1 .
@example [from_jd 0] returns the date 4713 BC-1-1. *)
val from_mjd : int -> t
* Make a date from its modified Julian day ( i.e. Julian day - 2 400 001 ) .
The Modified Julian day is more manageable than the Julian day .
@example [ from_mjd 0 ] returns the date 1858 - 11 - 17 .
The Modified Julian day is more manageable than the Julian day.
@example [from_mjd 0] returns the date 1858-11-17. *)
val from_day_of_year: year -> int -> t
* Make a date from a year and its day of the year .
@example [ from_day_of_year 2008 39 ] returns the date 2008 - 2 - 8 .
@since 2.0
@example [from_day_of_year 2008 39] returns the date 2008-2-8.
@since 2.0 *)
* { 2 Getters }
val days_in_month : [> `Year | `Month ] date -> int
* Number of days in the month of a date .
@example [ days_in_month ( make 2003 6 26 ) ] returns [ 30 ] .
@example [days_in_month (make 2003 6 26)] returns [30]. *)
val day_of_week : t -> day
* Day of the week .
@example [ ( make 2003 6 26 ) ] returns [ Thu ] .
@example [day_of_week (make 2003 6 26)] returns [Thu]. *)
val day_of_month : t -> int
* Day of the month .
@example [ day_of_month ( make 2003 6 26 ) ] returns [ 26 ] .
@example [day_of_month (make 2003 6 26)] returns [26]. *)
val day_of_year : t -> int
* Day of the year .
@example [ day_of_year ( make 2003 1 5 ) ] returns [ 5 ]
@example [ day_of_year ( make 2003 12 28 ) ] returns [ 362 ] .
@example [day_of_year (make 2003 1 5)] returns [5]
@example [day_of_year (make 2003 12 28)] returns [362]. *)
val week : t -> int
* Week .
@example [ week ( make 2000 1 3 ) ] returns [ 1 ] .
@example [ week ( make 2000 1 2 ) ] returns [ 52 ] .
@example [ week ( make 2003 12 28 ) ] returns [ 52 ] .
@example [ week ( make 2003 12 29 ) ] returns [ 1 ] .
@example [week (make 2000 1 3)] returns [1].
@example [week (make 2000 1 2)] returns [52].
@example [week (make 2003 12 28)] returns [52].
@example [week (make 2003 12 29)] returns [1]. *)
val month : [> `Month ] date -> month
* Month .
@example [ month ( make 2003 6 26 ) ] returns [ Jun ] .
@example [month (make 2003 6 26)] returns [Jun]. *)
val year : [> `Year ] date -> year
* Year .
@example [ year ( make 2003 6 26 ) ] returns [ 2003 ] .
@example [year (make 2003 6 26)] returns [2003]. *)
val to_jd : t -> int
* Julian day .
@example [ to_jd ( make ( -4712 ) 1 1 ) ] returns 0 .
@example [to_jd (make (-4712) 1 1)] returns 0. *)
val to_mjd : t -> int
* Modified Julian day ( i.e. Julian day - 2 400 001 ) .
The Modified Julian day is more manageable than the Julian day .
@example [ ( make 1858 11 17 ) ] returns 0 .
The Modified Julian day is more manageable than the Julian day.
@example [to_mjd (make 1858 11 17)] returns 0. *)
* { 2 Dates are comparable }
val equal: 'a date -> 'b date -> bool
* Equality function between two dates .
@see < Utils.Comparable.html#VALequal > Utils.Comparable.equal
@since 1.09.0
@see <Utils.Comparable.html#VALequal> Utils.Comparable.equal
@since 1.09.0 *)
val compare : 'a date -> 'b date -> int
* Comparison function between two dates .
@see < Utils.Comparable.html#VALcompare > Utils.Comparable.compare
@see <Utils.Comparable.html#VALcompare> Utils.Comparable.compare *)
val ( > ) : 'a date -> 'b date -> bool
* Check if the first date is later than the second
val ( >= ) : 'a date -> 'b date -> bool
* Check if the first date is later or equal to the second
val ( < ) : 'a date -> 'b date -> bool
* Check if the first date is earlier than the second
val ( <= ) : 'a date -> 'b date -> bool
* Check if the first date is earlier or equal to the second
val hash: 'a date -> int
* { 2 Boolean operations on dates }
val is_valid_date: year -> int -> int -> bool
* Check if a date is valid , that is the date has not been coerced to look
like a real date .
@example [ is_valid_date 2008 2 8 ] returns [ true ]
@example [ is_valid_date 2008 2 30 ] returns [ false ]
@since 2.0
like a real date.
@example [is_valid_date 2008 2 8] returns [true]
@example [is_valid_date 2008 2 30] returns [false]
@since 2.0 *)
val is_leap_day : t -> bool
* Return [ true ] if a date is a leap day
( i.e. February , 24th of a leap year ) ; [ false ] otherwise .
(i.e. February, 24th of a leap year); [false] otherwise. *)
val is_gregorian : t -> bool
val is_julian : t -> bool
* Return [ true ] iff a date belongs to the Julian calendar ;
[ false ] otherwise .
[false] otherwise. *)
* { 2 Coercions }
val to_unixtm : t -> Unix.tm
* Convert a date into the [ Unix.tm ] type .
The field [ is_isdst ] is always [ false ] . The fields [ Unix.tm_sec ] ,
[ Unix.tm_min ] and [ Unix.tm_hour ] are irrelevant .
@since 1.01
The field [is_isdst] is always [false]. The fields [Unix.tm_sec],
[Unix.tm_min] and [Unix.tm_hour] are irrelevant.
@since 1.01 *)
val from_unixtm : Unix.tm -> t
* Inverse of [ to_unixtm ] . Assume the current time zone .
@since 1.01
@since 1.01 *)
val to_unixfloat : t -> float
* Convert a date to a float such than [ to_unixfloat ( make 1970 1 1 ) ]
returns [ 0.0 ] . So such a float is convertible with those of the [ Unix ]
module . The fractional part of the result is always [ 0 ] .
@since 1.01
returns [0.0]. So such a float is convertible with those of the [Unix]
module. The fractional part of the result is always [0].
@since 1.01 *)
val from_unixfloat : float -> t
* Inverse of [ to_unixfloat ] . Ignore the fractional part of the argument .
Assume the current time zone .
@since 1.01
Assume the current time zone.
@since 1.01 *)
val to_business: t -> year * int * day
* Return the " business week " and the day in this week respecting ISO 8601 .
Notice that business weeks at the beginning and end of the year can
sometimes have year numbers which do n't match the real year .
@example [ to_business ( make 2000 1 3 ) ] returns [ 2000 , 1 , Mon ]
@example [ to_business ( make 2000 1 2 ) ] returns [ 1999 , 52 , Sun ]
@example [ to_business ( make 2003 12 28 ) ] returns [ 2003 , 52 , Sun ]
@example [ to_business ( make 2003 12 29 ) ] returns [ 2004 , 1 , Mon ] .
@since 1.09.0
Notice that business weeks at the beginning and end of the year can
sometimes have year numbers which don't match the real year.
@example [to_business (make 2000 1 3)] returns [2000, 1, Mon]
@example [to_business (make 2000 1 2)] returns [1999, 52, Sun]
@example [to_business (make 2003 12 28)] returns [2003, 52, Sun]
@example [to_business (make 2003 12 29)] returns [2004, 1, Mon].
@since 1.09.0 *)
val from_business: year -> int -> day -> t
* Inverse of [ to_business ] respecting ISO-8601 .
Notice that business weeks at the beginning and end of the year
can sometimes have year numbers which do n't match the real year .
@raise Invalid_argument if the date is bad .
@since 1.09.0
Notice that business weeks at the beginning and end of the year
can sometimes have year numbers which don't match the real year.
@raise Invalid_argument if the date is bad.
@since 1.09.0 *)
val int_of_day : day -> int
* Convert a day to an integer respecting ISO-8601 .
So , Monday is 1 , Tuesday is 2 , ... , and sunday is 7 .
So, Monday is 1, Tuesday is 2, ..., and sunday is 7. *)
val day_of_int : int -> day
* Inverse of [ int_of_day ] .
@raise Invalid_argument if the argument does not belong to [ 1 ; 7 ] .
@raise Invalid_argument if the argument does not belong to [1; 7]. *)
val int_of_month : month -> int
* Convert a month to an integer respecting ISO-8601 .
So , January is 1 , February is 2 and so on .
So, January is 1, February is 2 and so on. *)
val month_of_int : int -> month
* Inverse of [ int_of_month ] .
@raise Invalid_argument if the argument does not belong to [ 1 ; 12 ] .
@raise Invalid_argument if the argument does not belong to [1; 12]. *)
* A period is the number of days between two dates .
module Period : sig
* { 3 Arithmetic operations }
type +'a p constraint 'a = [< field ]
include Period.S with type +'a period = 'a p
* { 3 Constructors }
val make: int -> int -> int -> t
* [ make year month day ] makes a period of the specified length .
val lmake: ?year:int -> ?month:int -> ?day:int -> unit -> t
val year: int -> [> `Year ] period
val month: int -> [> `Year | `Month ] period
* [ month n ] makes a period of [ n ] months .
val week: int -> [> `Week | `Day ] period
* [ week n ] makes a period of [ n ] weeks .
val day: int -> [> `Week | `Day ] period
* { 3 Getters }
exception Not_computable
* @since 1.04
val nb_days: 'a period -> int
* Number of days in a period .
@raise Not_computable if the number of days is not computable .
@example [ nb_days ( day 6 ) ] returns [ 6 ]
@example [ nb_days ( year 1 ) ] raises [ Not_computable ] because a year is
not a constant number of days .
@since 1.04
@deprecated since 2.02 : use { ! safe_nb_days } instead
@raise Not_computable if the number of days is not computable.
@example [nb_days (day 6)] returns [6]
@example [nb_days (year 1)] raises [Not_computable] because a year is
not a constant number of days.
@since 1.04
@deprecated since 2.02: use {!safe_nb_days} instead *)
val safe_nb_days: [< `Week | `Day ] period -> int
* Equivalent to { ! nb_days } but never raises any exception .
@since 2.02
@since 2.02 *)
val ymd: 'a period -> int * int * int
* Number of years , months and days in a period .
@example [ ymd ( make 1 2 3 ) ] returns [ 1 , 2 , 3 ] .
@since 1.09.0
@example [ymd (make 1 2 3)] returns [1, 2, 3].
@since 1.09.0 *)
end
* { 2 Arithmetic operations on dates and periods }
val add : 'a date -> 'a Period.period -> 'a date
* [ add d p ] returns [ d + p ] .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@example [ add ( make 2003 12 31 ) ( Period.month 1 ) ] returns the date
2004 - 1 - 31
@example [ add ( make 2003 12 31 ) ( Period.month 2 ) ] returns the date
2004 - 3 - 2 ( following the coercion rule describes in the introduction ) .
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]].
@example [add (make 2003 12 31) (Period.month 1)] returns the date
2004-1-31
@example [add (make 2003 12 31) (Period.month 2)] returns the date
2004-3-2 (following the coercion rule describes in the introduction). *)
val sub : 'a date -> 'a date -> [> `Week | `Day ] Period.period
val precise_sub : 'a date -> 'a date -> Period.t
* [ precise_sub d1 d2 ] returns the period between [ d1 ] and [ d2 ] .
It is equivalent to [ sub ] , but :
- the period is expressed with a number of years , months and days , not
only with a number of days ;
- it is less efficient .
@since 2.03
It is equivalent to [sub], but:
- the period is expressed with a number of years, months and days, not
only with a number of days;
- it is less efficient.
@since 2.03 *)
val rem : 'a date -> 'a Period.period -> 'a date
* [ rem d p ] is equivalent to [ add d ( Period.opp p ) ] .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]]. *)
val next : 'a date -> ([< field ] as 'a) -> 'a date
* [ next d f ] returns the date corresponding to the next specified field .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@example [ next ( make 2003 12 31 ) ` Month ] returns the date 2004 - 1 - 31
( i.e. one month later ) .
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]].
@example [next (make 2003 12 31) `Month] returns the date 2004-1-31
(i.e. one month later). *)
val prev : 'a date -> ([< field ] as 'a) -> 'a date
* [ prev d f ] returns the date corresponding to the previous specified
field .
@raise Out_of_bounds when the resulting date is outside the Julian
period .
@raise Undefined when the resulting date belongs to [ [ October 5th ,
1582 ; October 14th , 1582 ] ] .
@example [ prev ( make 2003 12 31 ) ` Year ] returns the date 2002 - 12 - 31
( i.e. one year ago ) .
field.
@raise Out_of_bounds when the resulting date is outside the Julian
period.
@raise Undefined when the resulting date belongs to [[October 5th,
1582; October 14th, 1582]].
@example [prev (make 2003 12 31) `Year] returns the date 2002-12-31
(i.e. one year ago). *)
* { 2 Operations on years }
val is_leap_year : year -> bool
* Return [ true ] if a year is a leap year ; [ false ] otherwise .
val same_calendar : year -> year -> bool
* Return [ true ] if two years have the same calendar ; [ false ]
otherwise .
otherwise. *)
val days_in_year : ?month:month -> year -> int
* Number of days in a year .
[ days_in_year ~month y ] returns the number of days in the year [ y ] up
to the end of the given month . Thus [ days_in_year ~month : Dec y ] is the
same as [ days_in_year y ] .
[days_in_year ~month y] returns the number of days in the year [y] up
to the end of the given month. Thus [days_in_year ~month:Dec y] is the
same as [days_in_year y]. *)
val weeks_in_year: year -> int
* Number of weeks in a year .
val week_first_last: int -> year -> t * t
* Return the first and last days of a week in a year .
@since 1.08
@since 1.08 *)
val nth_weekday_of_month: year -> month -> day -> int -> t
* [ nth_weekday_of_month y m d n ] returns the [ n]-th day [ d ] in the month
[ m ] of the year [ y ] ( for instance the 3rd Thursday of the month ) .
@since 1.09.0
[m] of the year [y] (for instance the 3rd Thursday of the month).
@since 1.09.0 *)
val century : year -> int
* Century of a year .
@example [ century 2000 ] returns 20
@example [ century 2001 ] returns 21 .
@example [century 2000] returns 20
@example [century 2001] returns 21. *)
val millenium : year -> int
* Millenium of a year .
@example [ millenium 2000 ] returns 2
@example [ millenium 2001 ] returns 3 .
@example [millenium 2000] returns 2
@example [millenium 2001] returns 3. *)
val solar_number : year -> int
* Solar number .
In the Julian calendar there is a one - to - one relationship between the
Solar number and the day on which a particular date falls .
In the Julian calendar there is a one-to-one relationship between the
Solar number and the day on which a particular date falls. *)
val indiction : year -> int
* Indiction .
The Indiction was used in the middle ages to specify the position of a
year in a 15 year taxation cycle . It was introduced by emperor
1 September 312 and ceased to be used in
1806 .
The Indiction has no astronomical significance .
The Indiction was used in the middle ages to specify the position of a
year in a 15 year taxation cycle. It was introduced by emperor
Constantine the Great on 1 September 312 and ceased to be used in
1806.
The Indiction has no astronomical significance. *)
val golden_number : year -> int
* Golden number .
Considering that the relationship between the moon 's phases and the
days of the year repeats itself every 19 years , it is natural to
associate a number between 1 and 19 with each year .
This number is the so - called Golden number .
Considering that the relationship between the moon's phases and the
days of the year repeats itself every 19 years, it is natural to
associate a number between 1 and 19 with each year.
This number is the so-called Golden number. *)
val epact : year -> int
* Epact .
The Epact is a measure of the age of the moon ( i.e. the number of days
that have passed since an " official " new moon ) on a particular date .
The Epact is a measure of the age of the moon (i.e. the number of days
that have passed since an "official" new moon) on a particular date. *)
val easter : year -> t
* Easter Sunday .
In the Christian world , ( and the days immediately preceding it )
is the celebration of the death and resurrection of in
( approximately ) AD 30 .
In the Christian world, Easter (and the days immediately preceding it)
is the celebration of the death and resurrection of Jesus in
(approximately) AD 30. *)
val carnaval: year -> t
* Monday . [ carnaval y ] is [ easter y - 48 ] .
@since 1.09.0
@since 1.09.0 *)
val mardi_gras: year -> t
* Mardi Gras . [ mardi_gras y ] is [ easter y - 47 ] .
@since 1.09.0
@since 1.09.0 *)
val ash: year -> t
* Ash Wednesday . [ ash y ] is [ easter y - 46 ] .
@since 1.09.0
@since 1.09.0 *)
val palm: year -> t
* Palm Sunday . [ palm y ] is [ easter y - 7 ] .
@since 1.09.0
@since 1.09.0 *)
val easter_friday: year -> t
* Easter Friday . [ easter_friday y ] is [ easter y - 2 ] .
@since 1.09.0
@since 1.09.0 *)
val easter_saturday: year -> t
* Easter Saturday . [ easter_saturday y ] is [ easter y - 1 ] .
@since 1.09.0
@since 1.09.0 *)
val easter_monday: year -> t
* Easter Monday . [ easter_monday y ] is [ easter y + 1 ] .
@since 1.09.0
@since 1.09.0 *)
val ascension: year -> t
* Ascension . [ ascension y ] is [ easter y + 39 ] .
@since 1.09.0
@since 1.09.0 *)
val withsunday: year -> t
* Withsunday . [ withsunday y ] is [ easter y + 49 ] .
@since 1.09.0
@since 1.09.0 *)
val withmonday: year -> t
* Withmonday . [ withmonday y ] is [ easter y + 50 ] .
@since 1.09.0
@since 1.09.0 *)
val corpus_christi: year -> t
* Feast of Corpus Christi . [ corpus_christi y ] is [ easter + 60 ] .
@since 1.09.0
@since 1.09.0 *)
end
|
2639035435a5a51453bc610414401739513d544eee249ea24e8f2ccfe3ff1963 | gersak/vura | db.cljc | ;; This file is autogenerated using vura.timezones.compile/-main
(ns vura.timezones.db
(:require [clojure.string]))
(declare db locales)
(defn get-rule [rule]
(get-in db [:rules rule]))
(defn get-timezone [zone-name]
(if-let [zone' (get-in db [:zones zone-name])]
(if (string? zone') (get-timezone zone')
zone')
(throw
(ex-info "No such zone."
{:timezone zone-name
:available-timezones (keys (:zones db))}))))
(def available-zones
(sort (keys (:zones db))))
(def locales
{"CR" {:coordinates "+0956-08405", :zone "America/Costa_Rica"},
"TG" {:coordinates "+0608+00113", :zone "Africa/Lome"},
"TJ" {:coordinates "+3835+06848", :zone "Asia/Dushanbe"},
"ZA" {:coordinates "-2615+02800", :zone "Africa/Johannesburg"},
"IM" {:coordinates "+5409-00428", :zone "Europe/Isle_of_Man"},
"PE" {:coordinates "-1203-07703", :zone "America/Lima"},
"LC" {:coordinates "+1401-06100", :zone "America/St_Lucia"},
"CH" {:coordinates "+4723+00832", :zone "Europe/Zurich"},
"RU" {:coordinates "+6445+17729", :zone "Asia/Anadyr"},
"MP" {:coordinates "+1512+14545", :zone "Pacific/Saipan"},
"CK" {:coordinates "-2114-15946", :zone "Pacific/Rarotonga"},
"SI" {:coordinates "+4603+01431", :zone "Europe/Ljubljana"},
"AU" {:coordinates "-3143+12852", :zone "Australia/Eucla"},
"KR" {:coordinates "+3733+12658", :zone "Asia/Seoul"},
"IT" {:coordinates "+4154+01229", :zone "Europe/Rome"},
"FI" {:coordinates "+6010+02458", :zone "Europe/Helsinki"},
"GF" {:coordinates "+0456-05220", :zone "America/Cayenne"},
"SC" {:coordinates "-0440+05528", :zone "Indian/Mahe"},
"SX" {:coordinates "+180305-0630250", :zone "America/Lower_Princes"},
"TT" {:coordinates "+1039-06131", :zone "America/Port_of_Spain"},
"TK" {:coordinates "-0922-17114", :zone "Pacific/Fakaofo"},
"MY" {:coordinates "+0133+11020", :zone "Asia/Kuching"},
"SY" {:coordinates "+3330+03618", :zone "Asia/Damascus"},
"MN" {:coordinates "+4804+11430", :zone "Asia/Choibalsan"},
"TF" {:coordinates "-492110+0701303", :zone "Indian/Kerguelen"},
"KP" {:coordinates "+3901+12545", :zone "Asia/Pyongyang"},
"AM" {:coordinates "+4011+04430", :zone "Asia/Yerevan"},
"DZ" {:coordinates "+3647+00303", :zone "Africa/Algiers"},
"UY" {:coordinates "-345433-0561245", :zone "America/Montevideo"},
"TD" {:coordinates "+1207+01503", :zone "Africa/Ndjamena"},
"DJ" {:coordinates "+1136+04309", :zone "Africa/Djibouti"},
"BI" {:coordinates "-0323+02922", :zone "Africa/Bujumbura"},
"MK" {:coordinates "+4159+02126", :zone "Europe/Skopje"},
"MU" {:coordinates "-2010+05730", :zone "Indian/Mauritius"},
"LI" {:coordinates "+4709+00931", :zone "Europe/Vaduz"},
"NU" {:coordinates "-1901-16955", :zone "Pacific/Niue"},
"GR" {:coordinates "+3758+02343", :zone "Europe/Athens"},
"GY" {:coordinates "+0648-05810", :zone "America/Guyana"},
"CG" {:coordinates "-0416+01517", :zone "Africa/Brazzaville"},
"NF" {:coordinates "-2903+16758", :zone "Pacific/Norfolk"},
"ML" {:coordinates "+1239-00800", :zone "Africa/Bamako"},
"AX" {:coordinates "+6006+01957", :zone "Europe/Mariehamn"},
"GM" {:coordinates "+1328-01639", :zone "Africa/Banjul"},
"SA" {:coordinates "+2438+04643", :zone "Asia/Riyadh"},
"CX" {:coordinates "-1025+10543", :zone "Indian/Christmas"},
"BH" {:coordinates "+2623+05035", :zone "Asia/Bahrain"},
"NE" {:coordinates "+1331+00207", :zone "Africa/Niamey"},
"BN" {:coordinates "+0456+11455", :zone "Asia/Brunei"},
"MF" {:coordinates "+1804-06305", :zone "America/Marigot"},
"CD" {:coordinates "-1140+02728", :zone "Africa/Lubumbashi"},
"DK" {:coordinates "+5540+01235", :zone "Europe/Copenhagen"},
"BJ" {:coordinates "+0629+00237", :zone "Africa/Porto-Novo"},
"ME" {:coordinates "+4226+01916", :zone "Europe/Podgorica"},
"SJ" {:coordinates "+7800+01600", :zone "Arctic/Longyearbyen"},
"BO" {:coordinates "-1630-06809", :zone "America/La_Paz"},
"JO" {:coordinates "+3157+03556", :zone "Asia/Amman"},
"CV" {:coordinates "+1455-02331", :zone "Atlantic/Cape_Verde"},
"VE" {:coordinates "+1030-06656", :zone "America/Caracas"},
"CI" {:coordinates "+0519-00402", :zone "Africa/Abidjan"},
"UZ" {:coordinates "+4120+06918", :zone "Asia/Tashkent"},
"TN" {:coordinates "+3648+01011", :zone "Africa/Tunis"},
"IS" {:coordinates "+6409-02151", :zone "Atlantic/Reykjavik"},
"EH" {:coordinates "+2709-01312", :zone "Africa/El_Aaiun"},
"TM" {:coordinates "+3757+05823", :zone "Asia/Ashgabat"},
"GA" {:coordinates "+0023+00927", :zone "Africa/Libreville"},
"LS" {:coordinates "-2928+02730", :zone "Africa/Maseru"},
"TZ" {:coordinates "-0648+03917", :zone "Africa/Dar_es_Salaam"},
"AT" {:coordinates "+4813+01620", :zone "Europe/Vienna"},
"LT" {:coordinates "+5441+02519", :zone "Europe/Vilnius"},
"NP" {:coordinates "+2743+08519", :zone "Asia/Kathmandu"},
"BG" {:coordinates "+4241+02319", :zone "Europe/Sofia"},
"IL" {:coordinates "+314650+0351326", :zone "Asia/Jerusalem"},
"GU" {:coordinates "+1328+14445", :zone "Pacific/Guam"},
"PK" {:coordinates "+2452+06703", :zone "Asia/Karachi"},
"PT" {:coordinates "+3744-02540", :zone "Atlantic/Azores"},
"HR" {:coordinates "+4548+01558", :zone "Europe/Zagreb"},
"VU" {:coordinates "-1740+16825", :zone "Pacific/Efate"},
"PF" {:coordinates "-2308-13457", :zone "Pacific/Gambier"},
"BM" {:coordinates "+3217-06446", :zone "Atlantic/Bermuda"},
"MR" {:coordinates "+1806-01557", :zone "Africa/Nouakchott"},
"GE" {:coordinates "+4143+04449", :zone "Asia/Tbilisi"},
"HU" {:coordinates "+4730+01905", :zone "Europe/Budapest"},
"TW" {:coordinates "+2503+12130", :zone "Asia/Taipei"},
"MM" {:coordinates "+1647+09610", :zone "Asia/Yangon"},
"VG" {:coordinates "+1827-06437", :zone "America/Tortola"},
"YE" {:coordinates "+1245+04512", :zone "Asia/Aden"},
"SR" {:coordinates "+0550-05510", :zone "America/Paramaribo"},
"PN" {:coordinates "-2504-13005", :zone "Pacific/Pitcairn"},
"VA" {:coordinates "+415408+0122711", :zone "Europe/Vatican"},
"PR" {:coordinates "+182806-0660622", :zone "America/Puerto_Rico"},
"KW" {:coordinates "+2920+04759", :zone "Asia/Kuwait"},
"SE" {:coordinates "+5920+01803", :zone "Europe/Stockholm"},
"GB" {:coordinates "+513030-0000731", :zone "Europe/London"},
"UM" {:coordinates "+1917+16637", :zone "Pacific/Wake"},
"VN" {:coordinates "+1045+10640", :zone "Asia/Ho_Chi_Minh"},
"CF" {:coordinates "+0422+01835", :zone "Africa/Bangui"},
"PA" {:coordinates "+0858-07932", :zone "America/Panama"},
"VC" {:coordinates "+1309-06114", :zone "America/St_Vincent"},
"JP" {:coordinates "+353916+1394441", :zone "Asia/Tokyo"},
"IR" {:coordinates "+3540+05126", :zone "Asia/Tehran"},
"AF" {:coordinates "+3431+06912", :zone "Asia/Kabul"},
"LY" {:coordinates "+3254+01311", :zone "Africa/Tripoli"},
"MZ" {:coordinates "-2558+03235", :zone "Africa/Maputo"},
"RO" {:coordinates "+4426+02606", :zone "Europe/Bucharest"},
"QA" {:coordinates "+2517+05132", :zone "Asia/Qatar"},
"CM" {:coordinates "+0403+00942", :zone "Africa/Douala"},
"GG" {:coordinates "+492717-0023210", :zone "Europe/Guernsey"},
"BY" {:coordinates "+5354+02734", :zone "Europe/Minsk"},
"SD" {:coordinates "+1536+03232", :zone "Africa/Khartoum"},
"BQ" {:coordinates "+120903-0681636", :zone "America/Kralendijk"},
"MO" {:coordinates "+221150+1133230", :zone "Asia/Macau"},
"KY" {:coordinates "+1918-08123", :zone "America/Cayman"},
"AR" {:coordinates "-5448-06818", :zone "America/Argentina/Ushuaia"},
"BR" {:coordinates "-0958-06748", :zone "America/Rio_Branco"},
"ZW" {:coordinates "-1750+03103", :zone "Africa/Harare"},
"NR" {:coordinates "-0031+16655", :zone "Pacific/Nauru"},
"NZ" {:coordinates "-4357-17633", :zone "Pacific/Chatham"},
"AW" {:coordinates "+1230-06958", :zone "America/Aruba"},
"FJ" {:coordinates "-1808+17825", :zone "Pacific/Fiji"},
"ID" {:coordinates "-0232+14042", :zone "Asia/Jayapura"},
"SV" {:coordinates "+1342-08912", :zone "America/El_Salvador"},
"CN" {:coordinates "+4348+08735", :zone "Asia/Urumqi"},
"FM" {:coordinates "+0519+16259", :zone "Pacific/Kosrae"},
"HT" {:coordinates "+1832-07220", :zone "America/Port-au-Prince"},
"CC" {:coordinates "-1210+09655", :zone "Indian/Cocos"},
"RW" {:coordinates "-0157+03004", :zone "Africa/Kigali"},
"BA" {:coordinates "+4352+01825", :zone "Europe/Sarajevo"},
"TL" {:coordinates "-0833+12535", :zone "Asia/Dili"},
"JM" {:coordinates "+175805-0764736", :zone "America/Jamaica"},
"KM" {:coordinates "-1141+04316", :zone "Indian/Comoro"},
"KE" {:coordinates "-0117+03649", :zone "Africa/Nairobi"},
"WS" {:coordinates "-1350-17144", :zone "Pacific/Apia"},
"TO" {:coordinates "-2110-17510", :zone "Pacific/Tongatapu"},
"PY" {:coordinates "-2516-05740", :zone "America/Asuncion"},
"SH" {:coordinates "-1555-00542", :zone "Atlantic/St_Helena"},
"CY" {:coordinates "+3507+03357", :zone "Asia/Famagusta"},
"GH" {:coordinates "+0533-00013", :zone "Africa/Accra"},
"MA" {:coordinates "+3339-00735", :zone "Africa/Casablanca"},
"SG" {:coordinates "+0117+10351", :zone "Asia/Singapore"},
"LK" {:coordinates "+0656+07951", :zone "Asia/Colombo"},
"PH" {:coordinates "+1435+12100", :zone "Asia/Manila"},
"SM" {:coordinates "+4355+01228", :zone "Europe/San_Marino"},
"WF" {:coordinates "-1318-17610", :zone "Pacific/Wallis"},
"TR" {:coordinates "+4101+02858", :zone "Europe/Istanbul"},
"PS" {:coordinates "+313200+0350542", :zone "Asia/Hebron"},
"BZ" {:coordinates "+1730-08812", :zone "America/Belize"},
"CU" {:coordinates "+2308-08222", :zone "America/Havana"},
"TV" {:coordinates "-0831+17913", :zone "Pacific/Funafuti"},
"AD" {:coordinates "+4230+00131", :zone "Europe/Andorra"},
"SB" {:coordinates "-0932+16012", :zone "Pacific/Guadalcanal"},
"DM" {:coordinates "+1518-06124", :zone "America/Dominica"},
"LR" {:coordinates "+0618-01047", :zone "Africa/Monrovia"},
"OM" {:coordinates "+2336+05835", :zone "Asia/Muscat"},
"SO" {:coordinates "+0204+04522", :zone "Africa/Mogadishu"},
"DO" {:coordinates "+1828-06954", :zone "America/Santo_Domingo"},
"AL" {:coordinates "+4120+01950", :zone "Europe/Tirane"},
"BL" {:coordinates "+1753-06251", :zone "America/St_Barthelemy"},
"FR" {:coordinates "+4852+00220", :zone "Europe/Paris"},
"GW" {:coordinates "+1151-01535", :zone "Africa/Bissau"},
"MS" {:coordinates "+1643-06213", :zone "America/Montserrat"},
"BB" {:coordinates "+1306-05937", :zone "America/Barbados"},
"CA" {:coordinates "+6404-13925", :zone "America/Dawson"},
"MG" {:coordinates "-1855+04731", :zone "Indian/Antananarivo"},
"KH" {:coordinates "+1133+10455", :zone "Asia/Phnom_Penh"},
"LA" {:coordinates "+1758+10236", :zone "Asia/Vientiane"},
"GP" {:coordinates "+1614-06132", :zone "America/Guadeloupe"},
"HN" {:coordinates "+1406-08713", :zone "America/Tegucigalpa"},
"TH" {:coordinates "+1345+10031", :zone "Asia/Bangkok"},
"DE" {:coordinates "+4742+00841", :zone "Europe/Busingen"},
"LB" {:coordinates "+3353+03530", :zone "Asia/Beirut"},
"KZ" {:coordinates "+5113+05121", :zone "Asia/Oral"},
"AS" {:coordinates "-1416-17042", :zone "Pacific/Pago_Pago"},
"EC" {:coordinates "-0054-08936", :zone "Pacific/Galapagos"},
"NO" {:coordinates "+5955+01045", :zone "Europe/Oslo"},
"AO" {:coordinates "-0848+01314", :zone "Africa/Luanda"},
"FK" {:coordinates "-5142-05751", :zone "Atlantic/Stanley"},
"ET" {:coordinates "+0902+03842", :zone "Africa/Addis_Ababa"},
"GS" {:coordinates "-5416-03632", :zone "Atlantic/South_Georgia"},
"MD" {:coordinates "+4700+02850", :zone "Europe/Chisinau"},
"AG" {:coordinates "+1703-06148", :zone "America/Antigua"},
"BE" {:coordinates "+5050+00420", :zone "Europe/Brussels"},
"MV" {:coordinates "+0410+07330", :zone "Indian/Maldives"},
"SZ" {:coordinates "-2618+03106", :zone "Africa/Mbabane"},
"CZ" {:coordinates "+5005+01426", :zone "Europe/Prague"},
"CL" {:coordinates "-2709-10926", :zone "Pacific/Easter"},
"BT" {:coordinates "+2728+08939", :zone "Asia/Thimphu"},
"NL" {:coordinates "+5222+00454", :zone "Europe/Amsterdam"},
"EG" {:coordinates "+3003+03115", :zone "Africa/Cairo"},
"MQ" {:coordinates "+1436-06105", :zone "America/Martinique"},
"SN" {:coordinates "+1440-01726", :zone "Africa/Dakar"},
"FO" {:coordinates "+6201-00646", :zone "Atlantic/Faroe"},
"EE" {:coordinates "+5925+02445", :zone "Europe/Tallinn"},
"AQ" {:coordinates "-7824+10654", :zone "Antarctica/Vostok"},
"ST" {:coordinates "+0020+00644", :zone "Africa/Sao_Tome"},
"KN" {:coordinates "+1718-06243", :zone "America/St_Kitts"},
"BW" {:coordinates "-2439+02555", :zone "Africa/Gaborone"},
"MH" {:coordinates "+0905+16720", :zone "Pacific/Kwajalein"},
"NI" {:coordinates "+1209-08617", :zone "America/Managua"},
"PG" {:coordinates "-0613+15534", :zone "Pacific/Bougainville"},
"VI" {:coordinates "+1821-06456", :zone "America/St_Thomas"},
"IQ" {:coordinates "+3321+04425", :zone "Asia/Baghdad"},
"KG" {:coordinates "+4254+07436", :zone "Asia/Bishkek"},
"US" {:coordinates "+211825-1575130", :zone "Pacific/Honolulu"},
"ZM" {:coordinates "-1525+02817", :zone "Africa/Lusaka"},
"MC" {:coordinates "+4342+00723", :zone "Europe/Monaco"},
"GI" {:coordinates "+3608-00521", :zone "Europe/Gibraltar"},
"NC" {:coordinates "-2216+16627", :zone "Pacific/Noumea"},
"GT" {:coordinates "+1438-09031", :zone "America/Guatemala"},
"BF" {:coordinates "+1222-00131", :zone "Africa/Ouagadougou"},
"YT" {:coordinates "-1247+04514", :zone "Indian/Mayotte"},
"LU" {:coordinates "+4936+00609", :zone "Europe/Luxembourg"},
"UA" {:coordinates "+4750+03510", :zone "Europe/Zaporozhye"},
"IE" {:coordinates "+5320-00615", :zone "Europe/Dublin"},
"LV" {:coordinates "+5657+02406", :zone "Europe/Riga"},
"GD" {:coordinates "+1203-06145", :zone "America/Grenada"},
"MW" {:coordinates "-1547+03500", :zone "Africa/Blantyre"},
"BS" {:coordinates "+2505-07721", :zone "America/Nassau"},
"AZ" {:coordinates "+4023+04951", :zone "Asia/Baku"},
"SK" {:coordinates "+4809+01707", :zone "Europe/Bratislava"},
"GQ" {:coordinates "+0345+00847", :zone "Africa/Malabo"},
"TC" {:coordinates "+2128-07108", :zone "America/Grand_Turk"},
"RE" {:coordinates "-2052+05528", :zone "Indian/Reunion"},
"IN" {:coordinates "+2232+08822", :zone "Asia/Kolkata"},
"ES" {:coordinates "+2806-01524", :zone "Atlantic/Canary"},
"GL" {:coordinates "+7634-06847", :zone "America/Thule"},
"KI" {:coordinates "+0152-15720", :zone "Pacific/Kiritimati"},
"HK" {:coordinates "+2217+11409", :zone "Asia/Hong_Kong"},
"CO" {:coordinates "+0436-07405", :zone "America/Bogota"},
"SS" {:coordinates "+0451+03137", :zone "Africa/Juba"},
"RS" {:coordinates "+4450+02030", :zone "Europe/Belgrade"},
"IO" {:coordinates "-0720+07225", :zone "Indian/Chagos"},
"NG" {:coordinates "+0627+00324", :zone "Africa/Lagos"},
"UG" {:coordinates "+0019+03225", :zone "Africa/Kampala"},
"CW" {:coordinates "+1211-06900", :zone "America/Curacao"},
"SL" {:coordinates "+0830-01315", :zone "Africa/Freetown"},
"ER" {:coordinates "+1520+03853", :zone "Africa/Asmara"},
"JE" {:coordinates "+491101-0020624", :zone "Europe/Jersey"},
"AE" {:coordinates "+2518+05518", :zone "Asia/Dubai"},
"PM" {:coordinates "+4703-05620", :zone "America/Miquelon"},
"BD" {:coordinates "+2343+09025", :zone "Asia/Dhaka"},
"MT" {:coordinates "+3554+01431", :zone "Europe/Malta"},
"AI" {:coordinates "+1812-06304", :zone "America/Anguilla"},
"GN" {:coordinates "+0931-01343", :zone "Africa/Conakry"},
"PW" {:coordinates "+0720+13429", :zone "Pacific/Palau"},
"NA" {:coordinates "-2234+01706", :zone "Africa/Windhoek"},
"MX" {:coordinates "+2048-10515", :zone "America/Bahia_Banderas"},
"PL" {:coordinates "+5215+02100", :zone "Europe/Warsaw"}}
)
(def timezone->locale
(reduce
(fn [result [locale {:keys [zone]}]]
(assoc result zone locale))
nil
locales))
(defn get-timezone-locale [timezone]
(get timezone->locale timezone))
(defn get-locale-timezone [locale]
(get-in
locales
[(clojure.string/upper-case locale) :zone]))
(defn get-locale [locale]
(get locales (clojure.string/upper-case locale)))
(def db-extensions
{:zones
{"GMT"
{:offset 0, :rule "-" , :format "GMT", :from 0}}})
(def db
(merge-with
merge
db-extensions
{:zones
{"Asia/Rangoon" "Asia/Yangon",
"Mexico/BajaNorte" "America/Tijuana",
"Europe/Amsterdam"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"America/Montevideo"
{:offset -10800000,
:rule "Uruguay",
:format "-03/-02",
:from 155088000000},
"Africa/Kinshasa" "Africa/Lagos",
"Asia/Sakhalin"
{:offset 39600000, :rule "-", :format "+11", :from 1456797600000},
"America/Santarem"
{:offset -10800000, :rule "-", :format "-03", :from 1212278400000},
"Europe/Tiraspol" "Europe/Chisinau",
"Africa/Ouagadougou" "Africa/Abidjan",
"Asia/Amman"
{:offset 7200000,
:rule "Jordan",
:format "EE%sT",
:from -1230768000000},
"Europe/Tallinn"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 1012521600000},
"Africa/Blantyre" "Africa/Maputo",
"America/Nipigon"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from -880927200000},
"America/Jamaica"
{:offset -18000000, :rule "-", :format "EST", :from 441763200000},
"Africa/El_Aaiun"
{:offset 3600000,
:rule "Morocco",
:format "+01/+00",
:from 1538362800000},
"Australia/LHI" "Australia/Lord_Howe",
"America/Costa_Rica"
{:offset -21600000,
:rule "CR",
:format "C%sT",
:from -1546300800000},
"Canada/Eastern" "America/Toronto",
"Asia/Kuala_Lumpur"
{:offset 28800000, :rule "-", :format "+08", :from 378691200000},
"America/Cordoba" "America/Argentina/Cordoba",
"Asia/Kuwait" "Asia/Riyadh",
"Asia/Tokyo"
{:offset 32400000,
:rule "Japan",
:format "J%sT",
:from -2587766400000},
"America/Maceio"
{:offset -10800000, :rule "-", :format "-03", :from 1033430400000},
"Europe/Brussels"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"America/Nome"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"Australia/Broken_Hill"
{:offset 34200000, :rule "AS", :format "AC%sT", :from 946684800000},
"Asia/Chita"
{:offset 32400000, :rule "-", :format "+09", :from 1456797600000},
"Universal" "Etc/UTC",
"Africa/Timbuktu" "Africa/Abidjan",
"Africa/Casablanca"
{:offset 3600000,
:rule "Morocco",
:format "+01/+00",
:from 1538362800000},
"Europe/Isle_of_Man" "Europe/London",
"America/Ensenada" "America/Tijuana",
"America/Argentina/San_Luis"
{:offset -10800000, :rule "-", :format "-03", :from 1254355200000},
"America/St_Johns"
{:offset -12600000,
:rule "Canada",
:format "N%sT",
:from 1320105600000},
"Europe/Berlin"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Africa/Lome" "Africa/Abidjan",
"America/North_Dakota/Center"
{:offset -21600000, :rule "US", :format "C%sT", :from 717904800000},
"Asia/Aqtobe"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"Antarctica/Macquarie"
{:offset 39600000, :rule "-", :format "+11", :from 1270090800000},
"Asia/Seoul"
{:offset 32400000, :rule "ROK", :format "K%sT", :from -265680000000},
"Chile/EasterIsland" "Pacific/Easter",
"US/Hawaii" "Pacific/Honolulu",
"America/Punta_Arenas"
{:offset -10800000, :rule "-", :format "-03", :from 1480550400000},
"Indian/Christmas"
{:offset 25200000, :rule "-", :format "+07", :from -2364076800000},
"Atlantic/Madeira"
{:offset 0, :rule "EU", :format "WE%sT", :from 431226000000},
"Asia/Barnaul"
{:offset 25200000, :rule "-", :format "+07", :from 1456797600000},
"Asia/Colombo"
{:offset 19800000, :rule "-", :format "+0530", :from 1143851400000},
"America/Argentina/Mendoza"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Asia/Novokuznetsk"
{:offset 25200000, :rule "-", :format "+07", :from 1298944800000},
"America/Indiana/Vevay"
{:offset -18000000, :rule "US", :format "E%sT", :from 1136073600000},
"America/Argentina/Rio_Gallegos"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Etc/GMT" {:offset 0, :rule "-", :format "GMT", :from nil},
"US/Aleutian" "America/Adak",
"America/Fortaleza"
{:offset -10800000, :rule "-", :format "-03", :from 1033430400000},
"Australia/South" "Australia/Adelaide",
"Europe/Uzhgorod"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 788918400000},
"Asia/Beirut"
{:offset 7200000,
:rule "Lebanon",
:format "EE%sT",
:from -2840140800000},
"Australia/Yancowinna" "Australia/Broken_Hill",
"Africa/Sao_Tome"
{:offset 0, :rule "-", :format "GMT", :from 1546308000000},
"GMT" "Etc/GMT",
"Cuba" "America/Havana",
"Asia/Dubai"
{:offset 14400000, :rule "-", :format "+04", :from -1577923200000},
"Europe/Stockholm"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Portugal" "Europe/Lisbon",
"America/Boise"
{:offset -25200000, :rule "US", :format "M%sT", :from 128916000000},
"America/Scoresbysund"
{:offset -3600000,
:rule "EU",
:format "-01/+00",
:from 352252800000},
"Indian/Maldives"
{:offset 18000000, :rule "-", :format "+05", :from -315619200000},
"Europe/Simferopol"
{:offset 10800000, :rule "-", :format "MSK", :from 1412128800000},
"Pacific/Efate"
{:offset 39600000,
:rule "Vanuatu",
:format "+11/+12",
:from -1829347200000},
"GMT-0" "Etc/GMT",
"Asia/Qatar"
{:offset 10800000, :rule "-", :format "+03", :from 76204800000},
"GMT+0" "Etc/GMT",
"GMT0" "Etc/GMT",
"Europe/Jersey" "Europe/London",
"Pacific/Honolulu"
{:offset -36000000, :rule "-", :format "HST", :from -712792800000},
"America/Tegucigalpa"
{:offset -21600000,
:rule "Hond",
:format "C%sT",
:from -1538524800000},
"Atlantic/South_Georgia"
{:offset -7200000, :rule "-", :format "-02", :from -2524521600000},
"Asia/Hong_Kong"
{:offset 28800000, :rule "HK", :format "HK%sT", :from -762645600000},
"Pacific/Pohnpei"
{:offset 39600000, :rule "-", :format "+11", :from -770601600000},
"Pacific/Norfolk"
{:offset 39600000,
:rule "AN",
:format "+11/+12",
:from 1561939200000},
"America/Santiago"
{:offset -14400000,
:rule "Chile",
:format "-04/-03",
:from -715395600000},
"America/Indiana/Knox"
{:offset -21600000, :rule "US", :format "C%sT", :from 1143856800000},
"Etc/GMT0" "Etc/GMT",
"Australia/Brisbane"
{:offset 36000000, :rule "AQ", :format "AE%sT", :from 31536000000},
"America/Anguilla" "America/Port_of_Spain",
"Asia/Hovd"
{:offset 25200000,
:rule "Mongol",
:format "+07/+08",
:from 252460800000},
"Asia/Jakarta"
{:offset 25200000, :rule "-", :format "WIB", :from -189388800000},
"Atlantic/Stanley"
{:offset -10800000, :rule "-", :format "-03", :from 1283306400000},
"America/Jujuy" "America/Argentina/Jujuy",
"Indian/Comoro" "Africa/Nairobi",
"America/Sao_Paulo"
{:offset -10800000,
:rule "Brazil",
:format "-03/-02",
:from -189388800000},
"Asia/Macao" "Asia/Macau",
"Etc/GMT+12"
{:offset -43200000, :rule "-", :format "-12", :from nil},
"Asia/Macau"
{:offset 28800000,
:rule "Macau",
:format "C%sT",
:from -767836800000},
"America/Menominee"
{:offset -21600000, :rule "US", :format "C%sT", :from 102477600000},
"Asia/Bahrain" "Asia/Qatar",
"Asia/Katmandu" "Asia/Kathmandu",
"America/Montreal" "America/Toronto",
"Atlantic/St_Helena" "Africa/Abidjan",
"MET" {:offset 3600000, :rule "C-Eur", :format "ME%sT", :from nil},
"Africa/Tunis"
{:offset 3600000,
:rule "Tunisia",
:format "CE%sT",
:from -1856822400000},
"Africa/Lusaka" "Africa/Maputo",
"Etc/GMT+2" {:offset -7200000, :rule "-", :format "-02", :from nil},
"CST6CDT" {:offset -21600000, :rule "US", :format "C%sT", :from nil},
"Pacific/Easter"
{:offset -21600000,
:rule "Chile",
:format "-06/-05",
:from 383799600000},
"Asia/Ashkhabad" "Asia/Ashgabat",
"Africa/Cairo"
{:offset 7200000,
:rule "Egypt",
:format "EE%sT",
:from -2185401600000},
"Etc/GMT-10" {:offset 36000000, :rule "-", :format "+10", :from nil},
"Pacific/Chuuk"
{:offset 36000000, :rule "-", :format "+10", :from -770601600000},
"US/Eastern" "America/New_York",
"America/Montserrat" "America/Port_of_Spain",
"Pacific/Tarawa"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"America/Resolute"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from 1172718000000},
"Pacific/Saipan" "Pacific/Guam",
"Asia/Thimbu" "Asia/Thimphu",
"Asia/Muscat" "Asia/Dubai",
"Asia/Saigon" "Asia/Ho_Chi_Minh",
"Hongkong" "Asia/Hong_Kong",
"Europe/Zaporozhye"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 788918400000},
"Asia/Aqtau"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"Asia/Hebron"
{:offset 7200000,
:rule "Palestine",
:format "EE%sT",
:from 915148800000},
"Asia/Kuching"
{:offset 28800000, :rule "-", :format "+08", :from -767923200000},
"Pacific/Tahiti"
{:offset -36000000, :rule "-", :format "-10", :from -1806710400000},
"America/Argentina/Jujuy"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Etc/GMT+1" {:offset -3600000, :rule "-", :format "-01", :from nil},
"Atlantic/Faroe"
{:offset 0, :rule "EU", :format "WE%sT", :from 347155200000},
"Asia/Vladivostok"
{:offset 36000000, :rule "-", :format "+10", :from 1412128800000},
"Europe/Oslo"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Australia/Tasmania" "Australia/Hobart",
"Asia/Oral"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"Arctic/Longyearbyen" "Europe/Oslo",
"America/Indiana/Marengo"
{:offset -18000000, :rule "US", :format "E%sT", :from 1136073600000},
"America/Rainy_River"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from -880927200000},
"America/Barbados"
{:offset -14400000,
:rule "Barb",
:format "A%sT",
:from -1199232000000},
"Indian/Chagos"
{:offset 21600000, :rule "-", :format "+06", :from 820454400000},
"Indian/Cocos"
{:offset 23400000, :rule "-", :format "+0630", :from -2208988800000},
"Australia/Victoria" "Australia/Melbourne",
"Africa/Harare" "Africa/Maputo",
"America/Aruba" "America/Curacao",
"America/El_Salvador"
{:offset -21600000,
:rule "Salv",
:format "C%sT",
:from -1546300800000},
"America/Porto_Velho"
{:offset -14400000, :rule "-", :format "-04", :from 589075200000},
"Etc/GMT-4" {:offset 14400000, :rule "-", :format "+04", :from nil},
"Navajo" "America/Denver",
"Australia/Hobart"
{:offset 36000000, :rule "AT", :format "AE%sT", :from -94694400000},
"America/Ojinaga"
{:offset -25200000, :rule "US", :format "M%sT", :from 1262304000000},
"Asia/Jayapura"
{:offset 32400000, :rule "-", :format "WIT", :from -189388800000},
"Etc/Universal" "Etc/UTC",
"America/Goose_Bay"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 1320105600000},
"America/Panama"
{:offset -18000000, :rule "-", :format "EST", :from -1948752000000},
"Africa/Dar_es_Salaam" "Africa/Nairobi",
"America/Mendoza" "America/Argentina/Mendoza",
"Asia/Tehran"
{:offset 12600000,
:rule "Iran",
:format "+0330/+0430",
:from 283996800000},
"America/Blanc-Sablon"
{:offset -14400000, :rule "-", :format "AST", :from 0},
"PST8PDT" {:offset -28800000, :rule "US", :format "P%sT", :from nil},
"Pacific/Johnston" "Pacific/Honolulu",
"Etc/GMT-12" {:offset 43200000, :rule "-", :format "+12", :from nil},
"America/Noronha"
{:offset -7200000, :rule "-", :format "-02", :from 1033430400000},
"America/St_Kitts" "America/Port_of_Spain",
"Etc/GMT+10"
{:offset -36000000, :rule "-", :format "-10", :from nil},
"Pacific/Enderbury"
{:offset 46800000, :rule "-", :format "+13", :from 786240000000},
"Australia/Queensland" "Australia/Brisbane",
"Etc/GMT+5" {:offset -18000000, :rule "-", :format "-05", :from nil},
"Pacific/Ponape" "Pacific/Pohnpei",
"Antarctica/McMurdo" "Pacific/Auckland",
"Africa/Ceuta"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 504921600000},
"Asia/Baku"
{:offset 14400000,
:rule "Azer",
:format "+04/+05",
:from 852076800000},
"Europe/Sofia"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 852076800000},
"CET" {:offset 3600000, :rule "C-Eur", :format "CE%sT", :from nil},
"America/Pangnirtung"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 970365600000},
"America/Monterrey"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 599616000000},
"Asia/Pontianak"
{:offset 25200000, :rule "-", :format "WIB", :from 567993600000},
"America/Moncton"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 1167609600000},
"Europe/Belfast" "Europe/London",
"America/Dominica" "America/Port_of_Spain",
"America/Swift_Current"
{:offset -21600000, :rule "-", :format "CST", :from 73447200000},
"Eire" "Europe/Dublin",
"America/Argentina/Salta"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"America/Sitka"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"America/Creston"
{:offset -25200000, :rule "-", :format "MST", :from -1627948800000},
"America/St_Vincent" "America/Port_of_Spain",
"Europe/Andorra"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 478490400000},
"Pacific/Wallis"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"Asia/Ujung_Pandang" "Asia/Makassar",
"Africa/Niamey" "Africa/Lagos",
"MST7MDT" {:offset -25200000, :rule "US", :format "M%sT", :from nil},
"Asia/Manila"
{:offset 28800000,
:rule "Phil",
:format "P%sT",
:from -794188800000},
"HST" {:offset -36000000, :rule "-", :format "HST", :from nil},
"Asia/Shanghai"
{:offset 28800000, :rule "PRC", :format "C%sT", :from -652320000000},
"Etc/GMT+4" {:offset -14400000, :rule "-", :format "-04", :from nil},
"Europe/London"
{:offset 0, :rule "EU", :format "GMT/BST", :from 820454400000},
"Europe/Vienna"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 347155200000},
"Jamaica" "America/Jamaica",
"Africa/Kigali" "Africa/Maputo",
"Etc/GMT-0" "Etc/GMT",
"Libya" "Africa/Tripoli",
"Pacific/Auckland"
{:offset 43200000, :rule "NZ", :format "NZ%sT", :from -757382400000},
"EET" {:offset 7200000, :rule "EU", :format "EE%sT", :from nil},
"Europe/Luxembourg"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"Europe/Bucharest"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 852076800000},
"Asia/Khandyga"
{:offset 32400000, :rule "-", :format "+09", :from 1412128800000},
"Asia/Kolkata"
{:offset 19800000, :rule "-", :format "IST", :from -765331200000},
"America/Louisville" "America/Kentucky/Louisville",
"America/Atka" "America/Adak",
"Etc/UTC" {:offset 0, :rule "-", :format "UTC", :from nil},
"Pacific/Gambier"
{:offset -32400000, :rule "-", :format "-09", :from -1806710400000},
"Asia/Dushanbe"
{:offset 18000000, :rule "-", :format "+05", :from 683690400000},
"Asia/Choibalsan"
{:offset 28800000,
:rule "Mongol",
:format "+08/+09",
:from 1204329600000},
"Asia/Phnom_Penh" "Asia/Bangkok",
"Pacific/Guadalcanal"
{:offset 39600000, :rule "-", :format "+11", :from -1806710400000},
"US/Arizona" "America/Phoenix",
"Pacific/Yap" "Pacific/Chuuk",
"Europe/Tirane"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 457488000000},
"Africa/Maseru" "Africa/Johannesburg",
"America/Cambridge_Bay"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 986094000000},
"America/Denver"
{:offset -25200000, :rule "US", :format "M%sT", :from -94694400000},
"America/Thule"
{:offset -14400000,
:rule "Thule",
:format "A%sT",
:from -1686096000000},
"America/St_Barthelemy" "America/Port_of_Spain",
"Etc/GMT+3" {:offset -10800000, :rule "-", :format "-03", :from nil},
"Asia/Srednekolymsk"
{:offset 39600000, :rule "-", :format "+11", :from 1412128800000},
"America/Recife"
{:offset -10800000, :rule "-", :format "-03", :from 1033430400000},
"Europe/Belgrade"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 404956800000},
"Europe/Kiev"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 788918400000},
"Europe/Zagreb" "Europe/Belgrade",
"Asia/Chungking" "Asia/Shanghai",
"Canada/Mountain" "America/Edmonton",
"Pacific/Samoa" "Pacific/Pago_Pago",
"Africa/Douala" "Africa/Lagos",
"America/Argentina/La_Rioja"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Europe/Kaliningrad"
{:offset 7200000, :rule "-", :format "EET", :from 1412128800000},
"Asia/Gaza"
{:offset 7200000,
:rule "Palestine",
:format "EE%sT",
:from 1325376000000},
"US/Alaska" "America/Anchorage",
"Asia/Yerevan"
{:offset 14400000,
:rule "Armenia",
:format "+04/+05",
:from 1293840000000},
"Europe/Warsaw"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 567993600000},
"Australia/Currie"
{:offset 36000000, :rule "AT", :format "AE%sT", :from 47174400000},
"Africa/Nouakchott" "Africa/Abidjan",
"Egypt" "Africa/Cairo",
"Africa/Brazzaville" "Africa/Lagos",
"Asia/Yekaterinburg"
{:offset 18000000, :rule "-", :format "+05", :from 1412128800000},
"America/Belize"
{:offset -21600000,
:rule "Belize",
:format "%s",
:from -1822521600000},
"Atlantic/Azores"
{:offset -3600000,
:rule "EU",
:format "-01/+00",
:from 730947600000},
"Etc/GMT-9" {:offset 32400000, :rule "-", :format "+09", :from nil},
"America/Argentina/San_Juan"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"US/Michigan" "America/Detroit",
"Asia/Kamchatka"
{:offset 43200000, :rule "-", :format "+12", :from 1298944800000},
"Asia/Qostanay"
{:offset 21600000, :rule "-", :format "+06", :from 1096596000000},
"America/Knox_IN" "America/Indiana/Knox",
"Australia/Adelaide"
{:offset 34200000, :rule "AS", :format "AC%sT", :from 31536000000},
"MST" {:offset -25200000, :rule "-", :format "MST", :from nil},
"ROK" "Asia/Seoul",
"America/Rankin_Inlet"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from 986094000000},
"Etc/UCT" "Etc/UTC",
"Pacific/Kwajalein"
{:offset 43200000, :rule "-", :format "+12", :from 744249600000},
"Asia/Yangon"
{:offset 23400000, :rule "-", :format "+0630", :from -778550400000},
"Mexico/BajaSur" "America/Mazatlan",
"Canada/Pacific" "America/Vancouver",
"America/Tortola" "America/Port_of_Spain",
"Japan" "Asia/Tokyo",
"Europe/Volgograd"
{:offset 14400000, :rule "-", :format "+04", :from 1538359200000},
"America/Inuvik"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 315532800000},
"UCT" "Etc/UTC",
"Asia/Pyongyang"
{:offset 32400000, :rule "-", :format "KST", :from 1525217400000},
"Canada/Central" "America/Winnipeg",
"Asia/Vientiane" "Asia/Bangkok",
"Africa/Lubumbashi" "Africa/Maputo",
"W-SU" "Europe/Moscow",
"America/Dawson"
{:offset -28800000,
:rule "Canada",
:format "P%sT",
:from 315532800000},
"Asia/Ulan_Bator" "Asia/Ulaanbaatar",
"Asia/Yakutsk"
{:offset 32400000, :rule "-", :format "+09", :from 1412128800000},
"Europe/San_Marino" "Europe/Rome",
"America/Porto_Acre" "America/Rio_Branco",
"Pacific/Rarotonga"
{:offset -36000000,
:rule "Cook",
:format "-10/-0930",
:from 278726400000},
"GB" "Europe/London",
"America/Curacao"
{:offset -14400000, :rule "-", :format "AST", :from -157766400000},
"America/La_Paz"
{:offset -14400000, :rule "-", :format "-04", :from -1194048000000},
"Europe/Astrakhan"
{:offset 14400000, :rule "-", :format "+04", :from 1456797600000},
"Europe/Prague"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 283996800000},
"America/Chihuahua"
{:offset -25200000,
:rule "Mexico",
:format "M%sT",
:from 891745200000},
"America/Los_Angeles"
{:offset -28800000, :rule "US", :format "P%sT", :from -94694400000},
"America/Lima"
{:offset -18000000,
:rule "Peru",
:format "-05/-04",
:from -1940889600000},
"America/Caracas"
{:offset -14400000, :rule "-", :format "-04", :from 1462069800000},
"Africa/Dakar" "Africa/Abidjan",
"Kwajalein" "Pacific/Kwajalein",
"Etc/GMT-14" {:offset 50400000, :rule "-", :format "+14", :from nil},
"America/Buenos_Aires" "America/Argentina/Buenos_Aires",
"America/Virgin" "America/Port_of_Spain",
"Asia/Nicosia"
{:offset 7200000,
:rule "EUAsia",
:format "EE%sT",
:from 904608000000},
"America/Indiana/Petersburg"
{:offset -18000000, :rule "US", :format "E%sT", :from 1193882400000},
"Etc/GMT-2" {:offset 7200000, :rule "-", :format "+02", :from nil},
"America/Tijuana"
{:offset -28800000, :rule "US", :format "P%sT", :from 1262304000000},
"Europe/Guernsey" "Europe/London",
"Africa/Conakry" "Africa/Abidjan",
"Europe/Dublin"
{:offset 3600000,
:rule "Eire",
:format "IST/GMT",
:from -39484800000},
"Europe/Helsinki"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 410227200000},
"Africa/Abidjan"
{:offset 0, :rule "-", :format "GMT", :from -1830384000000},
"America/Campo_Grande"
{:offset -14400000,
:rule "Brazil",
:format "-04/-03",
:from -1767225600000},
"America/Guatemala"
{:offset -21600000,
:rule "Guat",
:format "C%sT",
:from -1617062400000},
"Pacific/Tongatapu"
{:offset 46800000,
:rule "Tonga",
:format "+13/+14",
:from 915148800000},
"Africa/Monrovia"
{:offset 0, :rule "-", :format "GMT", :from 63072000000},
"Atlantic/Bermuda"
{:offset -14400000, :rule "US", :format "A%sT", :from 189302400000},
"Asia/Almaty"
{:offset 21600000, :rule "-", :format "+06", :from 1096596000000},
"Asia/Bishkek"
{:offset 21600000, :rule "-", :format "+06", :from 1122854400000},
"Indian/Mayotte" "Africa/Nairobi",
"America/Martinique"
{:offset -14400000, :rule "-", :format "AST", :from 336614400000},
"America/Shiprock" "America/Denver",
"America/Danmarkshavn"
{:offset 0, :rule "-", :format "GMT", :from 820454400000},
"Asia/Tel_Aviv" "Asia/Jerusalem",
"Europe/Athens"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 347155200000},
"Brazil/Acre" "America/Rio_Branco",
"Europe/Sarajevo" "Europe/Belgrade",
"EST" {:offset -18000000, :rule "-", :format "EST", :from nil},
"NZ" "Pacific/Auckland",
"America/Yellowknife"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 315532800000},
"Africa/Freetown" "Africa/Abidjan",
"Asia/Tbilisi"
{:offset 14400000, :rule "-", :format "+04", :from 1111888800000},
"Canada/Yukon" "America/Whitehorse",
"Pacific/Pago_Pago"
{:offset -39600000, :rule "-", :format "SST", :from -1861920000000},
"America/Argentina/Ushuaia"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"ROC" "Asia/Taipei",
"America/Metlakatla"
{:offset -32400000,
:rule "US",
:format "AK%sT",
:from 1546308000000},
"America/Boa_Vista"
{:offset -14400000, :rule "-", :format "-04", :from 970358400000},
"Pacific/Nauru"
{:offset 43200000, :rule "-", :format "+12", :from 286682400000},
"Asia/Brunei"
{:offset 28800000, :rule "-", :format "+08", :from -1167609600000},
"Pacific/Palau"
{:offset 32400000, :rule "-", :format "+09", :from -2177452800000},
"Asia/Dili"
{:offset 32400000, :rule "-", :format "+09", :from 967766400000},
"Etc/GMT+8" {:offset -28800000, :rule "-", :format "-08", :from nil},
"Etc/Zulu" "Etc/UTC",
"America/Port-au-Prince"
{:offset -18000000,
:rule "Haiti",
:format "E%sT",
:from -1672488000000},
"Pacific/Chatham"
{:offset 45900000,
:rule "Chatham",
:format "+1245/+1345",
:from -757382400000},
"America/Indiana/Indianapolis"
{:offset -18000000, :rule "US", :format "E%sT", :from 1136073600000},
"Atlantic/Reykjavik"
{:offset 0, :rule "-", :format "GMT", :from -55292400000},
"Iran" "Asia/Tehran",
"America/Kentucky/Louisville"
{:offset -18000000, :rule "US", :format "E%sT", :from 149824800000},
"Africa/Asmera" "Africa/Nairobi",
"Australia/Sydney"
{:offset 36000000, :rule "AN", :format "AE%sT", :from 31536000000},
"America/Indiana/Vincennes"
{:offset -18000000, :rule "US", :format "E%sT", :from 1193882400000},
"America/Bogota"
{:offset -18000000,
:rule "CO",
:format "-05/-04",
:from -1740960000000},
"US/Indiana-Starke" "America/Indiana/Knox",
"America/Phoenix"
{:offset -25200000, :rule "-", :format "MST", :from -57974400000},
"Africa/Djibouti" "Africa/Nairobi",
"Etc/GMT-3" {:offset 10800000, :rule "-", :format "+03", :from nil},
"Africa/Banjul" "Africa/Abidjan",
"Brazil/East" "America/Sao_Paulo",
"Asia/Atyrau"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"America/Cayenne"
{:offset -10800000, :rule "-", :format "-03", :from -71107200000},
"America/Santa_Isabel" "America/Tijuana",
"America/Grand_Turk"
{:offset -18000000, :rule "US", :format "E%sT", :from 1519873200000},
"Europe/Vilnius"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 1041379200000},
"America/Hermosillo"
{:offset -25200000, :rule "-", :format "MST", :from 915148800000},
"America/Yakutat"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"Africa/Kampala" "Africa/Nairobi",
"Europe/Copenhagen"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Asia/Novosibirsk"
{:offset 25200000, :rule "-", :format "+07", :from 1467338400000},
"Europe/Monaco"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"Brazil/West" "America/Manaus",
"EST5EDT" {:offset -18000000, :rule "US", :format "E%sT", :from nil},
"America/Chicago"
{:offset -21600000, :rule "US", :format "C%sT", :from -94694400000},
"Etc/GMT-1" {:offset 3600000, :rule "-", :format "+01", :from nil},
"America/Godthab"
{:offset -10800000,
:rule "EU",
:format "-03/-02",
:from 323402400000},
"Canada/Atlantic" "America/Halifax",
"Asia/Singapore"
{:offset 28800000, :rule "-", :format "+08", :from 378691200000},
"Etc/GMT-8" {:offset 28800000, :rule "-", :format "+08", :from nil},
"America/Lower_Princes" "America/Curacao",
"Africa/Accra"
{:offset 0,
:rule "Ghana",
:format "GMT/+0020",
:from -1640995200000},
"America/Asuncion"
{:offset -14400000,
:rule "Para",
:format "-04/-03",
:from 134006400000},
"America/Thunder_Bay"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 126230400000},
"America/Bahia"
{:offset -10800000, :rule "-", :format "-03", :from 1349049600000},
"Pacific/Majuro"
{:offset 43200000, :rule "-", :format "+12", :from -7948800000},
"Etc/GMT+9" {:offset -32400000, :rule "-", :format "-09", :from nil},
"Asia/Tomsk"
{:offset 25200000, :rule "-", :format "+07", :from 1462068000000},
"Africa/Mbabane" "Africa/Johannesburg",
"Pacific/Fakaofo"
{:offset 46800000, :rule "-", :format "+13", :from 1322697600000},
"Africa/Addis_Ababa" "Africa/Nairobi",
"America/Nassau"
{:offset -18000000, :rule "US", :format "E%sT", :from 189302400000},
"Asia/Makassar"
{:offset 28800000, :rule "-", :format "WITA", :from -767923200000},
"Europe/Nicosia" "Asia/Nicosia",
"Australia/West" "Australia/Perth",
"America/Whitehorse"
{:offset -28800000,
:rule "Canada",
:format "P%sT",
:from 315532800000},
"Asia/Urumqi"
{:offset 21600000, :rule "-", :format "+06", :from -1325462400000},
"Asia/Famagusta"
{:offset 7200000,
:rule "EUAsia",
:format "EE%sT",
:from 1506819600000},
"US/Samoa" "Pacific/Pago_Pago",
"Asia/Samarkand"
{:offset 18000000, :rule "-", :format "+05", :from 694224000000},
"Asia/Calcutta" "Asia/Kolkata",
"Pacific/Niue"
{:offset -39600000, :rule "-", :format "-11", :from 276048000000},
"Australia/Perth"
{:offset 28800000, :rule "AW", :format "AW%sT", :from -836438400000},
"Africa/Bissau"
{:offset 0, :rule "-", :format "GMT", :from 157766400000},
"Asia/Thimphu"
{:offset 21600000, :rule "-", :format "+06", :from 560044800000},
"America/Antigua" "America/Port_of_Spain",
"Africa/Khartoum"
{:offset 7200000, :rule "-", :format "CAT", :from 1509494400000},
"America/Guyana"
{:offset -14400000, :rule "-", :format "-04", :from 662688000000},
"America/Puerto_Rico"
{:offset -14400000, :rule "-", :format "AST", :from -757382400000},
"Pacific/Apia"
{:offset 46800000,
:rule "WS",
:format "+13/+14",
:from 1322784000000},
"America/Indiana/Winamac"
{:offset -18000000, :rule "US", :format "E%sT", :from 1172714400000},
"US/East-Indiana" "America/Indiana/Indianapolis",
"Pacific/Galapagos"
{:offset -21600000,
:rule "Ecuador",
:format "-06/-05",
:from 504921600000},
"Europe/Skopje" "Europe/Belgrade",
"GB-Eire" "Europe/London",
"Europe/Istanbul"
{:offset 10800000, :rule "-", :format "+03", :from 1472688000000},
"Chile/Continental" "America/Santiago",
"Asia/Jerusalem"
{:offset 7200000,
:rule "Zion",
:format "I%sT",
:from -1640995200000},
"Asia/Magadan"
{:offset 39600000, :rule "-", :format "+11", :from 1459476000000},
"UTC" "Etc/UTC",
"America/North_Dakota/Beulah"
{:offset -21600000, :rule "US", :format "C%sT", :from 1288576800000},
"America/Guadeloupe" "America/Port_of_Spain",
"America/St_Lucia" "America/Port_of_Spain",
"America/Mexico_City"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 1012521600000},
"Africa/Johannesburg"
{:offset 7200000, :rule "SA", :format "SAST", :from -2109283200000},
"Africa/Bamako" "Africa/Abidjan",
"Etc/GMT+0" "Etc/GMT",
"America/Toronto"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 126230400000},
"Etc/GMT-7" {:offset 25200000, :rule "-", :format "+07", :from nil},
"America/Managua"
{:offset -21600000, :rule "Nic", :format "C%sT", :from 852076800000},
"America/Belem"
{:offset -10800000, :rule "-", :format "-03", :from 589075200000},
"Europe/Lisbon"
{:offset 0, :rule "EU", :format "WE%sT", :from 825642000000},
"Asia/Kashgar" "Asia/Urumqi",
"America/Juneau"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"America/Fort_Wayne" "America/Indiana/Indianapolis",
"US/Mountain" "America/Denver",
"Etc/GMT+6" {:offset -21600000, :rule "-", :format "-06", :from nil},
"Europe/Minsk"
{:offset 10800000, :rule "-", :format "+03", :from 1298944800000},
"America/Indiana/Tell_City"
{:offset -21600000, :rule "US", :format "C%sT", :from 1143856800000},
"Australia/North" "Australia/Darwin",
"Europe/Moscow"
{:offset 10800000, :rule "-", :format "MSK", :from 1412128800000},
"Pacific/Kosrae"
{:offset 39600000, :rule "-", :format "+11", :from 915148800000},
"Europe/Ulyanovsk"
{:offset 14400000, :rule "-", :format "+04", :from 1456797600000},
"Africa/Lagos"
{:offset 3600000, :rule "-", :format "WAT", :from -1588464000000},
"Asia/Harbin" "Asia/Shanghai",
"Iceland" "Atlantic/Reykjavik",
"Mexico/General" "America/Mexico_City",
"America/Guayaquil"
{:offset -18000000,
:rule "Ecuador",
:format "-05/-04",
:from -1230768000000},
"America/Argentina/Cordoba"
{:offset -10800000,
:rule "Arg",
:format "-03/-02",
:from 951868800000},
"Africa/Windhoek"
{:offset 7200000, :rule "Namibia", :format "%s", :from 636249600000},
"Europe/Rome"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Asia/Krasnoyarsk"
{:offset 25200000, :rule "-", :format "+07", :from 1412128800000},
"America/Glace_Bay"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 126230400000},
"Asia/Karachi"
{:offset 18000000,
:rule "Pakistan",
:format "PK%sT",
:from 36633600000},
"Europe/Busingen" "Europe/Zurich",
"Asia/Aden" "Asia/Riyadh",
"America/Mazatlan"
{:offset -25200000, :rule "Mexico", :format "M%sT", :from 0},
"America/Winnipeg"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from 1136073600000},
"Europe/Chisinau"
{:offset 7200000,
:rule "Moldova",
:format "EE%sT",
:from 852076800000},
"America/Argentina/Buenos_Aires"
{:offset -10800000,
:rule "Arg",
:format "-03/-02",
:from 951868800000},
"Europe/Riga"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 978307200000},
"Pacific/Pitcairn"
{:offset -28800000, :rule "-", :format "-08", :from 891388800000},
"Turkey" "Europe/Istanbul",
"Pacific/Guam"
{:offset 36000000, :rule "-", :format "ChST", :from 975628800000},
"Indian/Reunion"
{:offset 14400000, :rule "-", :format "+04", :from -1848873600000},
"Pacific/Bougainville"
{:offset 39600000, :rule "-", :format "+11", :from 1417399200000},
"Africa/Malabo" "Africa/Lagos",
"America/New_York"
{:offset -18000000, :rule "US", :format "E%sT", :from -94694400000},
"America/Coral_Harbour" "America/Atikokan",
"Africa/Tripoli"
{:offset 7200000, :rule "-", :format "EET", :from 1380592800000},
"Asia/Bangkok"
{:offset 25200000, :rule "-", :format "+07", :from -1570060800000},
"America/Atikokan"
{:offset -18000000, :rule "-", :format "EST", :from -767916000000},
"America/Detroit"
{:offset -18000000, :rule "US", :format "E%sT", :from 165549600000},
"Poland" "Europe/Warsaw",
"Etc/GMT+11"
{:offset -39600000, :rule "-", :format "-11", :from nil},
"Asia/Ashgabat"
{:offset 18000000, :rule "-", :format "+05", :from 694231200000},
"America/Edmonton"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 536457600000},
"Europe/Podgorica" "Europe/Belgrade",
"Europe/Saratov"
{:offset 14400000, :rule "-", :format "+04", :from 1480557600000},
"Greenwich" "Etc/GMT",
"Australia/ACT" "Australia/Sydney",
"Asia/Damascus"
{:offset 7200000,
:rule "Syria",
:format "EE%sT",
:from -1577923200000},
"Africa/Bujumbura" "Africa/Maputo",
"Australia/Lord_Howe"
{:offset 37800000,
:rule "LH",
:format "+1030/+11",
:from 489024000000},
"Singapore" "Asia/Singapore",
"Africa/Bangui" "Africa/Lagos",
"America/Kentucky/Monticello"
{:offset -18000000, :rule "US", :format "E%sT", :from 970365600000},
"Europe/Mariehamn" "Europe/Helsinki",
"Australia/Eucla"
{:offset 31500000,
:rule "AW",
:format "+0845/+0945",
:from -836438400000},
"Canada/Newfoundland" "America/St_Johns",
"America/North_Dakota/New_Salem"
{:offset -21600000, :rule "US", :format "C%sT", :from 1064973600000},
"Africa/Juba"
{:offset 10800000, :rule "-", :format "EAT", :from 946728000000},
"Africa/Gaborone" "Africa/Maputo",
"Etc/GMT-5" {:offset 18000000, :rule "-", :format "+05", :from nil},
"Canada/Saskatchewan" "America/Regina",
"Europe/Ljubljana" "Europe/Belgrade",
"Australia/Lindeman"
{:offset 36000000,
:rule "Holiday",
:format "AE%sT",
:from 709948800000},
"Africa/Mogadishu" "Africa/Nairobi",
"America/St_Thomas" "America/Port_of_Spain",
"America/Havana"
{:offset -18000000,
:rule "Cuba",
:format "C%sT",
:from -1404388800000},
"Asia/Ulaanbaatar"
{:offset 28800000,
:rule "Mongol",
:format "+08/+09",
:from 252460800000},
"Europe/Vaduz" "Europe/Zurich",
"America/Anchorage"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"America/Iqaluit"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 970365600000},
"Asia/Riyadh"
{:offset 10800000, :rule "-", :format "+03", :from -719625600000},
"America/Vancouver"
{:offset -28800000,
:rule "Canada",
:format "P%sT",
:from 536457600000},
"US/Pacific" "America/Los_Angeles",
"America/Grenada" "America/Port_of_Spain",
"America/Rio_Branco"
{:offset -18000000, :rule "-", :format "-05", :from 1383264000000},
"Europe/Bratislava" "Europe/Prague",
"Pacific/Fiji"
{:offset 43200000,
:rule "Fiji",
:format "+12/+13",
:from -1709942400000},
"Asia/Omsk"
{:offset 21600000, :rule "-", :format "+06", :from 1412128800000},
"America/Catamarca" "America/Argentina/Catamarca",
"Pacific/Funafuti"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"America/Merida"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 407548800000},
"Asia/Istanbul" "Europe/Istanbul",
"America/Cayman" "America/Panama",
"Etc/GMT+7" {:offset -25200000, :rule "-", :format "-07", :from nil},
"Etc/GMT-6" {:offset 21600000, :rule "-", :format "+06", :from nil},
"Zulu" "Etc/UTC",
"Pacific/Noumea"
{:offset 39600000,
:rule "NC",
:format "+11/+12",
:from -1829347200000},
"Indian/Mahe"
{:offset 14400000, :rule "-", :format "+04", :from -2006640000000},
"Asia/Irkutsk"
{:offset 28800000, :rule "-", :format "+08", :from 1412128800000},
"Antarctica/Palmer"
{:offset -10800000, :rule "-", :format "-03", :from 1480550400000},
"America/Bahia_Banderas"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 1270087200000},
"Europe/Budapest"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 336621600000},
"America/Regina"
{:offset -21600000, :rule "-", :format "CST", :from -305762400000},
"America/Halifax"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 126230400000},
"Asia/Anadyr"
{:offset 43200000, :rule "-", :format "+12", :from 1298944800000},
"America/Cuiaba"
{:offset -14400000,
:rule "Brazil",
:format "-04/-03",
:from 1096588800000},
"Australia/NSW" "Australia/Sydney",
"Africa/Porto-Novo" "Africa/Lagos",
"America/Argentina/Catamarca"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Indian/Mauritius"
{:offset 14400000,
:rule "Mauritius",
:format "+04/+05",
:from -1988150400000},
"Europe/Samara"
{:offset 14400000, :rule "-", :format "+04", :from 1298944800000},
"America/Eirunepe"
{:offset -18000000, :rule "-", :format "-05", :from 1383264000000},
"America/Fort_Nelson"
{:offset -25200000, :rule "-", :format "MST", :from 1425175200000},
"Atlantic/Faeroe" "Atlantic/Faroe",
"Africa/Asmara" "Africa/Nairobi",
"Asia/Tashkent"
{:offset 18000000, :rule "-", :format "+05", :from 694224000000},
"Etc/GMT-11" {:offset 39600000, :rule "-", :format "+11", :from nil},
"Africa/Maputo"
{:offset 7200000, :rule "-", :format "CAT", :from -2109283200000},
"Pacific/Kiritimati"
{:offset 50400000, :rule "-", :format "+14", :from 786240000000},
"PRC" "Asia/Shanghai",
"America/Argentina/ComodRivadavia" "America/Argentina/Catamarca",
"Asia/Qyzylorda"
{:offset 18000000, :rule "-", :format "+05", :from 1543622400000},
"Pacific/Midway" "Pacific/Pago_Pago",
"America/Kralendijk" "America/Curacao",
"Asia/Kabul"
{:offset 16200000, :rule "-", :format "+0430", :from -788918400000},
"America/Port_of_Spain"
{:offset -14400000, :rule "-", :format "AST", :from -1825113600000},
"Europe/Zurich"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 347155200000},
"America/Indianapolis" "America/Indiana/Indianapolis",
"NZ-CHAT" "Pacific/Chatham",
"Atlantic/Jan_Mayen" "Europe/Oslo",
"Asia/Kathmandu"
{:offset 20700000, :rule "-", :format "+0545", :from 504921600000},
"Africa/Algiers"
{:offset 3600000, :rule "-", :format "CET", :from 357523200000},
"America/Matamoros"
{:offset -21600000, :rule "US", :format "C%sT", :from 1262304000000},
"America/Araguaina"
{:offset -10800000, :rule "-", :format "-03", :from 1377993600000},
"America/Rosario" "America/Argentina/Cordoba",
"Etc/Greenwich" "Etc/GMT",
"America/Argentina/Tucuman"
{:offset -10800000,
:rule "Arg",
:format "-03/-02",
:from 1086048000000},
"Antarctica/South_Pole" "Pacific/Auckland",
"America/Marigot" "America/Port_of_Spain",
"Pacific/Marquesas"
{:offset -34200000,
:rule "-",
:format "-0930",
:from -1806710400000},
"Pacific/Truk" "Pacific/Chuuk",
"Asia/Baghdad"
{:offset 10800000,
:rule "Iraq",
:format "+03/+04",
:from 389059200000},
"America/Dawson_Creek"
{:offset -25200000, :rule "-", :format "MST", :from 81482400000},
"Europe/Kirov"
{:offset 10800000, :rule "-", :format "+03", :from 1412128800000},
"America/Santo_Domingo"
{:offset -14400000, :rule "-", :format "AST", :from 975632400000},
"US/Central" "America/Chicago",
"America/Miquelon"
{:offset -10800000,
:rule "Canada",
:format "-03/-02",
:from 536457600000},
"Pacific/Wake"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"Asia/Ust-Nera"
{:offset 36000000, :rule "-", :format "+10", :from 1412128800000},
"Australia/Canberra" "Australia/Sydney",
"Indian/Antananarivo" "Africa/Nairobi",
"Brazil/DeNoronha" "America/Noronha",
"Europe/Malta"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 347155200000},
"Europe/Paris"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"Africa/Luanda" "Africa/Lagos",
"Europe/Madrid"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 283996800000},
"Asia/Chongqing" "Asia/Shanghai",
"Europe/Gibraltar"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 378691200000},
"America/Cancun"
{:offset -18000000, :rule "-", :format "EST", :from 1422756000000},
"Asia/Dacca" "Asia/Dhaka",
"Israel" "Asia/Jerusalem",
"Pacific/Port_Moresby"
{:offset 36000000, :rule "-", :format "+10", :from -2366755200000},
"Atlantic/Cape_Verde"
{:offset -3600000, :rule "-", :format "-01", :from 184039200000},
"Australia/Darwin"
{:offset 34200000,
:rule "Aus",
:format "AC%sT",
:from -2230156800000},
"Africa/Nairobi"
{:offset 10800000, :rule "-", :format "EAT", :from -315619200000},
"WET" {:offset 0, :rule "EU", :format "WE%sT", :from nil},
"Atlantic/Canary"
{:offset 0, :rule "EU", :format "WE%sT", :from 336618000000},
"Africa/Libreville" "Africa/Lagos",
"America/Paramaribo"
{:offset -10800000, :rule "-", :format "-03", :from 465436800000},
"Asia/Ho_Chi_Minh"
{:offset 25200000, :rule "-", :format "+07", :from 170812800000},
"Europe/Vatican" "Europe/Rome",
"Africa/Ndjamena"
{:offset 3600000, :rule "-", :format "WAT", :from 320716800000},
"Australia/Melbourne"
{:offset 36000000, :rule "AV", :format "AE%sT", :from 31536000000},
"America/Manaus"
{:offset -14400000, :rule "-", :format "-04", :from 778377600000},
"Etc/GMT-13" {:offset 46800000, :rule "-", :format "+13", :from nil},
"America/Adak"
{:offset -36000000, :rule "US", :format "H%sT", :from 436492800000},
"Asia/Taipei"
{:offset 28800000,
:rule "Taiwan",
:format "C%sT",
:from -767919600000},
"Asia/Dhaka"
{:offset 21600000,
:rule "Dhaka",
:format "+06/+07",
:from 1230768000000}},
:rules
{"CR" nil,
"Pakistan" nil,
"Nic" nil,
"Perry" nil,
"Tunisia" nil,
"Uruguay" nil,
"Denver" nil,
"Hungary" nil,
"Cuba"
{:standard
{:from 1351987200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 0, :minute 0, :time-suffix "s"},
:month 11,
:save 0},
:daylight-savings
{:from 1362873600000,
:clock? :standard,
:floating-day "Sun>=8",
:time {:hour 0, :minute 0, :time-suffix "s"},
:month 3,
:save 3600000}},
"E-Eur"
{:daylight-savings
{:from 354672000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 846374400000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Haiti"
{:daylight-savings
{:from 1489284000000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1509847200000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Chicago" nil,
"Shang" nil,
"NT_YK" nil,
"Bulg" nil,
"Salv" nil,
"Moldova"
{:daylight-savings
{:from 859687200000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 877834800000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 3, :minute 0},
:month 10,
:save 0}},
"Winn" nil,
"Chile"
{:standard
{:from 1554606000000,
:clock? :utc,
:floating-day "Sun>=2",
:time {:hour 3, :minute 0, :time-suffix "u"},
:month 4,
:save 0},
:daylight-savings
{:from 1567915200000,
:clock? :utc,
:floating-day "Sun>=2",
:time {:hour 4, :minute 0, :time-suffix "u"},
:month 9,
:save 3600000}},
"SA" nil,
"Aus" nil,
"Brazil" nil,
"EUAsia"
{:daylight-savings
{:from 354675600000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 3,
:save 3600000},
:standard
{:from 846378000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 10,
:save 0}},
"Hond" nil,
"SpainAfrica" nil,
"Sudan" nil,
"Guam" nil,
"EU"
{:daylight-savings
{:from 354675600000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 3,
:save 3600000},
:standard
{:from 846378000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 10,
:save 0}},
"Pulaski" nil,
"Arg" nil,
"Palestine"
{:standard
{:from 1477702800000,
:clock? :utc,
:floating-day "lastSat",
:time {:hour 1, :minute 0},
:month 10,
:save 0},
:daylight-savings
{:from 1553817600000,
:clock? :utc,
:floating-day "lastFri",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000}},
"Eire"
{:standard
{:from 354675600000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 3,
:save 0},
:daylight-savings
{:from 846378000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 10,
:save -3600000}},
"Iraq" nil,
"Canada"
{:daylight-savings
{:from 1173578400000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1194141600000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Belgium" nil,
"Louisville" nil,
"Mexico"
{:daylight-savings
{:from 1018144800000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 4,
:save 3600000},
:standard
{:from 1035684000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 2, :minute 0},
:month 10,
:save 0}},
"Libya" nil,
"W-Eur"
{:daylight-savings
{:from 354675600000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "s"},
:month 3,
:save 3600000},
:standard
{:from 846378000000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "s"},
:month 10,
:save 0}},
"Moncton" nil,
"Detroit" nil,
"Romania" nil,
"SanLuis" nil,
"AT"
{:daylight-savings
{:from 1002420000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000},
:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0}},
"Malta" nil,
"Fiji"
{:standard
{:from 1421550000000,
:clock? :utc,
:floating-day "Sun>=12",
:time {:hour 3, :minute 0},
:month 1,
:save 0},
:daylight-savings
{:from 1573351200000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 11,
:save 3600000}},
"StJohns" nil,
"Egypt" nil,
"ROK" nil,
"Syria"
{:daylight-savings
{:from 1333065600000,
:clock? :utc,
:floating-day "lastFri",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1256860800000,
:clock? :utc,
:floating-day "lastFri",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Regina" nil,
"Japan" nil,
"AN"
{:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000}},
"Ecuador" nil,
"Zion"
{:daylight-savings
{:from 1364522400000,
:clock? :utc,
:floating-day "Fri>=23",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1382839200000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 2, :minute 0},
:month 10,
:save 0}},
"Ghana" nil,
"Latvia" nil,
"Vincennes" nil,
"Namibia" nil,
"Tonga" nil,
"Marengo" nil,
"Greece" nil,
"Toronto" nil,
"Swift" nil,
"Vanc" nil,
"Russia" nil,
"Italy" nil,
"Belize" nil,
"France" nil,
"NZ"
{:daylight-savings
{:from 1191117600000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 9,
:save 3600000},
:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0}},
"AW" nil,
"Iran"
{:daylight-savings
{:from 3729024000000,
:clock? :utc,
:day 20,
:time {:hour 24, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 3744921600000,
:clock? :utc,
:day 20,
:time {:hour 24, :minute 0},
:month 9,
:save 0}},
"Port" nil,
"Armenia" nil,
"WS"
{:standard
{:from 1333252800000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 4, :minute 0},
:month 4,
:save 0},
:daylight-savings
{:from 1348974000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 3, :minute 0},
:month 9,
:save 1}},
"Norway" nil,
"Algeria" nil,
"Czech" nil,
"Lux" nil,
"Taiwan" nil,
"Albania" nil,
"Chatham"
{:daylight-savings
{:from 1191120300000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 45, :time-suffix "s"},
:month 9,
:save 3600000},
:standard
{:from 1207449900000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 45, :time-suffix "s"},
:month 4,
:save 0}},
"CA" nil,
"Cyprus" nil,
"AV"
{:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000}},
"Dhaka" nil,
"Pike" nil,
"Finland" nil,
"Para"
{:daylight-savings
{:from 1286064000000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 0, :minute 0},
:month 10,
:save 3600000},
:standard
{:from 1364083200000,
:clock? :utc,
:floating-day "Sun>=22",
:time {:hour 0, :minute 0},
:month 3,
:save 0}},
"GB-Eire" nil,
"Kyrgyz" nil,
"Denmark" nil,
"AS"
{:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000}},
"Peru" nil,
"RussiaAsia" nil,
"Neth" nil,
"Iceland" nil,
"NBorneo" nil,
"Falk" nil,
"Spain" nil,
"Germany" nil,
"Azer" nil,
"Turkey" nil,
"Starke" nil,
"AQ" nil,
"Poland" nil,
"NYC" nil,
"E-EurAsia"
{:daylight-savings
{:from 354672000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 846374400000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Bahamas" nil,
"Phil" nil,
"US"
{:daylight-savings
{:from 1173578400000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1194141600000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Mauritius" nil,
"EgyptAsia" nil,
"NC" nil,
"Macau" nil,
"Morocco" nil,
"Indianapolis" nil,
"LH"
{:standard
{:from 1207447200000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 10,
:save 1800000}},
"Austria" nil,
"C-Eur"
{:daylight-savings
{:from 354679200000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 3,
:save 3600000},
:standard
{:from 846381600000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 0}},
"Holiday" nil,
"Barb" nil,
"Jordan"
{:daylight-savings
{:from 1395964800000,
:clock? :utc,
:floating-day "lastThu",
:time {:hour 24, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1414713600000,
:clock? :standard,
:floating-day "lastFri",
:time {:hour 0, :minute 0, :time-suffix "s"},
:month 10,
:save 0}},
"PRC" nil,
"HK" nil,
"Menominee" nil,
"Guat" nil,
"CO" nil,
"Lebanon"
{:daylight-savings
{:from 733276800000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 941328000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Swiss" nil,
"Halifax" nil,
"Cook" nil,
"Mongol" nil,
"SovietZone" nil,
"Thule"
{:daylight-savings
{:from 1173578400000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1194141600000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Vanuatu" nil,
"DR" nil,
"Edm" nil}}
))
| null | https://raw.githubusercontent.com/gersak/vura/e7c3fc8b738b73eaa00255f39d889afab611a069/timezones/src/vura/timezones/db.cljc | clojure | This file is autogenerated using vura.timezones.compile/-main |
(ns vura.timezones.db
(:require [clojure.string]))
(declare db locales)
(defn get-rule [rule]
(get-in db [:rules rule]))
(defn get-timezone [zone-name]
(if-let [zone' (get-in db [:zones zone-name])]
(if (string? zone') (get-timezone zone')
zone')
(throw
(ex-info "No such zone."
{:timezone zone-name
:available-timezones (keys (:zones db))}))))
(def available-zones
(sort (keys (:zones db))))
(def locales
{"CR" {:coordinates "+0956-08405", :zone "America/Costa_Rica"},
"TG" {:coordinates "+0608+00113", :zone "Africa/Lome"},
"TJ" {:coordinates "+3835+06848", :zone "Asia/Dushanbe"},
"ZA" {:coordinates "-2615+02800", :zone "Africa/Johannesburg"},
"IM" {:coordinates "+5409-00428", :zone "Europe/Isle_of_Man"},
"PE" {:coordinates "-1203-07703", :zone "America/Lima"},
"LC" {:coordinates "+1401-06100", :zone "America/St_Lucia"},
"CH" {:coordinates "+4723+00832", :zone "Europe/Zurich"},
"RU" {:coordinates "+6445+17729", :zone "Asia/Anadyr"},
"MP" {:coordinates "+1512+14545", :zone "Pacific/Saipan"},
"CK" {:coordinates "-2114-15946", :zone "Pacific/Rarotonga"},
"SI" {:coordinates "+4603+01431", :zone "Europe/Ljubljana"},
"AU" {:coordinates "-3143+12852", :zone "Australia/Eucla"},
"KR" {:coordinates "+3733+12658", :zone "Asia/Seoul"},
"IT" {:coordinates "+4154+01229", :zone "Europe/Rome"},
"FI" {:coordinates "+6010+02458", :zone "Europe/Helsinki"},
"GF" {:coordinates "+0456-05220", :zone "America/Cayenne"},
"SC" {:coordinates "-0440+05528", :zone "Indian/Mahe"},
"SX" {:coordinates "+180305-0630250", :zone "America/Lower_Princes"},
"TT" {:coordinates "+1039-06131", :zone "America/Port_of_Spain"},
"TK" {:coordinates "-0922-17114", :zone "Pacific/Fakaofo"},
"MY" {:coordinates "+0133+11020", :zone "Asia/Kuching"},
"SY" {:coordinates "+3330+03618", :zone "Asia/Damascus"},
"MN" {:coordinates "+4804+11430", :zone "Asia/Choibalsan"},
"TF" {:coordinates "-492110+0701303", :zone "Indian/Kerguelen"},
"KP" {:coordinates "+3901+12545", :zone "Asia/Pyongyang"},
"AM" {:coordinates "+4011+04430", :zone "Asia/Yerevan"},
"DZ" {:coordinates "+3647+00303", :zone "Africa/Algiers"},
"UY" {:coordinates "-345433-0561245", :zone "America/Montevideo"},
"TD" {:coordinates "+1207+01503", :zone "Africa/Ndjamena"},
"DJ" {:coordinates "+1136+04309", :zone "Africa/Djibouti"},
"BI" {:coordinates "-0323+02922", :zone "Africa/Bujumbura"},
"MK" {:coordinates "+4159+02126", :zone "Europe/Skopje"},
"MU" {:coordinates "-2010+05730", :zone "Indian/Mauritius"},
"LI" {:coordinates "+4709+00931", :zone "Europe/Vaduz"},
"NU" {:coordinates "-1901-16955", :zone "Pacific/Niue"},
"GR" {:coordinates "+3758+02343", :zone "Europe/Athens"},
"GY" {:coordinates "+0648-05810", :zone "America/Guyana"},
"CG" {:coordinates "-0416+01517", :zone "Africa/Brazzaville"},
"NF" {:coordinates "-2903+16758", :zone "Pacific/Norfolk"},
"ML" {:coordinates "+1239-00800", :zone "Africa/Bamako"},
"AX" {:coordinates "+6006+01957", :zone "Europe/Mariehamn"},
"GM" {:coordinates "+1328-01639", :zone "Africa/Banjul"},
"SA" {:coordinates "+2438+04643", :zone "Asia/Riyadh"},
"CX" {:coordinates "-1025+10543", :zone "Indian/Christmas"},
"BH" {:coordinates "+2623+05035", :zone "Asia/Bahrain"},
"NE" {:coordinates "+1331+00207", :zone "Africa/Niamey"},
"BN" {:coordinates "+0456+11455", :zone "Asia/Brunei"},
"MF" {:coordinates "+1804-06305", :zone "America/Marigot"},
"CD" {:coordinates "-1140+02728", :zone "Africa/Lubumbashi"},
"DK" {:coordinates "+5540+01235", :zone "Europe/Copenhagen"},
"BJ" {:coordinates "+0629+00237", :zone "Africa/Porto-Novo"},
"ME" {:coordinates "+4226+01916", :zone "Europe/Podgorica"},
"SJ" {:coordinates "+7800+01600", :zone "Arctic/Longyearbyen"},
"BO" {:coordinates "-1630-06809", :zone "America/La_Paz"},
"JO" {:coordinates "+3157+03556", :zone "Asia/Amman"},
"CV" {:coordinates "+1455-02331", :zone "Atlantic/Cape_Verde"},
"VE" {:coordinates "+1030-06656", :zone "America/Caracas"},
"CI" {:coordinates "+0519-00402", :zone "Africa/Abidjan"},
"UZ" {:coordinates "+4120+06918", :zone "Asia/Tashkent"},
"TN" {:coordinates "+3648+01011", :zone "Africa/Tunis"},
"IS" {:coordinates "+6409-02151", :zone "Atlantic/Reykjavik"},
"EH" {:coordinates "+2709-01312", :zone "Africa/El_Aaiun"},
"TM" {:coordinates "+3757+05823", :zone "Asia/Ashgabat"},
"GA" {:coordinates "+0023+00927", :zone "Africa/Libreville"},
"LS" {:coordinates "-2928+02730", :zone "Africa/Maseru"},
"TZ" {:coordinates "-0648+03917", :zone "Africa/Dar_es_Salaam"},
"AT" {:coordinates "+4813+01620", :zone "Europe/Vienna"},
"LT" {:coordinates "+5441+02519", :zone "Europe/Vilnius"},
"NP" {:coordinates "+2743+08519", :zone "Asia/Kathmandu"},
"BG" {:coordinates "+4241+02319", :zone "Europe/Sofia"},
"IL" {:coordinates "+314650+0351326", :zone "Asia/Jerusalem"},
"GU" {:coordinates "+1328+14445", :zone "Pacific/Guam"},
"PK" {:coordinates "+2452+06703", :zone "Asia/Karachi"},
"PT" {:coordinates "+3744-02540", :zone "Atlantic/Azores"},
"HR" {:coordinates "+4548+01558", :zone "Europe/Zagreb"},
"VU" {:coordinates "-1740+16825", :zone "Pacific/Efate"},
"PF" {:coordinates "-2308-13457", :zone "Pacific/Gambier"},
"BM" {:coordinates "+3217-06446", :zone "Atlantic/Bermuda"},
"MR" {:coordinates "+1806-01557", :zone "Africa/Nouakchott"},
"GE" {:coordinates "+4143+04449", :zone "Asia/Tbilisi"},
"HU" {:coordinates "+4730+01905", :zone "Europe/Budapest"},
"TW" {:coordinates "+2503+12130", :zone "Asia/Taipei"},
"MM" {:coordinates "+1647+09610", :zone "Asia/Yangon"},
"VG" {:coordinates "+1827-06437", :zone "America/Tortola"},
"YE" {:coordinates "+1245+04512", :zone "Asia/Aden"},
"SR" {:coordinates "+0550-05510", :zone "America/Paramaribo"},
"PN" {:coordinates "-2504-13005", :zone "Pacific/Pitcairn"},
"VA" {:coordinates "+415408+0122711", :zone "Europe/Vatican"},
"PR" {:coordinates "+182806-0660622", :zone "America/Puerto_Rico"},
"KW" {:coordinates "+2920+04759", :zone "Asia/Kuwait"},
"SE" {:coordinates "+5920+01803", :zone "Europe/Stockholm"},
"GB" {:coordinates "+513030-0000731", :zone "Europe/London"},
"UM" {:coordinates "+1917+16637", :zone "Pacific/Wake"},
"VN" {:coordinates "+1045+10640", :zone "Asia/Ho_Chi_Minh"},
"CF" {:coordinates "+0422+01835", :zone "Africa/Bangui"},
"PA" {:coordinates "+0858-07932", :zone "America/Panama"},
"VC" {:coordinates "+1309-06114", :zone "America/St_Vincent"},
"JP" {:coordinates "+353916+1394441", :zone "Asia/Tokyo"},
"IR" {:coordinates "+3540+05126", :zone "Asia/Tehran"},
"AF" {:coordinates "+3431+06912", :zone "Asia/Kabul"},
"LY" {:coordinates "+3254+01311", :zone "Africa/Tripoli"},
"MZ" {:coordinates "-2558+03235", :zone "Africa/Maputo"},
"RO" {:coordinates "+4426+02606", :zone "Europe/Bucharest"},
"QA" {:coordinates "+2517+05132", :zone "Asia/Qatar"},
"CM" {:coordinates "+0403+00942", :zone "Africa/Douala"},
"GG" {:coordinates "+492717-0023210", :zone "Europe/Guernsey"},
"BY" {:coordinates "+5354+02734", :zone "Europe/Minsk"},
"SD" {:coordinates "+1536+03232", :zone "Africa/Khartoum"},
"BQ" {:coordinates "+120903-0681636", :zone "America/Kralendijk"},
"MO" {:coordinates "+221150+1133230", :zone "Asia/Macau"},
"KY" {:coordinates "+1918-08123", :zone "America/Cayman"},
"AR" {:coordinates "-5448-06818", :zone "America/Argentina/Ushuaia"},
"BR" {:coordinates "-0958-06748", :zone "America/Rio_Branco"},
"ZW" {:coordinates "-1750+03103", :zone "Africa/Harare"},
"NR" {:coordinates "-0031+16655", :zone "Pacific/Nauru"},
"NZ" {:coordinates "-4357-17633", :zone "Pacific/Chatham"},
"AW" {:coordinates "+1230-06958", :zone "America/Aruba"},
"FJ" {:coordinates "-1808+17825", :zone "Pacific/Fiji"},
"ID" {:coordinates "-0232+14042", :zone "Asia/Jayapura"},
"SV" {:coordinates "+1342-08912", :zone "America/El_Salvador"},
"CN" {:coordinates "+4348+08735", :zone "Asia/Urumqi"},
"FM" {:coordinates "+0519+16259", :zone "Pacific/Kosrae"},
"HT" {:coordinates "+1832-07220", :zone "America/Port-au-Prince"},
"CC" {:coordinates "-1210+09655", :zone "Indian/Cocos"},
"RW" {:coordinates "-0157+03004", :zone "Africa/Kigali"},
"BA" {:coordinates "+4352+01825", :zone "Europe/Sarajevo"},
"TL" {:coordinates "-0833+12535", :zone "Asia/Dili"},
"JM" {:coordinates "+175805-0764736", :zone "America/Jamaica"},
"KM" {:coordinates "-1141+04316", :zone "Indian/Comoro"},
"KE" {:coordinates "-0117+03649", :zone "Africa/Nairobi"},
"WS" {:coordinates "-1350-17144", :zone "Pacific/Apia"},
"TO" {:coordinates "-2110-17510", :zone "Pacific/Tongatapu"},
"PY" {:coordinates "-2516-05740", :zone "America/Asuncion"},
"SH" {:coordinates "-1555-00542", :zone "Atlantic/St_Helena"},
"CY" {:coordinates "+3507+03357", :zone "Asia/Famagusta"},
"GH" {:coordinates "+0533-00013", :zone "Africa/Accra"},
"MA" {:coordinates "+3339-00735", :zone "Africa/Casablanca"},
"SG" {:coordinates "+0117+10351", :zone "Asia/Singapore"},
"LK" {:coordinates "+0656+07951", :zone "Asia/Colombo"},
"PH" {:coordinates "+1435+12100", :zone "Asia/Manila"},
"SM" {:coordinates "+4355+01228", :zone "Europe/San_Marino"},
"WF" {:coordinates "-1318-17610", :zone "Pacific/Wallis"},
"TR" {:coordinates "+4101+02858", :zone "Europe/Istanbul"},
"PS" {:coordinates "+313200+0350542", :zone "Asia/Hebron"},
"BZ" {:coordinates "+1730-08812", :zone "America/Belize"},
"CU" {:coordinates "+2308-08222", :zone "America/Havana"},
"TV" {:coordinates "-0831+17913", :zone "Pacific/Funafuti"},
"AD" {:coordinates "+4230+00131", :zone "Europe/Andorra"},
"SB" {:coordinates "-0932+16012", :zone "Pacific/Guadalcanal"},
"DM" {:coordinates "+1518-06124", :zone "America/Dominica"},
"LR" {:coordinates "+0618-01047", :zone "Africa/Monrovia"},
"OM" {:coordinates "+2336+05835", :zone "Asia/Muscat"},
"SO" {:coordinates "+0204+04522", :zone "Africa/Mogadishu"},
"DO" {:coordinates "+1828-06954", :zone "America/Santo_Domingo"},
"AL" {:coordinates "+4120+01950", :zone "Europe/Tirane"},
"BL" {:coordinates "+1753-06251", :zone "America/St_Barthelemy"},
"FR" {:coordinates "+4852+00220", :zone "Europe/Paris"},
"GW" {:coordinates "+1151-01535", :zone "Africa/Bissau"},
"MS" {:coordinates "+1643-06213", :zone "America/Montserrat"},
"BB" {:coordinates "+1306-05937", :zone "America/Barbados"},
"CA" {:coordinates "+6404-13925", :zone "America/Dawson"},
"MG" {:coordinates "-1855+04731", :zone "Indian/Antananarivo"},
"KH" {:coordinates "+1133+10455", :zone "Asia/Phnom_Penh"},
"LA" {:coordinates "+1758+10236", :zone "Asia/Vientiane"},
"GP" {:coordinates "+1614-06132", :zone "America/Guadeloupe"},
"HN" {:coordinates "+1406-08713", :zone "America/Tegucigalpa"},
"TH" {:coordinates "+1345+10031", :zone "Asia/Bangkok"},
"DE" {:coordinates "+4742+00841", :zone "Europe/Busingen"},
"LB" {:coordinates "+3353+03530", :zone "Asia/Beirut"},
"KZ" {:coordinates "+5113+05121", :zone "Asia/Oral"},
"AS" {:coordinates "-1416-17042", :zone "Pacific/Pago_Pago"},
"EC" {:coordinates "-0054-08936", :zone "Pacific/Galapagos"},
"NO" {:coordinates "+5955+01045", :zone "Europe/Oslo"},
"AO" {:coordinates "-0848+01314", :zone "Africa/Luanda"},
"FK" {:coordinates "-5142-05751", :zone "Atlantic/Stanley"},
"ET" {:coordinates "+0902+03842", :zone "Africa/Addis_Ababa"},
"GS" {:coordinates "-5416-03632", :zone "Atlantic/South_Georgia"},
"MD" {:coordinates "+4700+02850", :zone "Europe/Chisinau"},
"AG" {:coordinates "+1703-06148", :zone "America/Antigua"},
"BE" {:coordinates "+5050+00420", :zone "Europe/Brussels"},
"MV" {:coordinates "+0410+07330", :zone "Indian/Maldives"},
"SZ" {:coordinates "-2618+03106", :zone "Africa/Mbabane"},
"CZ" {:coordinates "+5005+01426", :zone "Europe/Prague"},
"CL" {:coordinates "-2709-10926", :zone "Pacific/Easter"},
"BT" {:coordinates "+2728+08939", :zone "Asia/Thimphu"},
"NL" {:coordinates "+5222+00454", :zone "Europe/Amsterdam"},
"EG" {:coordinates "+3003+03115", :zone "Africa/Cairo"},
"MQ" {:coordinates "+1436-06105", :zone "America/Martinique"},
"SN" {:coordinates "+1440-01726", :zone "Africa/Dakar"},
"FO" {:coordinates "+6201-00646", :zone "Atlantic/Faroe"},
"EE" {:coordinates "+5925+02445", :zone "Europe/Tallinn"},
"AQ" {:coordinates "-7824+10654", :zone "Antarctica/Vostok"},
"ST" {:coordinates "+0020+00644", :zone "Africa/Sao_Tome"},
"KN" {:coordinates "+1718-06243", :zone "America/St_Kitts"},
"BW" {:coordinates "-2439+02555", :zone "Africa/Gaborone"},
"MH" {:coordinates "+0905+16720", :zone "Pacific/Kwajalein"},
"NI" {:coordinates "+1209-08617", :zone "America/Managua"},
"PG" {:coordinates "-0613+15534", :zone "Pacific/Bougainville"},
"VI" {:coordinates "+1821-06456", :zone "America/St_Thomas"},
"IQ" {:coordinates "+3321+04425", :zone "Asia/Baghdad"},
"KG" {:coordinates "+4254+07436", :zone "Asia/Bishkek"},
"US" {:coordinates "+211825-1575130", :zone "Pacific/Honolulu"},
"ZM" {:coordinates "-1525+02817", :zone "Africa/Lusaka"},
"MC" {:coordinates "+4342+00723", :zone "Europe/Monaco"},
"GI" {:coordinates "+3608-00521", :zone "Europe/Gibraltar"},
"NC" {:coordinates "-2216+16627", :zone "Pacific/Noumea"},
"GT" {:coordinates "+1438-09031", :zone "America/Guatemala"},
"BF" {:coordinates "+1222-00131", :zone "Africa/Ouagadougou"},
"YT" {:coordinates "-1247+04514", :zone "Indian/Mayotte"},
"LU" {:coordinates "+4936+00609", :zone "Europe/Luxembourg"},
"UA" {:coordinates "+4750+03510", :zone "Europe/Zaporozhye"},
"IE" {:coordinates "+5320-00615", :zone "Europe/Dublin"},
"LV" {:coordinates "+5657+02406", :zone "Europe/Riga"},
"GD" {:coordinates "+1203-06145", :zone "America/Grenada"},
"MW" {:coordinates "-1547+03500", :zone "Africa/Blantyre"},
"BS" {:coordinates "+2505-07721", :zone "America/Nassau"},
"AZ" {:coordinates "+4023+04951", :zone "Asia/Baku"},
"SK" {:coordinates "+4809+01707", :zone "Europe/Bratislava"},
"GQ" {:coordinates "+0345+00847", :zone "Africa/Malabo"},
"TC" {:coordinates "+2128-07108", :zone "America/Grand_Turk"},
"RE" {:coordinates "-2052+05528", :zone "Indian/Reunion"},
"IN" {:coordinates "+2232+08822", :zone "Asia/Kolkata"},
"ES" {:coordinates "+2806-01524", :zone "Atlantic/Canary"},
"GL" {:coordinates "+7634-06847", :zone "America/Thule"},
"KI" {:coordinates "+0152-15720", :zone "Pacific/Kiritimati"},
"HK" {:coordinates "+2217+11409", :zone "Asia/Hong_Kong"},
"CO" {:coordinates "+0436-07405", :zone "America/Bogota"},
"SS" {:coordinates "+0451+03137", :zone "Africa/Juba"},
"RS" {:coordinates "+4450+02030", :zone "Europe/Belgrade"},
"IO" {:coordinates "-0720+07225", :zone "Indian/Chagos"},
"NG" {:coordinates "+0627+00324", :zone "Africa/Lagos"},
"UG" {:coordinates "+0019+03225", :zone "Africa/Kampala"},
"CW" {:coordinates "+1211-06900", :zone "America/Curacao"},
"SL" {:coordinates "+0830-01315", :zone "Africa/Freetown"},
"ER" {:coordinates "+1520+03853", :zone "Africa/Asmara"},
"JE" {:coordinates "+491101-0020624", :zone "Europe/Jersey"},
"AE" {:coordinates "+2518+05518", :zone "Asia/Dubai"},
"PM" {:coordinates "+4703-05620", :zone "America/Miquelon"},
"BD" {:coordinates "+2343+09025", :zone "Asia/Dhaka"},
"MT" {:coordinates "+3554+01431", :zone "Europe/Malta"},
"AI" {:coordinates "+1812-06304", :zone "America/Anguilla"},
"GN" {:coordinates "+0931-01343", :zone "Africa/Conakry"},
"PW" {:coordinates "+0720+13429", :zone "Pacific/Palau"},
"NA" {:coordinates "-2234+01706", :zone "Africa/Windhoek"},
"MX" {:coordinates "+2048-10515", :zone "America/Bahia_Banderas"},
"PL" {:coordinates "+5215+02100", :zone "Europe/Warsaw"}}
)
(def timezone->locale
(reduce
(fn [result [locale {:keys [zone]}]]
(assoc result zone locale))
nil
locales))
(defn get-timezone-locale [timezone]
(get timezone->locale timezone))
(defn get-locale-timezone [locale]
(get-in
locales
[(clojure.string/upper-case locale) :zone]))
(defn get-locale [locale]
(get locales (clojure.string/upper-case locale)))
(def db-extensions
{:zones
{"GMT"
{:offset 0, :rule "-" , :format "GMT", :from 0}}})
(def db
(merge-with
merge
db-extensions
{:zones
{"Asia/Rangoon" "Asia/Yangon",
"Mexico/BajaNorte" "America/Tijuana",
"Europe/Amsterdam"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"America/Montevideo"
{:offset -10800000,
:rule "Uruguay",
:format "-03/-02",
:from 155088000000},
"Africa/Kinshasa" "Africa/Lagos",
"Asia/Sakhalin"
{:offset 39600000, :rule "-", :format "+11", :from 1456797600000},
"America/Santarem"
{:offset -10800000, :rule "-", :format "-03", :from 1212278400000},
"Europe/Tiraspol" "Europe/Chisinau",
"Africa/Ouagadougou" "Africa/Abidjan",
"Asia/Amman"
{:offset 7200000,
:rule "Jordan",
:format "EE%sT",
:from -1230768000000},
"Europe/Tallinn"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 1012521600000},
"Africa/Blantyre" "Africa/Maputo",
"America/Nipigon"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from -880927200000},
"America/Jamaica"
{:offset -18000000, :rule "-", :format "EST", :from 441763200000},
"Africa/El_Aaiun"
{:offset 3600000,
:rule "Morocco",
:format "+01/+00",
:from 1538362800000},
"Australia/LHI" "Australia/Lord_Howe",
"America/Costa_Rica"
{:offset -21600000,
:rule "CR",
:format "C%sT",
:from -1546300800000},
"Canada/Eastern" "America/Toronto",
"Asia/Kuala_Lumpur"
{:offset 28800000, :rule "-", :format "+08", :from 378691200000},
"America/Cordoba" "America/Argentina/Cordoba",
"Asia/Kuwait" "Asia/Riyadh",
"Asia/Tokyo"
{:offset 32400000,
:rule "Japan",
:format "J%sT",
:from -2587766400000},
"America/Maceio"
{:offset -10800000, :rule "-", :format "-03", :from 1033430400000},
"Europe/Brussels"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"America/Nome"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"Australia/Broken_Hill"
{:offset 34200000, :rule "AS", :format "AC%sT", :from 946684800000},
"Asia/Chita"
{:offset 32400000, :rule "-", :format "+09", :from 1456797600000},
"Universal" "Etc/UTC",
"Africa/Timbuktu" "Africa/Abidjan",
"Africa/Casablanca"
{:offset 3600000,
:rule "Morocco",
:format "+01/+00",
:from 1538362800000},
"Europe/Isle_of_Man" "Europe/London",
"America/Ensenada" "America/Tijuana",
"America/Argentina/San_Luis"
{:offset -10800000, :rule "-", :format "-03", :from 1254355200000},
"America/St_Johns"
{:offset -12600000,
:rule "Canada",
:format "N%sT",
:from 1320105600000},
"Europe/Berlin"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Africa/Lome" "Africa/Abidjan",
"America/North_Dakota/Center"
{:offset -21600000, :rule "US", :format "C%sT", :from 717904800000},
"Asia/Aqtobe"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"Antarctica/Macquarie"
{:offset 39600000, :rule "-", :format "+11", :from 1270090800000},
"Asia/Seoul"
{:offset 32400000, :rule "ROK", :format "K%sT", :from -265680000000},
"Chile/EasterIsland" "Pacific/Easter",
"US/Hawaii" "Pacific/Honolulu",
"America/Punta_Arenas"
{:offset -10800000, :rule "-", :format "-03", :from 1480550400000},
"Indian/Christmas"
{:offset 25200000, :rule "-", :format "+07", :from -2364076800000},
"Atlantic/Madeira"
{:offset 0, :rule "EU", :format "WE%sT", :from 431226000000},
"Asia/Barnaul"
{:offset 25200000, :rule "-", :format "+07", :from 1456797600000},
"Asia/Colombo"
{:offset 19800000, :rule "-", :format "+0530", :from 1143851400000},
"America/Argentina/Mendoza"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Asia/Novokuznetsk"
{:offset 25200000, :rule "-", :format "+07", :from 1298944800000},
"America/Indiana/Vevay"
{:offset -18000000, :rule "US", :format "E%sT", :from 1136073600000},
"America/Argentina/Rio_Gallegos"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Etc/GMT" {:offset 0, :rule "-", :format "GMT", :from nil},
"US/Aleutian" "America/Adak",
"America/Fortaleza"
{:offset -10800000, :rule "-", :format "-03", :from 1033430400000},
"Australia/South" "Australia/Adelaide",
"Europe/Uzhgorod"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 788918400000},
"Asia/Beirut"
{:offset 7200000,
:rule "Lebanon",
:format "EE%sT",
:from -2840140800000},
"Australia/Yancowinna" "Australia/Broken_Hill",
"Africa/Sao_Tome"
{:offset 0, :rule "-", :format "GMT", :from 1546308000000},
"GMT" "Etc/GMT",
"Cuba" "America/Havana",
"Asia/Dubai"
{:offset 14400000, :rule "-", :format "+04", :from -1577923200000},
"Europe/Stockholm"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Portugal" "Europe/Lisbon",
"America/Boise"
{:offset -25200000, :rule "US", :format "M%sT", :from 128916000000},
"America/Scoresbysund"
{:offset -3600000,
:rule "EU",
:format "-01/+00",
:from 352252800000},
"Indian/Maldives"
{:offset 18000000, :rule "-", :format "+05", :from -315619200000},
"Europe/Simferopol"
{:offset 10800000, :rule "-", :format "MSK", :from 1412128800000},
"Pacific/Efate"
{:offset 39600000,
:rule "Vanuatu",
:format "+11/+12",
:from -1829347200000},
"GMT-0" "Etc/GMT",
"Asia/Qatar"
{:offset 10800000, :rule "-", :format "+03", :from 76204800000},
"GMT+0" "Etc/GMT",
"GMT0" "Etc/GMT",
"Europe/Jersey" "Europe/London",
"Pacific/Honolulu"
{:offset -36000000, :rule "-", :format "HST", :from -712792800000},
"America/Tegucigalpa"
{:offset -21600000,
:rule "Hond",
:format "C%sT",
:from -1538524800000},
"Atlantic/South_Georgia"
{:offset -7200000, :rule "-", :format "-02", :from -2524521600000},
"Asia/Hong_Kong"
{:offset 28800000, :rule "HK", :format "HK%sT", :from -762645600000},
"Pacific/Pohnpei"
{:offset 39600000, :rule "-", :format "+11", :from -770601600000},
"Pacific/Norfolk"
{:offset 39600000,
:rule "AN",
:format "+11/+12",
:from 1561939200000},
"America/Santiago"
{:offset -14400000,
:rule "Chile",
:format "-04/-03",
:from -715395600000},
"America/Indiana/Knox"
{:offset -21600000, :rule "US", :format "C%sT", :from 1143856800000},
"Etc/GMT0" "Etc/GMT",
"Australia/Brisbane"
{:offset 36000000, :rule "AQ", :format "AE%sT", :from 31536000000},
"America/Anguilla" "America/Port_of_Spain",
"Asia/Hovd"
{:offset 25200000,
:rule "Mongol",
:format "+07/+08",
:from 252460800000},
"Asia/Jakarta"
{:offset 25200000, :rule "-", :format "WIB", :from -189388800000},
"Atlantic/Stanley"
{:offset -10800000, :rule "-", :format "-03", :from 1283306400000},
"America/Jujuy" "America/Argentina/Jujuy",
"Indian/Comoro" "Africa/Nairobi",
"America/Sao_Paulo"
{:offset -10800000,
:rule "Brazil",
:format "-03/-02",
:from -189388800000},
"Asia/Macao" "Asia/Macau",
"Etc/GMT+12"
{:offset -43200000, :rule "-", :format "-12", :from nil},
"Asia/Macau"
{:offset 28800000,
:rule "Macau",
:format "C%sT",
:from -767836800000},
"America/Menominee"
{:offset -21600000, :rule "US", :format "C%sT", :from 102477600000},
"Asia/Bahrain" "Asia/Qatar",
"Asia/Katmandu" "Asia/Kathmandu",
"America/Montreal" "America/Toronto",
"Atlantic/St_Helena" "Africa/Abidjan",
"MET" {:offset 3600000, :rule "C-Eur", :format "ME%sT", :from nil},
"Africa/Tunis"
{:offset 3600000,
:rule "Tunisia",
:format "CE%sT",
:from -1856822400000},
"Africa/Lusaka" "Africa/Maputo",
"Etc/GMT+2" {:offset -7200000, :rule "-", :format "-02", :from nil},
"CST6CDT" {:offset -21600000, :rule "US", :format "C%sT", :from nil},
"Pacific/Easter"
{:offset -21600000,
:rule "Chile",
:format "-06/-05",
:from 383799600000},
"Asia/Ashkhabad" "Asia/Ashgabat",
"Africa/Cairo"
{:offset 7200000,
:rule "Egypt",
:format "EE%sT",
:from -2185401600000},
"Etc/GMT-10" {:offset 36000000, :rule "-", :format "+10", :from nil},
"Pacific/Chuuk"
{:offset 36000000, :rule "-", :format "+10", :from -770601600000},
"US/Eastern" "America/New_York",
"America/Montserrat" "America/Port_of_Spain",
"Pacific/Tarawa"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"America/Resolute"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from 1172718000000},
"Pacific/Saipan" "Pacific/Guam",
"Asia/Thimbu" "Asia/Thimphu",
"Asia/Muscat" "Asia/Dubai",
"Asia/Saigon" "Asia/Ho_Chi_Minh",
"Hongkong" "Asia/Hong_Kong",
"Europe/Zaporozhye"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 788918400000},
"Asia/Aqtau"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"Asia/Hebron"
{:offset 7200000,
:rule "Palestine",
:format "EE%sT",
:from 915148800000},
"Asia/Kuching"
{:offset 28800000, :rule "-", :format "+08", :from -767923200000},
"Pacific/Tahiti"
{:offset -36000000, :rule "-", :format "-10", :from -1806710400000},
"America/Argentina/Jujuy"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Etc/GMT+1" {:offset -3600000, :rule "-", :format "-01", :from nil},
"Atlantic/Faroe"
{:offset 0, :rule "EU", :format "WE%sT", :from 347155200000},
"Asia/Vladivostok"
{:offset 36000000, :rule "-", :format "+10", :from 1412128800000},
"Europe/Oslo"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Australia/Tasmania" "Australia/Hobart",
"Asia/Oral"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"Arctic/Longyearbyen" "Europe/Oslo",
"America/Indiana/Marengo"
{:offset -18000000, :rule "US", :format "E%sT", :from 1136073600000},
"America/Rainy_River"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from -880927200000},
"America/Barbados"
{:offset -14400000,
:rule "Barb",
:format "A%sT",
:from -1199232000000},
"Indian/Chagos"
{:offset 21600000, :rule "-", :format "+06", :from 820454400000},
"Indian/Cocos"
{:offset 23400000, :rule "-", :format "+0630", :from -2208988800000},
"Australia/Victoria" "Australia/Melbourne",
"Africa/Harare" "Africa/Maputo",
"America/Aruba" "America/Curacao",
"America/El_Salvador"
{:offset -21600000,
:rule "Salv",
:format "C%sT",
:from -1546300800000},
"America/Porto_Velho"
{:offset -14400000, :rule "-", :format "-04", :from 589075200000},
"Etc/GMT-4" {:offset 14400000, :rule "-", :format "+04", :from nil},
"Navajo" "America/Denver",
"Australia/Hobart"
{:offset 36000000, :rule "AT", :format "AE%sT", :from -94694400000},
"America/Ojinaga"
{:offset -25200000, :rule "US", :format "M%sT", :from 1262304000000},
"Asia/Jayapura"
{:offset 32400000, :rule "-", :format "WIT", :from -189388800000},
"Etc/Universal" "Etc/UTC",
"America/Goose_Bay"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 1320105600000},
"America/Panama"
{:offset -18000000, :rule "-", :format "EST", :from -1948752000000},
"Africa/Dar_es_Salaam" "Africa/Nairobi",
"America/Mendoza" "America/Argentina/Mendoza",
"Asia/Tehran"
{:offset 12600000,
:rule "Iran",
:format "+0330/+0430",
:from 283996800000},
"America/Blanc-Sablon"
{:offset -14400000, :rule "-", :format "AST", :from 0},
"PST8PDT" {:offset -28800000, :rule "US", :format "P%sT", :from nil},
"Pacific/Johnston" "Pacific/Honolulu",
"Etc/GMT-12" {:offset 43200000, :rule "-", :format "+12", :from nil},
"America/Noronha"
{:offset -7200000, :rule "-", :format "-02", :from 1033430400000},
"America/St_Kitts" "America/Port_of_Spain",
"Etc/GMT+10"
{:offset -36000000, :rule "-", :format "-10", :from nil},
"Pacific/Enderbury"
{:offset 46800000, :rule "-", :format "+13", :from 786240000000},
"Australia/Queensland" "Australia/Brisbane",
"Etc/GMT+5" {:offset -18000000, :rule "-", :format "-05", :from nil},
"Pacific/Ponape" "Pacific/Pohnpei",
"Antarctica/McMurdo" "Pacific/Auckland",
"Africa/Ceuta"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 504921600000},
"Asia/Baku"
{:offset 14400000,
:rule "Azer",
:format "+04/+05",
:from 852076800000},
"Europe/Sofia"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 852076800000},
"CET" {:offset 3600000, :rule "C-Eur", :format "CE%sT", :from nil},
"America/Pangnirtung"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 970365600000},
"America/Monterrey"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 599616000000},
"Asia/Pontianak"
{:offset 25200000, :rule "-", :format "WIB", :from 567993600000},
"America/Moncton"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 1167609600000},
"Europe/Belfast" "Europe/London",
"America/Dominica" "America/Port_of_Spain",
"America/Swift_Current"
{:offset -21600000, :rule "-", :format "CST", :from 73447200000},
"Eire" "Europe/Dublin",
"America/Argentina/Salta"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"America/Sitka"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"America/Creston"
{:offset -25200000, :rule "-", :format "MST", :from -1627948800000},
"America/St_Vincent" "America/Port_of_Spain",
"Europe/Andorra"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 478490400000},
"Pacific/Wallis"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"Asia/Ujung_Pandang" "Asia/Makassar",
"Africa/Niamey" "Africa/Lagos",
"MST7MDT" {:offset -25200000, :rule "US", :format "M%sT", :from nil},
"Asia/Manila"
{:offset 28800000,
:rule "Phil",
:format "P%sT",
:from -794188800000},
"HST" {:offset -36000000, :rule "-", :format "HST", :from nil},
"Asia/Shanghai"
{:offset 28800000, :rule "PRC", :format "C%sT", :from -652320000000},
"Etc/GMT+4" {:offset -14400000, :rule "-", :format "-04", :from nil},
"Europe/London"
{:offset 0, :rule "EU", :format "GMT/BST", :from 820454400000},
"Europe/Vienna"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 347155200000},
"Jamaica" "America/Jamaica",
"Africa/Kigali" "Africa/Maputo",
"Etc/GMT-0" "Etc/GMT",
"Libya" "Africa/Tripoli",
"Pacific/Auckland"
{:offset 43200000, :rule "NZ", :format "NZ%sT", :from -757382400000},
"EET" {:offset 7200000, :rule "EU", :format "EE%sT", :from nil},
"Europe/Luxembourg"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"Europe/Bucharest"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 852076800000},
"Asia/Khandyga"
{:offset 32400000, :rule "-", :format "+09", :from 1412128800000},
"Asia/Kolkata"
{:offset 19800000, :rule "-", :format "IST", :from -765331200000},
"America/Louisville" "America/Kentucky/Louisville",
"America/Atka" "America/Adak",
"Etc/UTC" {:offset 0, :rule "-", :format "UTC", :from nil},
"Pacific/Gambier"
{:offset -32400000, :rule "-", :format "-09", :from -1806710400000},
"Asia/Dushanbe"
{:offset 18000000, :rule "-", :format "+05", :from 683690400000},
"Asia/Choibalsan"
{:offset 28800000,
:rule "Mongol",
:format "+08/+09",
:from 1204329600000},
"Asia/Phnom_Penh" "Asia/Bangkok",
"Pacific/Guadalcanal"
{:offset 39600000, :rule "-", :format "+11", :from -1806710400000},
"US/Arizona" "America/Phoenix",
"Pacific/Yap" "Pacific/Chuuk",
"Europe/Tirane"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 457488000000},
"Africa/Maseru" "Africa/Johannesburg",
"America/Cambridge_Bay"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 986094000000},
"America/Denver"
{:offset -25200000, :rule "US", :format "M%sT", :from -94694400000},
"America/Thule"
{:offset -14400000,
:rule "Thule",
:format "A%sT",
:from -1686096000000},
"America/St_Barthelemy" "America/Port_of_Spain",
"Etc/GMT+3" {:offset -10800000, :rule "-", :format "-03", :from nil},
"Asia/Srednekolymsk"
{:offset 39600000, :rule "-", :format "+11", :from 1412128800000},
"America/Recife"
{:offset -10800000, :rule "-", :format "-03", :from 1033430400000},
"Europe/Belgrade"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 404956800000},
"Europe/Kiev"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 788918400000},
"Europe/Zagreb" "Europe/Belgrade",
"Asia/Chungking" "Asia/Shanghai",
"Canada/Mountain" "America/Edmonton",
"Pacific/Samoa" "Pacific/Pago_Pago",
"Africa/Douala" "Africa/Lagos",
"America/Argentina/La_Rioja"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Europe/Kaliningrad"
{:offset 7200000, :rule "-", :format "EET", :from 1412128800000},
"Asia/Gaza"
{:offset 7200000,
:rule "Palestine",
:format "EE%sT",
:from 1325376000000},
"US/Alaska" "America/Anchorage",
"Asia/Yerevan"
{:offset 14400000,
:rule "Armenia",
:format "+04/+05",
:from 1293840000000},
"Europe/Warsaw"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 567993600000},
"Australia/Currie"
{:offset 36000000, :rule "AT", :format "AE%sT", :from 47174400000},
"Africa/Nouakchott" "Africa/Abidjan",
"Egypt" "Africa/Cairo",
"Africa/Brazzaville" "Africa/Lagos",
"Asia/Yekaterinburg"
{:offset 18000000, :rule "-", :format "+05", :from 1412128800000},
"America/Belize"
{:offset -21600000,
:rule "Belize",
:format "%s",
:from -1822521600000},
"Atlantic/Azores"
{:offset -3600000,
:rule "EU",
:format "-01/+00",
:from 730947600000},
"Etc/GMT-9" {:offset 32400000, :rule "-", :format "+09", :from nil},
"America/Argentina/San_Juan"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"US/Michigan" "America/Detroit",
"Asia/Kamchatka"
{:offset 43200000, :rule "-", :format "+12", :from 1298944800000},
"Asia/Qostanay"
{:offset 21600000, :rule "-", :format "+06", :from 1096596000000},
"America/Knox_IN" "America/Indiana/Knox",
"Australia/Adelaide"
{:offset 34200000, :rule "AS", :format "AC%sT", :from 31536000000},
"MST" {:offset -25200000, :rule "-", :format "MST", :from nil},
"ROK" "Asia/Seoul",
"America/Rankin_Inlet"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from 986094000000},
"Etc/UCT" "Etc/UTC",
"Pacific/Kwajalein"
{:offset 43200000, :rule "-", :format "+12", :from 744249600000},
"Asia/Yangon"
{:offset 23400000, :rule "-", :format "+0630", :from -778550400000},
"Mexico/BajaSur" "America/Mazatlan",
"Canada/Pacific" "America/Vancouver",
"America/Tortola" "America/Port_of_Spain",
"Japan" "Asia/Tokyo",
"Europe/Volgograd"
{:offset 14400000, :rule "-", :format "+04", :from 1538359200000},
"America/Inuvik"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 315532800000},
"UCT" "Etc/UTC",
"Asia/Pyongyang"
{:offset 32400000, :rule "-", :format "KST", :from 1525217400000},
"Canada/Central" "America/Winnipeg",
"Asia/Vientiane" "Asia/Bangkok",
"Africa/Lubumbashi" "Africa/Maputo",
"W-SU" "Europe/Moscow",
"America/Dawson"
{:offset -28800000,
:rule "Canada",
:format "P%sT",
:from 315532800000},
"Asia/Ulan_Bator" "Asia/Ulaanbaatar",
"Asia/Yakutsk"
{:offset 32400000, :rule "-", :format "+09", :from 1412128800000},
"Europe/San_Marino" "Europe/Rome",
"America/Porto_Acre" "America/Rio_Branco",
"Pacific/Rarotonga"
{:offset -36000000,
:rule "Cook",
:format "-10/-0930",
:from 278726400000},
"GB" "Europe/London",
"America/Curacao"
{:offset -14400000, :rule "-", :format "AST", :from -157766400000},
"America/La_Paz"
{:offset -14400000, :rule "-", :format "-04", :from -1194048000000},
"Europe/Astrakhan"
{:offset 14400000, :rule "-", :format "+04", :from 1456797600000},
"Europe/Prague"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 283996800000},
"America/Chihuahua"
{:offset -25200000,
:rule "Mexico",
:format "M%sT",
:from 891745200000},
"America/Los_Angeles"
{:offset -28800000, :rule "US", :format "P%sT", :from -94694400000},
"America/Lima"
{:offset -18000000,
:rule "Peru",
:format "-05/-04",
:from -1940889600000},
"America/Caracas"
{:offset -14400000, :rule "-", :format "-04", :from 1462069800000},
"Africa/Dakar" "Africa/Abidjan",
"Kwajalein" "Pacific/Kwajalein",
"Etc/GMT-14" {:offset 50400000, :rule "-", :format "+14", :from nil},
"America/Buenos_Aires" "America/Argentina/Buenos_Aires",
"America/Virgin" "America/Port_of_Spain",
"Asia/Nicosia"
{:offset 7200000,
:rule "EUAsia",
:format "EE%sT",
:from 904608000000},
"America/Indiana/Petersburg"
{:offset -18000000, :rule "US", :format "E%sT", :from 1193882400000},
"Etc/GMT-2" {:offset 7200000, :rule "-", :format "+02", :from nil},
"America/Tijuana"
{:offset -28800000, :rule "US", :format "P%sT", :from 1262304000000},
"Europe/Guernsey" "Europe/London",
"Africa/Conakry" "Africa/Abidjan",
"Europe/Dublin"
{:offset 3600000,
:rule "Eire",
:format "IST/GMT",
:from -39484800000},
"Europe/Helsinki"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 410227200000},
"Africa/Abidjan"
{:offset 0, :rule "-", :format "GMT", :from -1830384000000},
"America/Campo_Grande"
{:offset -14400000,
:rule "Brazil",
:format "-04/-03",
:from -1767225600000},
"America/Guatemala"
{:offset -21600000,
:rule "Guat",
:format "C%sT",
:from -1617062400000},
"Pacific/Tongatapu"
{:offset 46800000,
:rule "Tonga",
:format "+13/+14",
:from 915148800000},
"Africa/Monrovia"
{:offset 0, :rule "-", :format "GMT", :from 63072000000},
"Atlantic/Bermuda"
{:offset -14400000, :rule "US", :format "A%sT", :from 189302400000},
"Asia/Almaty"
{:offset 21600000, :rule "-", :format "+06", :from 1096596000000},
"Asia/Bishkek"
{:offset 21600000, :rule "-", :format "+06", :from 1122854400000},
"Indian/Mayotte" "Africa/Nairobi",
"America/Martinique"
{:offset -14400000, :rule "-", :format "AST", :from 336614400000},
"America/Shiprock" "America/Denver",
"America/Danmarkshavn"
{:offset 0, :rule "-", :format "GMT", :from 820454400000},
"Asia/Tel_Aviv" "Asia/Jerusalem",
"Europe/Athens"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 347155200000},
"Brazil/Acre" "America/Rio_Branco",
"Europe/Sarajevo" "Europe/Belgrade",
"EST" {:offset -18000000, :rule "-", :format "EST", :from nil},
"NZ" "Pacific/Auckland",
"America/Yellowknife"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 315532800000},
"Africa/Freetown" "Africa/Abidjan",
"Asia/Tbilisi"
{:offset 14400000, :rule "-", :format "+04", :from 1111888800000},
"Canada/Yukon" "America/Whitehorse",
"Pacific/Pago_Pago"
{:offset -39600000, :rule "-", :format "SST", :from -1861920000000},
"America/Argentina/Ushuaia"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"ROC" "Asia/Taipei",
"America/Metlakatla"
{:offset -32400000,
:rule "US",
:format "AK%sT",
:from 1546308000000},
"America/Boa_Vista"
{:offset -14400000, :rule "-", :format "-04", :from 970358400000},
"Pacific/Nauru"
{:offset 43200000, :rule "-", :format "+12", :from 286682400000},
"Asia/Brunei"
{:offset 28800000, :rule "-", :format "+08", :from -1167609600000},
"Pacific/Palau"
{:offset 32400000, :rule "-", :format "+09", :from -2177452800000},
"Asia/Dili"
{:offset 32400000, :rule "-", :format "+09", :from 967766400000},
"Etc/GMT+8" {:offset -28800000, :rule "-", :format "-08", :from nil},
"Etc/Zulu" "Etc/UTC",
"America/Port-au-Prince"
{:offset -18000000,
:rule "Haiti",
:format "E%sT",
:from -1672488000000},
"Pacific/Chatham"
{:offset 45900000,
:rule "Chatham",
:format "+1245/+1345",
:from -757382400000},
"America/Indiana/Indianapolis"
{:offset -18000000, :rule "US", :format "E%sT", :from 1136073600000},
"Atlantic/Reykjavik"
{:offset 0, :rule "-", :format "GMT", :from -55292400000},
"Iran" "Asia/Tehran",
"America/Kentucky/Louisville"
{:offset -18000000, :rule "US", :format "E%sT", :from 149824800000},
"Africa/Asmera" "Africa/Nairobi",
"Australia/Sydney"
{:offset 36000000, :rule "AN", :format "AE%sT", :from 31536000000},
"America/Indiana/Vincennes"
{:offset -18000000, :rule "US", :format "E%sT", :from 1193882400000},
"America/Bogota"
{:offset -18000000,
:rule "CO",
:format "-05/-04",
:from -1740960000000},
"US/Indiana-Starke" "America/Indiana/Knox",
"America/Phoenix"
{:offset -25200000, :rule "-", :format "MST", :from -57974400000},
"Africa/Djibouti" "Africa/Nairobi",
"Etc/GMT-3" {:offset 10800000, :rule "-", :format "+03", :from nil},
"Africa/Banjul" "Africa/Abidjan",
"Brazil/East" "America/Sao_Paulo",
"Asia/Atyrau"
{:offset 18000000, :rule "-", :format "+05", :from 1096596000000},
"America/Cayenne"
{:offset -10800000, :rule "-", :format "-03", :from -71107200000},
"America/Santa_Isabel" "America/Tijuana",
"America/Grand_Turk"
{:offset -18000000, :rule "US", :format "E%sT", :from 1519873200000},
"Europe/Vilnius"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 1041379200000},
"America/Hermosillo"
{:offset -25200000, :rule "-", :format "MST", :from 915148800000},
"America/Yakutat"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"Africa/Kampala" "Africa/Nairobi",
"Europe/Copenhagen"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Asia/Novosibirsk"
{:offset 25200000, :rule "-", :format "+07", :from 1467338400000},
"Europe/Monaco"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"Brazil/West" "America/Manaus",
"EST5EDT" {:offset -18000000, :rule "US", :format "E%sT", :from nil},
"America/Chicago"
{:offset -21600000, :rule "US", :format "C%sT", :from -94694400000},
"Etc/GMT-1" {:offset 3600000, :rule "-", :format "+01", :from nil},
"America/Godthab"
{:offset -10800000,
:rule "EU",
:format "-03/-02",
:from 323402400000},
"Canada/Atlantic" "America/Halifax",
"Asia/Singapore"
{:offset 28800000, :rule "-", :format "+08", :from 378691200000},
"Etc/GMT-8" {:offset 28800000, :rule "-", :format "+08", :from nil},
"America/Lower_Princes" "America/Curacao",
"Africa/Accra"
{:offset 0,
:rule "Ghana",
:format "GMT/+0020",
:from -1640995200000},
"America/Asuncion"
{:offset -14400000,
:rule "Para",
:format "-04/-03",
:from 134006400000},
"America/Thunder_Bay"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 126230400000},
"America/Bahia"
{:offset -10800000, :rule "-", :format "-03", :from 1349049600000},
"Pacific/Majuro"
{:offset 43200000, :rule "-", :format "+12", :from -7948800000},
"Etc/GMT+9" {:offset -32400000, :rule "-", :format "-09", :from nil},
"Asia/Tomsk"
{:offset 25200000, :rule "-", :format "+07", :from 1462068000000},
"Africa/Mbabane" "Africa/Johannesburg",
"Pacific/Fakaofo"
{:offset 46800000, :rule "-", :format "+13", :from 1322697600000},
"Africa/Addis_Ababa" "Africa/Nairobi",
"America/Nassau"
{:offset -18000000, :rule "US", :format "E%sT", :from 189302400000},
"Asia/Makassar"
{:offset 28800000, :rule "-", :format "WITA", :from -767923200000},
"Europe/Nicosia" "Asia/Nicosia",
"Australia/West" "Australia/Perth",
"America/Whitehorse"
{:offset -28800000,
:rule "Canada",
:format "P%sT",
:from 315532800000},
"Asia/Urumqi"
{:offset 21600000, :rule "-", :format "+06", :from -1325462400000},
"Asia/Famagusta"
{:offset 7200000,
:rule "EUAsia",
:format "EE%sT",
:from 1506819600000},
"US/Samoa" "Pacific/Pago_Pago",
"Asia/Samarkand"
{:offset 18000000, :rule "-", :format "+05", :from 694224000000},
"Asia/Calcutta" "Asia/Kolkata",
"Pacific/Niue"
{:offset -39600000, :rule "-", :format "-11", :from 276048000000},
"Australia/Perth"
{:offset 28800000, :rule "AW", :format "AW%sT", :from -836438400000},
"Africa/Bissau"
{:offset 0, :rule "-", :format "GMT", :from 157766400000},
"Asia/Thimphu"
{:offset 21600000, :rule "-", :format "+06", :from 560044800000},
"America/Antigua" "America/Port_of_Spain",
"Africa/Khartoum"
{:offset 7200000, :rule "-", :format "CAT", :from 1509494400000},
"America/Guyana"
{:offset -14400000, :rule "-", :format "-04", :from 662688000000},
"America/Puerto_Rico"
{:offset -14400000, :rule "-", :format "AST", :from -757382400000},
"Pacific/Apia"
{:offset 46800000,
:rule "WS",
:format "+13/+14",
:from 1322784000000},
"America/Indiana/Winamac"
{:offset -18000000, :rule "US", :format "E%sT", :from 1172714400000},
"US/East-Indiana" "America/Indiana/Indianapolis",
"Pacific/Galapagos"
{:offset -21600000,
:rule "Ecuador",
:format "-06/-05",
:from 504921600000},
"Europe/Skopje" "Europe/Belgrade",
"GB-Eire" "Europe/London",
"Europe/Istanbul"
{:offset 10800000, :rule "-", :format "+03", :from 1472688000000},
"Chile/Continental" "America/Santiago",
"Asia/Jerusalem"
{:offset 7200000,
:rule "Zion",
:format "I%sT",
:from -1640995200000},
"Asia/Magadan"
{:offset 39600000, :rule "-", :format "+11", :from 1459476000000},
"UTC" "Etc/UTC",
"America/North_Dakota/Beulah"
{:offset -21600000, :rule "US", :format "C%sT", :from 1288576800000},
"America/Guadeloupe" "America/Port_of_Spain",
"America/St_Lucia" "America/Port_of_Spain",
"America/Mexico_City"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 1012521600000},
"Africa/Johannesburg"
{:offset 7200000, :rule "SA", :format "SAST", :from -2109283200000},
"Africa/Bamako" "Africa/Abidjan",
"Etc/GMT+0" "Etc/GMT",
"America/Toronto"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 126230400000},
"Etc/GMT-7" {:offset 25200000, :rule "-", :format "+07", :from nil},
"America/Managua"
{:offset -21600000, :rule "Nic", :format "C%sT", :from 852076800000},
"America/Belem"
{:offset -10800000, :rule "-", :format "-03", :from 589075200000},
"Europe/Lisbon"
{:offset 0, :rule "EU", :format "WE%sT", :from 825642000000},
"Asia/Kashgar" "Asia/Urumqi",
"America/Juneau"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"America/Fort_Wayne" "America/Indiana/Indianapolis",
"US/Mountain" "America/Denver",
"Etc/GMT+6" {:offset -21600000, :rule "-", :format "-06", :from nil},
"Europe/Minsk"
{:offset 10800000, :rule "-", :format "+03", :from 1298944800000},
"America/Indiana/Tell_City"
{:offset -21600000, :rule "US", :format "C%sT", :from 1143856800000},
"Australia/North" "Australia/Darwin",
"Europe/Moscow"
{:offset 10800000, :rule "-", :format "MSK", :from 1412128800000},
"Pacific/Kosrae"
{:offset 39600000, :rule "-", :format "+11", :from 915148800000},
"Europe/Ulyanovsk"
{:offset 14400000, :rule "-", :format "+04", :from 1456797600000},
"Africa/Lagos"
{:offset 3600000, :rule "-", :format "WAT", :from -1588464000000},
"Asia/Harbin" "Asia/Shanghai",
"Iceland" "Atlantic/Reykjavik",
"Mexico/General" "America/Mexico_City",
"America/Guayaquil"
{:offset -18000000,
:rule "Ecuador",
:format "-05/-04",
:from -1230768000000},
"America/Argentina/Cordoba"
{:offset -10800000,
:rule "Arg",
:format "-03/-02",
:from 951868800000},
"Africa/Windhoek"
{:offset 7200000, :rule "Namibia", :format "%s", :from 636249600000},
"Europe/Rome"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 315532800000},
"Asia/Krasnoyarsk"
{:offset 25200000, :rule "-", :format "+07", :from 1412128800000},
"America/Glace_Bay"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 126230400000},
"Asia/Karachi"
{:offset 18000000,
:rule "Pakistan",
:format "PK%sT",
:from 36633600000},
"Europe/Busingen" "Europe/Zurich",
"Asia/Aden" "Asia/Riyadh",
"America/Mazatlan"
{:offset -25200000, :rule "Mexico", :format "M%sT", :from 0},
"America/Winnipeg"
{:offset -21600000,
:rule "Canada",
:format "C%sT",
:from 1136073600000},
"Europe/Chisinau"
{:offset 7200000,
:rule "Moldova",
:format "EE%sT",
:from 852076800000},
"America/Argentina/Buenos_Aires"
{:offset -10800000,
:rule "Arg",
:format "-03/-02",
:from 951868800000},
"Europe/Riga"
{:offset 7200000, :rule "EU", :format "EE%sT", :from 978307200000},
"Pacific/Pitcairn"
{:offset -28800000, :rule "-", :format "-08", :from 891388800000},
"Turkey" "Europe/Istanbul",
"Pacific/Guam"
{:offset 36000000, :rule "-", :format "ChST", :from 975628800000},
"Indian/Reunion"
{:offset 14400000, :rule "-", :format "+04", :from -1848873600000},
"Pacific/Bougainville"
{:offset 39600000, :rule "-", :format "+11", :from 1417399200000},
"Africa/Malabo" "Africa/Lagos",
"America/New_York"
{:offset -18000000, :rule "US", :format "E%sT", :from -94694400000},
"America/Coral_Harbour" "America/Atikokan",
"Africa/Tripoli"
{:offset 7200000, :rule "-", :format "EET", :from 1380592800000},
"Asia/Bangkok"
{:offset 25200000, :rule "-", :format "+07", :from -1570060800000},
"America/Atikokan"
{:offset -18000000, :rule "-", :format "EST", :from -767916000000},
"America/Detroit"
{:offset -18000000, :rule "US", :format "E%sT", :from 165549600000},
"Poland" "Europe/Warsaw",
"Etc/GMT+11"
{:offset -39600000, :rule "-", :format "-11", :from nil},
"Asia/Ashgabat"
{:offset 18000000, :rule "-", :format "+05", :from 694231200000},
"America/Edmonton"
{:offset -25200000,
:rule "Canada",
:format "M%sT",
:from 536457600000},
"Europe/Podgorica" "Europe/Belgrade",
"Europe/Saratov"
{:offset 14400000, :rule "-", :format "+04", :from 1480557600000},
"Greenwich" "Etc/GMT",
"Australia/ACT" "Australia/Sydney",
"Asia/Damascus"
{:offset 7200000,
:rule "Syria",
:format "EE%sT",
:from -1577923200000},
"Africa/Bujumbura" "Africa/Maputo",
"Australia/Lord_Howe"
{:offset 37800000,
:rule "LH",
:format "+1030/+11",
:from 489024000000},
"Singapore" "Asia/Singapore",
"Africa/Bangui" "Africa/Lagos",
"America/Kentucky/Monticello"
{:offset -18000000, :rule "US", :format "E%sT", :from 970365600000},
"Europe/Mariehamn" "Europe/Helsinki",
"Australia/Eucla"
{:offset 31500000,
:rule "AW",
:format "+0845/+0945",
:from -836438400000},
"Canada/Newfoundland" "America/St_Johns",
"America/North_Dakota/New_Salem"
{:offset -21600000, :rule "US", :format "C%sT", :from 1064973600000},
"Africa/Juba"
{:offset 10800000, :rule "-", :format "EAT", :from 946728000000},
"Africa/Gaborone" "Africa/Maputo",
"Etc/GMT-5" {:offset 18000000, :rule "-", :format "+05", :from nil},
"Canada/Saskatchewan" "America/Regina",
"Europe/Ljubljana" "Europe/Belgrade",
"Australia/Lindeman"
{:offset 36000000,
:rule "Holiday",
:format "AE%sT",
:from 709948800000},
"Africa/Mogadishu" "Africa/Nairobi",
"America/St_Thomas" "America/Port_of_Spain",
"America/Havana"
{:offset -18000000,
:rule "Cuba",
:format "C%sT",
:from -1404388800000},
"Asia/Ulaanbaatar"
{:offset 28800000,
:rule "Mongol",
:format "+08/+09",
:from 252460800000},
"Europe/Vaduz" "Europe/Zurich",
"America/Anchorage"
{:offset -32400000, :rule "US", :format "AK%sT", :from 436492800000},
"America/Iqaluit"
{:offset -18000000,
:rule "Canada",
:format "E%sT",
:from 970365600000},
"Asia/Riyadh"
{:offset 10800000, :rule "-", :format "+03", :from -719625600000},
"America/Vancouver"
{:offset -28800000,
:rule "Canada",
:format "P%sT",
:from 536457600000},
"US/Pacific" "America/Los_Angeles",
"America/Grenada" "America/Port_of_Spain",
"America/Rio_Branco"
{:offset -18000000, :rule "-", :format "-05", :from 1383264000000},
"Europe/Bratislava" "Europe/Prague",
"Pacific/Fiji"
{:offset 43200000,
:rule "Fiji",
:format "+12/+13",
:from -1709942400000},
"Asia/Omsk"
{:offset 21600000, :rule "-", :format "+06", :from 1412128800000},
"America/Catamarca" "America/Argentina/Catamarca",
"Pacific/Funafuti"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"America/Merida"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 407548800000},
"Asia/Istanbul" "Europe/Istanbul",
"America/Cayman" "America/Panama",
"Etc/GMT+7" {:offset -25200000, :rule "-", :format "-07", :from nil},
"Etc/GMT-6" {:offset 21600000, :rule "-", :format "+06", :from nil},
"Zulu" "Etc/UTC",
"Pacific/Noumea"
{:offset 39600000,
:rule "NC",
:format "+11/+12",
:from -1829347200000},
"Indian/Mahe"
{:offset 14400000, :rule "-", :format "+04", :from -2006640000000},
"Asia/Irkutsk"
{:offset 28800000, :rule "-", :format "+08", :from 1412128800000},
"Antarctica/Palmer"
{:offset -10800000, :rule "-", :format "-03", :from 1480550400000},
"America/Bahia_Banderas"
{:offset -21600000,
:rule "Mexico",
:format "C%sT",
:from 1270087200000},
"Europe/Budapest"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 336621600000},
"America/Regina"
{:offset -21600000, :rule "-", :format "CST", :from -305762400000},
"America/Halifax"
{:offset -14400000,
:rule "Canada",
:format "A%sT",
:from 126230400000},
"Asia/Anadyr"
{:offset 43200000, :rule "-", :format "+12", :from 1298944800000},
"America/Cuiaba"
{:offset -14400000,
:rule "Brazil",
:format "-04/-03",
:from 1096588800000},
"Australia/NSW" "Australia/Sydney",
"Africa/Porto-Novo" "Africa/Lagos",
"America/Argentina/Catamarca"
{:offset -10800000, :rule "-", :format "-03", :from 1222819200000},
"Indian/Mauritius"
{:offset 14400000,
:rule "Mauritius",
:format "+04/+05",
:from -1988150400000},
"Europe/Samara"
{:offset 14400000, :rule "-", :format "+04", :from 1298944800000},
"America/Eirunepe"
{:offset -18000000, :rule "-", :format "-05", :from 1383264000000},
"America/Fort_Nelson"
{:offset -25200000, :rule "-", :format "MST", :from 1425175200000},
"Atlantic/Faeroe" "Atlantic/Faroe",
"Africa/Asmara" "Africa/Nairobi",
"Asia/Tashkent"
{:offset 18000000, :rule "-", :format "+05", :from 694224000000},
"Etc/GMT-11" {:offset 39600000, :rule "-", :format "+11", :from nil},
"Africa/Maputo"
{:offset 7200000, :rule "-", :format "CAT", :from -2109283200000},
"Pacific/Kiritimati"
{:offset 50400000, :rule "-", :format "+14", :from 786240000000},
"PRC" "Asia/Shanghai",
"America/Argentina/ComodRivadavia" "America/Argentina/Catamarca",
"Asia/Qyzylorda"
{:offset 18000000, :rule "-", :format "+05", :from 1543622400000},
"Pacific/Midway" "Pacific/Pago_Pago",
"America/Kralendijk" "America/Curacao",
"Asia/Kabul"
{:offset 16200000, :rule "-", :format "+0430", :from -788918400000},
"America/Port_of_Spain"
{:offset -14400000, :rule "-", :format "AST", :from -1825113600000},
"Europe/Zurich"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 347155200000},
"America/Indianapolis" "America/Indiana/Indianapolis",
"NZ-CHAT" "Pacific/Chatham",
"Atlantic/Jan_Mayen" "Europe/Oslo",
"Asia/Kathmandu"
{:offset 20700000, :rule "-", :format "+0545", :from 504921600000},
"Africa/Algiers"
{:offset 3600000, :rule "-", :format "CET", :from 357523200000},
"America/Matamoros"
{:offset -21600000, :rule "US", :format "C%sT", :from 1262304000000},
"America/Araguaina"
{:offset -10800000, :rule "-", :format "-03", :from 1377993600000},
"America/Rosario" "America/Argentina/Cordoba",
"Etc/Greenwich" "Etc/GMT",
"America/Argentina/Tucuman"
{:offset -10800000,
:rule "Arg",
:format "-03/-02",
:from 1086048000000},
"Antarctica/South_Pole" "Pacific/Auckland",
"America/Marigot" "America/Port_of_Spain",
"Pacific/Marquesas"
{:offset -34200000,
:rule "-",
:format "-0930",
:from -1806710400000},
"Pacific/Truk" "Pacific/Chuuk",
"Asia/Baghdad"
{:offset 10800000,
:rule "Iraq",
:format "+03/+04",
:from 389059200000},
"America/Dawson_Creek"
{:offset -25200000, :rule "-", :format "MST", :from 81482400000},
"Europe/Kirov"
{:offset 10800000, :rule "-", :format "+03", :from 1412128800000},
"America/Santo_Domingo"
{:offset -14400000, :rule "-", :format "AST", :from 975632400000},
"US/Central" "America/Chicago",
"America/Miquelon"
{:offset -10800000,
:rule "Canada",
:format "-03/-02",
:from 536457600000},
"Pacific/Wake"
{:offset 43200000, :rule "-", :format "+12", :from -2177452800000},
"Asia/Ust-Nera"
{:offset 36000000, :rule "-", :format "+10", :from 1412128800000},
"Australia/Canberra" "Australia/Sydney",
"Indian/Antananarivo" "Africa/Nairobi",
"Brazil/DeNoronha" "America/Noronha",
"Europe/Malta"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 347155200000},
"Europe/Paris"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 220924800000},
"Africa/Luanda" "Africa/Lagos",
"Europe/Madrid"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 283996800000},
"Asia/Chongqing" "Asia/Shanghai",
"Europe/Gibraltar"
{:offset 3600000, :rule "EU", :format "CE%sT", :from 378691200000},
"America/Cancun"
{:offset -18000000, :rule "-", :format "EST", :from 1422756000000},
"Asia/Dacca" "Asia/Dhaka",
"Israel" "Asia/Jerusalem",
"Pacific/Port_Moresby"
{:offset 36000000, :rule "-", :format "+10", :from -2366755200000},
"Atlantic/Cape_Verde"
{:offset -3600000, :rule "-", :format "-01", :from 184039200000},
"Australia/Darwin"
{:offset 34200000,
:rule "Aus",
:format "AC%sT",
:from -2230156800000},
"Africa/Nairobi"
{:offset 10800000, :rule "-", :format "EAT", :from -315619200000},
"WET" {:offset 0, :rule "EU", :format "WE%sT", :from nil},
"Atlantic/Canary"
{:offset 0, :rule "EU", :format "WE%sT", :from 336618000000},
"Africa/Libreville" "Africa/Lagos",
"America/Paramaribo"
{:offset -10800000, :rule "-", :format "-03", :from 465436800000},
"Asia/Ho_Chi_Minh"
{:offset 25200000, :rule "-", :format "+07", :from 170812800000},
"Europe/Vatican" "Europe/Rome",
"Africa/Ndjamena"
{:offset 3600000, :rule "-", :format "WAT", :from 320716800000},
"Australia/Melbourne"
{:offset 36000000, :rule "AV", :format "AE%sT", :from 31536000000},
"America/Manaus"
{:offset -14400000, :rule "-", :format "-04", :from 778377600000},
"Etc/GMT-13" {:offset 46800000, :rule "-", :format "+13", :from nil},
"America/Adak"
{:offset -36000000, :rule "US", :format "H%sT", :from 436492800000},
"Asia/Taipei"
{:offset 28800000,
:rule "Taiwan",
:format "C%sT",
:from -767919600000},
"Asia/Dhaka"
{:offset 21600000,
:rule "Dhaka",
:format "+06/+07",
:from 1230768000000}},
:rules
{"CR" nil,
"Pakistan" nil,
"Nic" nil,
"Perry" nil,
"Tunisia" nil,
"Uruguay" nil,
"Denver" nil,
"Hungary" nil,
"Cuba"
{:standard
{:from 1351987200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 0, :minute 0, :time-suffix "s"},
:month 11,
:save 0},
:daylight-savings
{:from 1362873600000,
:clock? :standard,
:floating-day "Sun>=8",
:time {:hour 0, :minute 0, :time-suffix "s"},
:month 3,
:save 3600000}},
"E-Eur"
{:daylight-savings
{:from 354672000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 846374400000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Haiti"
{:daylight-savings
{:from 1489284000000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1509847200000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Chicago" nil,
"Shang" nil,
"NT_YK" nil,
"Bulg" nil,
"Salv" nil,
"Moldova"
{:daylight-savings
{:from 859687200000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 877834800000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 3, :minute 0},
:month 10,
:save 0}},
"Winn" nil,
"Chile"
{:standard
{:from 1554606000000,
:clock? :utc,
:floating-day "Sun>=2",
:time {:hour 3, :minute 0, :time-suffix "u"},
:month 4,
:save 0},
:daylight-savings
{:from 1567915200000,
:clock? :utc,
:floating-day "Sun>=2",
:time {:hour 4, :minute 0, :time-suffix "u"},
:month 9,
:save 3600000}},
"SA" nil,
"Aus" nil,
"Brazil" nil,
"EUAsia"
{:daylight-savings
{:from 354675600000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 3,
:save 3600000},
:standard
{:from 846378000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 10,
:save 0}},
"Hond" nil,
"SpainAfrica" nil,
"Sudan" nil,
"Guam" nil,
"EU"
{:daylight-savings
{:from 354675600000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 3,
:save 3600000},
:standard
{:from 846378000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 10,
:save 0}},
"Pulaski" nil,
"Arg" nil,
"Palestine"
{:standard
{:from 1477702800000,
:clock? :utc,
:floating-day "lastSat",
:time {:hour 1, :minute 0},
:month 10,
:save 0},
:daylight-savings
{:from 1553817600000,
:clock? :utc,
:floating-day "lastFri",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000}},
"Eire"
{:standard
{:from 354675600000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 3,
:save 0},
:daylight-savings
{:from 846378000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "u"},
:month 10,
:save -3600000}},
"Iraq" nil,
"Canada"
{:daylight-savings
{:from 1173578400000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1194141600000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Belgium" nil,
"Louisville" nil,
"Mexico"
{:daylight-savings
{:from 1018144800000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 4,
:save 3600000},
:standard
{:from 1035684000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 2, :minute 0},
:month 10,
:save 0}},
"Libya" nil,
"W-Eur"
{:daylight-savings
{:from 354675600000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "s"},
:month 3,
:save 3600000},
:standard
{:from 846378000000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 1, :minute 0, :time-suffix "s"},
:month 10,
:save 0}},
"Moncton" nil,
"Detroit" nil,
"Romania" nil,
"SanLuis" nil,
"AT"
{:daylight-savings
{:from 1002420000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000},
:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0}},
"Malta" nil,
"Fiji"
{:standard
{:from 1421550000000,
:clock? :utc,
:floating-day "Sun>=12",
:time {:hour 3, :minute 0},
:month 1,
:save 0},
:daylight-savings
{:from 1573351200000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 11,
:save 3600000}},
"StJohns" nil,
"Egypt" nil,
"ROK" nil,
"Syria"
{:daylight-savings
{:from 1333065600000,
:clock? :utc,
:floating-day "lastFri",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1256860800000,
:clock? :utc,
:floating-day "lastFri",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Regina" nil,
"Japan" nil,
"AN"
{:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000}},
"Ecuador" nil,
"Zion"
{:daylight-savings
{:from 1364522400000,
:clock? :utc,
:floating-day "Fri>=23",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1382839200000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 2, :minute 0},
:month 10,
:save 0}},
"Ghana" nil,
"Latvia" nil,
"Vincennes" nil,
"Namibia" nil,
"Tonga" nil,
"Marengo" nil,
"Greece" nil,
"Toronto" nil,
"Swift" nil,
"Vanc" nil,
"Russia" nil,
"Italy" nil,
"Belize" nil,
"France" nil,
"NZ"
{:daylight-savings
{:from 1191117600000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 9,
:save 3600000},
:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0}},
"AW" nil,
"Iran"
{:daylight-savings
{:from 3729024000000,
:clock? :utc,
:day 20,
:time {:hour 24, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 3744921600000,
:clock? :utc,
:day 20,
:time {:hour 24, :minute 0},
:month 9,
:save 0}},
"Port" nil,
"Armenia" nil,
"WS"
{:standard
{:from 1333252800000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 4, :minute 0},
:month 4,
:save 0},
:daylight-savings
{:from 1348974000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 3, :minute 0},
:month 9,
:save 1}},
"Norway" nil,
"Algeria" nil,
"Czech" nil,
"Lux" nil,
"Taiwan" nil,
"Albania" nil,
"Chatham"
{:daylight-savings
{:from 1191120300000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 45, :time-suffix "s"},
:month 9,
:save 3600000},
:standard
{:from 1207449900000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 45, :time-suffix "s"},
:month 4,
:save 0}},
"CA" nil,
"Cyprus" nil,
"AV"
{:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000}},
"Dhaka" nil,
"Pike" nil,
"Finland" nil,
"Para"
{:daylight-savings
{:from 1286064000000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 0, :minute 0},
:month 10,
:save 3600000},
:standard
{:from 1364083200000,
:clock? :utc,
:floating-day "Sun>=22",
:time {:hour 0, :minute 0},
:month 3,
:save 0}},
"GB-Eire" nil,
"Kyrgyz" nil,
"Denmark" nil,
"AS"
{:standard
{:from 1207447200000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :standard,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 3600000}},
"Peru" nil,
"RussiaAsia" nil,
"Neth" nil,
"Iceland" nil,
"NBorneo" nil,
"Falk" nil,
"Spain" nil,
"Germany" nil,
"Azer" nil,
"Turkey" nil,
"Starke" nil,
"AQ" nil,
"Poland" nil,
"NYC" nil,
"E-EurAsia"
{:daylight-savings
{:from 354672000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 846374400000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Bahamas" nil,
"Phil" nil,
"US"
{:daylight-savings
{:from 1173578400000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1194141600000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Mauritius" nil,
"EgyptAsia" nil,
"NC" nil,
"Macau" nil,
"Morocco" nil,
"Indianapolis" nil,
"LH"
{:standard
{:from 1207447200000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 4,
:save 0},
:daylight-savings
{:from 1223172000000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 10,
:save 1800000}},
"Austria" nil,
"C-Eur"
{:daylight-savings
{:from 354679200000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 3,
:save 3600000},
:standard
{:from 846381600000,
:clock? :standard,
:floating-day "lastSun",
:time {:hour 2, :minute 0, :time-suffix "s"},
:month 10,
:save 0}},
"Holiday" nil,
"Barb" nil,
"Jordan"
{:daylight-savings
{:from 1395964800000,
:clock? :utc,
:floating-day "lastThu",
:time {:hour 24, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1414713600000,
:clock? :standard,
:floating-day "lastFri",
:time {:hour 0, :minute 0, :time-suffix "s"},
:month 10,
:save 0}},
"PRC" nil,
"HK" nil,
"Menominee" nil,
"Guat" nil,
"CO" nil,
"Lebanon"
{:daylight-savings
{:from 733276800000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 941328000000,
:clock? :utc,
:floating-day "lastSun",
:time {:hour 0, :minute 0},
:month 10,
:save 0}},
"Swiss" nil,
"Halifax" nil,
"Cook" nil,
"Mongol" nil,
"SovietZone" nil,
"Thule"
{:daylight-savings
{:from 1173578400000,
:clock? :utc,
:floating-day "Sun>=8",
:time {:hour 2, :minute 0},
:month 3,
:save 3600000},
:standard
{:from 1194141600000,
:clock? :utc,
:floating-day "Sun>=1",
:time {:hour 2, :minute 0},
:month 11,
:save 0}},
"Vanuatu" nil,
"DR" nil,
"Edm" nil}}
))
|
9c7877d58b5d374e66e5efdc4ac5d73da2e9b574363e1bafc4f75a411c03d202 | tek/polysemy-log | DataLogTest.hs | module Polysemy.Log.Test.DataLogTest where
import Polysemy.Test (UnitTest, assertEq, runTestAuto)
import Polysemy.Log.Atomic (interpretDataLogAtomic)
import qualified Polysemy.Log.Effect.DataLog as DataLog
import Polysemy.Log.Effect.DataLog (DataLog)
data CustomLog =
User Text
|
Fatal Int
deriving stock (Eq, Show)
prog ::
Members [DataLog CustomLog, AtomicState [CustomLog]] r =>
Sem r [CustomLog]
prog = do
DataLog.dataLog (User "user")
DataLog.dataLog (Fatal 5)
atomicGet
target :: [CustomLog]
target =
[Fatal 5, User "user"]
test_dataLog :: UnitTest
test_dataLog =
runTestAuto do
assertEq @_ @IO target =<< interpretDataLogAtomic @CustomLog prog
| null | https://raw.githubusercontent.com/tek/polysemy-log/385efb9043de0fef84943982723cbf32ed6caee4/packages/polysemy-log/test/Polysemy/Log/Test/DataLogTest.hs | haskell | module Polysemy.Log.Test.DataLogTest where
import Polysemy.Test (UnitTest, assertEq, runTestAuto)
import Polysemy.Log.Atomic (interpretDataLogAtomic)
import qualified Polysemy.Log.Effect.DataLog as DataLog
import Polysemy.Log.Effect.DataLog (DataLog)
data CustomLog =
User Text
|
Fatal Int
deriving stock (Eq, Show)
prog ::
Members [DataLog CustomLog, AtomicState [CustomLog]] r =>
Sem r [CustomLog]
prog = do
DataLog.dataLog (User "user")
DataLog.dataLog (Fatal 5)
atomicGet
target :: [CustomLog]
target =
[Fatal 5, User "user"]
test_dataLog :: UnitTest
test_dataLog =
runTestAuto do
assertEq @_ @IO target =<< interpretDataLogAtomic @CustomLog prog
|
|
4dead9482716a78e39ba4e96d10b87faf722a233c75c8a514e6fcbad9d7bb878 | Bogdanp/racket-redis | hash.rkt | #lang racket/base
(require rackunit
redis
"common.rkt")
(provide
hash-tests)
(define hash-tests
(test-suite
"hash"
(test-commands "HMSET"
(check-exn
exn:fail:contract?
(lambda _
(redis-hash-set! test-client "a" "a" "1" "b")))
(redis-hash-set! test-client "a" "a" "1" "b" "2")
(check-equal? (redis-hash-get test-client "a")
(hash #"a" #"1"
#"b" #"2")))))
(module+ test
(require rackunit/text-ui)
(run-tests hash-tests))
| null | https://raw.githubusercontent.com/Bogdanp/racket-redis/0f6c1a723f25f40dd9c6f682dee30fa8a9288f86/redis-test/redis/hash.rkt | racket | #lang racket/base
(require rackunit
redis
"common.rkt")
(provide
hash-tests)
(define hash-tests
(test-suite
"hash"
(test-commands "HMSET"
(check-exn
exn:fail:contract?
(lambda _
(redis-hash-set! test-client "a" "a" "1" "b")))
(redis-hash-set! test-client "a" "a" "1" "b" "2")
(check-equal? (redis-hash-get test-client "a")
(hash #"a" #"1"
#"b" #"2")))))
(module+ test
(require rackunit/text-ui)
(run-tests hash-tests))
|
|
e9ceadc340017c0fcec9e8d5fa298347f668f310a3fcc4025cdc43c53e92e888 | freizl/dive-into-haskell | Main.hs | module Main where
import Data.Char
main :: IO ()
main = putStrLn "Hello, Haskell!"
isSubseqOf :: (Eq a) => [a] -> [a] -> Bool
isSubseqOf [] [] = True
isSubseqOf [] _ = True
isSubseqOf _ [] = False
isSubseqOf target@(x:xs) source@(y:ys)
| x == y = isSubseqOf xs ys
| otherwise = isSubseqOf target ys
capitalizeWords :: String -> [(String, String)]
capitalizeWords xs = map (\w -> (w, capWord w)) (words xs)
capWord :: String -> String
capWord [] = []
capWord (x:xs) = toUpper x : xs
capitalizeParagraph :: String -> String
capitalizeParagraph [] = []
capitalizeParagraph xs =
let (x1, x2) = break (== '.') xs
next = if length xs > 0 then (take 1 x2 ++ capitalizeParagraph (drop 1 x2)) else []
in
takeWhile isSpace x1 ++ capWord (dropWhile isSpace x1) ++ next
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/readings/haskell-book/11/Main.hs | haskell | module Main where
import Data.Char
main :: IO ()
main = putStrLn "Hello, Haskell!"
isSubseqOf :: (Eq a) => [a] -> [a] -> Bool
isSubseqOf [] [] = True
isSubseqOf [] _ = True
isSubseqOf _ [] = False
isSubseqOf target@(x:xs) source@(y:ys)
| x == y = isSubseqOf xs ys
| otherwise = isSubseqOf target ys
capitalizeWords :: String -> [(String, String)]
capitalizeWords xs = map (\w -> (w, capWord w)) (words xs)
capWord :: String -> String
capWord [] = []
capWord (x:xs) = toUpper x : xs
capitalizeParagraph :: String -> String
capitalizeParagraph [] = []
capitalizeParagraph xs =
let (x1, x2) = break (== '.') xs
next = if length xs > 0 then (take 1 x2 ++ capitalizeParagraph (drop 1 x2)) else []
in
takeWhile isSpace x1 ++ capWord (dropWhile isSpace x1) ++ next
|
|
9d008af2e6f840296e832bdd18aaaa9913f600e02b264a6a473e67985b027eef | xenserver/gpumon | mock.ml | exception Library_not_loaded of string
exception Symbol_not_loaded of string
type interface = unit
type device = unit
type enable_state = Disabled | Enabled
type memory_info = {total: int64; free: int64; used: int64}
type pci_info = {
bus_id: string
; domain: int32
; bus: int32
; device: int32
; pci_device_id: int32
; pci_subsystem_id: int32
}
type utilization = {gpu: int; memory: int}
let memory_info = {total= 0L; free= 0L; used= 0L}
let pci_info =
{
bus_id= ""
; domain= 0l
; bus= 0l
; device= 0l
; pci_device_id= 0l
; pci_subsystem_id= 0l
}
let utilization = {gpu= 0; memory= 0}
type pgpu_metadata = string
type vgpu_metadata = string
type vgpu_instance = int
type vm_domid = string
type vgpu_compatibility_t = unit
type vm_compat = None | Cold | Hybernate | Sleep | Live
type pgpu_compat_limit = None | HostDriver | GuestDriver | GPU | Other
let library_open () = ()
let library_close () = ()
let init () = ()
let shutdown () = ()
let device_get_count _interface = 0
let device_get_handle_by_index _interface _int = ()
let device_get_handle_by_pci_bus_id _interface _string = ()
let device_get_memory_info _interface _device = memory_info
let device_get_pci_info _interface _device = pci_info
let device_get_temperature _interface _device = 0
let device_get_power_usage _interface _device = 0
let device_get_utilization_rates _interface _device = utilization
let device_set_persistence_mode _interface _device _enable_state = ()
let device_get_pgpu_metadata _interface _device = ""
let pgpu_metadata_get_pgpu_version _pgpu_metadata = 0
let pgpu_metadata_get_pgpu_revision _pgpu_metadata = 0
let pgpu_metadata_get_pgpu_host_driver_version _pgpu_metadata = ""
let device_get_active_vgpus _interface _device = []
let vgpu_instance_get_vm_domid _interface _vgpu_instance = ""
let vgpu_instance_get_vgpu_uuid _interface _vgpu_instance = ""
let get_vgpu_metadata _interface _vgpu_instance = ""
let get_pgpu_vgpu_compatibility _interface _vgpu_metadata _pgpu_metadata = ()
let vgpu_compat_get_vm_compat _vgpu_compatibility_t = []
let vgpu_compat_get_pgpu_compat_limit _vgpu_compatibility_t = []
let get_vgpus_for_vm _iface _device _vm_domid = []
let get_vgpu_for_uuid _iface _vgpu_uuid _vgpus = []
module NVML = struct
let attach () = ()
let detach () = ()
let is_attached () = true
let get () : interface option = None
end
| null | https://raw.githubusercontent.com/xenserver/gpumon/dae894f3cd810f07f2b103635e0e6465bd739468/mocks/mock.ml | ocaml | exception Library_not_loaded of string
exception Symbol_not_loaded of string
type interface = unit
type device = unit
type enable_state = Disabled | Enabled
type memory_info = {total: int64; free: int64; used: int64}
type pci_info = {
bus_id: string
; domain: int32
; bus: int32
; device: int32
; pci_device_id: int32
; pci_subsystem_id: int32
}
type utilization = {gpu: int; memory: int}
let memory_info = {total= 0L; free= 0L; used= 0L}
let pci_info =
{
bus_id= ""
; domain= 0l
; bus= 0l
; device= 0l
; pci_device_id= 0l
; pci_subsystem_id= 0l
}
let utilization = {gpu= 0; memory= 0}
type pgpu_metadata = string
type vgpu_metadata = string
type vgpu_instance = int
type vm_domid = string
type vgpu_compatibility_t = unit
type vm_compat = None | Cold | Hybernate | Sleep | Live
type pgpu_compat_limit = None | HostDriver | GuestDriver | GPU | Other
let library_open () = ()
let library_close () = ()
let init () = ()
let shutdown () = ()
let device_get_count _interface = 0
let device_get_handle_by_index _interface _int = ()
let device_get_handle_by_pci_bus_id _interface _string = ()
let device_get_memory_info _interface _device = memory_info
let device_get_pci_info _interface _device = pci_info
let device_get_temperature _interface _device = 0
let device_get_power_usage _interface _device = 0
let device_get_utilization_rates _interface _device = utilization
let device_set_persistence_mode _interface _device _enable_state = ()
let device_get_pgpu_metadata _interface _device = ""
let pgpu_metadata_get_pgpu_version _pgpu_metadata = 0
let pgpu_metadata_get_pgpu_revision _pgpu_metadata = 0
let pgpu_metadata_get_pgpu_host_driver_version _pgpu_metadata = ""
let device_get_active_vgpus _interface _device = []
let vgpu_instance_get_vm_domid _interface _vgpu_instance = ""
let vgpu_instance_get_vgpu_uuid _interface _vgpu_instance = ""
let get_vgpu_metadata _interface _vgpu_instance = ""
let get_pgpu_vgpu_compatibility _interface _vgpu_metadata _pgpu_metadata = ()
let vgpu_compat_get_vm_compat _vgpu_compatibility_t = []
let vgpu_compat_get_pgpu_compat_limit _vgpu_compatibility_t = []
let get_vgpus_for_vm _iface _device _vm_domid = []
let get_vgpu_for_uuid _iface _vgpu_uuid _vgpus = []
module NVML = struct
let attach () = ()
let detach () = ()
let is_attached () = true
let get () : interface option = None
end
|
|
6ed727c05f0a8b8ac12321e04204fef45e14bb8dbb720d52e6219ce54e163dac | leo-project/leo_gateway | leo_large_object_put_handler.erl | %%======================================================================
%%
Leo Gateway Large Object PUT Handler
%%
Copyright ( c ) 2012 - 2015 Rakuten , Inc.
%%
This file is provided to you 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(leo_large_object_put_handler).
-behaviour(gen_server).
-include("leo_gateway.hrl").
-include("leo_http.hrl").
-include_lib("leo_logger/include/leo_logger.hrl").
-include_lib("leo_object_storage/include/leo_object_storage.hrl").
-include_lib("leo_s3_libs/include/leo_s3_bucket.hrl").
-include_lib("leo_dcerl/include/leo_dcerl.hrl").
-include_lib("eunit/include/eunit.hrl").
%% Application callbacks
-export([start_link/2, start_link/3, stop/1]).
-export([put/2, rollback/1, result/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-undef(DEF_SEPARATOR).
-define(DEF_SEPARATOR, <<"\n">>).
-undef(DEF_TIMEOUT).
-define(DEF_TIMEOUT, 30000).
-record(state, {bucket_info :: #?BUCKET{},
key = <<>> :: binary(),
max_obj_len = 0 :: non_neg_integer(),
stacked_bin = <<>> :: binary(),
num_of_chunks = 0 :: non_neg_integer(),
total_len = 0 :: non_neg_integer(),
md5_context = <<>> :: any(),
errors = [] :: list(),
monitor_set :: gw_set()
}).
%%====================================================================
%% API
%%====================================================================
-spec(start_link(Key, Length) ->
ok | {error, any()} when Key::binary(),
Length::non_neg_integer()).
start_link(Key, Length) ->
BucketName = erlang:hd(leo_misc:binary_tokens(Key, <<"/">>)),
BucketInfo = #?BUCKET{name = BucketName},
start_link(BucketInfo, Key, Length).
-spec(start_link(BucketInfo, Key, Length) ->
ok | {error, any()} when BucketInfo::#?BUCKET{},
Key::binary(),
Length::non_neg_integer()).
start_link(BucketInfo, Key, Length) ->
gen_server:start_link(?MODULE, [BucketInfo, Key, Length], []).
%% @doc Stop this server
%%
-spec(stop(Pid) ->
ok when Pid::pid()).
stop(Pid) ->
gen_server:call(Pid, stop, ?DEF_TIMEOUT).
%% @doc Insert a chunked object into the storage cluster
%%
-spec(put(Pid, Bin) ->
ok | {error, any()} when Pid::pid(),
Bin::binary()).
put(Pid, Bin) ->
gen_server:call(Pid, {put, Bin}, ?DEF_TIMEOUT).
%% @doc Make a rollback before all operations
%%
-spec(rollback(Pid) ->
ok | {error, any()} when Pid::pid()).
rollback(Pid) ->
gen_server:call(Pid, rollback, ?DEF_TIMEOUT).
%% @doc Retrieve a result
%%
-spec(result(Pid) ->
ok | {error, any()} when Pid::pid()).
result(Pid) ->
gen_server:call(Pid, result, infinity).
%%====================================================================
GEN_SERVER
%%====================================================================
init([BucketInfo, Key, Length]) ->
State = #state{bucket_info = BucketInfo,
key = Key,
max_obj_len = Length,
num_of_chunks = 1,
stacked_bin = <<>>,
md5_context = crypto:hash_init(md5),
errors = [],
monitor_set = sets:new()},
{ok, State}.
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call({put, Bin}, _From, #state{bucket_info = BucketInfo,
key = Key,
max_obj_len = MaxObjLen,
stacked_bin = StackedBin,
num_of_chunks = NumOfChunks,
total_len = TotalLen,
errors = [],
monitor_set = MonitorSet,
md5_context = Context} = State) ->
Size = erlang:byte_size(Bin),
TotalLen_1 = TotalLen + Size,
Bin_1 = << StackedBin/binary, Bin/binary >>,
case (erlang:byte_size(Bin_1) >= MaxObjLen) of
true ->
NumOfChunksBin = list_to_binary(integer_to_list(NumOfChunks)),
<< Bin_2:MaxObjLen/binary, StackedBin_1/binary >> = Bin_1,
ChunkedKey = << Key/binary,
?DEF_SEPARATOR/binary,
NumOfChunksBin/binary >>,
{Ret, State_1} =
case send_object(#put_req_params{path = ChunkedKey,
body = Bin_2,
dsize = MaxObjLen,
cindex = NumOfChunks,
bucket_info = BucketInfo}, leo_date:clock()) of
{ok, SpawnRet} ->
Context_1 = crypto:hash_update(Context, Bin_2),
<< Head:8/binary, _Rest/binary>> = Bin_2,
Offset = MaxObjLen * NumOfChunks,
?debug("handle_call",
"Save Chunk, Key: ~p, Chunk: ~p, Offset: ~p, Bin: ~p",
[Key, NumOfChunks, Offset, leo_hex:binary_to_hex(Head)]),
{ok, State#state{stacked_bin = StackedBin_1,
num_of_chunks = NumOfChunks + 1,
total_len = TotalLen_1,
monitor_set = sets:add_element(SpawnRet, MonitorSet),
md5_context = Context_1}};
{error, Cause} ->
{{error, Cause}, State#state{stacked_bin = StackedBin_1,
num_of_chunks = NumOfChunks + 1,
total_len = TotalLen_1,
monitor_set = MonitorSet}}
end,
{reply, Ret, State_1};
false ->
{reply, ok, State#state{stacked_bin = Bin_1,
total_len = TotalLen_1}}
end;
handle_call({put, _Bin}, _From, #state{key = Key,
errors = Errors} = State) ->
?debug("handle_call", "Large Put Failed Key: ~p, Error: ~p", [Key, Errors]),
{reply, {error, Errors}, State};
handle_call(rollback, _From, #state{key = Key} = State) ->
catch leo_large_object_commons:delete_chunked_objects(Key),
{reply, ok, State#state{errors = []}};
handle_call(result, _From, #state{bucket_info = BucketInfo,
key = Key,
md5_context = Context,
stacked_bin = StackedBin,
num_of_chunks = NumOfChunks,
total_len = TotalLen,
monitor_set = MonitorSet,
errors = []} = State) ->
Ret = case StackedBin of
<<>> ->
{ok, {NumOfChunks - 1, Context}};
_ ->
NumOfChunksBin = list_to_binary(integer_to_list(NumOfChunks)),
Size = erlang:byte_size(StackedBin),
Key_1 = << Key/binary,
?DEF_SEPARATOR/binary,
NumOfChunksBin/binary >>,
case leo_gateway_rpc_handler:put(
#put_req_params{path = Key_1,
body = StackedBin,
dsize = Size,
cindex = NumOfChunks,
bucket_info = BucketInfo}) of
{ok,_ETag} ->
{ok, {NumOfChunks,
crypto:hash_update(Context, StackedBin)}};
{error, Cause} ->
{error, Cause}
end
end,
State_1 = State#state{stacked_bin = <<>>,
errors = []},
case wait_sub_process(MonitorSet, []) of
[] ->
case Ret of
{ok, {NumOfChunks_1, Context_1}} ->
Digest = crypto:hash_final(Context_1),
Reply = {ok, #large_obj_info{
key = Key,
num_of_chunks = NumOfChunks_1,
length = TotalLen,
md5_context = Digest}},
{reply, Reply, State_1#state{md5_context = Digest}};
{error, Reason} ->
Reply = {error, {#large_obj_info{
key = Key,
num_of_chunks = NumOfChunks}, Reason}},
{reply, Reply, State_1}
end;
Errors ->
{reply, {error, Errors}, State}
end;
handle_call(result, _From, #state{key = Key,
num_of_chunks = NumOfChunks,
errors = Errors} = State) ->
Cause = lists:reverse(Errors),
Reply = {error, {#large_obj_info{key = Key,
num_of_chunks = NumOfChunks}, Cause}},
{reply, Reply, State#state{stacked_bin = <<>>,
errors = []}}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', MonitorRef, _Type, Pid, _Info}, #state{monitor_set = MonitorSet} = State) ->
NewMonitorSet = sets:del_element({Pid, MonitorRef}, MonitorSet),
{noreply, State#state{monitor_set = NewMonitorSet}};
handle_info({async_notify, Key, Ret} = _Info, #state{errors = Errors} = State) ->
case Ret of
{ok, _CheckSum} ->
{noreply, State};
{error, Cause} ->
?error("handle_info/2", [{key, binary_to_list(Key)}, {cause, Cause}]),
{noreply, State#state{errors = [{error, Cause}|Errors]}}
end.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%====================================================================
%% Private Functions
%%====================================================================
%% @doc Checkout a worker and execute the request
@private
-spec(send_object(PutReq, Times) ->
{ok, SpawnRet} | {error, Cause} when PutReq::#put_req_params{},
Times::non_neg_integer(),
SpawnRet::{pid(), reference()},
Cause::any()).
send_object(PutReq, BeginTime) ->
Key = PutReq#put_req_params.path,
case leo_pod:checkout(?POD_LOH_WORKER) of
{ok, Worker} ->
Fun = fun() ->
Ret = case catch gen_server:call(Worker, {put, PutReq}, infinity) of
{'EXIT', {Reason, _Stack}} ->
{error, Reason};
Result ->
Result
end,
ok = leo_pod:checkin(?POD_LOH_WORKER, Worker),
erlang:send(self(), {async_notify, Key, Ret})
end,
SpawnRet = erlang:spawn_monitor(Fun),
{ok, SpawnRet};
{error,_Cause} ->
Latency = erlang:round((leo_date:clock() - BeginTime) / 1000),
case (?DEF_REQ_TIMEOUT < Latency) of
true ->
Cause = timeout,
erlang:send(self(), {async_notify, Key, {error, Cause}}),
?error("send_object/2", [{key, Key}, {cause, Cause},
{latency, Latency}]),
{error, Cause};
false ->
timer:sleep(?DEF_WAIT_TIME_OF_CHECKOUT),
send_object(PutReq, BeginTime)
end
end.
%% @doc Waits sub processes
@private
wait_sub_process(MonitorSet, Errors) ->
Size = sets:size(MonitorSet),
case Size of
0 ->
Errors;
_ ->
receive
{async_notify, _Key, {ok, _CheckSum}} ->
wait_sub_process(MonitorSet, Errors);
{async_notify, Key, {error, Cause}} ->
?error("wait_sub_process/2",
[{key, binary_to_list(Key)}, {cause, Cause}]),
wait_sub_process(MonitorSet, [{error, Cause}|Errors]);
{'DOWN', MonitorRef, _Type, Pid, _Info} ->
NewMonitorSet = sets:del_element({Pid, MonitorRef}, MonitorSet),
wait_sub_process(NewMonitorSet, Errors);
Other ->
?error("wait_sub_process/2", [{unknown_message, Other}]),
wait_sub_process(MonitorSet, Errors)
end
end.
| null | https://raw.githubusercontent.com/leo-project/leo_gateway/7bac8912b762688f0ef237b31fee17e30e3888a3/src/leo_large_object_put_handler.erl | erlang | ======================================================================
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
======================================================================
Application callbacks
====================================================================
API
====================================================================
@doc Stop this server
@doc Insert a chunked object into the storage cluster
@doc Make a rollback before all operations
@doc Retrieve a result
====================================================================
====================================================================
====================================================================
Private Functions
====================================================================
@doc Checkout a worker and execute the request
@doc Waits sub processes | Leo Gateway Large Object PUT Handler
Copyright ( c ) 2012 - 2015 Rakuten , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(leo_large_object_put_handler).
-behaviour(gen_server).
-include("leo_gateway.hrl").
-include("leo_http.hrl").
-include_lib("leo_logger/include/leo_logger.hrl").
-include_lib("leo_object_storage/include/leo_object_storage.hrl").
-include_lib("leo_s3_libs/include/leo_s3_bucket.hrl").
-include_lib("leo_dcerl/include/leo_dcerl.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([start_link/2, start_link/3, stop/1]).
-export([put/2, rollback/1, result/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-undef(DEF_SEPARATOR).
-define(DEF_SEPARATOR, <<"\n">>).
-undef(DEF_TIMEOUT).
-define(DEF_TIMEOUT, 30000).
-record(state, {bucket_info :: #?BUCKET{},
key = <<>> :: binary(),
max_obj_len = 0 :: non_neg_integer(),
stacked_bin = <<>> :: binary(),
num_of_chunks = 0 :: non_neg_integer(),
total_len = 0 :: non_neg_integer(),
md5_context = <<>> :: any(),
errors = [] :: list(),
monitor_set :: gw_set()
}).
-spec(start_link(Key, Length) ->
ok | {error, any()} when Key::binary(),
Length::non_neg_integer()).
start_link(Key, Length) ->
BucketName = erlang:hd(leo_misc:binary_tokens(Key, <<"/">>)),
BucketInfo = #?BUCKET{name = BucketName},
start_link(BucketInfo, Key, Length).
-spec(start_link(BucketInfo, Key, Length) ->
ok | {error, any()} when BucketInfo::#?BUCKET{},
Key::binary(),
Length::non_neg_integer()).
start_link(BucketInfo, Key, Length) ->
gen_server:start_link(?MODULE, [BucketInfo, Key, Length], []).
-spec(stop(Pid) ->
ok when Pid::pid()).
stop(Pid) ->
gen_server:call(Pid, stop, ?DEF_TIMEOUT).
-spec(put(Pid, Bin) ->
ok | {error, any()} when Pid::pid(),
Bin::binary()).
put(Pid, Bin) ->
gen_server:call(Pid, {put, Bin}, ?DEF_TIMEOUT).
-spec(rollback(Pid) ->
ok | {error, any()} when Pid::pid()).
rollback(Pid) ->
gen_server:call(Pid, rollback, ?DEF_TIMEOUT).
-spec(result(Pid) ->
ok | {error, any()} when Pid::pid()).
result(Pid) ->
gen_server:call(Pid, result, infinity).
GEN_SERVER
init([BucketInfo, Key, Length]) ->
State = #state{bucket_info = BucketInfo,
key = Key,
max_obj_len = Length,
num_of_chunks = 1,
stacked_bin = <<>>,
md5_context = crypto:hash_init(md5),
errors = [],
monitor_set = sets:new()},
{ok, State}.
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call({put, Bin}, _From, #state{bucket_info = BucketInfo,
key = Key,
max_obj_len = MaxObjLen,
stacked_bin = StackedBin,
num_of_chunks = NumOfChunks,
total_len = TotalLen,
errors = [],
monitor_set = MonitorSet,
md5_context = Context} = State) ->
Size = erlang:byte_size(Bin),
TotalLen_1 = TotalLen + Size,
Bin_1 = << StackedBin/binary, Bin/binary >>,
case (erlang:byte_size(Bin_1) >= MaxObjLen) of
true ->
NumOfChunksBin = list_to_binary(integer_to_list(NumOfChunks)),
<< Bin_2:MaxObjLen/binary, StackedBin_1/binary >> = Bin_1,
ChunkedKey = << Key/binary,
?DEF_SEPARATOR/binary,
NumOfChunksBin/binary >>,
{Ret, State_1} =
case send_object(#put_req_params{path = ChunkedKey,
body = Bin_2,
dsize = MaxObjLen,
cindex = NumOfChunks,
bucket_info = BucketInfo}, leo_date:clock()) of
{ok, SpawnRet} ->
Context_1 = crypto:hash_update(Context, Bin_2),
<< Head:8/binary, _Rest/binary>> = Bin_2,
Offset = MaxObjLen * NumOfChunks,
?debug("handle_call",
"Save Chunk, Key: ~p, Chunk: ~p, Offset: ~p, Bin: ~p",
[Key, NumOfChunks, Offset, leo_hex:binary_to_hex(Head)]),
{ok, State#state{stacked_bin = StackedBin_1,
num_of_chunks = NumOfChunks + 1,
total_len = TotalLen_1,
monitor_set = sets:add_element(SpawnRet, MonitorSet),
md5_context = Context_1}};
{error, Cause} ->
{{error, Cause}, State#state{stacked_bin = StackedBin_1,
num_of_chunks = NumOfChunks + 1,
total_len = TotalLen_1,
monitor_set = MonitorSet}}
end,
{reply, Ret, State_1};
false ->
{reply, ok, State#state{stacked_bin = Bin_1,
total_len = TotalLen_1}}
end;
handle_call({put, _Bin}, _From, #state{key = Key,
errors = Errors} = State) ->
?debug("handle_call", "Large Put Failed Key: ~p, Error: ~p", [Key, Errors]),
{reply, {error, Errors}, State};
handle_call(rollback, _From, #state{key = Key} = State) ->
catch leo_large_object_commons:delete_chunked_objects(Key),
{reply, ok, State#state{errors = []}};
handle_call(result, _From, #state{bucket_info = BucketInfo,
key = Key,
md5_context = Context,
stacked_bin = StackedBin,
num_of_chunks = NumOfChunks,
total_len = TotalLen,
monitor_set = MonitorSet,
errors = []} = State) ->
Ret = case StackedBin of
<<>> ->
{ok, {NumOfChunks - 1, Context}};
_ ->
NumOfChunksBin = list_to_binary(integer_to_list(NumOfChunks)),
Size = erlang:byte_size(StackedBin),
Key_1 = << Key/binary,
?DEF_SEPARATOR/binary,
NumOfChunksBin/binary >>,
case leo_gateway_rpc_handler:put(
#put_req_params{path = Key_1,
body = StackedBin,
dsize = Size,
cindex = NumOfChunks,
bucket_info = BucketInfo}) of
{ok,_ETag} ->
{ok, {NumOfChunks,
crypto:hash_update(Context, StackedBin)}};
{error, Cause} ->
{error, Cause}
end
end,
State_1 = State#state{stacked_bin = <<>>,
errors = []},
case wait_sub_process(MonitorSet, []) of
[] ->
case Ret of
{ok, {NumOfChunks_1, Context_1}} ->
Digest = crypto:hash_final(Context_1),
Reply = {ok, #large_obj_info{
key = Key,
num_of_chunks = NumOfChunks_1,
length = TotalLen,
md5_context = Digest}},
{reply, Reply, State_1#state{md5_context = Digest}};
{error, Reason} ->
Reply = {error, {#large_obj_info{
key = Key,
num_of_chunks = NumOfChunks}, Reason}},
{reply, Reply, State_1}
end;
Errors ->
{reply, {error, Errors}, State}
end;
handle_call(result, _From, #state{key = Key,
num_of_chunks = NumOfChunks,
errors = Errors} = State) ->
Cause = lists:reverse(Errors),
Reply = {error, {#large_obj_info{key = Key,
num_of_chunks = NumOfChunks}, Cause}},
{reply, Reply, State#state{stacked_bin = <<>>,
errors = []}}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', MonitorRef, _Type, Pid, _Info}, #state{monitor_set = MonitorSet} = State) ->
NewMonitorSet = sets:del_element({Pid, MonitorRef}, MonitorSet),
{noreply, State#state{monitor_set = NewMonitorSet}};
handle_info({async_notify, Key, Ret} = _Info, #state{errors = Errors} = State) ->
case Ret of
{ok, _CheckSum} ->
{noreply, State};
{error, Cause} ->
?error("handle_info/2", [{key, binary_to_list(Key)}, {cause, Cause}]),
{noreply, State#state{errors = [{error, Cause}|Errors]}}
end.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
@private
-spec(send_object(PutReq, Times) ->
{ok, SpawnRet} | {error, Cause} when PutReq::#put_req_params{},
Times::non_neg_integer(),
SpawnRet::{pid(), reference()},
Cause::any()).
send_object(PutReq, BeginTime) ->
Key = PutReq#put_req_params.path,
case leo_pod:checkout(?POD_LOH_WORKER) of
{ok, Worker} ->
Fun = fun() ->
Ret = case catch gen_server:call(Worker, {put, PutReq}, infinity) of
{'EXIT', {Reason, _Stack}} ->
{error, Reason};
Result ->
Result
end,
ok = leo_pod:checkin(?POD_LOH_WORKER, Worker),
erlang:send(self(), {async_notify, Key, Ret})
end,
SpawnRet = erlang:spawn_monitor(Fun),
{ok, SpawnRet};
{error,_Cause} ->
Latency = erlang:round((leo_date:clock() - BeginTime) / 1000),
case (?DEF_REQ_TIMEOUT < Latency) of
true ->
Cause = timeout,
erlang:send(self(), {async_notify, Key, {error, Cause}}),
?error("send_object/2", [{key, Key}, {cause, Cause},
{latency, Latency}]),
{error, Cause};
false ->
timer:sleep(?DEF_WAIT_TIME_OF_CHECKOUT),
send_object(PutReq, BeginTime)
end
end.
@private
wait_sub_process(MonitorSet, Errors) ->
Size = sets:size(MonitorSet),
case Size of
0 ->
Errors;
_ ->
receive
{async_notify, _Key, {ok, _CheckSum}} ->
wait_sub_process(MonitorSet, Errors);
{async_notify, Key, {error, Cause}} ->
?error("wait_sub_process/2",
[{key, binary_to_list(Key)}, {cause, Cause}]),
wait_sub_process(MonitorSet, [{error, Cause}|Errors]);
{'DOWN', MonitorRef, _Type, Pid, _Info} ->
NewMonitorSet = sets:del_element({Pid, MonitorRef}, MonitorSet),
wait_sub_process(NewMonitorSet, Errors);
Other ->
?error("wait_sub_process/2", [{unknown_message, Other}]),
wait_sub_process(MonitorSet, Errors)
end
end.
|
e60d89d950bf2fc8f68b60cdfc14c44f2e84b2e4cad200344a336bb40642cbea | nick8325/quickspec | Terms.hs | Theory exploration which accepts one term at a time .
{-# OPTIONS_HADDOCK hide #-}
# LANGUAGE RecordWildCards , FlexibleContexts , PatternGuards #
module QuickSpec.Internal.Explore.Terms where
import qualified Data.Map.Strict as Map
import Data.Map(Map)
import QuickSpec.Internal.Term
import QuickSpec.Internal.Prop
import QuickSpec.Internal.Type
import QuickSpec.Internal.Pruning
import QuickSpec.Internal.Testing
import QuickSpec.Internal.Testing.DecisionTree hiding (Result, Singleton)
import Control.Monad.Trans.State.Strict hiding (State)
import Data.Lens.Light
import QuickSpec.Internal.Utils
import QuickSpec.Internal.Terminal
data Terms testcase result term norm =
Terms {
-- Empty decision tree.
tm_empty :: DecisionTree testcase result term,
-- Terms already explored. These are stored in the *values* of the map.
-- The keys are those terms but normalised.
-- We do it like this so that explore can guarantee to always return
-- the same representative for each equivalence class (see below).
tm_terms :: Map norm term,
-- Decision tree mapping test case results to terms.
-- Terms are not stored normalised.
-- Terms of different types must not be equal, because that results in
-- ill-typed equations and bad things happening in the pruner.
tm_tree :: Map Type (DecisionTree testcase result term) }
tree = lens tm_tree (\x y -> y { tm_tree = x })
treeForType :: Type -> Lens (Terms testcase result term norm) (DecisionTree testcase result term)
treeForType ty = reading (\Terms{..} -> keyDefault ty tm_empty # tree)
initialState ::
(term -> testcase -> result) ->
Terms testcase result term norm
initialState eval =
Terms {
tm_empty = empty eval,
tm_terms = Map.empty,
tm_tree = Map.empty }
data Result term =
-- Discovered a new law.
Discovered (Prop term)
-- Term is equal to an existing term so redundant.
| Knew (Prop term)
| Singleton
The Prop returned is always t : = : u , where t is the term passed to explore
-- and u is the representative of t's equivalence class, not normalised.
-- The representatives of the equivalence classes are guaranteed not to change.
--
-- Discovered properties are not added to the pruner.
explore :: (Pretty term, Typed term, Ord norm, Ord result, MonadTester testcase term m, MonadPruner term norm m, MonadTerminal m) =>
term -> StateT (Terms testcase result term norm) m (Result term)
explore t = do
res <- explore' t
--case res of
-- Discovered prop -> putLine ("discovered " ++ prettyShow prop)
-- Knew prop -> putLine ("knew " ++ prettyShow prop)
Singleton - > putLine ( " singleton " + + prettyShow t )
return res
explore' :: (Pretty term, Typed term, Ord norm, Ord result, MonadTester testcase term m, MonadPruner term norm m) =>
term -> StateT (Terms testcase result term norm) m (Result term)
explore' t = do
norm <- normaliser
exp norm $ \prop -> do
res <- test prop
case res of
Nothing -> do
return (Discovered prop)
Just tc -> do
treeForType ty %= addTestCase tc
exp norm $
error "returned counterexample failed to falsify property"
where
ty = typ t
exp norm found = do
tm@Terms{..} <- get
case Map.lookup t' tm_terms of
Just u -> return (Knew (t === u))
Nothing ->
case insert t (tm ^. treeForType ty) of
Distinct tree -> do
put (setL (treeForType ty) tree tm { tm_terms = Map.insert t' t tm_terms })
return Singleton
EqualTo u
-- tm_terms is not kept normalised wrt the discovered laws;
-- instead, we normalise it lazily like so.
| t' == u' -> do
put tm { tm_terms = Map.insert u' u tm_terms }
return (Knew prop)
-- Ask QuickCheck for a counterexample to the property.
| otherwise -> found prop
where
u' = norm u
prop = t === u
where
t' = norm t
| null | https://raw.githubusercontent.com/nick8325/quickspec/cb61f719d3d667674431867037ff44dec22ca4f9/src/QuickSpec/Internal/Explore/Terms.hs | haskell | # OPTIONS_HADDOCK hide #
Empty decision tree.
Terms already explored. These are stored in the *values* of the map.
The keys are those terms but normalised.
We do it like this so that explore can guarantee to always return
the same representative for each equivalence class (see below).
Decision tree mapping test case results to terms.
Terms are not stored normalised.
Terms of different types must not be equal, because that results in
ill-typed equations and bad things happening in the pruner.
Discovered a new law.
Term is equal to an existing term so redundant.
and u is the representative of t's equivalence class, not normalised.
The representatives of the equivalence classes are guaranteed not to change.
Discovered properties are not added to the pruner.
case res of
Discovered prop -> putLine ("discovered " ++ prettyShow prop)
Knew prop -> putLine ("knew " ++ prettyShow prop)
tm_terms is not kept normalised wrt the discovered laws;
instead, we normalise it lazily like so.
Ask QuickCheck for a counterexample to the property. | Theory exploration which accepts one term at a time .
# LANGUAGE RecordWildCards , FlexibleContexts , PatternGuards #
module QuickSpec.Internal.Explore.Terms where
import qualified Data.Map.Strict as Map
import Data.Map(Map)
import QuickSpec.Internal.Term
import QuickSpec.Internal.Prop
import QuickSpec.Internal.Type
import QuickSpec.Internal.Pruning
import QuickSpec.Internal.Testing
import QuickSpec.Internal.Testing.DecisionTree hiding (Result, Singleton)
import Control.Monad.Trans.State.Strict hiding (State)
import Data.Lens.Light
import QuickSpec.Internal.Utils
import QuickSpec.Internal.Terminal
data Terms testcase result term norm =
Terms {
tm_empty :: DecisionTree testcase result term,
tm_terms :: Map norm term,
tm_tree :: Map Type (DecisionTree testcase result term) }
tree = lens tm_tree (\x y -> y { tm_tree = x })
treeForType :: Type -> Lens (Terms testcase result term norm) (DecisionTree testcase result term)
treeForType ty = reading (\Terms{..} -> keyDefault ty tm_empty # tree)
initialState ::
(term -> testcase -> result) ->
Terms testcase result term norm
initialState eval =
Terms {
tm_empty = empty eval,
tm_terms = Map.empty,
tm_tree = Map.empty }
data Result term =
Discovered (Prop term)
| Knew (Prop term)
| Singleton
The Prop returned is always t : = : u , where t is the term passed to explore
explore :: (Pretty term, Typed term, Ord norm, Ord result, MonadTester testcase term m, MonadPruner term norm m, MonadTerminal m) =>
term -> StateT (Terms testcase result term norm) m (Result term)
explore t = do
res <- explore' t
Singleton - > putLine ( " singleton " + + prettyShow t )
return res
explore' :: (Pretty term, Typed term, Ord norm, Ord result, MonadTester testcase term m, MonadPruner term norm m) =>
term -> StateT (Terms testcase result term norm) m (Result term)
explore' t = do
norm <- normaliser
exp norm $ \prop -> do
res <- test prop
case res of
Nothing -> do
return (Discovered prop)
Just tc -> do
treeForType ty %= addTestCase tc
exp norm $
error "returned counterexample failed to falsify property"
where
ty = typ t
exp norm found = do
tm@Terms{..} <- get
case Map.lookup t' tm_terms of
Just u -> return (Knew (t === u))
Nothing ->
case insert t (tm ^. treeForType ty) of
Distinct tree -> do
put (setL (treeForType ty) tree tm { tm_terms = Map.insert t' t tm_terms })
return Singleton
EqualTo u
| t' == u' -> do
put tm { tm_terms = Map.insert u' u tm_terms }
return (Knew prop)
| otherwise -> found prop
where
u' = norm u
prop = t === u
where
t' = norm t
|
8ce88630cebdc179c5616a7f2352c144a2924011f98e092132da771fcfded4a8 | msakai/toysolver | BCD2.hs | {-# LANGUAGE BangPatterns #-}
# OPTIONS_GHC -Wall -fno - warn - unused - do - bind #
{-# OPTIONS_HADDOCK show-extensions #-}
-----------------------------------------------------------------------------
-- |
Module : ToySolver . SAT.PBO.BCD2
Copyright : ( c ) 2014
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : non-portable
--
-- Reference:
--
* , , ,
-- Core-Guided binary search algorithms for maximum satisfiability,
Twenty - Fifth AAAI Conference on Artificial Intelligence , 2011 .
-- <>
--
* A. Morgado , , and ,
-- Improvements to Core-Guided binary search for MaxSAT,
in Theory and Applications of Satisfiability Testing ( SAT 2012 ) ,
pp . 284 - 297 .
-- <-3-642-31612-8_22>
-- <>
--
-----------------------------------------------------------------------------
module ToySolver.SAT.PBO.BCD2
( Options (..)
, solve
) where
import Control.Concurrent.STM
import Control.Monad
import Data.IORef
import Data.Default.Class
import qualified Data.IntSet as IntSet
import qualified Data.IntMap as IntMap
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Vector as V
import qualified ToySolver.SAT as SAT
import qualified ToySolver.SAT.Types as SAT
import qualified ToySolver.SAT.PBO.Context as C
import qualified ToySolver.Combinatorial.SubsetSum as SubsetSum
import Text.Printf
-- | Options for BCD2 algorithm.
--
-- The default value can be obtained by 'def'.
data Options
= Options
{ optEnableHardening :: Bool
, optEnableBiasedSearch :: Bool
, optSolvingNormalFirst :: Bool
}
instance Default Options where
def =
Options
{ optEnableHardening = True
, optEnableBiasedSearch = True
, optSolvingNormalFirst = True
}
data CoreInfo
= CoreInfo
{ coreLits :: SAT.LitSet
, coreLBRef :: !(IORef Integer)
, coreUBSelectors :: !(IORef (Map Integer SAT.Lit))
}
newCoreInfo :: SAT.LitSet -> Integer -> IO CoreInfo
newCoreInfo lits lb = do
lbRef <- newIORef lb
selsRef <- newIORef Map.empty
return
CoreInfo
{ coreLits = lits
, coreLBRef = lbRef
, coreUBSelectors = selsRef
}
deleteCoreInfo :: SAT.Solver -> CoreInfo -> IO ()
deleteCoreInfo solver core = do
m <- readIORef (coreUBSelectors core)
-- Delete soft upperbound constraints by fixing selector variables
forM_ (Map.elems m) $ \sel ->
SAT.addClause solver [-sel]
getCoreLB :: CoreInfo -> IO Integer
getCoreLB = readIORef . coreLBRef
solve :: C.Context cxt => cxt -> SAT.Solver -> Options -> IO ()
solve cxt solver opt = solveWBO (C.normalize cxt) solver opt
solveWBO :: C.Context cxt => cxt -> SAT.Solver -> Options -> IO ()
solveWBO cxt solver opt = do
C.logMessage cxt $ printf "BCD2: Hardening is %s." (if optEnableHardening opt then "enabled" else "disabled")
C.logMessage cxt $ printf "BCD2: BiasedSearch is %s." (if optEnableBiasedSearch opt then "enabled" else "disabled")
SAT.modifyConfig solver $ \config -> config{ SAT.configEnableBackwardSubsumptionRemoval = True }
unrelaxedRef <- newIORef $ IntSet.fromList [lit | (lit,_) <- sels]
relaxedRef <- newIORef IntSet.empty
hardenedRef <- newIORef IntSet.empty
nsatRef <- newIORef 1
nunsatRef <- newIORef 1
lastUBRef <- newIORef $ SAT.pbLinUpperBound obj
coresRef <- newIORef []
let getLB = do
xs <- readIORef coresRef
foldM (\s core -> do{ v <- getCoreLB core; return $! s + v }) 0 xs
deductedWeightRef <- newIORef weights
let deductWeight d core =
modifyIORef' deductedWeightRef $ IntMap.unionWith (+) $
IntMap.fromSet (const (- d)) (coreLits core)
updateLB oldLB core = do
newLB <- getLB
C.addLowerBound cxt newLB
deductWeight (newLB - oldLB) core
SAT.addPBAtLeast solver (coreCostFun core) =<< getCoreLB core -- redundant, but useful for direct search
let loop = do
lb <- getLB
ub <- do
ub1 <- atomically $ C.getSearchUpperBound cxt
FIXME : The refinement should be done in Context.addSolution ,
-- for generality and to avoid duplicated computation.
let ub2 = refineUB (map fst obj) ub1
when (ub1 /= ub2) $ C.logMessage cxt $ printf "BCD2: refineUB: %d -> %d" ub1 ub2
return ub2
when (ub < lb) $ C.setFinished cxt
fin <- atomically $ C.isFinished cxt
unless fin $ do
when (optEnableHardening opt) $ do
deductedWeight <- readIORef deductedWeightRef
hardened <- readIORef hardenedRef
let lits = IntMap.keysSet (IntMap.filter (\w -> lb + w > ub) deductedWeight) `IntSet.difference` hardened
unless (IntSet.null lits) $ do
C.logMessage cxt $ printf "BCD2: hardening fixes %d literals" (IntSet.size lits)
forM_ (IntSet.toList lits) $ \lit -> SAT.addClause solver [lit]
modifyIORef unrelaxedRef (`IntSet.difference` lits)
modifyIORef relaxedRef (`IntSet.difference` lits)
modifyIORef hardenedRef (`IntSet.union` lits)
ub0 <- readIORef lastUBRef
when (ub < ub0) $ do
C.logMessage cxt $ printf "BCD2: updating upper bound: %d -> %d" ub0 ub
SAT.addPBAtMost solver obj ub
writeIORef lastUBRef ub
cores <- readIORef coresRef
unrelaxed <- readIORef unrelaxedRef
relaxed <- readIORef relaxedRef
hardened <- readIORef hardenedRef
nsat <- readIORef nsatRef
nunsat <- readIORef nunsatRef
C.logMessage cxt $ printf "BCD2: %d <= obj <= %d" lb ub
C.logMessage cxt $ printf "BCD2: #cores=%d, #unrelaxed=%d, #relaxed=%d, #hardened=%d"
(length cores) (IntSet.size unrelaxed) (IntSet.size relaxed) (IntSet.size hardened)
C.logMessage cxt $ printf "BCD2: #sat=%d #unsat=%d bias=%d/%d" nsat nunsat nunsat (nunsat + nsat)
lastModel <- atomically $ C.getBestModel cxt
sels <- liftM IntMap.fromList $ forM cores $ \core -> do
coreLB <- getCoreLB core
let coreUB = SAT.pbLinUpperBound (coreCostFun core)
if coreUB < coreLB then do
-- Note: we have detected unsatisfiability
C.logMessage cxt $ printf "BCD2: coreLB (%d) exceeds coreUB (%d)" coreLB coreUB
SAT.addClause solver []
sel <- getCoreUBAssumption core coreUB
return (sel, (core, coreUB))
else do
let estimated =
case lastModel of
Nothing -> coreUB
Just m ->
-- Since we might have added some hard constraints after obtaining @m@,
it 's possible that @coreLB@ is larger than @SAT.evalPBLinSum m ( coreCostFun core)@.
coreLB `max` SAT.evalPBLinSum m (coreCostFun core)
mid =
if optEnableBiasedSearch opt
then coreLB + (estimated - coreLB) * nunsat `div` (nunsat + nsat)
else (coreLB + estimated) `div` 2
sel <- getCoreUBAssumption core mid
return (sel, (core,mid))
ret <- SAT.solveWith solver (IntMap.keys sels ++ IntSet.toList unrelaxed)
if ret then do
modifyIORef' nsatRef (+1)
C.addSolution cxt =<< SAT.getModel solver
loop
else do
modifyIORef' nunsatRef (+1)
failed <- SAT.getFailedAssumptions solver
case IntSet.toList failed of
[] -> C.setFinished cxt
[sel] | Just (core,mid) <- IntMap.lookup sel sels -> do
C.logMessage cxt $ printf "BCD2: updating lower bound of a core"
let newCoreLB = mid + 1
newCoreLB' = refineLB (IntMap.elems (IntMap.restrictKeys weights (coreLits core))) newCoreLB
when (newCoreLB /= newCoreLB') $ C.logMessage cxt $
printf "BCD2: refineLB: %d -> %d" newCoreLB newCoreLB'
writeIORef (coreLBRef core) newCoreLB'
SAT.addClause solver [-sel] -- Delete soft upperbound constraint(s) by fixing a selector variable
updateLB lb core
loop
_ -> do
let torelax = unrelaxed `IntSet.intersection` failed
intersected = IntMap.elems (IntMap.restrictKeys sels failed)
disjoint = [core | (sel,(core,_)) <- IntMap.toList (IntMap.withoutKeys sels failed)]
modifyIORef unrelaxedRef (`IntSet.difference` torelax)
modifyIORef relaxedRef (`IntSet.union` torelax)
delta <- do
xs1 <- forM intersected $ \(core,mid) -> do
coreLB <- getCoreLB core
return $ mid - coreLB + 1
let xs2 = [weights IntMap.! lit | lit <- IntSet.toList torelax]
return $! minimum (xs1 ++ xs2)
let mergedCoreLits = IntSet.unions $ torelax : [coreLits core | (core,_) <- intersected]
mergedCoreLB <- liftM ((delta +) . sum) $ mapM (getCoreLB . fst) intersected
let mergedCoreLB' = refineLB (IntMap.elems (IntMap.restrictKeys weights mergedCoreLits)) mergedCoreLB
mergedCore <- newCoreInfo mergedCoreLits mergedCoreLB'
writeIORef coresRef (mergedCore : disjoint)
forM_ intersected $ \(core, _) -> deleteCoreInfo solver core
if null intersected then
C.logMessage cxt $ printf "BCD2: found a new core of size %d: cost of the new core is >=%d"
(IntSet.size torelax) mergedCoreLB'
else
C.logMessage cxt $ printf "BCD2: relaxing %d and merging with %d cores into a new core of size %d: cost of the new core is >=%d"
(IntSet.size torelax) (length intersected) (IntSet.size mergedCoreLits) mergedCoreLB'
when (mergedCoreLB /= mergedCoreLB') $
C.logMessage cxt $ printf "BCD2: refineLB: %d -> %d" mergedCoreLB mergedCoreLB'
updateLB lb mergedCore
loop
best <- atomically $ C.getBestModel cxt
case best of
Nothing | optSolvingNormalFirst opt -> do
ret <- SAT.solve solver
if ret then
C.addSolution cxt =<< SAT.getModel solver
else
C.setFinished cxt
_ -> return ()
loop
where
obj :: SAT.PBLinSum
obj = C.getObjectiveFunction cxt
sels :: [(SAT.Lit, Integer)]
sels = [(-lit, w) | (w,lit) <- obj]
weights :: SAT.LitMap Integer
weights = IntMap.fromList sels
coreCostFun :: CoreInfo -> SAT.PBLinSum
coreCostFun c = [(weights IntMap.! lit, -lit) | lit <- IntSet.toList (coreLits c)]
getCoreUBAssumption :: CoreInfo -> Integer -> IO SAT.Lit
getCoreUBAssumption core ub = do
m <- readIORef (coreUBSelectors core)
case Map.splitLookup ub m of
(_, Just sel, _) -> return sel
(lo, Nothing, hi) -> do
sel <- SAT.newVar solver
SAT.addPBAtMostSoft solver sel (coreCostFun core) ub
writeIORef (coreUBSelectors core) (Map.insert ub sel m)
unless (Map.null lo) $
snd ( Map.findMax ) → sel
unless (Map.null hi) $
SAT.addClause solver [- sel, snd (Map.findMin hi)] -- sel → Map.findMin hi
return sel
| The smallest integer greater - than or equal - to @n@ that can be obtained by summing a subset of @ws@.
Note that the definition is different from the one in Morgado et al .
refineLB
:: [Integer] -- ^ @ws@
-> Integer -- ^ @n@
-> Integer
refineLB ws n =
case SubsetSum.minSubsetSum (V.fromList ws) n of
Nothing -> sum [w | w <- ws, w > 0] + 1
Just (obj, _) -> obj
| The greatest integer lesser - than or equal - to @n@ that can be obtained by summing a subset of @ws@.
refineUB
:: [Integer] -- ^ @ws@
-> Integer -- ^ @n@
-> Integer
refineUB ws n
| n < 0 = n
| otherwise =
case SubsetSum.maxSubsetSum (V.fromList ws) n of
Nothing -> sum [w | w <- ws, w < 0] - 1
Just (obj, _) -> obj
| null | https://raw.githubusercontent.com/msakai/toysolver/6233d130d3dcea32fa34c26feebd151f546dea85/src/ToySolver/SAT/PBO/BCD2.hs | haskell | # LANGUAGE BangPatterns #
# OPTIONS_HADDOCK show-extensions #
---------------------------------------------------------------------------
|
License : BSD-style
Maintainer :
Stability : provisional
Portability : non-portable
Reference:
Core-Guided binary search algorithms for maximum satisfiability,
<>
Improvements to Core-Guided binary search for MaxSAT,
<-3-642-31612-8_22>
<>
---------------------------------------------------------------------------
| Options for BCD2 algorithm.
The default value can be obtained by 'def'.
Delete soft upperbound constraints by fixing selector variables
redundant, but useful for direct search
for generality and to avoid duplicated computation.
Note: we have detected unsatisfiability
Since we might have added some hard constraints after obtaining @m@,
Delete soft upperbound constraint(s) by fixing a selector variable
sel → Map.findMin hi
^ @ws@
^ @n@
^ @ws@
^ @n@ | # OPTIONS_GHC -Wall -fno - warn - unused - do - bind #
Module : ToySolver . SAT.PBO.BCD2
Copyright : ( c ) 2014
* , , ,
Twenty - Fifth AAAI Conference on Artificial Intelligence , 2011 .
* A. Morgado , , and ,
in Theory and Applications of Satisfiability Testing ( SAT 2012 ) ,
pp . 284 - 297 .
module ToySolver.SAT.PBO.BCD2
( Options (..)
, solve
) where
import Control.Concurrent.STM
import Control.Monad
import Data.IORef
import Data.Default.Class
import qualified Data.IntSet as IntSet
import qualified Data.IntMap as IntMap
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Vector as V
import qualified ToySolver.SAT as SAT
import qualified ToySolver.SAT.Types as SAT
import qualified ToySolver.SAT.PBO.Context as C
import qualified ToySolver.Combinatorial.SubsetSum as SubsetSum
import Text.Printf
data Options
= Options
{ optEnableHardening :: Bool
, optEnableBiasedSearch :: Bool
, optSolvingNormalFirst :: Bool
}
instance Default Options where
def =
Options
{ optEnableHardening = True
, optEnableBiasedSearch = True
, optSolvingNormalFirst = True
}
data CoreInfo
= CoreInfo
{ coreLits :: SAT.LitSet
, coreLBRef :: !(IORef Integer)
, coreUBSelectors :: !(IORef (Map Integer SAT.Lit))
}
newCoreInfo :: SAT.LitSet -> Integer -> IO CoreInfo
newCoreInfo lits lb = do
lbRef <- newIORef lb
selsRef <- newIORef Map.empty
return
CoreInfo
{ coreLits = lits
, coreLBRef = lbRef
, coreUBSelectors = selsRef
}
deleteCoreInfo :: SAT.Solver -> CoreInfo -> IO ()
deleteCoreInfo solver core = do
m <- readIORef (coreUBSelectors core)
forM_ (Map.elems m) $ \sel ->
SAT.addClause solver [-sel]
getCoreLB :: CoreInfo -> IO Integer
getCoreLB = readIORef . coreLBRef
solve :: C.Context cxt => cxt -> SAT.Solver -> Options -> IO ()
solve cxt solver opt = solveWBO (C.normalize cxt) solver opt
solveWBO :: C.Context cxt => cxt -> SAT.Solver -> Options -> IO ()
solveWBO cxt solver opt = do
C.logMessage cxt $ printf "BCD2: Hardening is %s." (if optEnableHardening opt then "enabled" else "disabled")
C.logMessage cxt $ printf "BCD2: BiasedSearch is %s." (if optEnableBiasedSearch opt then "enabled" else "disabled")
SAT.modifyConfig solver $ \config -> config{ SAT.configEnableBackwardSubsumptionRemoval = True }
unrelaxedRef <- newIORef $ IntSet.fromList [lit | (lit,_) <- sels]
relaxedRef <- newIORef IntSet.empty
hardenedRef <- newIORef IntSet.empty
nsatRef <- newIORef 1
nunsatRef <- newIORef 1
lastUBRef <- newIORef $ SAT.pbLinUpperBound obj
coresRef <- newIORef []
let getLB = do
xs <- readIORef coresRef
foldM (\s core -> do{ v <- getCoreLB core; return $! s + v }) 0 xs
deductedWeightRef <- newIORef weights
let deductWeight d core =
modifyIORef' deductedWeightRef $ IntMap.unionWith (+) $
IntMap.fromSet (const (- d)) (coreLits core)
updateLB oldLB core = do
newLB <- getLB
C.addLowerBound cxt newLB
deductWeight (newLB - oldLB) core
let loop = do
lb <- getLB
ub <- do
ub1 <- atomically $ C.getSearchUpperBound cxt
FIXME : The refinement should be done in Context.addSolution ,
let ub2 = refineUB (map fst obj) ub1
when (ub1 /= ub2) $ C.logMessage cxt $ printf "BCD2: refineUB: %d -> %d" ub1 ub2
return ub2
when (ub < lb) $ C.setFinished cxt
fin <- atomically $ C.isFinished cxt
unless fin $ do
when (optEnableHardening opt) $ do
deductedWeight <- readIORef deductedWeightRef
hardened <- readIORef hardenedRef
let lits = IntMap.keysSet (IntMap.filter (\w -> lb + w > ub) deductedWeight) `IntSet.difference` hardened
unless (IntSet.null lits) $ do
C.logMessage cxt $ printf "BCD2: hardening fixes %d literals" (IntSet.size lits)
forM_ (IntSet.toList lits) $ \lit -> SAT.addClause solver [lit]
modifyIORef unrelaxedRef (`IntSet.difference` lits)
modifyIORef relaxedRef (`IntSet.difference` lits)
modifyIORef hardenedRef (`IntSet.union` lits)
ub0 <- readIORef lastUBRef
when (ub < ub0) $ do
C.logMessage cxt $ printf "BCD2: updating upper bound: %d -> %d" ub0 ub
SAT.addPBAtMost solver obj ub
writeIORef lastUBRef ub
cores <- readIORef coresRef
unrelaxed <- readIORef unrelaxedRef
relaxed <- readIORef relaxedRef
hardened <- readIORef hardenedRef
nsat <- readIORef nsatRef
nunsat <- readIORef nunsatRef
C.logMessage cxt $ printf "BCD2: %d <= obj <= %d" lb ub
C.logMessage cxt $ printf "BCD2: #cores=%d, #unrelaxed=%d, #relaxed=%d, #hardened=%d"
(length cores) (IntSet.size unrelaxed) (IntSet.size relaxed) (IntSet.size hardened)
C.logMessage cxt $ printf "BCD2: #sat=%d #unsat=%d bias=%d/%d" nsat nunsat nunsat (nunsat + nsat)
lastModel <- atomically $ C.getBestModel cxt
sels <- liftM IntMap.fromList $ forM cores $ \core -> do
coreLB <- getCoreLB core
let coreUB = SAT.pbLinUpperBound (coreCostFun core)
if coreUB < coreLB then do
C.logMessage cxt $ printf "BCD2: coreLB (%d) exceeds coreUB (%d)" coreLB coreUB
SAT.addClause solver []
sel <- getCoreUBAssumption core coreUB
return (sel, (core, coreUB))
else do
let estimated =
case lastModel of
Nothing -> coreUB
Just m ->
it 's possible that @coreLB@ is larger than @SAT.evalPBLinSum m ( coreCostFun core)@.
coreLB `max` SAT.evalPBLinSum m (coreCostFun core)
mid =
if optEnableBiasedSearch opt
then coreLB + (estimated - coreLB) * nunsat `div` (nunsat + nsat)
else (coreLB + estimated) `div` 2
sel <- getCoreUBAssumption core mid
return (sel, (core,mid))
ret <- SAT.solveWith solver (IntMap.keys sels ++ IntSet.toList unrelaxed)
if ret then do
modifyIORef' nsatRef (+1)
C.addSolution cxt =<< SAT.getModel solver
loop
else do
modifyIORef' nunsatRef (+1)
failed <- SAT.getFailedAssumptions solver
case IntSet.toList failed of
[] -> C.setFinished cxt
[sel] | Just (core,mid) <- IntMap.lookup sel sels -> do
C.logMessage cxt $ printf "BCD2: updating lower bound of a core"
let newCoreLB = mid + 1
newCoreLB' = refineLB (IntMap.elems (IntMap.restrictKeys weights (coreLits core))) newCoreLB
when (newCoreLB /= newCoreLB') $ C.logMessage cxt $
printf "BCD2: refineLB: %d -> %d" newCoreLB newCoreLB'
writeIORef (coreLBRef core) newCoreLB'
updateLB lb core
loop
_ -> do
let torelax = unrelaxed `IntSet.intersection` failed
intersected = IntMap.elems (IntMap.restrictKeys sels failed)
disjoint = [core | (sel,(core,_)) <- IntMap.toList (IntMap.withoutKeys sels failed)]
modifyIORef unrelaxedRef (`IntSet.difference` torelax)
modifyIORef relaxedRef (`IntSet.union` torelax)
delta <- do
xs1 <- forM intersected $ \(core,mid) -> do
coreLB <- getCoreLB core
return $ mid - coreLB + 1
let xs2 = [weights IntMap.! lit | lit <- IntSet.toList torelax]
return $! minimum (xs1 ++ xs2)
let mergedCoreLits = IntSet.unions $ torelax : [coreLits core | (core,_) <- intersected]
mergedCoreLB <- liftM ((delta +) . sum) $ mapM (getCoreLB . fst) intersected
let mergedCoreLB' = refineLB (IntMap.elems (IntMap.restrictKeys weights mergedCoreLits)) mergedCoreLB
mergedCore <- newCoreInfo mergedCoreLits mergedCoreLB'
writeIORef coresRef (mergedCore : disjoint)
forM_ intersected $ \(core, _) -> deleteCoreInfo solver core
if null intersected then
C.logMessage cxt $ printf "BCD2: found a new core of size %d: cost of the new core is >=%d"
(IntSet.size torelax) mergedCoreLB'
else
C.logMessage cxt $ printf "BCD2: relaxing %d and merging with %d cores into a new core of size %d: cost of the new core is >=%d"
(IntSet.size torelax) (length intersected) (IntSet.size mergedCoreLits) mergedCoreLB'
when (mergedCoreLB /= mergedCoreLB') $
C.logMessage cxt $ printf "BCD2: refineLB: %d -> %d" mergedCoreLB mergedCoreLB'
updateLB lb mergedCore
loop
best <- atomically $ C.getBestModel cxt
case best of
Nothing | optSolvingNormalFirst opt -> do
ret <- SAT.solve solver
if ret then
C.addSolution cxt =<< SAT.getModel solver
else
C.setFinished cxt
_ -> return ()
loop
where
obj :: SAT.PBLinSum
obj = C.getObjectiveFunction cxt
sels :: [(SAT.Lit, Integer)]
sels = [(-lit, w) | (w,lit) <- obj]
weights :: SAT.LitMap Integer
weights = IntMap.fromList sels
coreCostFun :: CoreInfo -> SAT.PBLinSum
coreCostFun c = [(weights IntMap.! lit, -lit) | lit <- IntSet.toList (coreLits c)]
getCoreUBAssumption :: CoreInfo -> Integer -> IO SAT.Lit
getCoreUBAssumption core ub = do
m <- readIORef (coreUBSelectors core)
case Map.splitLookup ub m of
(_, Just sel, _) -> return sel
(lo, Nothing, hi) -> do
sel <- SAT.newVar solver
SAT.addPBAtMostSoft solver sel (coreCostFun core) ub
writeIORef (coreUBSelectors core) (Map.insert ub sel m)
unless (Map.null lo) $
snd ( Map.findMax ) → sel
unless (Map.null hi) $
return sel
| The smallest integer greater - than or equal - to @n@ that can be obtained by summing a subset of @ws@.
Note that the definition is different from the one in Morgado et al .
refineLB
-> Integer
refineLB ws n =
case SubsetSum.minSubsetSum (V.fromList ws) n of
Nothing -> sum [w | w <- ws, w > 0] + 1
Just (obj, _) -> obj
| The greatest integer lesser - than or equal - to @n@ that can be obtained by summing a subset of @ws@.
refineUB
-> Integer
refineUB ws n
| n < 0 = n
| otherwise =
case SubsetSum.maxSubsetSum (V.fromList ws) n of
Nothing -> sum [w | w <- ws, w < 0] - 1
Just (obj, _) -> obj
|
6a4d25c4e67f528a582d3e01376130e04bb3bf6a3d0abd8e3321c5c6c3381301 | mfp/ocaml-stomp | test_receive.ml | Copyright ( c ) 2009 >
open Arg
open Printf
open ExtString
open ExtList
module S = Mq_stomp_client.Make_generic(Mq_concurrency.Posix_thread)
let () = Random.self_init ()
let port = ref 61613
let address = ref "127.0.0.1"
let num_msgs = ref max_int
let login = ref None
let passcode = ref None
let dests = ref []
let use_nl_eof = ref false
let ack = ref false
let verbose = ref false
let readsubs = ref false
let durable = ref false
let headers = ref []
let prefetch = ref 0
let nthreads = ref 0
let msg = "Usage: test_receive [options]"
let set_some r x = r := Some x
let set_some_f f r x = r := Some (f x)
let args =
Arg.align
[
"-n", Set_int num_msgs, "N Receive N messages (default: unlimited)";
"-a", Set_string address, sprintf "ADDRESS Address (default: %s)" !address;
"-p", Set_int port, sprintf "PORT Port (default: %d)" !port;
"-s", String (fun s -> dests := s :: !dests), "NAME Subscribe to destination NAME.";
"--concurrency", Set_int nthreads, " Concurrency factor.";
"--prefetch", Set_int prefetch, " Prefetch (default: disabled)";
"--stdin", Set readsubs, " Read list of destinations to from stdin.";
"--ack", Set ack, " Send ACKs for received messages.";
"--durable", Set durable, " Create durable destinations in RabbitMQ.";
"--header", String (fun s -> headers := s :: !headers), " Use custom header in SUBSCRIBE.";
"--login", String (set_some login), "LOGIN Use the given login (default: none).";
"--passcode", String (set_some passcode), "PASSCODE Use the given passcode (default: none).";
"--newline", Set use_nl_eof, " Use \\0\\n to signal end of frame (default: no).";
"--verbose", Set verbose, " Verbose mode.";
]
let read_subs () =
let rec loop ls =
match try Some (read_line ()) with _ -> None with
None -> ls
| Some line -> loop (line :: ls)
in loop []
let () =
Arg.parse args ignore msg;
if !num_msgs <= 0 then begin
Arg.usage args msg;
exit 1;
end;
let cnt = ref 0 in
let t0 = ref (Unix.gettimeofday ()) in
let payload = ref 0 in
let print_rate () =
let dt = Unix.gettimeofday () -. !t0 in
printf "\n\nReceived %d messages in %.1fs (%8.1f/s)\n"
!cnt dt (float !cnt /. dt);
printf "Total payload %d KB (%d KB/s).\n" (!payload / 1024)
(truncate (float !payload /. 1024. /. dt));
exit 1 in
let subs = if !readsubs then !dests @ read_subs () else !dests in
let hs =
List.filter_map
(fun s -> try Some (String.split s ":") with _ -> None) !headers in
let hs =
if !durable then ["auto-delete", "false"; "durable", "true"] @ hs
else hs in
let hs = if !ack then ("ack", "client") :: hs else hs in
let hs = match !prefetch with
n when n > 0 -> ("prefetch", string_of_int n) :: hs
| _ -> hs in
let finish = ref false in
let run num_msgs =
let c = S.connect ?login:!login ?passcode:!passcode ~eof_nl:!use_nl_eof
(Unix.ADDR_INET (Unix.inet_addr_of_string !address, !port))
in
if !nthreads <= 1 then begin
printf "Subscribing to %d destination(s)... %!" (List.length subs);
if !verbose then printf "\n";
end;
List.iteri
(fun i dst ->
if !nthreads <= 1 && !verbose && i mod 10 = 0 then printf "%d \r%!" i;
S.subscribe ~headers:hs c dst)
subs;
if !nthreads <= 1 then printf "DONE \n%!";
(try
for i = 1 to num_msgs do
if !finish then raise Exit;
let msg = S.receive_msg c in
incr cnt;
payload := !payload + String.length msg.Mq.msg_body;
if !cnt = 1 then t0 := Unix.gettimeofday ();
if !ack then S.ack_msg c msg;
if !verbose && !cnt mod 11 = 0 then printf "%d \r%!" !cnt;
done;
S.disconnect c;
with Exit -> ())
in
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _ -> print_endline "SIGINT"; finish := true; print_rate ()));
begin match !nthreads with
n when n <= 1 -> run !num_msgs
| n ->
let ts = List.init n (fun _ -> Thread.create run (!num_msgs / n)) in
List.iter Thread.join ts
end;
print_rate ()
| null | https://raw.githubusercontent.com/mfp/ocaml-stomp/5dd4319af7212a0a82b1db8e373642d9d7891580/test_receive.ml | ocaml | Copyright ( c ) 2009 >
open Arg
open Printf
open ExtString
open ExtList
module S = Mq_stomp_client.Make_generic(Mq_concurrency.Posix_thread)
let () = Random.self_init ()
let port = ref 61613
let address = ref "127.0.0.1"
let num_msgs = ref max_int
let login = ref None
let passcode = ref None
let dests = ref []
let use_nl_eof = ref false
let ack = ref false
let verbose = ref false
let readsubs = ref false
let durable = ref false
let headers = ref []
let prefetch = ref 0
let nthreads = ref 0
let msg = "Usage: test_receive [options]"
let set_some r x = r := Some x
let set_some_f f r x = r := Some (f x)
let args =
Arg.align
[
"-n", Set_int num_msgs, "N Receive N messages (default: unlimited)";
"-a", Set_string address, sprintf "ADDRESS Address (default: %s)" !address;
"-p", Set_int port, sprintf "PORT Port (default: %d)" !port;
"-s", String (fun s -> dests := s :: !dests), "NAME Subscribe to destination NAME.";
"--concurrency", Set_int nthreads, " Concurrency factor.";
"--prefetch", Set_int prefetch, " Prefetch (default: disabled)";
"--stdin", Set readsubs, " Read list of destinations to from stdin.";
"--ack", Set ack, " Send ACKs for received messages.";
"--durable", Set durable, " Create durable destinations in RabbitMQ.";
"--header", String (fun s -> headers := s :: !headers), " Use custom header in SUBSCRIBE.";
"--login", String (set_some login), "LOGIN Use the given login (default: none).";
"--passcode", String (set_some passcode), "PASSCODE Use the given passcode (default: none).";
"--newline", Set use_nl_eof, " Use \\0\\n to signal end of frame (default: no).";
"--verbose", Set verbose, " Verbose mode.";
]
let read_subs () =
let rec loop ls =
match try Some (read_line ()) with _ -> None with
None -> ls
| Some line -> loop (line :: ls)
in loop []
let () =
Arg.parse args ignore msg;
if !num_msgs <= 0 then begin
Arg.usage args msg;
exit 1;
end;
let cnt = ref 0 in
let t0 = ref (Unix.gettimeofday ()) in
let payload = ref 0 in
let print_rate () =
let dt = Unix.gettimeofday () -. !t0 in
printf "\n\nReceived %d messages in %.1fs (%8.1f/s)\n"
!cnt dt (float !cnt /. dt);
printf "Total payload %d KB (%d KB/s).\n" (!payload / 1024)
(truncate (float !payload /. 1024. /. dt));
exit 1 in
let subs = if !readsubs then !dests @ read_subs () else !dests in
let hs =
List.filter_map
(fun s -> try Some (String.split s ":") with _ -> None) !headers in
let hs =
if !durable then ["auto-delete", "false"; "durable", "true"] @ hs
else hs in
let hs = if !ack then ("ack", "client") :: hs else hs in
let hs = match !prefetch with
n when n > 0 -> ("prefetch", string_of_int n) :: hs
| _ -> hs in
let finish = ref false in
let run num_msgs =
let c = S.connect ?login:!login ?passcode:!passcode ~eof_nl:!use_nl_eof
(Unix.ADDR_INET (Unix.inet_addr_of_string !address, !port))
in
if !nthreads <= 1 then begin
printf "Subscribing to %d destination(s)... %!" (List.length subs);
if !verbose then printf "\n";
end;
List.iteri
(fun i dst ->
if !nthreads <= 1 && !verbose && i mod 10 = 0 then printf "%d \r%!" i;
S.subscribe ~headers:hs c dst)
subs;
if !nthreads <= 1 then printf "DONE \n%!";
(try
for i = 1 to num_msgs do
if !finish then raise Exit;
let msg = S.receive_msg c in
incr cnt;
payload := !payload + String.length msg.Mq.msg_body;
if !cnt = 1 then t0 := Unix.gettimeofday ();
if !ack then S.ack_msg c msg;
if !verbose && !cnt mod 11 = 0 then printf "%d \r%!" !cnt;
done;
S.disconnect c;
with Exit -> ())
in
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _ -> print_endline "SIGINT"; finish := true; print_rate ()));
begin match !nthreads with
n when n <= 1 -> run !num_msgs
| n ->
let ts = List.init n (fun _ -> Thread.create run (!num_msgs / n)) in
List.iter Thread.join ts
end;
print_rate ()
|
|
21428e9ac21cb6cf065049ff7472c16228d5cd36dca337df9857207e6f9d13c0 | aaronc/fx-clj | i18n.clj | (ns fx-clj.i18n
(:require [fx-clj.core :as fx]))
(defn make-hello []
(fx/with-resource-bundle
"TestResources"
(fx/text "%hello")))
(defn make-view []
(fx/v-box
(fx/text "Default:")
(make-hello)
(fx/text "In Spanish:")
(fx/with-locale
"es"
(make-hello))))
(fx/sandbox #'make-view)
| null | https://raw.githubusercontent.com/aaronc/fx-clj/29639356d8d1253438ecf61e123caacefa9269ec/test/fx_clj/i18n.clj | clojure | (ns fx-clj.i18n
(:require [fx-clj.core :as fx]))
(defn make-hello []
(fx/with-resource-bundle
"TestResources"
(fx/text "%hello")))
(defn make-view []
(fx/v-box
(fx/text "Default:")
(make-hello)
(fx/text "In Spanish:")
(fx/with-locale
"es"
(make-hello))))
(fx/sandbox #'make-view)
|
|
a7d5c99be39d955b6e5e7d04f52ef0b38227bb48665696ded31f7c4e17155c6f | ymilky/franzy-admin | topics.clj | (ns franzy.admin.topics
(:require [franzy.admin.codec :as codec]
[franzy.common.configuration.codec :as config-codec])
(:import (kafka.utils ZkUtils)
(kafka.admin AdminUtils)
(scala.collection Set)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reading Topics
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn topic-exists? [^ZkUtils zk-utils ^String topic]
"Checks to see if a particular topic exists, by topic name."
(AdminUtils/topicExists zk-utils topic))
(defn all-topics
"Returns a lazy sequence of all Kafka topics visible in the current connection."
[^ZkUtils zk-utils]
(->> (.getAllTopics zk-utils)
(codec/decode)))
(defn topics-by-consumer-group
"Returns all the topics for a particular consumer group name."
[^ZkUtils zk-utils ^String group]
(->> (.getTopicsByConsumerGroup zk-utils group)
(codec/decode)))
(defn topics-metadata
[^ZkUtils zk-utils topics]
"Returns a list of topic metadata from Zookeeper, given one or more topics as a set or string."
(some->
(cond
(set? topics)
topics
;;because people don't list....maybe remove
(sequential? topics)
(into #{} topics)
(string? topics)
#{topics}
:else (throw (ex-info "Topics must be a set, sequential collection, or a string." {:topics topics})))
^Set (codec/encode)
(AdminUtils/fetchTopicMetadataFromZk zk-utils)
(codec/decode)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Writing to Topics
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-topic!
"Creates a topic with a given name, number of partitions, replication factor, and optional topic configuration.
Topic configuration should be specified by a Clojure map, example: {\"cleanup.policy\" \"compact\"},
which will be converted to Java Properties, or alternatively via Java Properties directly.
If no replication factor is provided, a replication factor of 1 is assumed.
If the topic already exists in Zookeeper, a TopicExistsException will be thrown,
If the topic otherwise collides with an existing topic, an InvalidTopicException will be thrown.
Note: It may take some time for a topic and its partitions to propogate and the client isn't notified and doesn't block waiting for this automatically.
Be careful if auditing the topic and its partitions before this happens.
Inconsistent ZK state may interfere with queries that pull from related Zookeeper nodes. Typically You will receive a NoNodeException in these cases.
If your application requires constant polling of admin state, either try to block until the operation completes and/or check the associated Zookeeper nodes manually using a Zookeeper client."
([^ZkUtils zk-utils ^String topic partitions]
(create-topic! zk-utils topic partitions 1 nil))
([^ZkUtils zk-utils ^String topic partitions replication-factor]
(create-topic! zk-utils topic partitions replication-factor nil))
([^ZkUtils zk-utils ^String topic partitions replication-factor topic-config]
(->> (or topic-config {})
(config-codec/encode)
(AdminUtils/createTopic zk-utils topic (int partitions) (int (or replication-factor 1))))))
(defn delete-topic!
"Marks a topic for deletion.
After a topic has been marked for deletion, it will no longer accept requests to produce or consume.
Note that this does not mean the topic will be deleted immediately. If for example you check if the topic exists, it may still return true.
If the topic has already been marked for deletion in Zookeeper, a TopicAlreadyMarkedForDeletionException will be thrown.
If another error occurs, an AdminOperationException will be thrown."
[^ZkUtils zk-utils ^String topic]
(AdminUtils/deleteTopic zk-utils topic))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Replicas
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn topic-replica-assignments
"Returns the assigned replicas for a given list of topics.
Returns a vector of maps where the key is the topic partition and the values are a vector of assigned replica IDs.
Example:
`{{:topic \"cheeses\", :partition 0} [1001], {:topic \"gigantic-cheeses\", :partition 0} [1001]}`"
[^ZkUtils zk-utils topics]
(->>
(codec/encode topics)
(.getReplicaAssignmentForTopics zk-utils)
(codec/decode)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Zookeeper
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn delete-topics-path []
"Returns the Zookeeper path used to delete topics."
(ZkUtils/DeleteTopicsPath))
(defn delete-topic-path [^String topic]
"Returns the Zookeeper path used to delete a topic."
(ZkUtils/getDeleteTopicPath topic))
(defn topic-path [^String topic]
"Returns the path in Zookeeper to a given topic."
(ZkUtils/getTopicPath topic))
| null | https://raw.githubusercontent.com/ymilky/franzy-admin/94588c5ce1b50f4a61b2fb4a4ec4d47568b83287/src/franzy/admin/topics.clj | clojure |
Reading Topics
because people don't list....maybe remove
Writing to Topics
Zookeeper
| (ns franzy.admin.topics
(:require [franzy.admin.codec :as codec]
[franzy.common.configuration.codec :as config-codec])
(:import (kafka.utils ZkUtils)
(kafka.admin AdminUtils)
(scala.collection Set)))
(defn topic-exists? [^ZkUtils zk-utils ^String topic]
"Checks to see if a particular topic exists, by topic name."
(AdminUtils/topicExists zk-utils topic))
(defn all-topics
"Returns a lazy sequence of all Kafka topics visible in the current connection."
[^ZkUtils zk-utils]
(->> (.getAllTopics zk-utils)
(codec/decode)))
(defn topics-by-consumer-group
"Returns all the topics for a particular consumer group name."
[^ZkUtils zk-utils ^String group]
(->> (.getTopicsByConsumerGroup zk-utils group)
(codec/decode)))
(defn topics-metadata
[^ZkUtils zk-utils topics]
"Returns a list of topic metadata from Zookeeper, given one or more topics as a set or string."
(some->
(cond
(set? topics)
topics
(sequential? topics)
(into #{} topics)
(string? topics)
#{topics}
:else (throw (ex-info "Topics must be a set, sequential collection, or a string." {:topics topics})))
^Set (codec/encode)
(AdminUtils/fetchTopicMetadataFromZk zk-utils)
(codec/decode)))
(defn create-topic!
"Creates a topic with a given name, number of partitions, replication factor, and optional topic configuration.
Topic configuration should be specified by a Clojure map, example: {\"cleanup.policy\" \"compact\"},
which will be converted to Java Properties, or alternatively via Java Properties directly.
If no replication factor is provided, a replication factor of 1 is assumed.
If the topic already exists in Zookeeper, a TopicExistsException will be thrown,
If the topic otherwise collides with an existing topic, an InvalidTopicException will be thrown.
Note: It may take some time for a topic and its partitions to propogate and the client isn't notified and doesn't block waiting for this automatically.
Be careful if auditing the topic and its partitions before this happens.
Inconsistent ZK state may interfere with queries that pull from related Zookeeper nodes. Typically You will receive a NoNodeException in these cases.
If your application requires constant polling of admin state, either try to block until the operation completes and/or check the associated Zookeeper nodes manually using a Zookeeper client."
([^ZkUtils zk-utils ^String topic partitions]
(create-topic! zk-utils topic partitions 1 nil))
([^ZkUtils zk-utils ^String topic partitions replication-factor]
(create-topic! zk-utils topic partitions replication-factor nil))
([^ZkUtils zk-utils ^String topic partitions replication-factor topic-config]
(->> (or topic-config {})
(config-codec/encode)
(AdminUtils/createTopic zk-utils topic (int partitions) (int (or replication-factor 1))))))
(defn delete-topic!
"Marks a topic for deletion.
After a topic has been marked for deletion, it will no longer accept requests to produce or consume.
Note that this does not mean the topic will be deleted immediately. If for example you check if the topic exists, it may still return true.
If the topic has already been marked for deletion in Zookeeper, a TopicAlreadyMarkedForDeletionException will be thrown.
If another error occurs, an AdminOperationException will be thrown."
[^ZkUtils zk-utils ^String topic]
(AdminUtils/deleteTopic zk-utils topic))
Replicas
(defn topic-replica-assignments
"Returns the assigned replicas for a given list of topics.
Returns a vector of maps where the key is the topic partition and the values are a vector of assigned replica IDs.
Example:
`{{:topic \"cheeses\", :partition 0} [1001], {:topic \"gigantic-cheeses\", :partition 0} [1001]}`"
[^ZkUtils zk-utils topics]
(->>
(codec/encode topics)
(.getReplicaAssignmentForTopics zk-utils)
(codec/decode)))
(defn delete-topics-path []
"Returns the Zookeeper path used to delete topics."
(ZkUtils/DeleteTopicsPath))
(defn delete-topic-path [^String topic]
"Returns the Zookeeper path used to delete a topic."
(ZkUtils/getDeleteTopicPath topic))
(defn topic-path [^String topic]
"Returns the path in Zookeeper to a given topic."
(ZkUtils/getTopicPath topic))
|
c2e4ffc6d7d888160f0eee6e250a428cae1e74685106ee9f5703c832a3a4234f | jackfirth/rebellion | sorted-set.rkt | #lang racket/base
(require racket/contract/base)
(provide
(all-from-out rebellion/collection/private/mutable-sorted-set)
(all-from-out rebellion/collection/private/regular-immutable-sorted-set)
(all-from-out rebellion/collection/private/sorted-set-builder)
(all-from-out rebellion/collection/private/sorted-set-interface)
(all-from-out rebellion/collection/private/synchronized-sorted-set)
(all-from-out rebellion/collection/private/unmodifiable-sorted-set)
(contract-out
[sorted-set (-> #:comparator comparator? any/c ... immutable-sorted-set?)]
[sequence->sorted-set (-> (sequence/c any/c) #:comparator comparator? immutable-sorted-set?)]
[into-sorted-set (-> comparator? (reducer/c any/c immutable-sorted-set?))]))
(require racket/sequence
rebellion/base/comparator
rebellion/collection/private/mutable-sorted-set
rebellion/collection/private/regular-immutable-sorted-set
(submod rebellion/collection/private/regular-immutable-sorted-set private-for-rebellion-only)
rebellion/collection/private/sorted-set-interface
rebellion/collection/private/sorted-set-builder
rebellion/collection/private/synchronized-sorted-set
rebellion/collection/private/unmodifiable-sorted-set
rebellion/private/guarded-block
rebellion/private/static-name
rebellion/streaming/reducer
rebellion/streaming/transducer)
;@----------------------------------------------------------------------------------------------------
(define (sorted-set #:comparator comparator . elements)
(sequence->sorted-set elements #:comparator comparator))
(define/guard (sequence->sorted-set elements #:comparator comparator)
;; We only avoid copying if the input is a regular-immutable-sorted-set? instead of any
;; immutable-sorted-set? because the latter includes subset views. A subset view could be a tiny
;; portion of a much larger backing set, and there's a soft expectation that copying a sequence into
;; an immutable collection retains space linear in the size of the returned collection.
(guard (and (regular-immutable-sorted-set? elements)
(equal? (sorted-set-comparator elements) comparator)) then
elements)
(transduce elements #:into (into-sorted-set comparator)))
(define (into-sorted-set comparator)
(make-effectful-fold-reducer
sorted-set-builder-add
(λ () (make-sorted-set-builder comparator))
build-sorted-set
#:name (name into-sorted-set)))
| null | https://raw.githubusercontent.com/jackfirth/rebellion/ca733d034e90234c1aba599251aa238fed2fffa9/collection/sorted-set.rkt | racket | @----------------------------------------------------------------------------------------------------
We only avoid copying if the input is a regular-immutable-sorted-set? instead of any
immutable-sorted-set? because the latter includes subset views. A subset view could be a tiny
portion of a much larger backing set, and there's a soft expectation that copying a sequence into
an immutable collection retains space linear in the size of the returned collection. | #lang racket/base
(require racket/contract/base)
(provide
(all-from-out rebellion/collection/private/mutable-sorted-set)
(all-from-out rebellion/collection/private/regular-immutable-sorted-set)
(all-from-out rebellion/collection/private/sorted-set-builder)
(all-from-out rebellion/collection/private/sorted-set-interface)
(all-from-out rebellion/collection/private/synchronized-sorted-set)
(all-from-out rebellion/collection/private/unmodifiable-sorted-set)
(contract-out
[sorted-set (-> #:comparator comparator? any/c ... immutable-sorted-set?)]
[sequence->sorted-set (-> (sequence/c any/c) #:comparator comparator? immutable-sorted-set?)]
[into-sorted-set (-> comparator? (reducer/c any/c immutable-sorted-set?))]))
(require racket/sequence
rebellion/base/comparator
rebellion/collection/private/mutable-sorted-set
rebellion/collection/private/regular-immutable-sorted-set
(submod rebellion/collection/private/regular-immutable-sorted-set private-for-rebellion-only)
rebellion/collection/private/sorted-set-interface
rebellion/collection/private/sorted-set-builder
rebellion/collection/private/synchronized-sorted-set
rebellion/collection/private/unmodifiable-sorted-set
rebellion/private/guarded-block
rebellion/private/static-name
rebellion/streaming/reducer
rebellion/streaming/transducer)
(define (sorted-set #:comparator comparator . elements)
(sequence->sorted-set elements #:comparator comparator))
(define/guard (sequence->sorted-set elements #:comparator comparator)
(guard (and (regular-immutable-sorted-set? elements)
(equal? (sorted-set-comparator elements) comparator)) then
elements)
(transduce elements #:into (into-sorted-set comparator)))
(define (into-sorted-set comparator)
(make-effectful-fold-reducer
sorted-set-builder-add
(λ () (make-sorted-set-builder comparator))
build-sorted-set
#:name (name into-sorted-set)))
|
20e47bbd65f772d82df2b765738a1512c0c5907c94c06e2f75658dc6722429e4 | snoyberg/haskellers | api-test.hs | {-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Enumerator
import qualified Data.ByteString.Lazy as L
mkReq p = Request
{ method = "GET"
, secure = False
, host = "localhost"
, port = 3000
, path = p
, queryString = []
, requestHeaders = [("Accept", "application/json")]
, requestBody = L.empty
}
main = do
httpLbsRedirect (mkReq "/") >>= (L.putStrLn . responseBody)
httpLbsRedirect (mkReq "/user/5/") >>= (L.putStrLn . responseBody)
httpLbsRedirect (mkReq "/user/")
{ queryString = [("ident", "")]
} >>= (L.putStrLn . responseBody)
| null | https://raw.githubusercontent.com/snoyberg/haskellers/ff152a73902f0e0e55615c83cfc5e888d052f1e3/src/api-test.hs | haskell | # LANGUAGE OverloadedStrings # | import Network.HTTP.Enumerator
import qualified Data.ByteString.Lazy as L
mkReq p = Request
{ method = "GET"
, secure = False
, host = "localhost"
, port = 3000
, path = p
, queryString = []
, requestHeaders = [("Accept", "application/json")]
, requestBody = L.empty
}
main = do
httpLbsRedirect (mkReq "/") >>= (L.putStrLn . responseBody)
httpLbsRedirect (mkReq "/user/5/") >>= (L.putStrLn . responseBody)
httpLbsRedirect (mkReq "/user/")
{ queryString = [("ident", "")]
} >>= (L.putStrLn . responseBody)
|
a16bf93139d08afd23945856da18692b2776848c4335101a36378813d4b8634d | melisgl/mgl-mat | package.lisp | (mgl-pax:define-package :mgl-cube
(:documentation "See MGL-CUBE:@CUBE-MANUAL.")
(:use #:common-lisp #:mgl-pax))
(mgl-pax:define-package :mgl-mat
(:documentation "See MGL-MAT:@MAT-MANUAL.")
(:use #:common-lisp #:mgl-pax #:mgl-cube #:cl-cuda)
(:import-from #:static-vectors #:static-vector #:static-vector-pointer))
| null | https://raw.githubusercontent.com/melisgl/mgl-mat/550369aaac5aeafe563b6dc8e3cc6bf4b74a1cc5/src/package.lisp | lisp | (mgl-pax:define-package :mgl-cube
(:documentation "See MGL-CUBE:@CUBE-MANUAL.")
(:use #:common-lisp #:mgl-pax))
(mgl-pax:define-package :mgl-mat
(:documentation "See MGL-MAT:@MAT-MANUAL.")
(:use #:common-lisp #:mgl-pax #:mgl-cube #:cl-cuda)
(:import-from #:static-vectors #:static-vector #:static-vector-pointer))
|
|
38b8b66f6fbd8530af270c2d92e345a7fafb4497b683bb9ff5e311946d0b3313 | makemeunsee/ichimiginikarasu | XmlHelper.hs | module XmlHelper (XmlNode, deepAssertions, children, deepGetChildren, unsafeText, attrFilter, noAttrFilter, debugHead) where
import Text.XML.Expat.Tree
import Text.XML.Expat.Proc
import Data.Text (Text)
type XmlNode = NodeG [] Text Text
children :: Text -> XmlNode -> [XmlNode]
children name = childFilter ((== name) . getName)
-- find all nested nodes matching the 'address' (tag hierarchy)
deepGetChildren :: [Text] -> XmlNode -> [XmlNode]
deepGetChildren address node = deepGetChildren' address [node]
deepGetChildren' :: [Text] -> [XmlNode] -> [XmlNode]
deepGetChildren' (name : names) nodes = deepGetChildren' names $ concatMap (children name) nodes
deepGetChildren' _ nodes = nodes
unsafeText :: XmlNode -> Text
unsafeText n = (getText . debugHead (show n) . filter isText . getChildren) n
noAttrFilter :: Text -> XmlNode -> Bool
noAttrFilter attrName = all ((/= attrName) . fst) . getAttributes
attrFilter :: Text -> Text -> XmlNode -> Bool
attrFilter attrName attrValue = elem (attrName, attrValue) . getAttributes
childFilter :: (XmlNode -> Bool) -> XmlNode -> [XmlNode]
childFilter childPredicate node = filter childPredicate $ getChildren node
-- assert node has at least a child matching each (address, text) requirement of the list
deepAssertions :: [([Text], Text)] -> XmlNode -> Bool
deepAssertions [] _ = True
deepAssertions ((address, value):rs) node = truth1 && truth2
where
truth1 = any (hasText value) $ deepGetChildren address node
truth2 = deepAssertions rs node
hasText :: Text -> XmlNode -> Bool
hasText text = elem text . fmap getText . filter isText . getChildren
debugHead :: String -> [a] -> a
debugHead text [] = error text
debugHead _ l = head l
| null | https://raw.githubusercontent.com/makemeunsee/ichimiginikarasu/b7959d77301533f6ff07b554d60c0816f616eaf9/src/XmlHelper.hs | haskell | find all nested nodes matching the 'address' (tag hierarchy)
assert node has at least a child matching each (address, text) requirement of the list | module XmlHelper (XmlNode, deepAssertions, children, deepGetChildren, unsafeText, attrFilter, noAttrFilter, debugHead) where
import Text.XML.Expat.Tree
import Text.XML.Expat.Proc
import Data.Text (Text)
type XmlNode = NodeG [] Text Text
children :: Text -> XmlNode -> [XmlNode]
children name = childFilter ((== name) . getName)
deepGetChildren :: [Text] -> XmlNode -> [XmlNode]
deepGetChildren address node = deepGetChildren' address [node]
deepGetChildren' :: [Text] -> [XmlNode] -> [XmlNode]
deepGetChildren' (name : names) nodes = deepGetChildren' names $ concatMap (children name) nodes
deepGetChildren' _ nodes = nodes
unsafeText :: XmlNode -> Text
unsafeText n = (getText . debugHead (show n) . filter isText . getChildren) n
noAttrFilter :: Text -> XmlNode -> Bool
noAttrFilter attrName = all ((/= attrName) . fst) . getAttributes
attrFilter :: Text -> Text -> XmlNode -> Bool
attrFilter attrName attrValue = elem (attrName, attrValue) . getAttributes
childFilter :: (XmlNode -> Bool) -> XmlNode -> [XmlNode]
childFilter childPredicate node = filter childPredicate $ getChildren node
deepAssertions :: [([Text], Text)] -> XmlNode -> Bool
deepAssertions [] _ = True
deepAssertions ((address, value):rs) node = truth1 && truth2
where
truth1 = any (hasText value) $ deepGetChildren address node
truth2 = deepAssertions rs node
hasText :: Text -> XmlNode -> Bool
hasText text = elem text . fmap getText . filter isText . getChildren
debugHead :: String -> [a] -> a
debugHead text [] = error text
debugHead _ l = head l
|
dfe04a2341dd79b0e322fb034192fff57c87637da429da13404612e6f63230da | hellonico/origami-fun | kalman.clj | (ns opencv4.video.kalman
(:require [opencv4.core :refer :all])
(:require [opencv4.utils :as u])
(:import
[org.opencv.core Mat Core CvType]
[org.opencv.videoio Videoio VideoCapture]
[org.opencv.video Video KalmanFilter]))
-a-kalman-filter-works-in-pictures/
; -kalman-filter-in-opencv-java
; init kalman
(def kalman (KalmanFilter. 4 2 0 CV_32F))
(def transition-matrix (new-mat 4 4 CV_32F))
(.put transition-matrix 0 0
(float-array [1 0 1 0
0 1 0 1
0 0 1 0
0 0 0 1]))
(.set_transitionMatrix kalman transition-matrix)
(def measure-matrix (new-mat 2 1 CV_32F))
(.setTo measure-matrix (new-scalar 0.0))
(.set_measurementMatrix kalman measure-matrix)
(def statePre (new-mat 4 1 CV_32F))
(.put statePre 0 0 (float-array [300 200 0 0]))
(.set_statePre kalman statePre)
(def process-noise-cov (new-mat 4 4 CV_32F))
(.setTo process-noise-cov (new-scalar 1.0))
(.mul process-noise-cov process-noise-cov 1e-1)
(.set_processNoiseCov kalman process-noise-cov)
(def measure-noise-cov (new-mat 4 4 CV_32F))
(.setTo measure-noise-cov (new-scalar 1.0))
(.mul measure-noise-cov measure-noise-cov 1e-1)
(.set_measurementNoiseCov kalman measure-noise-cov)
(def error-cov (new-mat 4 4 CV_32F))
(.setTo error-cov (new-scalar 1.0))
(.mul error-cov error-cov 0.1)
(.set_errorCovPost kalman error-cov)
; -Target-Tracking-with-OpenCV/blob/e1ceb8b716984d105de7d375a70ba7a937f27a82/src/sonkd/Kalman.java
; EASIER TO UNDERSTAND
; -filter-implementation-tracking.html
| null | https://raw.githubusercontent.com/hellonico/origami-fun/80117788530d942eaa9a80e2995b37409fa24889/test/opencv4/video/kalman.clj | clojure | -kalman-filter-in-opencv-java
init kalman
-Target-Tracking-with-OpenCV/blob/e1ceb8b716984d105de7d375a70ba7a937f27a82/src/sonkd/Kalman.java
EASIER TO UNDERSTAND
-filter-implementation-tracking.html | (ns opencv4.video.kalman
(:require [opencv4.core :refer :all])
(:require [opencv4.utils :as u])
(:import
[org.opencv.core Mat Core CvType]
[org.opencv.videoio Videoio VideoCapture]
[org.opencv.video Video KalmanFilter]))
-a-kalman-filter-works-in-pictures/
(def kalman (KalmanFilter. 4 2 0 CV_32F))
(def transition-matrix (new-mat 4 4 CV_32F))
(.put transition-matrix 0 0
(float-array [1 0 1 0
0 1 0 1
0 0 1 0
0 0 0 1]))
(.set_transitionMatrix kalman transition-matrix)
(def measure-matrix (new-mat 2 1 CV_32F))
(.setTo measure-matrix (new-scalar 0.0))
(.set_measurementMatrix kalman measure-matrix)
(def statePre (new-mat 4 1 CV_32F))
(.put statePre 0 0 (float-array [300 200 0 0]))
(.set_statePre kalman statePre)
(def process-noise-cov (new-mat 4 4 CV_32F))
(.setTo process-noise-cov (new-scalar 1.0))
(.mul process-noise-cov process-noise-cov 1e-1)
(.set_processNoiseCov kalman process-noise-cov)
(def measure-noise-cov (new-mat 4 4 CV_32F))
(.setTo measure-noise-cov (new-scalar 1.0))
(.mul measure-noise-cov measure-noise-cov 1e-1)
(.set_measurementNoiseCov kalman measure-noise-cov)
(def error-cov (new-mat 4 4 CV_32F))
(.setTo error-cov (new-scalar 1.0))
(.mul error-cov error-cov 0.1)
(.set_errorCovPost kalman error-cov)
|
ecf9ee12fc5e8f27c1523ec189996751c8e7dec7aa90e7a04bbc71e0ccc93690 | GillianPlatform/Gillian | ppx_sat.ml | open Ppxlib
let ext ext =
Extension.declare_with_path_arg
(Ppx_sat_expander.Extension_name.to_string ext)
Extension.Context.expression
Ast_pattern.(single_expr_payload __)
(fun ~loc:_ ~path:_ ~arg:_ expr -> Ppx_sat_expander.expand ~ext expr)
let () = Driver.register_transformation "sat" ~extensions:[ ext Sat; ext Ent ]
| null | https://raw.githubusercontent.com/GillianPlatform/Gillian/12f0d50bb3c407bfbce34cc5c08f5d60c71466be/ppx_sat/src/ppx_sat.ml | ocaml | open Ppxlib
let ext ext =
Extension.declare_with_path_arg
(Ppx_sat_expander.Extension_name.to_string ext)
Extension.Context.expression
Ast_pattern.(single_expr_payload __)
(fun ~loc:_ ~path:_ ~arg:_ expr -> Ppx_sat_expander.expand ~ext expr)
let () = Driver.register_transformation "sat" ~extensions:[ ext Sat; ext Ent ]
|
|
57f79d5e0f6f111914ffe2fb7e13ef96067ecd0715c3a6b17ec43e66da52b8e9 | RyanGlScott/text-show | FlagsSpec.hs | # LANGUAGE CPP #
|
Module : Spec . GHC.RTS.Flags
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ tests for ' ConType ' .
Module: Spec.GHC.RTS.Flags
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ tests for 'ConType'.
-}
module Spec.GHC.RTS.FlagsSpec (main, spec) where
import Prelude ()
import Prelude.Compat
import Test.Hspec (Spec, hspec, parallel)
#if MIN_VERSION_base(4,8,0)
import Data.Proxy.Compat (Proxy(..))
import GHC.RTS.Flags
import Instances.GHC.RTS.Flags
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (describe)
#endif
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
#if MIN_VERSION_base(4,8,0)
describe "RTSFlags" $
matchesTextShowSpec (Proxy :: Proxy RTSFlags)
describe "GCFlags" $
matchesTextShowSpec (Proxy :: Proxy GCFlags)
describe "ConcFlags" $
matchesTextShowSpec (Proxy :: Proxy ConcFlags)
# if MIN_VERSION_base(4,15,0)
describe "IoSubSystem" $
matchesTextShowSpec (Proxy :: Proxy IoSubSystem)
# endif
describe "MiscFlags" $
matchesTextShowSpec (Proxy :: Proxy MiscFlags)
describe "DebugFlags" $
matchesTextShowSpec (Proxy :: Proxy DebugFlags)
describe "CCFlags" $
matchesTextShowSpec (Proxy :: Proxy CCFlags)
describe "ProfFlags" $
matchesTextShowSpec (Proxy :: Proxy ProfFlags)
describe "TraceFlags" $
matchesTextShowSpec (Proxy :: Proxy TraceFlags)
describe "TickyFlags" $
matchesTextShowSpec (Proxy :: Proxy TickyFlags)
describe "GiveGCStats" $
matchesTextShowSpec (Proxy :: Proxy GiveGCStats')
describe "DoCostCentres" $
matchesTextShowSpec (Proxy :: Proxy DoCostCentres')
describe "DoHeapProfile" $
matchesTextShowSpec (Proxy :: Proxy DoHeapProfile')
describe "DoTrace" $
matchesTextShowSpec (Proxy :: Proxy DoTrace')
# if MIN_VERSION_base(4,10,0)
describe "ParFlags" $
matchesTextShowSpec (Proxy :: Proxy ParFlags)
# endif
#else
pure ()
#endif
| null | https://raw.githubusercontent.com/RyanGlScott/text-show/5ea297d0c7ae2d043f000c791cc12ac53f469944/tests/Spec/GHC/RTS/FlagsSpec.hs | haskell | # LANGUAGE CPP #
|
Module : Spec . GHC.RTS.Flags
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ tests for ' ConType ' .
Module: Spec.GHC.RTS.Flags
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ tests for 'ConType'.
-}
module Spec.GHC.RTS.FlagsSpec (main, spec) where
import Prelude ()
import Prelude.Compat
import Test.Hspec (Spec, hspec, parallel)
#if MIN_VERSION_base(4,8,0)
import Data.Proxy.Compat (Proxy(..))
import GHC.RTS.Flags
import Instances.GHC.RTS.Flags
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (describe)
#endif
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
#if MIN_VERSION_base(4,8,0)
describe "RTSFlags" $
matchesTextShowSpec (Proxy :: Proxy RTSFlags)
describe "GCFlags" $
matchesTextShowSpec (Proxy :: Proxy GCFlags)
describe "ConcFlags" $
matchesTextShowSpec (Proxy :: Proxy ConcFlags)
# if MIN_VERSION_base(4,15,0)
describe "IoSubSystem" $
matchesTextShowSpec (Proxy :: Proxy IoSubSystem)
# endif
describe "MiscFlags" $
matchesTextShowSpec (Proxy :: Proxy MiscFlags)
describe "DebugFlags" $
matchesTextShowSpec (Proxy :: Proxy DebugFlags)
describe "CCFlags" $
matchesTextShowSpec (Proxy :: Proxy CCFlags)
describe "ProfFlags" $
matchesTextShowSpec (Proxy :: Proxy ProfFlags)
describe "TraceFlags" $
matchesTextShowSpec (Proxy :: Proxy TraceFlags)
describe "TickyFlags" $
matchesTextShowSpec (Proxy :: Proxy TickyFlags)
describe "GiveGCStats" $
matchesTextShowSpec (Proxy :: Proxy GiveGCStats')
describe "DoCostCentres" $
matchesTextShowSpec (Proxy :: Proxy DoCostCentres')
describe "DoHeapProfile" $
matchesTextShowSpec (Proxy :: Proxy DoHeapProfile')
describe "DoTrace" $
matchesTextShowSpec (Proxy :: Proxy DoTrace')
# if MIN_VERSION_base(4,10,0)
describe "ParFlags" $
matchesTextShowSpec (Proxy :: Proxy ParFlags)
# endif
#else
pure ()
#endif
|
|
75743180455e0792fe053639b16917077894dd0554cf52e2bc9e397dbbf538a7 | circuithub/haskell-gerber | GraphicsState.hs | # language DeriveGeneric #
module Gerber.Evaluate.GraphicsState where
import Data.Monoid ( Dual, First, Last )
import Data.Monoid.Deletable ( Deletable )
import Data.Sequence (Seq)
import GHC.Generics ( Generic )
import Generics.Deriving.Monoid ( memptydefault, mappenddefault )
import Data.Text (Text)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Map.Strict as Map
import qualified Gerber.Command as Gerber
import qualified Gerber.DCodeNumber as Gerber
import qualified Gerber.Evaluate.Edge as Edge
import qualified Gerber.Evaluate.GraphicsState.ApertureEntry as Gerber
import qualified Gerber.Evaluate.GraphicsState.InterpolationMode as Gerber
import qualified Gerber.Evaluate.GraphicsState.StackStream as Gerber
import qualified Gerber.Format as Gerber
import qualified Gerber.MacroDefinition as MacroDefinition
import qualified Gerber.Mirroring as Gerber
import qualified Gerber.Padding as Gerber
import qualified Gerber.Polarity as Gerber
import qualified Gerber.StepRepeat as Gerber
import qualified Gerber.Unit as Gerber
data GraphicsState m = GraphicsState
{ coordinateSystem :: !( First ( Gerber.Padding, Gerber.Format, Gerber.Format ) )
, unit :: !( First Gerber.Unit )
, apertureDictionary :: !( IntMap.IntMap Gerber.ApertureEntry )
, macroDictionary :: !( Map.Map Text [MacroDefinition.Definition MacroDefinition.Modifier MacroDefinition.Modifier] )
, currentAperture :: !( Last Gerber.DCodeNumber )
, interpolationMode :: !( Last Gerber.InterpolationMode )
, currentPoint :: !( Last ( Float, Float ) )
, inRegion :: !( Last Bool )
, polarity :: !( Last Gerber.Polarity )
, currentContour :: !( Deletable ( First ( Float, Float ), Seq Edge.Edge ) )
, stepRepeat :: !( Deletable ( First Gerber.StepRepeat, Dual m ) )
, mirror :: !( Last Gerber.Mirroring )
, scale :: !( Last Float )
, rotate :: !( Last Float )
, blockApertureStack :: !( Gerber.StackStream Gerber.DCodeNumber Gerber.Command )
}
deriving ( Generic )
instance Monoid m => Semigroup ( GraphicsState m ) where
(<>) =
mappenddefault
instance Monoid m => Monoid ( GraphicsState m ) where
mempty =
memptydefault
initialGraphicsState :: Monoid m => GraphicsState m
initialGraphicsState =
mempty
{ polarity = pure Gerber.Dark
, currentPoint = pure ( 0, 0 )
}
| null | https://raw.githubusercontent.com/circuithub/haskell-gerber/aa986c2bc67c23f1495de98ee71377752fdb9a16/gerber/lib/Gerber/Evaluate/GraphicsState.hs | haskell | # language DeriveGeneric #
module Gerber.Evaluate.GraphicsState where
import Data.Monoid ( Dual, First, Last )
import Data.Monoid.Deletable ( Deletable )
import Data.Sequence (Seq)
import GHC.Generics ( Generic )
import Generics.Deriving.Monoid ( memptydefault, mappenddefault )
import Data.Text (Text)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Map.Strict as Map
import qualified Gerber.Command as Gerber
import qualified Gerber.DCodeNumber as Gerber
import qualified Gerber.Evaluate.Edge as Edge
import qualified Gerber.Evaluate.GraphicsState.ApertureEntry as Gerber
import qualified Gerber.Evaluate.GraphicsState.InterpolationMode as Gerber
import qualified Gerber.Evaluate.GraphicsState.StackStream as Gerber
import qualified Gerber.Format as Gerber
import qualified Gerber.MacroDefinition as MacroDefinition
import qualified Gerber.Mirroring as Gerber
import qualified Gerber.Padding as Gerber
import qualified Gerber.Polarity as Gerber
import qualified Gerber.StepRepeat as Gerber
import qualified Gerber.Unit as Gerber
data GraphicsState m = GraphicsState
{ coordinateSystem :: !( First ( Gerber.Padding, Gerber.Format, Gerber.Format ) )
, unit :: !( First Gerber.Unit )
, apertureDictionary :: !( IntMap.IntMap Gerber.ApertureEntry )
, macroDictionary :: !( Map.Map Text [MacroDefinition.Definition MacroDefinition.Modifier MacroDefinition.Modifier] )
, currentAperture :: !( Last Gerber.DCodeNumber )
, interpolationMode :: !( Last Gerber.InterpolationMode )
, currentPoint :: !( Last ( Float, Float ) )
, inRegion :: !( Last Bool )
, polarity :: !( Last Gerber.Polarity )
, currentContour :: !( Deletable ( First ( Float, Float ), Seq Edge.Edge ) )
, stepRepeat :: !( Deletable ( First Gerber.StepRepeat, Dual m ) )
, mirror :: !( Last Gerber.Mirroring )
, scale :: !( Last Float )
, rotate :: !( Last Float )
, blockApertureStack :: !( Gerber.StackStream Gerber.DCodeNumber Gerber.Command )
}
deriving ( Generic )
instance Monoid m => Semigroup ( GraphicsState m ) where
(<>) =
mappenddefault
instance Monoid m => Monoid ( GraphicsState m ) where
mempty =
memptydefault
initialGraphicsState :: Monoid m => GraphicsState m
initialGraphicsState =
mempty
{ polarity = pure Gerber.Dark
, currentPoint = pure ( 0, 0 )
}
|
|
5c320375f310debc7025652f5222b80a7bae03a3bf8ac38dcf0018751ae1edd4 | den1k/vimsical | redis_test.clj | (ns vimsical.backend.adapters.redis-test
(:require
[clojure.test :refer [deftest is use-fixtures]]
[vimsical.backend.adapters.redis.fixture :refer [*redis* redis]]
[taoensso.carmine :as car]))
(use-fixtures :each redis)
(deftest connection-test
(is *redis*))
(deftest read-write-test
(car/wcar redis (car/set :foo :bar))
(is (= "bar" (car/wcar redis (car/get :foo)))))
(deftest flush-each-test
(is (nil? (car/wcar redis (car/get :foo)))))
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/test/backend/vimsical/backend/adapters/redis_test.clj | clojure | (ns vimsical.backend.adapters.redis-test
(:require
[clojure.test :refer [deftest is use-fixtures]]
[vimsical.backend.adapters.redis.fixture :refer [*redis* redis]]
[taoensso.carmine :as car]))
(use-fixtures :each redis)
(deftest connection-test
(is *redis*))
(deftest read-write-test
(car/wcar redis (car/set :foo :bar))
(is (= "bar" (car/wcar redis (car/get :foo)))))
(deftest flush-each-test
(is (nil? (car/wcar redis (car/get :foo)))))
|
|
a9271b27957be4a29f28cd1223d673887f29f789ec85f50f9ca9a59a6d38c66c | GillianPlatform/Gillian | parser_state.mli | val procs_with_no_paths : SS.t ref
val preds_with_no_paths : SS.t ref
val lemmas_with_no_paths : SS.t ref
val internal_file : bool ref
val reset : unit -> unit
| null | https://raw.githubusercontent.com/GillianPlatform/Gillian/1c8d65120c04ef87cda689a9d41268e25b5ffa7e/GillianCore/GIL_Parser/parser_state.mli | ocaml | val procs_with_no_paths : SS.t ref
val preds_with_no_paths : SS.t ref
val lemmas_with_no_paths : SS.t ref
val internal_file : bool ref
val reset : unit -> unit
|
|
62c46ada16d49696b67b4e02d789573c59a106f2ea1824d87a79e8d5602bb968 | mejgun/haskell-tdlib | SearchHashtags.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Query.SearchHashtags where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
-- |
Searches for recently used hashtags by their prefix @prefix Hashtag prefix to search for @limit The maximum number of hashtags to be returned
data SearchHashtags = SearchHashtags
{ -- |
limit :: Maybe Int,
-- |
prefix :: Maybe String
}
deriving (Eq)
instance Show SearchHashtags where
show
SearchHashtags
{ limit = limit_,
prefix = prefix_
} =
"SearchHashtags"
++ U.cc
[ U.p "limit" limit_,
U.p "prefix" prefix_
]
instance T.ToJSON SearchHashtags where
toJSON
SearchHashtags
{ limit = limit_,
prefix = prefix_
} =
A.object
[ "@type" A..= T.String "searchHashtags",
"limit" A..= limit_,
"prefix" A..= prefix_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/81516bd04c25c7371d4a9a5c972499791111c407/src/TD/Query/SearchHashtags.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
|
| |
module TD.Query.SearchHashtags where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
Searches for recently used hashtags by their prefix @prefix Hashtag prefix to search for @limit The maximum number of hashtags to be returned
data SearchHashtags = SearchHashtags
limit :: Maybe Int,
prefix :: Maybe String
}
deriving (Eq)
instance Show SearchHashtags where
show
SearchHashtags
{ limit = limit_,
prefix = prefix_
} =
"SearchHashtags"
++ U.cc
[ U.p "limit" limit_,
U.p "prefix" prefix_
]
instance T.ToJSON SearchHashtags where
toJSON
SearchHashtags
{ limit = limit_,
prefix = prefix_
} =
A.object
[ "@type" A..= T.String "searchHashtags",
"limit" A..= limit_,
"prefix" A..= prefix_
]
|
36fd8c080e15c8d7b052fa945dd09ff6b17a0cfc8baf9d0dc24378d9ad7a8bb3 | tolysz/prepare-ghcjs | IPI642.hs | -----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.GHC.IPI642
Copyright : ( c ) The University of Glasgow 2004
-- License : BSD3
--
-- Maintainer :
-- Portability : portable
--
module Distribution.Simple.GHC.IPI642 (
InstalledPackageInfo(..),
toCurrent,
) where
import qualified Distribution.InstalledPackageInfo as Current
import qualified Distribution.Package as Current hiding (installedUnitId)
import Distribution.Simple.GHC.IPIConvert
| This is the InstalledPackageInfo type used by ghc-6.4.2 and later .
--
-- It's here purely for the 'Read' instance so that we can read the package
database used by those ghc versions . It is a little hacky to read the
-- package db directly, but we do need the info and until ghc-6.9 there was
-- no better method.
--
In ghc-6.4.1 and before the format was slightly different .
-- See "Distribution.Simple.GHC.IPI642"
--
data InstalledPackageInfo = InstalledPackageInfo {
package :: PackageIdentifier,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
description :: String,
category :: String,
exposed :: Bool,
exposedModules :: [String],
hiddenModules :: [String],
importDirs :: [FilePath],
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries:: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [PackageIdentifier],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving Read
toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo
toCurrent ipi@InstalledPackageInfo{} =
let pid = convertPackageId (package ipi)
mkExposedModule m = Current.ExposedModule m Nothing
in Current.InstalledPackageInfo {
Current.sourcePackageId = pid,
Current.installedUnitId = Current.mkLegacyUnitId pid,
Current.compatPackageKey = "",
Current.abiHash = Current.AbiHash "", -- bogus but old GHCs don't care.
Current.license = convertLicense (license ipi),
Current.copyright = copyright ipi,
Current.maintainer = maintainer ipi,
Current.author = author ipi,
Current.stability = stability ipi,
Current.homepage = homepage ipi,
Current.pkgUrl = pkgUrl ipi,
Current.synopsis = "",
Current.description = description ipi,
Current.category = category ipi,
Current.exposed = exposed ipi,
Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi),
Current.hiddenModules = map convertModuleName (hiddenModules ipi),
Current.trusted = Current.trusted Current.emptyInstalledPackageInfo,
Current.importDirs = importDirs ipi,
Current.libraryDirs = libraryDirs ipi,
Current.libraryDynDirs = [],
Current.dataDir = "",
Current.hsLibraries = hsLibraries ipi,
Current.extraLibraries = extraLibraries ipi,
Current.extraGHCiLibraries = extraGHCiLibraries ipi,
Current.includeDirs = includeDirs ipi,
Current.includes = includes ipi,
Current.depends = map (Current.mkLegacyUnitId . convertPackageId) (depends ipi),
Current.ccOptions = ccOptions ipi,
Current.ldOptions = ldOptions ipi,
Current.frameworkDirs = frameworkDirs ipi,
Current.frameworks = frameworks ipi,
Current.haddockInterfaces = haddockInterfaces ipi,
Current.haddockHTMLs = haddockHTMLs ipi,
Current.pkgRoot = Nothing
}
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts/cabal/Cabal/Distribution/Simple/GHC/IPI642.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Simple.GHC.IPI642
License : BSD3
Maintainer :
Portability : portable
It's here purely for the 'Read' instance so that we can read the package
package db directly, but we do need the info and until ghc-6.9 there was
no better method.
See "Distribution.Simple.GHC.IPI642"
bogus but old GHCs don't care. | Copyright : ( c ) The University of Glasgow 2004
module Distribution.Simple.GHC.IPI642 (
InstalledPackageInfo(..),
toCurrent,
) where
import qualified Distribution.InstalledPackageInfo as Current
import qualified Distribution.Package as Current hiding (installedUnitId)
import Distribution.Simple.GHC.IPIConvert
| This is the InstalledPackageInfo type used by ghc-6.4.2 and later .
database used by those ghc versions . It is a little hacky to read the
In ghc-6.4.1 and before the format was slightly different .
data InstalledPackageInfo = InstalledPackageInfo {
package :: PackageIdentifier,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
description :: String,
category :: String,
exposed :: Bool,
exposedModules :: [String],
hiddenModules :: [String],
importDirs :: [FilePath],
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries:: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [PackageIdentifier],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving Read
toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo
toCurrent ipi@InstalledPackageInfo{} =
let pid = convertPackageId (package ipi)
mkExposedModule m = Current.ExposedModule m Nothing
in Current.InstalledPackageInfo {
Current.sourcePackageId = pid,
Current.installedUnitId = Current.mkLegacyUnitId pid,
Current.compatPackageKey = "",
Current.license = convertLicense (license ipi),
Current.copyright = copyright ipi,
Current.maintainer = maintainer ipi,
Current.author = author ipi,
Current.stability = stability ipi,
Current.homepage = homepage ipi,
Current.pkgUrl = pkgUrl ipi,
Current.synopsis = "",
Current.description = description ipi,
Current.category = category ipi,
Current.exposed = exposed ipi,
Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi),
Current.hiddenModules = map convertModuleName (hiddenModules ipi),
Current.trusted = Current.trusted Current.emptyInstalledPackageInfo,
Current.importDirs = importDirs ipi,
Current.libraryDirs = libraryDirs ipi,
Current.libraryDynDirs = [],
Current.dataDir = "",
Current.hsLibraries = hsLibraries ipi,
Current.extraLibraries = extraLibraries ipi,
Current.extraGHCiLibraries = extraGHCiLibraries ipi,
Current.includeDirs = includeDirs ipi,
Current.includes = includes ipi,
Current.depends = map (Current.mkLegacyUnitId . convertPackageId) (depends ipi),
Current.ccOptions = ccOptions ipi,
Current.ldOptions = ldOptions ipi,
Current.frameworkDirs = frameworkDirs ipi,
Current.frameworks = frameworks ipi,
Current.haddockInterfaces = haddockInterfaces ipi,
Current.haddockHTMLs = haddockHTMLs ipi,
Current.pkgRoot = Nothing
}
|
f9ba2a3ff680fa9eb35130337010e4fbc654fd924eda952e7b9a911928d89960 | lambdaisland/souk | webfinger.clj | (ns repl-sessions.webfinger
(:require
[cheshire.core :as json]
[clojure.string :as str]
[hato.client :as hato]
[lambdaisland.uri :as uri]))
;; all of these work
"acct:"
"/@plexus"
"/@plexus"
""
""
;; rel seems to be ignored
(defn fetch-webfinger [domain resource]
(-> (uri/uri "-known/webfinger")
(assoc :host domain)
(uri/assoc-query :resource resource)
str
(hato/get {:as :json})
:body))
(fetch-webfinger "toot.cat" "acct:")
{:subject "acct:",
:aliases ["/@plexus" ""],
:links
[{:rel "-page",
:type "text/html",
:href "/@plexus"}
{:rel "self",
:type "application/activity+json",
:href ""}
{:rel "",
:template "={uri}"}]}
| null | https://raw.githubusercontent.com/lambdaisland/souk/bf25b247d989358af9a1a00f294d4de2a9c2d59c/repl_sessions/webfinger.clj | clojure | all of these work
rel seems to be ignored | (ns repl-sessions.webfinger
(:require
[cheshire.core :as json]
[clojure.string :as str]
[hato.client :as hato]
[lambdaisland.uri :as uri]))
"acct:"
"/@plexus"
"/@plexus"
""
""
(defn fetch-webfinger [domain resource]
(-> (uri/uri "-known/webfinger")
(assoc :host domain)
(uri/assoc-query :resource resource)
str
(hato/get {:as :json})
:body))
(fetch-webfinger "toot.cat" "acct:")
{:subject "acct:",
:aliases ["/@plexus" ""],
:links
[{:rel "-page",
:type "text/html",
:href "/@plexus"}
{:rel "self",
:type "application/activity+json",
:href ""}
{:rel "",
:template "={uri}"}]}
|
4f1992c21d2b190ac98eac93d247560a80d3b78f99b2f74a29ffc939bfbc71dd | bhauman/advent-of-clojure | day10.clj | (ns advent-2017.day10
(:require
[clojure.string :as string]
[clojure.core.reducers :as r]))
(def data [102,255,99,252,200,24,219,57,103,2,226,254,1,0,69,216])
;; optimized for speed
(defn inplace-reverse [x pos length]
(let [idx (mapv #(mod % (count x))
(range pos (+ pos length)))
vs (r/reduce #(cons (get x %2) %1) '() idx)]
(persistent!
(loop [[id & idx'] idx
[v & vs'] vs
x (transient x)]
(if id
(recur idx' vs' (assoc! x id v))
x)))))
(defn transition [[x pos skip] length]
[(inplace-reverse x pos length)
(+ pos length skip)
(inc skip)])
(def hash-round #(r/reduce transition %2 %1))
part 1
#_ (->> (hash-round data [(vec (range 256)) 0 0])
first
(take 2)
(apply *))
= > 5577
(defn sparse-hash [data]
(first
(nth (iterate (partial hash-round (concat data [17, 31, 73, 47, 23]))
[(vec (range 256)) 0 0])
64)))
(defn dense-hash [sparseh]
(->> sparseh
(partition 16)
(map #(reduce bit-xor %))
(map #(format "%02x" %))
(apply str)))
(def part-2 (comp dense-hash sparse-hash))
part 2
#_ (time (part-2 (map int (string/join "," data))))
Elapsed time : 55.868713 msecs
= > 44f4befb0f303c0bafd085f97741d51d
| null | https://raw.githubusercontent.com/bhauman/advent-of-clojure/856763baf45bf7bf452ffd304dc1b89f9bc879a6/src/advent-2017/day10.clj | clojure | optimized for speed | (ns advent-2017.day10
(:require
[clojure.string :as string]
[clojure.core.reducers :as r]))
(def data [102,255,99,252,200,24,219,57,103,2,226,254,1,0,69,216])
(defn inplace-reverse [x pos length]
(let [idx (mapv #(mod % (count x))
(range pos (+ pos length)))
vs (r/reduce #(cons (get x %2) %1) '() idx)]
(persistent!
(loop [[id & idx'] idx
[v & vs'] vs
x (transient x)]
(if id
(recur idx' vs' (assoc! x id v))
x)))))
(defn transition [[x pos skip] length]
[(inplace-reverse x pos length)
(+ pos length skip)
(inc skip)])
(def hash-round #(r/reduce transition %2 %1))
part 1
#_ (->> (hash-round data [(vec (range 256)) 0 0])
first
(take 2)
(apply *))
= > 5577
(defn sparse-hash [data]
(first
(nth (iterate (partial hash-round (concat data [17, 31, 73, 47, 23]))
[(vec (range 256)) 0 0])
64)))
(defn dense-hash [sparseh]
(->> sparseh
(partition 16)
(map #(reduce bit-xor %))
(map #(format "%02x" %))
(apply str)))
(def part-2 (comp dense-hash sparse-hash))
part 2
#_ (time (part-2 (map int (string/join "," data))))
Elapsed time : 55.868713 msecs
= > 44f4befb0f303c0bafd085f97741d51d
|
3ecf0d0b298b71b7a10f2f459cf67eb5d5d40c41c24bf4786085ce8a33795cde | 2049foundation/clickhouse-haskell | Client.hs | Copyright ( c ) 2020 - present , EMQX , Inc.
-- All rights reserved.
--
This source code is distributed under the terms of a MIT license ,
-- found in the LICENSE file.
# LANGUAGE ApplicativeDo #
# LANGUAGE BlockArguments #
# LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
-- | This module provides implementation of user's API
module Database.ClickHouseDriver.HTTP.Client
( -- * Setting
setupEnv,
runQuery,
-- * Query
getByteString,
getJSON,
getText,
getTextM,
getJsonM,
insertOneRow,
insertMany,
ping,
exec,
insertFromFile,
-- * Connection
defaultHttpClient,
httpClient,
defaultHttpPool,
)
where
import Control.Concurrent.Async (mapConcurrently)
import Control.Exception (SomeException, try)
import Control.Monad.State.Lazy (MonadIO (..))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString.Builder
( char8,
lazyByteString,
toLazyByteString,
)
import qualified Data.ByteString.Lazy.Char8 as C8
import Data.Default.Class (def)
import Data.Hashable (Hashable (hashWithSalt))
import Data.Pool (Pool, withResource)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import Data.Time.Clock (NominalDiffTime)
import Data.Typeable (Typeable)
import Database.ClickHouseDriver.Defines as Defines
( _DEFAULT_HOST,
_DEFAULT_HTTP_PORT,
)
import Database.ClickHouseDriver.HTTP.Connection
( createHttpPool,
defaultHttpConnection,
httpConnectDb,
)
import Database.ClickHouseDriver.HTTP.Helpers
( extract,
genURL,
toString,
)
import Database.ClickHouseDriver.HTTP.Types (Format (..), HttpConnection (..), JSONResult)
import Database.ClickHouseDriver.Types (ClickhouseType)
import Haxl.Core
( BlockedFetch (..),
DataSource (fetch),
DataSourceName (..),
Env (userEnv),
GenHaxl,
PerformFetch (SyncFetch),
ShowP (..),
StateKey (State),
dataFetch,
initEnv,
putFailure,
putSuccess,
runHaxl,
stateEmpty,
stateSet,
)
import Network.HTTP.Client
( RequestBody (..),
httpLbs,
method,
parseRequest,
requestBody,
responseBody,
streamFile,
)
import Text.Printf (printf)
{-Implementation in Haxl-}
--
data HttpClient a where
FetchByteString :: String -> HttpClient BS.ByteString
FetchJSON :: String -> HttpClient BS.ByteString
FetchCSV :: String -> HttpClient BS.ByteString
FetchText :: String -> HttpClient BS.ByteString
Ping :: HttpClient BS.ByteString
deriving instance Show (HttpClient a)
deriving instance Typeable HttpClient
deriving instance Eq (HttpClient a)
instance ShowP HttpClient where showp = show
instance Hashable (HttpClient a) where
hashWithSalt salt (FetchByteString cmd) = hashWithSalt salt cmd
hashWithSalt salt (FetchJSON cmd) = hashWithSalt salt cmd
hashWithSalt salt (FetchCSV cmd) = hashWithSalt salt cmd
hashWithSalt salt Ping = hashWithSalt salt ("ok" :: BS.ByteString)
instance DataSourceName HttpClient where
dataSourceName _ = "ClickhouseDataSource"
instance DataSource u HttpClient where
fetch (settings) _flags _usrenv = SyncFetch $ \blockedFetches -> do
printf "Fetching %d queries.\n" (length blockedFetches)
res <- mapConcurrently (fetchData settings) blockedFetches
case res of
[()] -> return ()
instance StateKey HttpClient where
data State HttpClient
= SingleHttp HttpConnection
| HttpPool (Pool HttpConnection)
class HttpEnvironment a where
toEnv :: a -> State HttpClient
pick :: a -> IO HttpConnection
instance HttpEnvironment HttpConnection where
toEnv = SingleHttp
pick = return
instance HttpEnvironment (Pool HttpConnection) where
toEnv = HttpPool
pick pool = withResource pool $ return
-- | fetch function
fetchData ::
State HttpClient -> --Connection configuration
BlockedFetch HttpClient -> --fetched data
IO ()
fetchData (settings) fetches = do
let (queryWithType, var) = case fetches of
BlockedFetch (FetchJSON query) var' -> (query ++ " FORMAT JSON", var')
BlockedFetch (FetchCSV query) var' -> (query ++ " FORMAT CSV", var')
BlockedFetch (FetchByteString query) var' -> (query, var')
BlockedFetch Ping var' -> ("ping", var')
e <- Control.Exception.try $ do
case settings of
SingleHttp http@(HttpConnection _ mng) -> do
url <- genURL http queryWithType
req <- parseRequest url
ans <- responseBody <$> httpLbs req mng
return $ LBS.toStrict ans
HttpPool pool ->
withResource pool $ \conn@(HttpConnection _ mng) -> do
url <- genURL conn queryWithType
req <- parseRequest url
ans <- responseBody <$> httpLbs req mng
return $ LBS.toStrict ans
either
(putFailure var)
(putSuccess var)
(e :: Either SomeException (BS.ByteString))
| Fetch data from ClickHouse client in the text format .
getByteString :: String -> GenHaxl u w BS.ByteString
getByteString = dataFetch . FetchByteString
getText :: String -> GenHaxl u w T.Text
getText cmd = fmap decodeUtf8 (getByteString cmd)
| Fetch data from ClickHouse client in the JSON format .
getJSON :: String -> GenHaxl u w JSONResult
getJSON cmd = fmap extract (dataFetch $ FetchJSON cmd)
| Fetch data from Clickhouse client with commands warped in a monad .
getTextM :: (Monad m, Traversable m) => m String -> GenHaxl u w (m T.Text)
getTextM = mapM getText
| Fetch data from Clickhouse client in the format of JSON
getJsonM :: (Monad m, Traversable m) => m String -> GenHaxl u w (m JSONResult)
getJsonM = mapM getJSON
-- | actual function used by user to perform fetching command
exec :: (HttpEnvironment a) => String -> Env a w -> IO (Either C8.ByteString String)
exec cmd' env = do
let cmd = C8.pack cmd'
conn@HttpConnection {httpManager = mng} <- pick $ userEnv env
url <- genURL conn ""
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = RequestBodyLBS cmd
}
mng
if ans /= ""
then return $ Left ans -- error message
else return $ Right "Created successfully"
| insert one row
insertOneRow ::
(HttpEnvironment a) =>
String ->
[ClickhouseType] ->
Env a w ->
IO (Either C8.ByteString String)
insertOneRow table_name arr environment = do
let row = toString arr
let cmd = C8.pack ("INSERT INTO " ++ table_name ++ " VALUES " ++ row)
settings@HttpConnection {httpManager = mng} <- pick $ userEnv environment
url <- genURL settings ""
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = RequestBodyLBS cmd
}
mng
if ans /= ""
error messagethe hellenic republic
else return $ Right "Inserted successfully"
| insert one or more rows
insertMany ::
(HttpEnvironment a) =>
String ->
[[ClickhouseType]] ->
Env a w ->
IO (Either C8.ByteString String)
insertMany table_name rows environment = do
let rowsString = map (lazyByteString . C8.pack . toString) rows
comma = char8 ','
preset = lazyByteString $ C8.pack $ "INSERT INTO " <> table_name <> " VALUES "
togo = preset <> (foldl1 (\x y -> x <> comma <> y) rowsString)
settings@HttpConnection {httpManager = mng} <- pick $ userEnv environment
url <- genURL settings ""
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = RequestBodyLBS $ toLazyByteString togo
}
mng
print "inserted successfully"
if ans /= ""
then return $ Left ans
else return $ Right "Successful insertion"
-- | insert data from
insertFromFile ::
(HttpEnvironment a) =>
String ->
Format ->
FilePath ->
Env a w ->
IO (Either C8.ByteString String)
insertFromFile table_name format file environment = do
fileReqBody <- streamFile file
settings@HttpConnection {httpManager = mng} <- pick $ userEnv environment
url <-
genURL
settings
( "INSERT INTO " <> table_name
<> case format of
CSV -> " FORMAT CSV"
JSON -> " FORMAT JSON"
TUPLE -> " VALUES"
)
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = fileReqBody
}
mng
if ans /= ""
then return $ Left ans -- error message
else return $ Right "Inserted successfully"
ping :: GenHaxl u w BS.ByteString
ping = dataFetch $ Ping
-- | Default environment
setupEnv :: (MonadIO m, HttpEnvironment a) => a -> m (Env a w)
setupEnv csetting = liftIO $ initEnv (stateSet (toEnv csetting) stateEmpty) csetting
defaultHttpClient :: (MonadIO m) => m (Env HttpConnection w)
defaultHttpClient = liftIO $ defaultHttpConnection >>= setupEnv
defaultHttpPool :: (MonadIO m) => Int -> NominalDiffTime -> Int -> m (Env (Pool HttpConnection) w)
defaultHttpPool numStripes idleTime maxResources =
liftIO $ createHttpPool def numStripes idleTime maxResources >>= setupEnv
httpClient :: (MonadIO m) => String -> String -> m (Env HttpConnection w)
httpClient user password = liftIO $ httpConnectDb user password Defines._DEFAULT_HTTP_PORT Defines._DEFAULT_HOST Nothing >>= setupEnv
-- | rename runHaxl function.
# INLINE runQuery #
runQuery :: (MonadIO m) => Env u w -> GenHaxl u w a -> m a
runQuery env haxl = liftIO $ runHaxl env haxl | null | https://raw.githubusercontent.com/2049foundation/clickhouse-haskell/d4777ae43bcd9cbf005b7dad312f8497ac59a156/src/Database/ClickHouseDriver/HTTP/Client.hs | haskell | All rights reserved.
found in the LICENSE file.
# LANGUAGE DeriveDataTypeable #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
| This module provides implementation of user's API
* Setting
* Query
* Connection
Implementation in Haxl
| fetch function
Connection configuration
fetched data
| actual function used by user to perform fetching command
error message
| insert data from
error message
| Default environment
| rename runHaxl function. | Copyright ( c ) 2020 - present , EMQX , Inc.
This source code is distributed under the terms of a MIT license ,
# LANGUAGE ApplicativeDo #
# LANGUAGE BlockArguments #
# LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
module Database.ClickHouseDriver.HTTP.Client
setupEnv,
runQuery,
getByteString,
getJSON,
getText,
getTextM,
getJsonM,
insertOneRow,
insertMany,
ping,
exec,
insertFromFile,
defaultHttpClient,
httpClient,
defaultHttpPool,
)
where
import Control.Concurrent.Async (mapConcurrently)
import Control.Exception (SomeException, try)
import Control.Monad.State.Lazy (MonadIO (..))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString.Builder
( char8,
lazyByteString,
toLazyByteString,
)
import qualified Data.ByteString.Lazy.Char8 as C8
import Data.Default.Class (def)
import Data.Hashable (Hashable (hashWithSalt))
import Data.Pool (Pool, withResource)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import Data.Time.Clock (NominalDiffTime)
import Data.Typeable (Typeable)
import Database.ClickHouseDriver.Defines as Defines
( _DEFAULT_HOST,
_DEFAULT_HTTP_PORT,
)
import Database.ClickHouseDriver.HTTP.Connection
( createHttpPool,
defaultHttpConnection,
httpConnectDb,
)
import Database.ClickHouseDriver.HTTP.Helpers
( extract,
genURL,
toString,
)
import Database.ClickHouseDriver.HTTP.Types (Format (..), HttpConnection (..), JSONResult)
import Database.ClickHouseDriver.Types (ClickhouseType)
import Haxl.Core
( BlockedFetch (..),
DataSource (fetch),
DataSourceName (..),
Env (userEnv),
GenHaxl,
PerformFetch (SyncFetch),
ShowP (..),
StateKey (State),
dataFetch,
initEnv,
putFailure,
putSuccess,
runHaxl,
stateEmpty,
stateSet,
)
import Network.HTTP.Client
( RequestBody (..),
httpLbs,
method,
parseRequest,
requestBody,
responseBody,
streamFile,
)
import Text.Printf (printf)
data HttpClient a where
FetchByteString :: String -> HttpClient BS.ByteString
FetchJSON :: String -> HttpClient BS.ByteString
FetchCSV :: String -> HttpClient BS.ByteString
FetchText :: String -> HttpClient BS.ByteString
Ping :: HttpClient BS.ByteString
deriving instance Show (HttpClient a)
deriving instance Typeable HttpClient
deriving instance Eq (HttpClient a)
instance ShowP HttpClient where showp = show
instance Hashable (HttpClient a) where
hashWithSalt salt (FetchByteString cmd) = hashWithSalt salt cmd
hashWithSalt salt (FetchJSON cmd) = hashWithSalt salt cmd
hashWithSalt salt (FetchCSV cmd) = hashWithSalt salt cmd
hashWithSalt salt Ping = hashWithSalt salt ("ok" :: BS.ByteString)
instance DataSourceName HttpClient where
dataSourceName _ = "ClickhouseDataSource"
instance DataSource u HttpClient where
fetch (settings) _flags _usrenv = SyncFetch $ \blockedFetches -> do
printf "Fetching %d queries.\n" (length blockedFetches)
res <- mapConcurrently (fetchData settings) blockedFetches
case res of
[()] -> return ()
instance StateKey HttpClient where
data State HttpClient
= SingleHttp HttpConnection
| HttpPool (Pool HttpConnection)
class HttpEnvironment a where
toEnv :: a -> State HttpClient
pick :: a -> IO HttpConnection
instance HttpEnvironment HttpConnection where
toEnv = SingleHttp
pick = return
instance HttpEnvironment (Pool HttpConnection) where
toEnv = HttpPool
pick pool = withResource pool $ return
fetchData ::
IO ()
fetchData (settings) fetches = do
let (queryWithType, var) = case fetches of
BlockedFetch (FetchJSON query) var' -> (query ++ " FORMAT JSON", var')
BlockedFetch (FetchCSV query) var' -> (query ++ " FORMAT CSV", var')
BlockedFetch (FetchByteString query) var' -> (query, var')
BlockedFetch Ping var' -> ("ping", var')
e <- Control.Exception.try $ do
case settings of
SingleHttp http@(HttpConnection _ mng) -> do
url <- genURL http queryWithType
req <- parseRequest url
ans <- responseBody <$> httpLbs req mng
return $ LBS.toStrict ans
HttpPool pool ->
withResource pool $ \conn@(HttpConnection _ mng) -> do
url <- genURL conn queryWithType
req <- parseRequest url
ans <- responseBody <$> httpLbs req mng
return $ LBS.toStrict ans
either
(putFailure var)
(putSuccess var)
(e :: Either SomeException (BS.ByteString))
| Fetch data from ClickHouse client in the text format .
getByteString :: String -> GenHaxl u w BS.ByteString
getByteString = dataFetch . FetchByteString
getText :: String -> GenHaxl u w T.Text
getText cmd = fmap decodeUtf8 (getByteString cmd)
| Fetch data from ClickHouse client in the JSON format .
getJSON :: String -> GenHaxl u w JSONResult
getJSON cmd = fmap extract (dataFetch $ FetchJSON cmd)
| Fetch data from Clickhouse client with commands warped in a monad .
getTextM :: (Monad m, Traversable m) => m String -> GenHaxl u w (m T.Text)
getTextM = mapM getText
| Fetch data from Clickhouse client in the format of JSON
getJsonM :: (Monad m, Traversable m) => m String -> GenHaxl u w (m JSONResult)
getJsonM = mapM getJSON
exec :: (HttpEnvironment a) => String -> Env a w -> IO (Either C8.ByteString String)
exec cmd' env = do
let cmd = C8.pack cmd'
conn@HttpConnection {httpManager = mng} <- pick $ userEnv env
url <- genURL conn ""
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = RequestBodyLBS cmd
}
mng
if ans /= ""
else return $ Right "Created successfully"
| insert one row
insertOneRow ::
(HttpEnvironment a) =>
String ->
[ClickhouseType] ->
Env a w ->
IO (Either C8.ByteString String)
insertOneRow table_name arr environment = do
let row = toString arr
let cmd = C8.pack ("INSERT INTO " ++ table_name ++ " VALUES " ++ row)
settings@HttpConnection {httpManager = mng} <- pick $ userEnv environment
url <- genURL settings ""
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = RequestBodyLBS cmd
}
mng
if ans /= ""
error messagethe hellenic republic
else return $ Right "Inserted successfully"
| insert one or more rows
insertMany ::
(HttpEnvironment a) =>
String ->
[[ClickhouseType]] ->
Env a w ->
IO (Either C8.ByteString String)
insertMany table_name rows environment = do
let rowsString = map (lazyByteString . C8.pack . toString) rows
comma = char8 ','
preset = lazyByteString $ C8.pack $ "INSERT INTO " <> table_name <> " VALUES "
togo = preset <> (foldl1 (\x y -> x <> comma <> y) rowsString)
settings@HttpConnection {httpManager = mng} <- pick $ userEnv environment
url <- genURL settings ""
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = RequestBodyLBS $ toLazyByteString togo
}
mng
print "inserted successfully"
if ans /= ""
then return $ Left ans
else return $ Right "Successful insertion"
insertFromFile ::
(HttpEnvironment a) =>
String ->
Format ->
FilePath ->
Env a w ->
IO (Either C8.ByteString String)
insertFromFile table_name format file environment = do
fileReqBody <- streamFile file
settings@HttpConnection {httpManager = mng} <- pick $ userEnv environment
url <-
genURL
settings
( "INSERT INTO " <> table_name
<> case format of
CSV -> " FORMAT CSV"
JSON -> " FORMAT JSON"
TUPLE -> " VALUES"
)
req <- parseRequest url
ans <-
responseBody
<$> httpLbs
req
{ method = "POST",
requestBody = fileReqBody
}
mng
if ans /= ""
else return $ Right "Inserted successfully"
ping :: GenHaxl u w BS.ByteString
ping = dataFetch $ Ping
setupEnv :: (MonadIO m, HttpEnvironment a) => a -> m (Env a w)
setupEnv csetting = liftIO $ initEnv (stateSet (toEnv csetting) stateEmpty) csetting
defaultHttpClient :: (MonadIO m) => m (Env HttpConnection w)
defaultHttpClient = liftIO $ defaultHttpConnection >>= setupEnv
defaultHttpPool :: (MonadIO m) => Int -> NominalDiffTime -> Int -> m (Env (Pool HttpConnection) w)
defaultHttpPool numStripes idleTime maxResources =
liftIO $ createHttpPool def numStripes idleTime maxResources >>= setupEnv
httpClient :: (MonadIO m) => String -> String -> m (Env HttpConnection w)
httpClient user password = liftIO $ httpConnectDb user password Defines._DEFAULT_HTTP_PORT Defines._DEFAULT_HOST Nothing >>= setupEnv
# INLINE runQuery #
runQuery :: (MonadIO m) => Env u w -> GenHaxl u w a -> m a
runQuery env haxl = liftIO $ runHaxl env haxl |
21a1a5bd9d308d97a1cad1370fd30bae92a1d8c9fd5f49084e976351e16e2f43 | raml-org/api-modeling-framework | jsonld.cljc | (ns api-modeling-framework.generators.syntax.jsonld
#?(:cljs (:require [api-modeling-framework.platform :as platform]
[api-modeling-framework.model.vocabulary :as v]))
#?(:clj (:require [api-modeling-framework.platform :as platform]
[api-modeling-framework.model.vocabulary :as v])))
(defn clean-references
"We don't serialise all the references for the model, just the id and the types"
([document]
(let [references (->> (get document v/document:references [])
(map (fn [ref] {"@id" (get ref "@id")
"@type" (get ref "@type")}))
(filter (fn [ref] (some? (get ref "@id")))))]
(if (> (count references) 0)
(assoc document v/document:references references)
(dissoc document v/document:references)))))
(defn generate-string
([document full-graph?] (platform/encode-json (if full-graph? document (clean-references document))))
([document] (generate-string document true)))
(defn generate-file
([location document full-graph?]
(platform/write-location location (platform/encode-json (if full-graph? (clean-references document)))))
([location document]
(generate-file location document true)))
| null | https://raw.githubusercontent.com/raml-org/api-modeling-framework/34bb3b6c3e3f91b775e27f8e389e04eb2c36beb7/src/api_modeling_framework/generators/syntax/jsonld.cljc | clojure | (ns api-modeling-framework.generators.syntax.jsonld
#?(:cljs (:require [api-modeling-framework.platform :as platform]
[api-modeling-framework.model.vocabulary :as v]))
#?(:clj (:require [api-modeling-framework.platform :as platform]
[api-modeling-framework.model.vocabulary :as v])))
(defn clean-references
"We don't serialise all the references for the model, just the id and the types"
([document]
(let [references (->> (get document v/document:references [])
(map (fn [ref] {"@id" (get ref "@id")
"@type" (get ref "@type")}))
(filter (fn [ref] (some? (get ref "@id")))))]
(if (> (count references) 0)
(assoc document v/document:references references)
(dissoc document v/document:references)))))
(defn generate-string
([document full-graph?] (platform/encode-json (if full-graph? document (clean-references document))))
([document] (generate-string document true)))
(defn generate-file
([location document full-graph?]
(platform/write-location location (platform/encode-json (if full-graph? (clean-references document)))))
([location document]
(generate-file location document true)))
|
|
376f09d3aab9ca749afd0c49ab661dbfcd6f9fd7d7176daa40d7d9b1eb31ccad | ghcjs/ghcjs | mc08.hs | -- Tests grouping WITH a by clause
# OPTIONS_GHC -XMonadComprehensions -XTransformListComp #
module Main where
import GHC.Exts(the, groupWith)
main = putStrLn (show output)
where
output = [ (the dept, sum salary, name)
| (dept, salary, name) <- [("A", 1, "Bob"), ("B", 2, "Fred"), ("A", 5, "Jim"), ("A", 9, "Jim")]
, then group by dept using groupWith]
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/deSugar/mc08.hs | haskell | Tests grouping WITH a by clause |
# OPTIONS_GHC -XMonadComprehensions -XTransformListComp #
module Main where
import GHC.Exts(the, groupWith)
main = putStrLn (show output)
where
output = [ (the dept, sum salary, name)
| (dept, salary, name) <- [("A", 1, "Bob"), ("B", 2, "Fred"), ("A", 5, "Jim"), ("A", 9, "Jim")]
, then group by dept using groupWith]
|
385ad8417a95b3dff3d115f23eeefc83c792fffea7627d72e4ceae6d825bf222 | grin-compiler/ghc-wpc-sample-programs | Parser.hs | |
Module : . : for the REPL commands .
License : : The Idris Community .
Module : Idris.REPL.Parser
Description : Parser for the REPL commands.
License : BSD3
Maintainer : The Idris Community.
-}
# LANGUAGE FlexibleContexts #
module Idris.REPL.Parser (
parseCmd
, help
, allHelp
, setOptions
) where
import Idris.AbsSyntax
import Idris.Colours
import Idris.Core.TT
import Idris.Help
import Idris.Imports
import Idris.Options
import qualified Idris.Parser as IP
import qualified Idris.Parser.Expr as IP
import qualified Idris.Parser.Helpers as IP
import qualified Idris.Parser.Ops as IP
import Idris.REPL.Commands
import Control.Applicative
import Control.Monad.State.Strict
import Data.Char (isSpace, toLower)
import Data.List
import Data.List.Split (splitOn)
import System.Console.ANSI (Color(..))
import System.FilePath ((</>))
import qualified Text.Megaparsec as P
parseCmd :: IState -> String -> String -> Either IP.ParseError (Either String Command)
parseCmd i inputname = IP.runparser pCmd i inputname . trim
where trim = f . f
where f = reverse . dropWhile isSpace
type CommandTable = [ ( [String], CmdArg, String
, String -> IP.IdrisParser (Either String Command) ) ]
setOptions :: [(String, Opt)]
setOptions = [("errorcontext", ErrContext),
("showimplicits", ShowImpl),
("originalerrors", ShowOrigErr),
("autosolve", AutoSolve),
("nobanner", NoBanner),
("warnreach", WarnReach),
("evaltypes", EvalTypes),
("desugarnats", DesugarNats)]
help :: [([String], CmdArg, String)]
help = (["<expr>"], NoArg, "Evaluate an expression") :
[ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
allHelp :: [([String], CmdArg, String)]
allHelp = [ (map (':' :) names, args, text)
| (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
parserCommandsForHelp :: CommandTable
parserCommandsForHelp =
[ exprArgCmd ["t", "type"] Check "Check the type of an expression"
, exprArgCmd ["core"] Core "View the core language representation of a term"
, nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
, (["doc"], NameArg, "Show internal documentation", cmd_doc)
, (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
, genArg "namespace" (P.many P.anySingle) MakeDoc)
, (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
, cmd_apropos)
, (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
, " Search for values by type", cmd_search)
, nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
, nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
, namespaceArgCmd ["browse"] Browse "List the contents of some namespace"
, nameArgCmd ["total"] TotCheck "Check the totality of a name"
, noArgCmd ["r", "reload"] Reload "Reload current file"
, noArgCmd ["w", "watch"] Watch "Watch the current file for changes"
, (["l", "load"], FileArg, "Load a new file"
, strArg (\f -> Load f Nothing))
, (["!"], ShellCommandArg, "Run a shell command", strArg RunShellCommand)
, (["cd"], FileArg, "Change working directory"
, strArg ChangeDirectory)
, (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons
, noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
, noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)"
, (["p", "prove"], MetaVarArg, "Prove a metavariable"
, nameArg (Prove False))
, (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell"
, nameArg (Prove True))
, (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
, (["rmproof"], NameArg, "Remove proof from proof stack"
, nameArg RmProof)
, (["showproof"], NameArg, "Show proof"
, nameArg ShowProof)
, noArgCmd ["proofs"] Proofs "Show available proofs"
, exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
, (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
, (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
, (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
, (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
, noArgCmd ["?", "h", "help"] Help "Display this help text"
, optArgCmd ["set"] SetOpt $ "Set an option (" ++ optionsList ++ ")"
, optArgCmd ["unset"] UnsetOpt "Unset an option"
, (["color", "colour"], ColourArg
, "Turn REPL colours on or off; set a specific colour"
, cmd_colour)
, (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
, (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)
, noArgCmd ["q", "quit"] Quit "Exit the Idris system"
, noArgCmd ["version"] ShowVersion "Display the Idris version"
, noArgCmd ["warranty"] Warranty "Displays warranty information"
, (["let"], ManyArgs DeclArg
, "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
, cmd_let)
, (["unlet", "undefine"], ManyArgs NameArg
, "Remove the listed repl definitions, or all repl definitions if no names given"
, cmd_unlet)
, nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
, (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
, "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
, cmd_pprint)
, (["verbosity"], NumberArg, "Set verbosity level", cmd_verb)
]
where optionsList = intercalate ", " $ map fst setOptions
parserCommands :: CommandTable
parserCommands =
[ noArgCmd ["u", "universes"] Universes "Display universe constraints"
, noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
, nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
, nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
, nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
, exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
, exprArgCmd ["spec"] Spec "?"
, exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression"
, exprArgCmd ["inline"] TestInline "?"
, proofArgCmd ["cs", "casesplit"] CaseSplitAt
":cs <line> <name> splits the pattern variable on the line"
, proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
":apc <line> <name> adds a pattern-matching proof clause to name on line"
, proofArgCmd ["ac", "addclause"] AddClauseFrom
":ac <line> <name> adds a clause for the definition of the name on the line"
, proofArgCmd ["am", "addmissing"] AddMissing
":am <line> <name> adds all missing pattern matches for the name on the line"
, proofArgCmd ["mw", "makewith"] MakeWith
":mw <line> <name> adds a with clause for the definition of the name on the line"
, proofArgCmd ["mc", "makecase"] MakeCase
":mc <line> <name> adds a case block for the definition of the metavariable on the line"
, proofArgCmd ["ml", "makelemma"] MakeLemma "?"
, (["log"], NumberArg, "Set logging level", cmd_log)
, ( ["logcats"]
, ManyArgs NameArg
, "Set logging categories"
, cmd_cats)
, (["lto", "loadto"], SeqArgs NumberArg FileArg
, "Load file up to line number", cmd_loadto)
, (["ps", "proofsearch"], NoArg
, ":ps <line> <name> <names> does proof search for name on line, with names as hints"
, cmd_proofsearch)
, (["ref", "refine"], NoArg
, ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
, cmd_refine)
, (["debugunify"], SeqArgs ExprArg ExprArg
, "(Debugging) Try to unify two expressions", const $ do
l <- IP.simpleExpr defaultSyntax
r <- IP.simpleExpr defaultSyntax
P.eof
return (Right (DebugUnify l r))
)
]
noArgCmd names command doc =
(names, NoArg, doc, noArgs command)
nameArgCmd names command doc =
(names, NameArg, doc, fnNameArg command)
namespaceArgCmd names command doc =
(names, NamespaceArg, doc, namespaceArg command)
exprArgCmd names command doc =
(names, ExprArg, doc, exprArg command)
optArgCmd names command doc =
(names, OptionArg, doc, optArg command)
proofArgCmd names command doc =
(names, NoArg, doc, proofArg command)
pCmd :: IP.IdrisParser (Either String Command)
pCmd = P.choice [ do c <- cmd names; parser c
| (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
<|> unrecognized
<|> nop
<|> eval
where nop = do P.eof; return (Right NOP)
unrecognized = do
IP.lchar ':'
cmd <- P.many P.anySingle
let cmd' = takeWhile (/=' ') cmd
return (Left $ "Unrecognized command: " ++ cmd')
cmd :: [String] -> IP.IdrisParser String
cmd xs = P.try $ do
IP.lchar ':'
docmd sorted_xs
where docmd [] = fail "Could not parse command"
docmd (x:xs) = P.try (IP.reserved x >> return x) <|> docmd xs
sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
noArgs :: Command -> String -> IP.IdrisParser (Either String Command)
noArgs cmd name = do
let emptyArgs = do
P.eof
return (Right cmd)
let failure = return (Left $ ":" ++ name ++ " takes no arguments")
emptyArgs <|> failure
eval :: IP.IdrisParser (Either String Command)
eval = do
t <- IP.fullExpr defaultSyntax
return $ Right (Eval t)
exprArg :: (PTerm -> Command) -> String -> IP.IdrisParser (Either String Command)
exprArg cmd name = do
let noArg = do
P.eof
return $ Left ("Usage is :" ++ name ++ " <expression>")
let justOperator = do
(op, fc) <- IP.withExtent IP.symbolicOperator
P.eof
return $ Right $ cmd (PRef fc [] (sUN op))
let properArg = do
t <- IP.fullExpr defaultSyntax
return $ Right (cmd t)
P.try noArg <|> P.try justOperator <|> properArg
genArg :: String -> IP.IdrisParser a -> (a -> Command)
-> String -> IP.IdrisParser (Either String Command)
genArg argName argParser cmd name = do
let emptyArgs = do P.eof; failure
oneArg = do arg <- argParser
P.eof
return (Right (cmd arg))
P.try emptyArgs <|> oneArg <|> failure
where
failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
nameArg, fnNameArg :: (Name -> Command) -> String -> IP.IdrisParser (Either String Command)
nameArg = genArg "name" IP.name
fnNameArg = genArg "functionname" IP.fnName
strArg :: (String -> Command) -> String -> IP.IdrisParser (Either String Command)
strArg = genArg "string" (P.many P.anySingle)
moduleArg :: (FilePath -> Command) -> String -> IP.IdrisParser (Either String Command)
moduleArg = genArg "module" (fmap toPath IP.identifier)
where
toPath n = foldl1' (</>) $ splitOn "." n
namespaceArg :: ([String] -> Command) -> String -> IP.IdrisParser (Either String Command)
namespaceArg = genArg "namespace" (fmap toNS IP.identifier)
where
toNS = splitOn "."
optArg :: (Opt -> Command) -> String -> IP.IdrisParser (Either String Command)
optArg cmd name = do
let emptyArgs = do
P.eof
return $ Left ("Usage is :" ++ name ++ " <option>")
let oneArg = do
o <- pOption
IP.whiteSpace
P.eof
return (Right (cmd o))
let failure = return $ Left "Unrecognized setting"
P.try emptyArgs <|> oneArg <|> failure
where
pOption :: IP.IdrisParser Opt
pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (IP.symbol a); return b) setOptions
proofArg :: (Bool -> Int -> Name -> Command) -> String -> IP.IdrisParser (Either String Command)
proofArg cmd name = do
upd <- P.option False $ do
IP.lchar '!'
return True
l <- IP.natural
n <- IP.name
return (Right (cmd upd (fromInteger l) n))
cmd_doc :: String -> IP.IdrisParser (Either String Command)
cmd_doc name = do
let constant = do
c <- IP.constant
P.eof
return $ Right (DocStr (Right c) FullDocs)
let pType = do
IP.reserved "Type"
P.eof
return $ Right (DocStr (Left $ sUN "Type") FullDocs)
let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
P.try constant <|> pType <|> fnName
cmd_consolewidth :: String -> IP.IdrisParser (Either String Command)
cmd_consolewidth name = do
w <- pConsoleWidth
return (Right (SetConsoleWidth w))
where
pConsoleWidth :: IP.IdrisParser ConsoleWidth
pConsoleWidth = do discard (IP.symbol "auto"); return AutomaticWidth
<|> do discard (IP.symbol "infinite"); return InfinitelyWide
<|> do n <- fromInteger <$> IP.natural
return (ColsWide n)
cmd_printdepth :: String -> IP.IdrisParser (Either String Command)
cmd_printdepth _ = do d <- optional (fromInteger <$> IP.natural)
return (Right $ SetPrinterDepth d)
cmd_execute :: String -> IP.IdrisParser (Either String Command)
cmd_execute name = do
tm <- P.option maintm (IP.fullExpr defaultSyntax)
return (Right (Execute tm))
where
maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
cmd_dynamic :: String -> IP.IdrisParser (Either String Command)
cmd_dynamic name = do
let optArg = do l <- P.many P.anySingle
if (l /= "")
then return $ Right (DynamicLink l)
else return $ Right ListDynamic
let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
P.try optArg <|> failure
cmd_pprint :: String -> IP.IdrisParser (Either String Command)
cmd_pprint name = do
fmt <- ppFormat
IP.whiteSpace
n <- fromInteger <$> IP.natural
IP.whiteSpace
t <- IP.fullExpr defaultSyntax
return (Right (PPrint fmt n t))
where
ppFormat :: IP.IdrisParser OutputFmt
ppFormat = (discard (IP.symbol "html") >> return HTMLOutput)
<|> (discard (IP.symbol "latex") >> return LaTeXOutput)
cmd_compile :: String -> IP.IdrisParser (Either String Command)
cmd_compile name = do
let defaultCodegen = Via IBCFormat "c"
let codegenOption :: IP.IdrisParser Codegen
codegenOption = do
let bytecodeCodegen = discard (IP.symbol "bytecode") *> return Bytecode
viaCodegen = do x <- IP.identifier
return (Via IBCFormat (map toLower x))
bytecodeCodegen <|> viaCodegen
let hasOneArg = do
i <- get
f <- IP.identifier
P.eof
return $ Right (Compile defaultCodegen f)
let hasTwoArgs = do
i <- get
codegen <- codegenOption
f <- IP.identifier
P.eof
return $ Right (Compile codegen f)
let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
P.try hasTwoArgs <|> P.try hasOneArg <|> failure
cmd_addproof :: String -> IP.IdrisParser (Either String Command)
cmd_addproof name = do
n <- P.option Nothing $ do
x <- IP.name
return (Just x)
P.eof
return (Right (AddProof n))
cmd_log :: String -> IP.IdrisParser (Either String Command)
cmd_log name = do
i <- fromIntegral <$> IP.natural
P.eof
return (Right (LogLvl i))
cmd_verb :: String -> IP.IdrisParser (Either String Command)
cmd_verb name = do
i <- fromIntegral <$> IP.natural
P.eof
return (Right (Verbosity i))
cmd_cats :: String -> IP.IdrisParser (Either String Command)
cmd_cats name = do
cs <- P.sepBy pLogCats (IP.whiteSpace)
P.eof
return $ Right $ LogCategory (concat cs)
where
badCat = do
c <- IP.identifier
fail $ "Category: " ++ c ++ " is not recognised."
pLogCats :: IP.IdrisParser [LogCat]
pLogCats = P.try (parserCats <$ IP.symbol (strLogCat IParse))
<|> P.try (elabCats <$ IP.symbol (strLogCat IElab))
<|> P.try (codegenCats <$ IP.symbol (strLogCat ICodeGen))
<|> P.try ([ICoverage] <$ IP.symbol (strLogCat ICoverage))
<|> P.try ([IIBC] <$ IP.symbol (strLogCat IIBC))
<|> P.try ([IErasure] <$ IP.symbol (strLogCat IErasure))
<|> badCat
cmd_let :: String -> IP.IdrisParser (Either String Command)
cmd_let name = do
defn <- concat <$> P.many (IP.decl defaultSyntax)
return (Right (NewDefn defn))
cmd_unlet :: String -> IP.IdrisParser (Either String Command)
cmd_unlet name = Right . Undefine <$> P.many IP.name
cmd_loadto :: String -> IP.IdrisParser (Either String Command)
cmd_loadto name = do
toline <- fromInteger <$> IP.natural
f <- P.many P.anySingle
return (Right (Load f (Just toline)))
cmd_colour :: String -> IP.IdrisParser (Either String Command)
cmd_colour name = fmap Right pSetColourCmd
where
colours :: [(String, Maybe Color)]
colours = [ ("black", Just Black)
, ("red", Just Red)
, ("green", Just Green)
, ("yellow", Just Yellow)
, ("blue", Just Blue)
, ("magenta", Just Magenta)
, ("cyan", Just Cyan)
, ("white", Just White)
, ("default", Nothing)
]
pSetColourCmd :: IP.IdrisParser Command
pSetColourCmd = (do c <- pColourType
let defaultColour = IdrisColour Nothing True False False False
opts <- P.sepBy pColourMod (IP.whiteSpace)
let colour = foldr ($) defaultColour $ reverse opts
return $ SetColour c colour)
<|> P.try (IP.symbol "on" >> return ColourOn)
<|> P.try (IP.symbol "off" >> return ColourOff)
pColour :: IP.IdrisParser (Maybe Color)
pColour = doColour colours
where doColour [] = fail "Unknown colour"
doColour ((s, c):cs) = (P.try (IP.symbol s) >> return c) <|> doColour cs
pColourMod :: IP.IdrisParser (IdrisColour -> IdrisColour)
pColourMod = P.try (doVivid <$ IP.symbol "vivid")
<|> P.try (doDull <$ IP.symbol "dull")
<|> P.try (doUnderline <$ IP.symbol "underline")
<|> P.try (doNoUnderline <$ IP.symbol "nounderline")
<|> P.try (doBold <$ IP.symbol "bold")
<|> P.try (doNoBold <$ IP.symbol "nobold")
<|> P.try (doItalic <$ IP.symbol "italic")
<|> P.try (doNoItalic <$ IP.symbol "noitalic")
<|> P.try (pColour >>= return . doSetColour)
where doVivid i = i { vivid = True }
doDull i = i { vivid = False }
doUnderline i = i { underline = True }
doNoUnderline i = i { underline = False }
doBold i = i { bold = True }
doNoBold i = i { bold = False }
doItalic i = i { italic = True }
doNoItalic i = i { italic = False }
doSetColour c i = i { colour = c }
-- | Generate the colour type names using the default Show instance.
colourTypes :: [(String, ColourType)]
colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
enumFromTo minBound maxBound
pColourType :: IP.IdrisParser ColourType
pColourType = doColourType colourTypes
where doColourType [] = fail $ "Unknown colour category. Options: " ++
(concat . intersperse ", " . map fst) colourTypes
doColourType ((s,ct):cts) = (P.try (IP.symbol s) >> return ct) <|> doColourType cts
idChar = P.oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
cmd_apropos :: String -> IP.IdrisParser (Either String Command)
cmd_apropos = packageBasedCmd (some idChar) Apropos
packageBasedCmd :: IP.IdrisParser a -> ([PkgName] -> a -> Command)
-> String -> IP.IdrisParser (Either String Command)
packageBasedCmd valParser cmd name =
P.try (do IP.lchar '('
pkgs <- P.sepBy (pkg <* IP.whiteSpace) (IP.lchar ',')
IP.lchar ')'
val <- valParser
return (Right (cmd pkgs val)))
<|> do val <- valParser
return (Right (cmd [] val))
where
pkg = either fail pure . pkgName =<< IP.packageName
cmd_search :: String -> IP.IdrisParser (Either String Command)
cmd_search = packageBasedCmd
(IP.fullExpr (defaultSyntax { implicitAllowed = True })) Search
cmd_proofsearch :: String -> IP.IdrisParser (Either String Command)
cmd_proofsearch name = do
upd <- P.option False (True <$ IP.lchar '!')
l <- fromInteger <$> IP.natural; n <- IP.name
hints <- P.many IP.fnName
return (Right (DoProofSearch upd True l n hints))
cmd_refine :: String -> IP.IdrisParser (Either String Command)
cmd_refine name = do
upd <- P.option False (do IP.lchar '!'; return True)
l <- fromInteger <$> IP.natural; n <- IP.name
hint <- IP.fnName
return (Right (DoProofSearch upd False l n [hint]))
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/idris-1.3.3/src/Idris/REPL/Parser.hs | haskell | NOTE: dragons
| Generate the colour type names using the default Show instance. | |
Module : . : for the REPL commands .
License : : The Idris Community .
Module : Idris.REPL.Parser
Description : Parser for the REPL commands.
License : BSD3
Maintainer : The Idris Community.
-}
# LANGUAGE FlexibleContexts #
module Idris.REPL.Parser (
parseCmd
, help
, allHelp
, setOptions
) where
import Idris.AbsSyntax
import Idris.Colours
import Idris.Core.TT
import Idris.Help
import Idris.Imports
import Idris.Options
import qualified Idris.Parser as IP
import qualified Idris.Parser.Expr as IP
import qualified Idris.Parser.Helpers as IP
import qualified Idris.Parser.Ops as IP
import Idris.REPL.Commands
import Control.Applicative
import Control.Monad.State.Strict
import Data.Char (isSpace, toLower)
import Data.List
import Data.List.Split (splitOn)
import System.Console.ANSI (Color(..))
import System.FilePath ((</>))
import qualified Text.Megaparsec as P
parseCmd :: IState -> String -> String -> Either IP.ParseError (Either String Command)
parseCmd i inputname = IP.runparser pCmd i inputname . trim
where trim = f . f
where f = reverse . dropWhile isSpace
type CommandTable = [ ( [String], CmdArg, String
, String -> IP.IdrisParser (Either String Command) ) ]
setOptions :: [(String, Opt)]
setOptions = [("errorcontext", ErrContext),
("showimplicits", ShowImpl),
("originalerrors", ShowOrigErr),
("autosolve", AutoSolve),
("nobanner", NoBanner),
("warnreach", WarnReach),
("evaltypes", EvalTypes),
("desugarnats", DesugarNats)]
help :: [([String], CmdArg, String)]
help = (["<expr>"], NoArg, "Evaluate an expression") :
[ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
allHelp :: [([String], CmdArg, String)]
allHelp = [ (map (':' :) names, args, text)
| (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
parserCommandsForHelp :: CommandTable
parserCommandsForHelp =
[ exprArgCmd ["t", "type"] Check "Check the type of an expression"
, exprArgCmd ["core"] Core "View the core language representation of a term"
, nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
, (["doc"], NameArg, "Show internal documentation", cmd_doc)
, (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
, genArg "namespace" (P.many P.anySingle) MakeDoc)
, (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
, cmd_apropos)
, (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
, " Search for values by type", cmd_search)
, nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
, nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
, namespaceArgCmd ["browse"] Browse "List the contents of some namespace"
, nameArgCmd ["total"] TotCheck "Check the totality of a name"
, noArgCmd ["r", "reload"] Reload "Reload current file"
, noArgCmd ["w", "watch"] Watch "Watch the current file for changes"
, (["l", "load"], FileArg, "Load a new file"
, strArg (\f -> Load f Nothing))
, (["!"], ShellCommandArg, "Run a shell command", strArg RunShellCommand)
, (["cd"], FileArg, "Change working directory"
, strArg ChangeDirectory)
, noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
, noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)"
, (["p", "prove"], MetaVarArg, "Prove a metavariable"
, nameArg (Prove False))
, (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell"
, nameArg (Prove True))
, (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
, (["rmproof"], NameArg, "Remove proof from proof stack"
, nameArg RmProof)
, (["showproof"], NameArg, "Show proof"
, nameArg ShowProof)
, noArgCmd ["proofs"] Proofs "Show available proofs"
, exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
, (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
, (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
, (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
, (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
, noArgCmd ["?", "h", "help"] Help "Display this help text"
, optArgCmd ["set"] SetOpt $ "Set an option (" ++ optionsList ++ ")"
, optArgCmd ["unset"] UnsetOpt "Unset an option"
, (["color", "colour"], ColourArg
, "Turn REPL colours on or off; set a specific colour"
, cmd_colour)
, (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
, (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)
, noArgCmd ["q", "quit"] Quit "Exit the Idris system"
, noArgCmd ["version"] ShowVersion "Display the Idris version"
, noArgCmd ["warranty"] Warranty "Displays warranty information"
, (["let"], ManyArgs DeclArg
, "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
, cmd_let)
, (["unlet", "undefine"], ManyArgs NameArg
, "Remove the listed repl definitions, or all repl definitions if no names given"
, cmd_unlet)
, nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
, (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
, "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
, cmd_pprint)
, (["verbosity"], NumberArg, "Set verbosity level", cmd_verb)
]
where optionsList = intercalate ", " $ map fst setOptions
parserCommands :: CommandTable
parserCommands =
[ noArgCmd ["u", "universes"] Universes "Display universe constraints"
, noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
, nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
, nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
, nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
, exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
, exprArgCmd ["spec"] Spec "?"
, exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression"
, exprArgCmd ["inline"] TestInline "?"
, proofArgCmd ["cs", "casesplit"] CaseSplitAt
":cs <line> <name> splits the pattern variable on the line"
, proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
":apc <line> <name> adds a pattern-matching proof clause to name on line"
, proofArgCmd ["ac", "addclause"] AddClauseFrom
":ac <line> <name> adds a clause for the definition of the name on the line"
, proofArgCmd ["am", "addmissing"] AddMissing
":am <line> <name> adds all missing pattern matches for the name on the line"
, proofArgCmd ["mw", "makewith"] MakeWith
":mw <line> <name> adds a with clause for the definition of the name on the line"
, proofArgCmd ["mc", "makecase"] MakeCase
":mc <line> <name> adds a case block for the definition of the metavariable on the line"
, proofArgCmd ["ml", "makelemma"] MakeLemma "?"
, (["log"], NumberArg, "Set logging level", cmd_log)
, ( ["logcats"]
, ManyArgs NameArg
, "Set logging categories"
, cmd_cats)
, (["lto", "loadto"], SeqArgs NumberArg FileArg
, "Load file up to line number", cmd_loadto)
, (["ps", "proofsearch"], NoArg
, ":ps <line> <name> <names> does proof search for name on line, with names as hints"
, cmd_proofsearch)
, (["ref", "refine"], NoArg
, ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
, cmd_refine)
, (["debugunify"], SeqArgs ExprArg ExprArg
, "(Debugging) Try to unify two expressions", const $ do
l <- IP.simpleExpr defaultSyntax
r <- IP.simpleExpr defaultSyntax
P.eof
return (Right (DebugUnify l r))
)
]
noArgCmd names command doc =
(names, NoArg, doc, noArgs command)
nameArgCmd names command doc =
(names, NameArg, doc, fnNameArg command)
namespaceArgCmd names command doc =
(names, NamespaceArg, doc, namespaceArg command)
exprArgCmd names command doc =
(names, ExprArg, doc, exprArg command)
optArgCmd names command doc =
(names, OptionArg, doc, optArg command)
proofArgCmd names command doc =
(names, NoArg, doc, proofArg command)
pCmd :: IP.IdrisParser (Either String Command)
pCmd = P.choice [ do c <- cmd names; parser c
| (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
<|> unrecognized
<|> nop
<|> eval
where nop = do P.eof; return (Right NOP)
unrecognized = do
IP.lchar ':'
cmd <- P.many P.anySingle
let cmd' = takeWhile (/=' ') cmd
return (Left $ "Unrecognized command: " ++ cmd')
cmd :: [String] -> IP.IdrisParser String
cmd xs = P.try $ do
IP.lchar ':'
docmd sorted_xs
where docmd [] = fail "Could not parse command"
docmd (x:xs) = P.try (IP.reserved x >> return x) <|> docmd xs
sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
noArgs :: Command -> String -> IP.IdrisParser (Either String Command)
noArgs cmd name = do
let emptyArgs = do
P.eof
return (Right cmd)
let failure = return (Left $ ":" ++ name ++ " takes no arguments")
emptyArgs <|> failure
eval :: IP.IdrisParser (Either String Command)
eval = do
t <- IP.fullExpr defaultSyntax
return $ Right (Eval t)
exprArg :: (PTerm -> Command) -> String -> IP.IdrisParser (Either String Command)
exprArg cmd name = do
let noArg = do
P.eof
return $ Left ("Usage is :" ++ name ++ " <expression>")
let justOperator = do
(op, fc) <- IP.withExtent IP.symbolicOperator
P.eof
return $ Right $ cmd (PRef fc [] (sUN op))
let properArg = do
t <- IP.fullExpr defaultSyntax
return $ Right (cmd t)
P.try noArg <|> P.try justOperator <|> properArg
genArg :: String -> IP.IdrisParser a -> (a -> Command)
-> String -> IP.IdrisParser (Either String Command)
genArg argName argParser cmd name = do
let emptyArgs = do P.eof; failure
oneArg = do arg <- argParser
P.eof
return (Right (cmd arg))
P.try emptyArgs <|> oneArg <|> failure
where
failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
nameArg, fnNameArg :: (Name -> Command) -> String -> IP.IdrisParser (Either String Command)
nameArg = genArg "name" IP.name
fnNameArg = genArg "functionname" IP.fnName
strArg :: (String -> Command) -> String -> IP.IdrisParser (Either String Command)
strArg = genArg "string" (P.many P.anySingle)
moduleArg :: (FilePath -> Command) -> String -> IP.IdrisParser (Either String Command)
moduleArg = genArg "module" (fmap toPath IP.identifier)
where
toPath n = foldl1' (</>) $ splitOn "." n
namespaceArg :: ([String] -> Command) -> String -> IP.IdrisParser (Either String Command)
namespaceArg = genArg "namespace" (fmap toNS IP.identifier)
where
toNS = splitOn "."
optArg :: (Opt -> Command) -> String -> IP.IdrisParser (Either String Command)
optArg cmd name = do
let emptyArgs = do
P.eof
return $ Left ("Usage is :" ++ name ++ " <option>")
let oneArg = do
o <- pOption
IP.whiteSpace
P.eof
return (Right (cmd o))
let failure = return $ Left "Unrecognized setting"
P.try emptyArgs <|> oneArg <|> failure
where
pOption :: IP.IdrisParser Opt
pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (IP.symbol a); return b) setOptions
proofArg :: (Bool -> Int -> Name -> Command) -> String -> IP.IdrisParser (Either String Command)
proofArg cmd name = do
upd <- P.option False $ do
IP.lchar '!'
return True
l <- IP.natural
n <- IP.name
return (Right (cmd upd (fromInteger l) n))
cmd_doc :: String -> IP.IdrisParser (Either String Command)
cmd_doc name = do
let constant = do
c <- IP.constant
P.eof
return $ Right (DocStr (Right c) FullDocs)
let pType = do
IP.reserved "Type"
P.eof
return $ Right (DocStr (Left $ sUN "Type") FullDocs)
let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
P.try constant <|> pType <|> fnName
cmd_consolewidth :: String -> IP.IdrisParser (Either String Command)
cmd_consolewidth name = do
w <- pConsoleWidth
return (Right (SetConsoleWidth w))
where
pConsoleWidth :: IP.IdrisParser ConsoleWidth
pConsoleWidth = do discard (IP.symbol "auto"); return AutomaticWidth
<|> do discard (IP.symbol "infinite"); return InfinitelyWide
<|> do n <- fromInteger <$> IP.natural
return (ColsWide n)
cmd_printdepth :: String -> IP.IdrisParser (Either String Command)
cmd_printdepth _ = do d <- optional (fromInteger <$> IP.natural)
return (Right $ SetPrinterDepth d)
cmd_execute :: String -> IP.IdrisParser (Either String Command)
cmd_execute name = do
tm <- P.option maintm (IP.fullExpr defaultSyntax)
return (Right (Execute tm))
where
maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
cmd_dynamic :: String -> IP.IdrisParser (Either String Command)
cmd_dynamic name = do
let optArg = do l <- P.many P.anySingle
if (l /= "")
then return $ Right (DynamicLink l)
else return $ Right ListDynamic
let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
P.try optArg <|> failure
cmd_pprint :: String -> IP.IdrisParser (Either String Command)
cmd_pprint name = do
fmt <- ppFormat
IP.whiteSpace
n <- fromInteger <$> IP.natural
IP.whiteSpace
t <- IP.fullExpr defaultSyntax
return (Right (PPrint fmt n t))
where
ppFormat :: IP.IdrisParser OutputFmt
ppFormat = (discard (IP.symbol "html") >> return HTMLOutput)
<|> (discard (IP.symbol "latex") >> return LaTeXOutput)
cmd_compile :: String -> IP.IdrisParser (Either String Command)
cmd_compile name = do
let defaultCodegen = Via IBCFormat "c"
let codegenOption :: IP.IdrisParser Codegen
codegenOption = do
let bytecodeCodegen = discard (IP.symbol "bytecode") *> return Bytecode
viaCodegen = do x <- IP.identifier
return (Via IBCFormat (map toLower x))
bytecodeCodegen <|> viaCodegen
let hasOneArg = do
i <- get
f <- IP.identifier
P.eof
return $ Right (Compile defaultCodegen f)
let hasTwoArgs = do
i <- get
codegen <- codegenOption
f <- IP.identifier
P.eof
return $ Right (Compile codegen f)
let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
P.try hasTwoArgs <|> P.try hasOneArg <|> failure
cmd_addproof :: String -> IP.IdrisParser (Either String Command)
cmd_addproof name = do
n <- P.option Nothing $ do
x <- IP.name
return (Just x)
P.eof
return (Right (AddProof n))
cmd_log :: String -> IP.IdrisParser (Either String Command)
cmd_log name = do
i <- fromIntegral <$> IP.natural
P.eof
return (Right (LogLvl i))
cmd_verb :: String -> IP.IdrisParser (Either String Command)
cmd_verb name = do
i <- fromIntegral <$> IP.natural
P.eof
return (Right (Verbosity i))
cmd_cats :: String -> IP.IdrisParser (Either String Command)
cmd_cats name = do
cs <- P.sepBy pLogCats (IP.whiteSpace)
P.eof
return $ Right $ LogCategory (concat cs)
where
badCat = do
c <- IP.identifier
fail $ "Category: " ++ c ++ " is not recognised."
pLogCats :: IP.IdrisParser [LogCat]
pLogCats = P.try (parserCats <$ IP.symbol (strLogCat IParse))
<|> P.try (elabCats <$ IP.symbol (strLogCat IElab))
<|> P.try (codegenCats <$ IP.symbol (strLogCat ICodeGen))
<|> P.try ([ICoverage] <$ IP.symbol (strLogCat ICoverage))
<|> P.try ([IIBC] <$ IP.symbol (strLogCat IIBC))
<|> P.try ([IErasure] <$ IP.symbol (strLogCat IErasure))
<|> badCat
cmd_let :: String -> IP.IdrisParser (Either String Command)
cmd_let name = do
defn <- concat <$> P.many (IP.decl defaultSyntax)
return (Right (NewDefn defn))
cmd_unlet :: String -> IP.IdrisParser (Either String Command)
cmd_unlet name = Right . Undefine <$> P.many IP.name
cmd_loadto :: String -> IP.IdrisParser (Either String Command)
cmd_loadto name = do
toline <- fromInteger <$> IP.natural
f <- P.many P.anySingle
return (Right (Load f (Just toline)))
cmd_colour :: String -> IP.IdrisParser (Either String Command)
cmd_colour name = fmap Right pSetColourCmd
where
colours :: [(String, Maybe Color)]
colours = [ ("black", Just Black)
, ("red", Just Red)
, ("green", Just Green)
, ("yellow", Just Yellow)
, ("blue", Just Blue)
, ("magenta", Just Magenta)
, ("cyan", Just Cyan)
, ("white", Just White)
, ("default", Nothing)
]
pSetColourCmd :: IP.IdrisParser Command
pSetColourCmd = (do c <- pColourType
let defaultColour = IdrisColour Nothing True False False False
opts <- P.sepBy pColourMod (IP.whiteSpace)
let colour = foldr ($) defaultColour $ reverse opts
return $ SetColour c colour)
<|> P.try (IP.symbol "on" >> return ColourOn)
<|> P.try (IP.symbol "off" >> return ColourOff)
pColour :: IP.IdrisParser (Maybe Color)
pColour = doColour colours
where doColour [] = fail "Unknown colour"
doColour ((s, c):cs) = (P.try (IP.symbol s) >> return c) <|> doColour cs
pColourMod :: IP.IdrisParser (IdrisColour -> IdrisColour)
pColourMod = P.try (doVivid <$ IP.symbol "vivid")
<|> P.try (doDull <$ IP.symbol "dull")
<|> P.try (doUnderline <$ IP.symbol "underline")
<|> P.try (doNoUnderline <$ IP.symbol "nounderline")
<|> P.try (doBold <$ IP.symbol "bold")
<|> P.try (doNoBold <$ IP.symbol "nobold")
<|> P.try (doItalic <$ IP.symbol "italic")
<|> P.try (doNoItalic <$ IP.symbol "noitalic")
<|> P.try (pColour >>= return . doSetColour)
where doVivid i = i { vivid = True }
doDull i = i { vivid = False }
doUnderline i = i { underline = True }
doNoUnderline i = i { underline = False }
doBold i = i { bold = True }
doNoBold i = i { bold = False }
doItalic i = i { italic = True }
doNoItalic i = i { italic = False }
doSetColour c i = i { colour = c }
colourTypes :: [(String, ColourType)]
colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
enumFromTo minBound maxBound
pColourType :: IP.IdrisParser ColourType
pColourType = doColourType colourTypes
where doColourType [] = fail $ "Unknown colour category. Options: " ++
(concat . intersperse ", " . map fst) colourTypes
doColourType ((s,ct):cts) = (P.try (IP.symbol s) >> return ct) <|> doColourType cts
idChar = P.oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
cmd_apropos :: String -> IP.IdrisParser (Either String Command)
cmd_apropos = packageBasedCmd (some idChar) Apropos
packageBasedCmd :: IP.IdrisParser a -> ([PkgName] -> a -> Command)
-> String -> IP.IdrisParser (Either String Command)
packageBasedCmd valParser cmd name =
P.try (do IP.lchar '('
pkgs <- P.sepBy (pkg <* IP.whiteSpace) (IP.lchar ',')
IP.lchar ')'
val <- valParser
return (Right (cmd pkgs val)))
<|> do val <- valParser
return (Right (cmd [] val))
where
pkg = either fail pure . pkgName =<< IP.packageName
cmd_search :: String -> IP.IdrisParser (Either String Command)
cmd_search = packageBasedCmd
(IP.fullExpr (defaultSyntax { implicitAllowed = True })) Search
cmd_proofsearch :: String -> IP.IdrisParser (Either String Command)
cmd_proofsearch name = do
upd <- P.option False (True <$ IP.lchar '!')
l <- fromInteger <$> IP.natural; n <- IP.name
hints <- P.many IP.fnName
return (Right (DoProofSearch upd True l n hints))
cmd_refine :: String -> IP.IdrisParser (Either String Command)
cmd_refine name = do
upd <- P.option False (do IP.lchar '!'; return True)
l <- fromInteger <$> IP.natural; n <- IP.name
hint <- IP.fnName
return (Right (DoProofSearch upd False l n [hint]))
|
2f25265f7da4fa582478eb4ffec9a5eeeb7d0a513b1a8d6fa4cf1f4a7d2480a6 | avsm/eeww | ctype.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. *)
(* *)
(**************************************************************************)
Operations on core types
open Asttypes
open Types
exception Unify of Errortrace.unification_error
exception Equality of Errortrace.equality_error
exception Moregen of Errortrace.moregen_error
exception Subtype of Errortrace.Subtype.error
exception Escape of type_expr Errortrace.escape
exception Tags of label * label
exception Cannot_expand
exception Cannot_apply
exception Matches_failure of Env.t * Errortrace.unification_error
(* Raised from [matches], hence the odd name *)
exception Incompatible
Raised from [ ]
(* All the following wrapper functions revert to the original level,
even in case of exception. *)
val with_local_level: ?post:('a -> unit) -> (unit -> 'a) -> 'a
(* [with_local_level (fun () -> cmd) ~post] evaluates [cmd] at a
raised level.
If given, [post] is applied to the result, at the original level.
It is expected to contain only level related post-processing. *)
val with_local_level_if: bool -> (unit -> 'a) -> post:('a -> unit) -> 'a
(* Same as [with_local_level], but only raise the level conditionally.
[post] also is only called if the level is raised. *)
val with_local_level_iter: (unit -> 'a * 'b list) -> post:('b -> unit) -> 'a
(* Variant of [with_local_level], where [post] is iterated on the
returned list. *)
val with_local_level_iter_if:
bool -> (unit -> 'a * 'b list) -> post:('b -> unit) -> 'a
(* Conditional variant of [with_local_level_iter] *)
val with_level: level: int -> (unit -> 'a) -> 'a
(* [with_level ~level (fun () -> cmd)] evaluates [cmd] with
[current_level] set to [level] *)
val with_level_if: bool -> level: int -> (unit -> 'a) -> 'a
(* Conditional variant of [with_level] *)
val with_local_level_if_principal: (unit -> 'a) -> post:('a -> unit) -> 'a
val with_local_level_iter_if_principal:
(unit -> 'a * 'b list) -> post:('b -> unit) -> 'a
Applications of [ with_local_level_if ] and [ with_local_level_iter_if ]
to [ ! Clflags.principal ]
to [!Clflags.principal] *)
val with_local_level_for_class: ?post:('a -> unit) -> (unit -> 'a) -> 'a
Variant of [ with_local_level ] , where the current level is raised but
the level is not touched
the nongen level is not touched *)
val with_raised_nongen_level: (unit -> 'a) -> 'a
Variant of [ with_local_level ] ,
raises the level to the current level
raises the nongen level to the current level *)
val reset_global_level: unit -> unit
(* Reset the global level before typing an expression *)
val increase_global_level: unit -> int
val restore_global_level: int -> unit
This pair of functions is only used in Typetexp
val create_scope : unit -> int
val newty: type_desc -> type_expr
val new_scoped_ty: int -> type_desc -> type_expr
val newvar: ?name:string -> unit -> type_expr
val newvar2: ?name:string -> int -> type_expr
(* Return a fresh variable *)
val new_global_var: ?name:string -> unit -> type_expr
(* Return a fresh variable, bound at toplevel
(as type variables ['a] in type constraints). *)
val newobj: type_expr -> type_expr
val newconstr: Path.t -> type_expr list -> type_expr
val none: type_expr
(* A dummy type expression *)
val object_fields: type_expr -> type_expr
val flatten_fields:
type_expr -> (string * field_kind * type_expr) list * type_expr
* Transform a field type into a list of pairs label - type .
The fields are sorted .
Beware of the interaction with GADTs :
Due to the introduction of object indexes for GADTs , the row variable of
an object may now be an expansible type abbreviation .
A first consequence is that [ flatten_fields ] will not completely flatten
the object , since the type abbreviation will not be expanded
( [ flatten_fields ] does not receive the current environment ) .
Another consequence is that various functions may be called with the
expansion of this type abbreviation , which is a , e.g. during
printing .
Concrete problems have been fixed , but new bugs may appear in the
future . ( Test cases were added to typing - gadts / test.ml )
The fields are sorted.
Beware of the interaction with GADTs:
Due to the introduction of object indexes for GADTs, the row variable of
an object may now be an expansible type abbreviation.
A first consequence is that [flatten_fields] will not completely flatten
the object, since the type abbreviation will not be expanded
([flatten_fields] does not receive the current environment).
Another consequence is that various functions may be called with the
expansion of this type abbreviation, which is a Tfield, e.g. during
printing.
Concrete problems have been fixed, but new bugs may appear in the
future. (Test cases were added to typing-gadts/test.ml)
*)
val associate_fields:
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr * field_kind * type_expr) list *
(string * field_kind * type_expr) list *
(string * field_kind * type_expr) list
val opened_object: type_expr -> bool
val set_object_name:
Ident.t -> type_expr list -> type_expr -> unit
val remove_object_name: type_expr -> unit
val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr
val sort_row_fields: (label * row_field) list -> (label * row_field) list
val merge_row_fields:
(label * row_field) list -> (label * row_field) list ->
(label * row_field) list * (label * row_field) list *
(label * row_field * row_field) list
val filter_row_fields:
bool -> (label * row_field) list -> (label * row_field) list
val generalize: type_expr -> unit
in - place the given type
val lower_contravariant: Env.t -> type_expr -> unit
(* Lower level of type variables inside contravariant branches;
to be used before generalize for expansive expressions *)
val lower_variables_only: Env.t -> int -> type_expr -> unit
(* Lower all variables to the given level *)
val enforce_current_level: Env.t -> type_expr -> unit
(* Lower whole type to !current_level *)
val generalize_structure: type_expr -> unit
the structure of a type , lowering variables
to ! current_level
to !current_level *)
val generalize_class_type : class_type -> unit
the components of a class type
val generalize_class_type_structure : class_type -> unit
the structure of the components of a class type
val generalize_class_signature_spine : Env.t -> class_signature -> unit
(* Special function to generalize methods during inference *)
val correct_levels: type_expr -> type_expr
(* Returns a copy with decreasing levels *)
val limited_generalize: type_expr -> type_expr -> unit
(* Only generalize some part of the type
Make the remaining of the type non-generalizable *)
val limited_generalize_class_type: type_expr -> class_type -> unit
(* Same, but for class types *)
val fully_generic: type_expr -> bool
val check_scope_escape : Env.t -> int -> type_expr -> unit
(* [check_scope_escape env lvl ty] ensures that [ty] could be raised
to the level [lvl] without any scope escape.
Raises [Escape] otherwise *)
val instance: ?partial:bool -> type_expr -> type_expr
(* Take an instance of a type scheme *)
(* partial=None -> normal
partial=false -> newvar() for non generic subterms
partial=true -> newty2 ty.level Tvar for non generic subterms *)
val generic_instance: type_expr -> type_expr
(* Same as instance, but new nodes at generic_level *)
val instance_list: type_expr list -> type_expr list
(* Take an instance of a list of type schemes *)
val new_local_type:
?loc:Location.t ->
?manifest_and_scope:(type_expr * int) -> unit -> type_declaration
val existential_name: constructor_description -> type_expr -> string
type existential_treatment =
| Keep_existentials_flexible
| Make_existentials_abstract of { env: Env.t ref; scope: int }
val instance_constructor: existential_treatment ->
constructor_description -> type_expr list * type_expr * type_expr list
(* Same, for a constructor. Also returns existentials. *)
val instance_parameterized_type:
?keep_names:bool ->
type_expr list -> type_expr -> type_expr list * type_expr
val instance_declaration: type_declaration -> type_declaration
val generic_instance_declaration: type_declaration -> type_declaration
(* Same as instance_declaration, but new nodes at generic_level *)
val instance_class:
type_expr list -> class_type -> type_expr list * class_type
val instance_poly:
?keep_names:bool ->
bool -> type_expr list -> type_expr -> type_expr list * type_expr
(* Take an instance of a type scheme containing free univars *)
val polyfy: Env.t -> type_expr -> type_expr list -> type_expr * bool
val instance_label:
bool -> label_description -> type_expr list * type_expr * type_expr
(* Same, for a label *)
val apply:
?use_current_level:bool ->
Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr
(* [apply [p1...pN] t [a1...aN]] applies the type function
[fun p1 ... pN -> t] to the arguments [a1...aN] and returns the
resulting instance of [t].
New nodes default to generic level except if [use_current_level] is
set to true.
Exception [Cannot_apply] is raised in case of failure. *)
val try_expand_once_opt: Env.t -> type_expr -> type_expr
val try_expand_safe_opt: Env.t -> type_expr -> type_expr
val expand_head_once: Env.t -> type_expr -> type_expr
val expand_head: Env.t -> type_expr -> type_expr
val expand_head_opt: Env.t -> type_expr -> type_expr
(** The compiler's own version of [expand_head] necessary for type-based
optimisations. *)
(** Expansion of types for error traces; lives here instead of in [Errortrace]
because the expansion machinery lives here. *)
* Create an [ Errortrace . Diff ] by expanding the two types
val expanded_diff :
Env.t ->
got:type_expr -> expected:type_expr ->
(Errortrace.expanded_type, 'variant) Errortrace.elt
* Create an [ Errortrace . Diff ] by * duplicating * the two types , so that each
one 's expansion is identical to itself . Despite the name , does create
[ Errortrace.expanded_type]s .
one's expansion is identical to itself. Despite the name, does create
[Errortrace.expanded_type]s. *)
val unexpanded_diff :
got:type_expr -> expected:type_expr ->
(Errortrace.expanded_type, 'variant) Errortrace.elt
val full_expand: may_forget_scope:bool -> Env.t -> type_expr -> type_expr
type typedecl_extraction_result =
| Typedecl of Path.t * Path.t * type_declaration
The original path of the types , and the first concrete
type declaration found expanding it .
type declaration found expanding it. *)
| Has_no_typedecl
| May_have_typedecl
val extract_concrete_typedecl:
Env.t -> type_expr -> typedecl_extraction_result
val unify: Env.t -> type_expr -> type_expr -> unit
Unify the two types given . Raise [ Unify ] if not possible .
val unify_gadt:
equations_level:int -> allow_recursive_equations:bool ->
Env.t ref -> type_expr -> type_expr -> Btype.TypePairs.t
Unify the two types given and update the environment with the
local constraints . Raise [ Unify ] if not possible .
Returns the pairs of types that have been equated .
local constraints. Raise [Unify] if not possible.
Returns the pairs of types that have been equated. *)
val unify_var: Env.t -> type_expr -> type_expr -> unit
Same as [ unify ] , but allow free univars when first type
is a variable .
is a variable. *)
val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr
(* A special case of unification with [l:'a -> 'b]. Raises
[Filter_arrow_failed] instead of [Unify]. *)
val filter_method: Env.t -> string -> type_expr -> type_expr
(* A special case of unification (with {m : 'a; 'b}). Raises
[Filter_method_failed] instead of [Unify]. *)
val occur_in: Env.t -> type_expr -> type_expr -> bool
val deep_occur: type_expr -> type_expr -> bool
val moregeneral: Env.t -> bool -> type_expr -> type_expr -> unit
Check if the first type scheme is more general than the second .
val is_moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool
val rigidify: type_expr -> type_expr list
" Rigidify " a type and return its type variable
val all_distinct_vars: Env.t -> type_expr list -> bool
(* Check those types are all distinct type variables *)
val matches: expand_error_trace:bool -> Env.t -> type_expr -> type_expr -> unit
Same as [ moregeneral false ] , implemented using the two above
functions and backtracking . Ignore levels . The [ expand_error_trace ]
flag controls whether the error raised performs expansion ; this
should almost always be [ true ] .
functions and backtracking. Ignore levels. The [expand_error_trace]
flag controls whether the error raised performs expansion; this
should almost always be [true]. *)
val does_match: Env.t -> type_expr -> type_expr -> bool
(* Same as [matches], but returns a [bool] *)
val reify_univars : Env.t -> Types.type_expr -> Types.type_expr
(* Replaces all the variables of a type by a univar. *)
(* Exceptions for special cases of unify *)
type filter_arrow_failure =
| Unification_error of Errortrace.unification_error
| Label_mismatch of
{ got : arg_label
; expected : arg_label
; expected_type : type_expr
}
| Not_a_function
exception Filter_arrow_failed of filter_arrow_failure
type filter_method_failure =
| Unification_error of Errortrace.unification_error
| Not_a_method
| Not_an_object of type_expr
exception Filter_method_failed of filter_method_failure
type class_match_failure =
CM_Virtual_class
| CM_Parameter_arity_mismatch of int * int
| CM_Type_parameter_mismatch of Env.t * Errortrace.equality_error
| CM_Class_type_mismatch of Env.t * class_type * class_type
| CM_Parameter_mismatch of Env.t * Errortrace.moregen_error
| CM_Val_type_mismatch of string * Env.t * Errortrace.comparison_error
| CM_Meth_type_mismatch of string * Env.t * Errortrace.comparison_error
| CM_Non_mutable_value of string
| CM_Non_concrete_value of string
| CM_Missing_value of string
| CM_Missing_method of string
| CM_Hide_public of string
| CM_Hide_virtual of string * string
| CM_Public_method of string
| CM_Private_method of string
| CM_Virtual_method of string
val match_class_types:
?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list
Check if the first class type is more general than the second .
val equal: Env.t -> bool -> type_expr list -> type_expr list -> unit
(* [equal env [x1...xn] tau [y1...yn] sigma]
checks whether the parameterized types
[/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. *)
val is_equal : Env.t -> bool -> type_expr list -> type_expr list -> bool
val equal_private :
Env.t -> type_expr list -> type_expr ->
type_expr list -> type_expr -> unit
(* [equal_private env t1 params1 t2 params2] checks that [t1::params1]
equals [t2::params2] but it is allowed to expand [t1] if it is a
private abbreviations. *)
val match_class_declarations:
Env.t -> type_expr list -> class_type -> type_expr list ->
class_type -> class_match_failure list
Check if the first class type is more general than the second .
val enlarge_type: Env.t -> type_expr -> type_expr * bool
(* Make a type larger, flag is true if some pruning had to be done *)
val subtype: Env.t -> type_expr -> type_expr -> unit -> unit
(* [subtype env t1 t2] checks that [t1] is a subtype of [t2].
It accumulates the constraints the type variables must
enforce and returns a function that enforces this
constraints. *)
(* Operations on class signatures *)
val new_class_signature : unit -> class_signature
val add_dummy_method : Env.t -> scope:int -> class_signature -> unit
type add_method_failure =
| Unexpected_method
| Type_mismatch of Errortrace.unification_error
exception Add_method_failed of add_method_failure
val add_method : Env.t ->
label -> private_flag -> virtual_flag -> type_expr -> class_signature -> unit
type add_instance_variable_failure =
| Mutability_mismatch of mutable_flag
| Type_mismatch of Errortrace.unification_error
exception Add_instance_variable_failed of add_instance_variable_failure
val add_instance_variable : strict:bool -> Env.t ->
label -> mutable_flag -> virtual_flag -> type_expr -> class_signature -> unit
type inherit_class_signature_failure =
| Self_type_mismatch of Errortrace.unification_error
| Method of label * add_method_failure
| Instance_variable of label * add_instance_variable_failure
exception Inherit_class_signature_failed of inherit_class_signature_failure
val inherit_class_signature : strict:bool -> Env.t ->
class_signature -> class_signature -> unit
val update_class_signature :
Env.t -> class_signature -> label list * label list
val hide_private_methods : Env.t -> class_signature -> unit
val close_class_signature : Env.t -> class_signature -> bool
exception Nondep_cannot_erase of Ident.t
val nondep_type: Env.t -> Ident.t list -> type_expr -> type_expr
(* Return a type equivalent to the given type but without
references to any of the given identifiers.
Raise [Nondep_cannot_erase id] if no such type exists because [id],
in particular, could not be erased. *)
val nondep_type_decl:
Env.t -> Ident.t list -> bool -> type_declaration -> type_declaration
(* Same for type declarations. *)
val nondep_extension_constructor:
Env.t -> Ident.t list -> extension_constructor ->
extension_constructor
(* Same for extension constructor *)
val nondep_class_declaration:
Env.t -> Ident.t list -> class_declaration -> class_declaration
(* Same for class declarations. *)
val nondep_cltype_declaration:
Env.t -> Ident.t list -> class_type_declaration -> class_type_declaration
(* Same for class type declarations. *)
correct_abbrev : - > Path.t - > type_expr list - > type_expr - > unit
val is_contractive: Env.t -> Path.t -> bool
val normalize_type: type_expr -> unit
val nongen_schema: Env.t -> type_expr -> bool
(* Check whether the given type scheme contains no non-generic
type variables *)
val nongen_class_declaration: class_declaration -> bool
(* Check whether the given class type contains no non-generic
type variables. Uses the empty environment. *)
type variable_kind = Row_variable | Type_variable
type closed_class_failure = {
free_variable: type_expr * variable_kind;
meth: string;
meth_ty: type_expr;
}
val free_variables: ?env:Env.t -> type_expr -> type_expr list
(* If env present, then check for incomplete definitions too *)
val closed_type_decl: type_declaration -> type_expr option
val closed_extension_constructor: extension_constructor -> type_expr option
val closed_class:
type_expr list -> class_signature ->
closed_class_failure option
(* Check whether all type variables are bound *)
val unalias: type_expr -> type_expr
val arity: type_expr -> int
(* Return the arity (as for curried functions) of the given type. *)
val collapse_conj_params: Env.t -> type_expr list -> unit
(* Collapse conjunctive types in class parameters *)
val get_current_level: unit -> int
val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b
val reset_reified_var_counter: unit -> unit
val immediacy : Env.t -> type_expr -> Type_immediacy.t
(* Stubs *)
val package_subtype :
(Env.t -> Path.t -> (Longident.t * type_expr) list ->
Path.t -> (Longident.t * type_expr) list -> bool) ref
(* Raises [Incompatible] *)
val mcomp : Env.t -> type_expr -> type_expr -> unit
| null | https://raw.githubusercontent.com/avsm/eeww/4d65720b5dd51376842ffe5c8c220d5329c1dc10/boot/ocaml/typing/ctype.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.
************************************************************************
Raised from [matches], hence the odd name
All the following wrapper functions revert to the original level,
even in case of exception.
[with_local_level (fun () -> cmd) ~post] evaluates [cmd] at a
raised level.
If given, [post] is applied to the result, at the original level.
It is expected to contain only level related post-processing.
Same as [with_local_level], but only raise the level conditionally.
[post] also is only called if the level is raised.
Variant of [with_local_level], where [post] is iterated on the
returned list.
Conditional variant of [with_local_level_iter]
[with_level ~level (fun () -> cmd)] evaluates [cmd] with
[current_level] set to [level]
Conditional variant of [with_level]
Reset the global level before typing an expression
Return a fresh variable
Return a fresh variable, bound at toplevel
(as type variables ['a] in type constraints).
A dummy type expression
Lower level of type variables inside contravariant branches;
to be used before generalize for expansive expressions
Lower all variables to the given level
Lower whole type to !current_level
Special function to generalize methods during inference
Returns a copy with decreasing levels
Only generalize some part of the type
Make the remaining of the type non-generalizable
Same, but for class types
[check_scope_escape env lvl ty] ensures that [ty] could be raised
to the level [lvl] without any scope escape.
Raises [Escape] otherwise
Take an instance of a type scheme
partial=None -> normal
partial=false -> newvar() for non generic subterms
partial=true -> newty2 ty.level Tvar for non generic subterms
Same as instance, but new nodes at generic_level
Take an instance of a list of type schemes
Same, for a constructor. Also returns existentials.
Same as instance_declaration, but new nodes at generic_level
Take an instance of a type scheme containing free univars
Same, for a label
[apply [p1...pN] t [a1...aN]] applies the type function
[fun p1 ... pN -> t] to the arguments [a1...aN] and returns the
resulting instance of [t].
New nodes default to generic level except if [use_current_level] is
set to true.
Exception [Cannot_apply] is raised in case of failure.
* The compiler's own version of [expand_head] necessary for type-based
optimisations.
* Expansion of types for error traces; lives here instead of in [Errortrace]
because the expansion machinery lives here.
A special case of unification with [l:'a -> 'b]. Raises
[Filter_arrow_failed] instead of [Unify].
A special case of unification (with {m : 'a; 'b}). Raises
[Filter_method_failed] instead of [Unify].
Check those types are all distinct type variables
Same as [matches], but returns a [bool]
Replaces all the variables of a type by a univar.
Exceptions for special cases of unify
[equal env [x1...xn] tau [y1...yn] sigma]
checks whether the parameterized types
[/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent.
[equal_private env t1 params1 t2 params2] checks that [t1::params1]
equals [t2::params2] but it is allowed to expand [t1] if it is a
private abbreviations.
Make a type larger, flag is true if some pruning had to be done
[subtype env t1 t2] checks that [t1] is a subtype of [t2].
It accumulates the constraints the type variables must
enforce and returns a function that enforces this
constraints.
Operations on class signatures
Return a type equivalent to the given type but without
references to any of the given identifiers.
Raise [Nondep_cannot_erase id] if no such type exists because [id],
in particular, could not be erased.
Same for type declarations.
Same for extension constructor
Same for class declarations.
Same for class type declarations.
Check whether the given type scheme contains no non-generic
type variables
Check whether the given class type contains no non-generic
type variables. Uses the empty environment.
If env present, then check for incomplete definitions too
Check whether all type variables are bound
Return the arity (as for curried functions) of the given type.
Collapse conjunctive types in class parameters
Stubs
Raises [Incompatible] | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Operations on core types
open Asttypes
open Types
exception Unify of Errortrace.unification_error
exception Equality of Errortrace.equality_error
exception Moregen of Errortrace.moregen_error
exception Subtype of Errortrace.Subtype.error
exception Escape of type_expr Errortrace.escape
exception Tags of label * label
exception Cannot_expand
exception Cannot_apply
exception Matches_failure of Env.t * Errortrace.unification_error
exception Incompatible
Raised from [ ]
val with_local_level: ?post:('a -> unit) -> (unit -> 'a) -> 'a
val with_local_level_if: bool -> (unit -> 'a) -> post:('a -> unit) -> 'a
val with_local_level_iter: (unit -> 'a * 'b list) -> post:('b -> unit) -> 'a
val with_local_level_iter_if:
bool -> (unit -> 'a * 'b list) -> post:('b -> unit) -> 'a
val with_level: level: int -> (unit -> 'a) -> 'a
val with_level_if: bool -> level: int -> (unit -> 'a) -> 'a
val with_local_level_if_principal: (unit -> 'a) -> post:('a -> unit) -> 'a
val with_local_level_iter_if_principal:
(unit -> 'a * 'b list) -> post:('b -> unit) -> 'a
Applications of [ with_local_level_if ] and [ with_local_level_iter_if ]
to [ ! Clflags.principal ]
to [!Clflags.principal] *)
val with_local_level_for_class: ?post:('a -> unit) -> (unit -> 'a) -> 'a
Variant of [ with_local_level ] , where the current level is raised but
the level is not touched
the nongen level is not touched *)
val with_raised_nongen_level: (unit -> 'a) -> 'a
Variant of [ with_local_level ] ,
raises the level to the current level
raises the nongen level to the current level *)
val reset_global_level: unit -> unit
val increase_global_level: unit -> int
val restore_global_level: int -> unit
This pair of functions is only used in Typetexp
val create_scope : unit -> int
val newty: type_desc -> type_expr
val new_scoped_ty: int -> type_desc -> type_expr
val newvar: ?name:string -> unit -> type_expr
val newvar2: ?name:string -> int -> type_expr
val new_global_var: ?name:string -> unit -> type_expr
val newobj: type_expr -> type_expr
val newconstr: Path.t -> type_expr list -> type_expr
val none: type_expr
val object_fields: type_expr -> type_expr
val flatten_fields:
type_expr -> (string * field_kind * type_expr) list * type_expr
* Transform a field type into a list of pairs label - type .
The fields are sorted .
Beware of the interaction with GADTs :
Due to the introduction of object indexes for GADTs , the row variable of
an object may now be an expansible type abbreviation .
A first consequence is that [ flatten_fields ] will not completely flatten
the object , since the type abbreviation will not be expanded
( [ flatten_fields ] does not receive the current environment ) .
Another consequence is that various functions may be called with the
expansion of this type abbreviation , which is a , e.g. during
printing .
Concrete problems have been fixed , but new bugs may appear in the
future . ( Test cases were added to typing - gadts / test.ml )
The fields are sorted.
Beware of the interaction with GADTs:
Due to the introduction of object indexes for GADTs, the row variable of
an object may now be an expansible type abbreviation.
A first consequence is that [flatten_fields] will not completely flatten
the object, since the type abbreviation will not be expanded
([flatten_fields] does not receive the current environment).
Another consequence is that various functions may be called with the
expansion of this type abbreviation, which is a Tfield, e.g. during
printing.
Concrete problems have been fixed, but new bugs may appear in the
future. (Test cases were added to typing-gadts/test.ml)
*)
val associate_fields:
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr * field_kind * type_expr) list *
(string * field_kind * type_expr) list *
(string * field_kind * type_expr) list
val opened_object: type_expr -> bool
val set_object_name:
Ident.t -> type_expr list -> type_expr -> unit
val remove_object_name: type_expr -> unit
val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr
val sort_row_fields: (label * row_field) list -> (label * row_field) list
val merge_row_fields:
(label * row_field) list -> (label * row_field) list ->
(label * row_field) list * (label * row_field) list *
(label * row_field * row_field) list
val filter_row_fields:
bool -> (label * row_field) list -> (label * row_field) list
val generalize: type_expr -> unit
in - place the given type
val lower_contravariant: Env.t -> type_expr -> unit
val lower_variables_only: Env.t -> int -> type_expr -> unit
val enforce_current_level: Env.t -> type_expr -> unit
val generalize_structure: type_expr -> unit
the structure of a type , lowering variables
to ! current_level
to !current_level *)
val generalize_class_type : class_type -> unit
the components of a class type
val generalize_class_type_structure : class_type -> unit
the structure of the components of a class type
val generalize_class_signature_spine : Env.t -> class_signature -> unit
val correct_levels: type_expr -> type_expr
val limited_generalize: type_expr -> type_expr -> unit
val limited_generalize_class_type: type_expr -> class_type -> unit
val fully_generic: type_expr -> bool
val check_scope_escape : Env.t -> int -> type_expr -> unit
val instance: ?partial:bool -> type_expr -> type_expr
val generic_instance: type_expr -> type_expr
val instance_list: type_expr list -> type_expr list
val new_local_type:
?loc:Location.t ->
?manifest_and_scope:(type_expr * int) -> unit -> type_declaration
val existential_name: constructor_description -> type_expr -> string
type existential_treatment =
| Keep_existentials_flexible
| Make_existentials_abstract of { env: Env.t ref; scope: int }
val instance_constructor: existential_treatment ->
constructor_description -> type_expr list * type_expr * type_expr list
val instance_parameterized_type:
?keep_names:bool ->
type_expr list -> type_expr -> type_expr list * type_expr
val instance_declaration: type_declaration -> type_declaration
val generic_instance_declaration: type_declaration -> type_declaration
val instance_class:
type_expr list -> class_type -> type_expr list * class_type
val instance_poly:
?keep_names:bool ->
bool -> type_expr list -> type_expr -> type_expr list * type_expr
val polyfy: Env.t -> type_expr -> type_expr list -> type_expr * bool
val instance_label:
bool -> label_description -> type_expr list * type_expr * type_expr
val apply:
?use_current_level:bool ->
Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr
val try_expand_once_opt: Env.t -> type_expr -> type_expr
val try_expand_safe_opt: Env.t -> type_expr -> type_expr
val expand_head_once: Env.t -> type_expr -> type_expr
val expand_head: Env.t -> type_expr -> type_expr
val expand_head_opt: Env.t -> type_expr -> type_expr
* Create an [ Errortrace . Diff ] by expanding the two types
val expanded_diff :
Env.t ->
got:type_expr -> expected:type_expr ->
(Errortrace.expanded_type, 'variant) Errortrace.elt
* Create an [ Errortrace . Diff ] by * duplicating * the two types , so that each
one 's expansion is identical to itself . Despite the name , does create
[ Errortrace.expanded_type]s .
one's expansion is identical to itself. Despite the name, does create
[Errortrace.expanded_type]s. *)
val unexpanded_diff :
got:type_expr -> expected:type_expr ->
(Errortrace.expanded_type, 'variant) Errortrace.elt
val full_expand: may_forget_scope:bool -> Env.t -> type_expr -> type_expr
type typedecl_extraction_result =
| Typedecl of Path.t * Path.t * type_declaration
The original path of the types , and the first concrete
type declaration found expanding it .
type declaration found expanding it. *)
| Has_no_typedecl
| May_have_typedecl
val extract_concrete_typedecl:
Env.t -> type_expr -> typedecl_extraction_result
val unify: Env.t -> type_expr -> type_expr -> unit
Unify the two types given . Raise [ Unify ] if not possible .
val unify_gadt:
equations_level:int -> allow_recursive_equations:bool ->
Env.t ref -> type_expr -> type_expr -> Btype.TypePairs.t
Unify the two types given and update the environment with the
local constraints . Raise [ Unify ] if not possible .
Returns the pairs of types that have been equated .
local constraints. Raise [Unify] if not possible.
Returns the pairs of types that have been equated. *)
val unify_var: Env.t -> type_expr -> type_expr -> unit
Same as [ unify ] , but allow free univars when first type
is a variable .
is a variable. *)
val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr
val filter_method: Env.t -> string -> type_expr -> type_expr
val occur_in: Env.t -> type_expr -> type_expr -> bool
val deep_occur: type_expr -> type_expr -> bool
val moregeneral: Env.t -> bool -> type_expr -> type_expr -> unit
Check if the first type scheme is more general than the second .
val is_moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool
val rigidify: type_expr -> type_expr list
" Rigidify " a type and return its type variable
val all_distinct_vars: Env.t -> type_expr list -> bool
val matches: expand_error_trace:bool -> Env.t -> type_expr -> type_expr -> unit
Same as [ moregeneral false ] , implemented using the two above
functions and backtracking . Ignore levels . The [ expand_error_trace ]
flag controls whether the error raised performs expansion ; this
should almost always be [ true ] .
functions and backtracking. Ignore levels. The [expand_error_trace]
flag controls whether the error raised performs expansion; this
should almost always be [true]. *)
val does_match: Env.t -> type_expr -> type_expr -> bool
val reify_univars : Env.t -> Types.type_expr -> Types.type_expr
type filter_arrow_failure =
| Unification_error of Errortrace.unification_error
| Label_mismatch of
{ got : arg_label
; expected : arg_label
; expected_type : type_expr
}
| Not_a_function
exception Filter_arrow_failed of filter_arrow_failure
type filter_method_failure =
| Unification_error of Errortrace.unification_error
| Not_a_method
| Not_an_object of type_expr
exception Filter_method_failed of filter_method_failure
type class_match_failure =
CM_Virtual_class
| CM_Parameter_arity_mismatch of int * int
| CM_Type_parameter_mismatch of Env.t * Errortrace.equality_error
| CM_Class_type_mismatch of Env.t * class_type * class_type
| CM_Parameter_mismatch of Env.t * Errortrace.moregen_error
| CM_Val_type_mismatch of string * Env.t * Errortrace.comparison_error
| CM_Meth_type_mismatch of string * Env.t * Errortrace.comparison_error
| CM_Non_mutable_value of string
| CM_Non_concrete_value of string
| CM_Missing_value of string
| CM_Missing_method of string
| CM_Hide_public of string
| CM_Hide_virtual of string * string
| CM_Public_method of string
| CM_Private_method of string
| CM_Virtual_method of string
val match_class_types:
?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list
Check if the first class type is more general than the second .
val equal: Env.t -> bool -> type_expr list -> type_expr list -> unit
val is_equal : Env.t -> bool -> type_expr list -> type_expr list -> bool
val equal_private :
Env.t -> type_expr list -> type_expr ->
type_expr list -> type_expr -> unit
val match_class_declarations:
Env.t -> type_expr list -> class_type -> type_expr list ->
class_type -> class_match_failure list
Check if the first class type is more general than the second .
val enlarge_type: Env.t -> type_expr -> type_expr * bool
val subtype: Env.t -> type_expr -> type_expr -> unit -> unit
val new_class_signature : unit -> class_signature
val add_dummy_method : Env.t -> scope:int -> class_signature -> unit
type add_method_failure =
| Unexpected_method
| Type_mismatch of Errortrace.unification_error
exception Add_method_failed of add_method_failure
val add_method : Env.t ->
label -> private_flag -> virtual_flag -> type_expr -> class_signature -> unit
type add_instance_variable_failure =
| Mutability_mismatch of mutable_flag
| Type_mismatch of Errortrace.unification_error
exception Add_instance_variable_failed of add_instance_variable_failure
val add_instance_variable : strict:bool -> Env.t ->
label -> mutable_flag -> virtual_flag -> type_expr -> class_signature -> unit
type inherit_class_signature_failure =
| Self_type_mismatch of Errortrace.unification_error
| Method of label * add_method_failure
| Instance_variable of label * add_instance_variable_failure
exception Inherit_class_signature_failed of inherit_class_signature_failure
val inherit_class_signature : strict:bool -> Env.t ->
class_signature -> class_signature -> unit
val update_class_signature :
Env.t -> class_signature -> label list * label list
val hide_private_methods : Env.t -> class_signature -> unit
val close_class_signature : Env.t -> class_signature -> bool
exception Nondep_cannot_erase of Ident.t
val nondep_type: Env.t -> Ident.t list -> type_expr -> type_expr
val nondep_type_decl:
Env.t -> Ident.t list -> bool -> type_declaration -> type_declaration
val nondep_extension_constructor:
Env.t -> Ident.t list -> extension_constructor ->
extension_constructor
val nondep_class_declaration:
Env.t -> Ident.t list -> class_declaration -> class_declaration
val nondep_cltype_declaration:
Env.t -> Ident.t list -> class_type_declaration -> class_type_declaration
correct_abbrev : - > Path.t - > type_expr list - > type_expr - > unit
val is_contractive: Env.t -> Path.t -> bool
val normalize_type: type_expr -> unit
val nongen_schema: Env.t -> type_expr -> bool
val nongen_class_declaration: class_declaration -> bool
type variable_kind = Row_variable | Type_variable
type closed_class_failure = {
free_variable: type_expr * variable_kind;
meth: string;
meth_ty: type_expr;
}
val free_variables: ?env:Env.t -> type_expr -> type_expr list
val closed_type_decl: type_declaration -> type_expr option
val closed_extension_constructor: extension_constructor -> type_expr option
val closed_class:
type_expr list -> class_signature ->
closed_class_failure option
val unalias: type_expr -> type_expr
val arity: type_expr -> int
val collapse_conj_params: Env.t -> type_expr list -> unit
val get_current_level: unit -> int
val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b
val reset_reified_var_counter: unit -> unit
val immediacy : Env.t -> type_expr -> Type_immediacy.t
val package_subtype :
(Env.t -> Path.t -> (Longident.t * type_expr) list ->
Path.t -> (Longident.t * type_expr) list -> bool) ref
val mcomp : Env.t -> type_expr -> type_expr -> unit
|
ead5ddff814019552356c52d5d03c1149c2563eefc3e60aebd5d5b9e3e37ef3a | acl2/acl2 | remove-trivial-vars.lisp | Standard System Library
;
Copyright ( C ) 2023 Kestrel Institute ( )
;
License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 .
;
Author : ( )
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "std/util/defines" :dir :system)
(include-book "xdoc/constructors" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define remove-equal-formals-actuals ((formals symbol-listp)
(actuals pseudo-term-listp))
:guard (= (len formals) (len actuals))
:returns (mv (new-formals symbol-listp :hyp (symbol-listp formals))
(new-actuals pseudo-term-listp :hyp (pseudo-term-listp actuals)))
:parents (remove-trivial-vars)
:short "Remove equal formals and actuals
from two lists of the same length."
:long
(xdoc::topstring
(xdoc::p
"This is used by @(tsee remove-trivial-vars),
but it may be more generally useful.
In fact, it could be generalized to an operation on lists."))
(b* (((when (endp formals)) (mv nil nil))
((unless (mbt (consp actuals))) (mv nil nil))
(formal (car formals))
(actual (car actuals))
((when (eq formal actual))
(remove-equal-formals-actuals (cdr formals) (cdr actuals)))
((mv rest-formals rest-actuals)
(remove-equal-formals-actuals (cdr formals) (cdr actuals))))
(mv (cons formal rest-formals)
(cons actual rest-actuals)))
///
(defthmd remove-equal-formals-actuals-same-len
(equal (len (mv-nth 0 (remove-equal-formals-actuals formals actuals)))
(len (mv-nth 1 (remove-equal-formals-actuals formals actuals)))))
(more-returns
(new-formals true-listp :rule-classes :type-prescription))
(more-returns
(new-actuals true-listp :rule-classes :type-prescription))
(defret acl2-count-of-remove-equal-formals-actuals.formals
(<= (acl2-count new-formals)
(acl2-count formals))
:rule-classes :linear)
(defret acl2-count-of-remove-equal-formals-actuals.actuals
(<= (acl2-count new-actuals)
(acl2-count actuals))
:rule-classes :linear))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defines remove-trivial-vars
:parents (std/system/term-transformations)
:short "Remove the trivial lambda-bound variables."
:long
(xdoc::topstring
(xdoc::p
"ACL2 lambda expressions in translated terms are always closed,
which means that they often include formal parameters
that are replaced by themselves (i.e. by the same symbols)
when the lambda expression is applied.
For instance, the untranslated term @('(let ((x 3)) (+ x y))')
is @('((lambda (x y) (binary-+ x y)) '3 y)') in translated form:
the lambda expression includes the extra formal parameter @('y')
which is not bound by the @(tsee let),
applied to @('y') itself,
making the lambda expression closed.")
(xdoc::p
"This function removes the formal parameters of lambda expressions
that are ``trivial'' in the sense that
they are replaced by identical actual parameters.
These are ``artificial'' variables,
not @(tsee let) variables.
We also remove the corresponding actual parameters, of course,
so that beta reduction still makes sense,
and the number of actual parameters still matches
the number of formal parameters.
Applying this function to the example above yields
@('((lambda (x) (binary-+ x y)) '3)').")
(xdoc::p
"If all the formal parameters are trivial,
we replace the lambda expression with its body.
A lambda expression with all trivial formal parameters
may not result from hand-written code,
but could result from generated code.")
(xdoc::p
"We obtain terms whose lambda expressions may not be closed.
These do not satisfy @(tsee termp),
but they still satisfy @(tsee pseudo-termp).
Furthermore, it is easy to close any open lambda expressions,
by adding formal parameters, and corresponding actual parameters,
for the free variables in the lambda expression.")
(xdoc::p
"For certain term transformations,
it may be more convenient to work
with the possibly open lamba expressions produced by this function.
This way, every lambda expression corresponds to a @(tsee let)
without any trivial bindings.
In other languages,
@(tsee let) expressions are normally not closed."))
(define remove-trivial-vars ((term pseudo-termp))
:returns (new-term pseudo-termp :hyp (pseudo-termp term))
(b* (((when (variablep term)) term)
((when (fquotep term)) term)
(fn (ffn-symb term))
((when (symbolp fn))
(fcons-term fn (remove-trivial-vars-lst (fargs term))))
(formals (lambda-formals fn))
(body (lambda-body fn))
(actuals (fargs term))
((unless (mbt (equal (len formals)
(len actuals)))) nil) ; for termination
((mv nontrivial-formals nontrivial-actuals)
(remove-equal-formals-actuals formals actuals))
((when (eq nontrivial-formals nil)) (remove-trivial-vars body)))
(fcons-term (make-lambda nontrivial-formals
(remove-trivial-vars body))
(remove-trivial-vars-lst nontrivial-actuals))))
(define remove-trivial-vars-lst ((terms pseudo-term-listp))
:returns (new-terms (and (pseudo-term-listp new-terms)
(equal (len new-terms) (len terms)))
:hyp (pseudo-term-listp terms))
(b* (((when (endp terms)) nil)
((cons term terms) terms)
(new-term (remove-trivial-vars term))
(new-terms (remove-trivial-vars-lst terms)))
(cons new-term new-terms)))
:guard-hints (("Goal" :expand ((pseudo-termp term))))
:returns-hints
(("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
| null | https://raw.githubusercontent.com/acl2/acl2/c2d69bad0ed3132cc19a00cb632de8b73558b1f9/books/kestrel/std/system/remove-trivial-vars.lisp | lisp |
for termination | Standard System Library
Copyright ( C ) 2023 Kestrel Institute ( )
License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 .
Author : ( )
(in-package "ACL2")
(include-book "std/util/defines" :dir :system)
(include-book "xdoc/constructors" :dir :system)
(define remove-equal-formals-actuals ((formals symbol-listp)
(actuals pseudo-term-listp))
:guard (= (len formals) (len actuals))
:returns (mv (new-formals symbol-listp :hyp (symbol-listp formals))
(new-actuals pseudo-term-listp :hyp (pseudo-term-listp actuals)))
:parents (remove-trivial-vars)
:short "Remove equal formals and actuals
from two lists of the same length."
:long
(xdoc::topstring
(xdoc::p
"This is used by @(tsee remove-trivial-vars),
but it may be more generally useful.
In fact, it could be generalized to an operation on lists."))
(b* (((when (endp formals)) (mv nil nil))
((unless (mbt (consp actuals))) (mv nil nil))
(formal (car formals))
(actual (car actuals))
((when (eq formal actual))
(remove-equal-formals-actuals (cdr formals) (cdr actuals)))
((mv rest-formals rest-actuals)
(remove-equal-formals-actuals (cdr formals) (cdr actuals))))
(mv (cons formal rest-formals)
(cons actual rest-actuals)))
///
(defthmd remove-equal-formals-actuals-same-len
(equal (len (mv-nth 0 (remove-equal-formals-actuals formals actuals)))
(len (mv-nth 1 (remove-equal-formals-actuals formals actuals)))))
(more-returns
(new-formals true-listp :rule-classes :type-prescription))
(more-returns
(new-actuals true-listp :rule-classes :type-prescription))
(defret acl2-count-of-remove-equal-formals-actuals.formals
(<= (acl2-count new-formals)
(acl2-count formals))
:rule-classes :linear)
(defret acl2-count-of-remove-equal-formals-actuals.actuals
(<= (acl2-count new-actuals)
(acl2-count actuals))
:rule-classes :linear))
(defines remove-trivial-vars
:parents (std/system/term-transformations)
:short "Remove the trivial lambda-bound variables."
:long
(xdoc::topstring
(xdoc::p
"ACL2 lambda expressions in translated terms are always closed,
which means that they often include formal parameters
that are replaced by themselves (i.e. by the same symbols)
when the lambda expression is applied.
For instance, the untranslated term @('(let ((x 3)) (+ x y))')
is @('((lambda (x y) (binary-+ x y)) '3 y)') in translated form:
the lambda expression includes the extra formal parameter @('y')
which is not bound by the @(tsee let),
applied to @('y') itself,
making the lambda expression closed.")
(xdoc::p
"This function removes the formal parameters of lambda expressions
that are ``trivial'' in the sense that
they are replaced by identical actual parameters.
These are ``artificial'' variables,
not @(tsee let) variables.
We also remove the corresponding actual parameters, of course,
so that beta reduction still makes sense,
and the number of actual parameters still matches
the number of formal parameters.
Applying this function to the example above yields
@('((lambda (x) (binary-+ x y)) '3)').")
(xdoc::p
"If all the formal parameters are trivial,
we replace the lambda expression with its body.
A lambda expression with all trivial formal parameters
may not result from hand-written code,
but could result from generated code.")
(xdoc::p
"We obtain terms whose lambda expressions may not be closed.
These do not satisfy @(tsee termp),
but they still satisfy @(tsee pseudo-termp).
Furthermore, it is easy to close any open lambda expressions,
by adding formal parameters, and corresponding actual parameters,
for the free variables in the lambda expression.")
(xdoc::p
"For certain term transformations,
it may be more convenient to work
with the possibly open lamba expressions produced by this function.
This way, every lambda expression corresponds to a @(tsee let)
without any trivial bindings.
In other languages,
@(tsee let) expressions are normally not closed."))
(define remove-trivial-vars ((term pseudo-termp))
:returns (new-term pseudo-termp :hyp (pseudo-termp term))
(b* (((when (variablep term)) term)
((when (fquotep term)) term)
(fn (ffn-symb term))
((when (symbolp fn))
(fcons-term fn (remove-trivial-vars-lst (fargs term))))
(formals (lambda-formals fn))
(body (lambda-body fn))
(actuals (fargs term))
((unless (mbt (equal (len formals)
((mv nontrivial-formals nontrivial-actuals)
(remove-equal-formals-actuals formals actuals))
((when (eq nontrivial-formals nil)) (remove-trivial-vars body)))
(fcons-term (make-lambda nontrivial-formals
(remove-trivial-vars body))
(remove-trivial-vars-lst nontrivial-actuals))))
(define remove-trivial-vars-lst ((terms pseudo-term-listp))
:returns (new-terms (and (pseudo-term-listp new-terms)
(equal (len new-terms) (len terms)))
:hyp (pseudo-term-listp terms))
(b* (((when (endp terms)) nil)
((cons term terms) terms)
(new-term (remove-trivial-vars term))
(new-terms (remove-trivial-vars-lst terms)))
(cons new-term new-terms)))
:guard-hints (("Goal" :expand ((pseudo-termp term))))
:returns-hints
(("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
|
2dbb667111a9199595f09709c17ba96e039470065d354879ad15cd12a0d3cf6a | shiguredo/eryngii | position.ml | type t = {
line : int;
col : int;
offset : int;
}
let zero = { line = 0; col = 0; offset = 0 }
let of_lexing_pos (pos : Lexing.position) =
{ line = pos.pos_lnum;
col = pos.pos_bol;
offset = pos.pos_cnum;
}
let add pos ~length =
{ pos with col = pos.col + length;
offset = pos.offset + length }
let newline pos =
{ line = pos.line + 1;
col = 0;
offset = pos.offset + 1;
}
| null | https://raw.githubusercontent.com/shiguredo/eryngii/6c70d9b28a45ed786c4847ee51bb03bfef35ac8d/position.ml | ocaml | type t = {
line : int;
col : int;
offset : int;
}
let zero = { line = 0; col = 0; offset = 0 }
let of_lexing_pos (pos : Lexing.position) =
{ line = pos.pos_lnum;
col = pos.pos_bol;
offset = pos.pos_cnum;
}
let add pos ~length =
{ pos with col = pos.col + length;
offset = pos.offset + length }
let newline pos =
{ line = pos.line + 1;
col = 0;
offset = pos.offset + 1;
}
|
|
05c009bbc964a7356e0c51ea16b53496fc81d1cbb564b16ae8bad6bbe6b442ed | naveensundarg/Common-Lisp-Actors | bouncer.lisp | (defactor Bouncer (name) (other)
(send other self)
(pr (concatenate 'string name " : " " bouncing"))
(sleep 3)
next)
(setq b1 (Bouncer :name "Bouncer 1"))
(setq b2 (Bouncer :name "Bouncer 2"))
(send b1 b2)
| null | https://raw.githubusercontent.com/naveensundarg/Common-Lisp-Actors/fd08ce1f62d77dc695c590e2e31d3cb46cab55b4/examples/bouncer.lisp | lisp | (defactor Bouncer (name) (other)
(send other self)
(pr (concatenate 'string name " : " " bouncing"))
(sleep 3)
next)
(setq b1 (Bouncer :name "Bouncer 1"))
(setq b2 (Bouncer :name "Bouncer 2"))
(send b1 b2)
|
|
58267ec9450aba480580ccd0c6830c7d2636bb09e13436146e707ed6264faa48 | pflanze/chj-schemelib | oo-lib-u8vector.scm | Copyright 2014 - 2018 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
;;; (at your option) any later version.
(require oo-vector-lib)
(include "cj-standarddeclares.scm")
(def-oo-vector-lib-for u8vector)
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/oo-lib-u8vector.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version. | Copyright 2014 - 2018 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
(require oo-vector-lib)
(include "cj-standarddeclares.scm")
(def-oo-vector-lib-for u8vector)
|
8219db11f54773318fec62576b1b48fe07e49ca0baac0d8cea3ddf4bd9a26299 | 2600hz/kazoo | kzd_multi_factor_provider.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(kzd_multi_factor_provider).
-export([new/0]).
-export([enabled/1, enabled/2, set_enabled/2]).
-export([name/1, name/2, set_name/2]).
-export([provider_name/1, provider_name/2, set_provider_name/2]).
-export([settings/1, settings/2, set_settings/2]).
-include("kz_documents.hrl").
-type doc() :: kz_json:object().
-export_type([doc/0]).
-define(SCHEMA, <<"multi_factor_provider">>).
-spec new() -> doc().
new() ->
kz_json_schema:default_object(?SCHEMA).
-spec enabled(doc()) -> kz_term:api_boolean().
enabled(Doc) ->
enabled(Doc, 'undefined').
-spec enabled(doc(), Default) -> boolean() | Default.
enabled(Doc, Default) ->
kz_json:get_boolean_value([<<"enabled">>], Doc, Default).
-spec set_enabled(doc(), boolean()) -> doc().
set_enabled(Doc, Enabled) ->
kz_json:set_value([<<"enabled">>], Enabled, Doc).
-spec name(doc()) -> kz_term:api_binary().
name(Doc) ->
name(Doc, 'undefined').
-spec name(doc(), Default) -> binary() | Default.
name(Doc, Default) ->
kz_json:get_binary_value([<<"name">>], Doc, Default).
-spec set_name(doc(), binary()) -> doc().
set_name(Doc, Name) ->
kz_json:set_value([<<"name">>], Name, Doc).
-spec provider_name(doc()) -> kz_term:api_binary().
provider_name(Doc) ->
provider_name(Doc, 'undefined').
-spec provider_name(doc(), Default) -> binary() | Default.
provider_name(Doc, Default) ->
kz_json:get_binary_value([<<"provider_name">>], Doc, Default).
-spec set_provider_name(doc(), binary()) -> doc().
set_provider_name(Doc, ProviderName) ->
kz_json:set_value([<<"provider_name">>], ProviderName, Doc).
-spec settings(doc()) -> kz_term:api_object().
settings(Doc) ->
settings(Doc, 'undefined').
-spec settings(doc(), Default) -> kz_json:object() | Default.
settings(Doc, Default) ->
kz_json:get_json_value([<<"settings">>], Doc, Default).
-spec set_settings(doc(), kz_json:object()) -> doc().
set_settings(Doc, Settings) ->
kz_json:set_value([<<"settings">>], Settings, Doc).
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_documents/src/kzd_multi_factor_provider.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
----------------------------------------------------------------------------- | ( C ) 2010 - 2020 , 2600Hz
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(kzd_multi_factor_provider).
-export([new/0]).
-export([enabled/1, enabled/2, set_enabled/2]).
-export([name/1, name/2, set_name/2]).
-export([provider_name/1, provider_name/2, set_provider_name/2]).
-export([settings/1, settings/2, set_settings/2]).
-include("kz_documents.hrl").
-type doc() :: kz_json:object().
-export_type([doc/0]).
-define(SCHEMA, <<"multi_factor_provider">>).
-spec new() -> doc().
new() ->
kz_json_schema:default_object(?SCHEMA).
-spec enabled(doc()) -> kz_term:api_boolean().
enabled(Doc) ->
enabled(Doc, 'undefined').
-spec enabled(doc(), Default) -> boolean() | Default.
enabled(Doc, Default) ->
kz_json:get_boolean_value([<<"enabled">>], Doc, Default).
-spec set_enabled(doc(), boolean()) -> doc().
set_enabled(Doc, Enabled) ->
kz_json:set_value([<<"enabled">>], Enabled, Doc).
-spec name(doc()) -> kz_term:api_binary().
name(Doc) ->
name(Doc, 'undefined').
-spec name(doc(), Default) -> binary() | Default.
name(Doc, Default) ->
kz_json:get_binary_value([<<"name">>], Doc, Default).
-spec set_name(doc(), binary()) -> doc().
set_name(Doc, Name) ->
kz_json:set_value([<<"name">>], Name, Doc).
-spec provider_name(doc()) -> kz_term:api_binary().
provider_name(Doc) ->
provider_name(Doc, 'undefined').
-spec provider_name(doc(), Default) -> binary() | Default.
provider_name(Doc, Default) ->
kz_json:get_binary_value([<<"provider_name">>], Doc, Default).
-spec set_provider_name(doc(), binary()) -> doc().
set_provider_name(Doc, ProviderName) ->
kz_json:set_value([<<"provider_name">>], ProviderName, Doc).
-spec settings(doc()) -> kz_term:api_object().
settings(Doc) ->
settings(Doc, 'undefined').
-spec settings(doc(), Default) -> kz_json:object() | Default.
settings(Doc, Default) ->
kz_json:get_json_value([<<"settings">>], Doc, Default).
-spec set_settings(doc(), kz_json:object()) -> doc().
set_settings(Doc, Settings) ->
kz_json:set_value([<<"settings">>], Settings, Doc).
|
17eeb40bd0aa7d583a4afbc1319b880080d31fa256896ec9db8c089b8dd6f706 | wireapp/wire-server | PrekeyBundle_user.hs | # LANGUAGE OverloadedLists #
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Test.Wire.API.Golden.Generated.PrekeyBundle_user where
import Data.Id (ClientId (ClientId, client), Id (Id))
import qualified Data.UUID as UUID (fromString)
import Imports (fromJust)
import Wire.API.User.Client.Prekey
( ClientPrekey (ClientPrekey, prekeyClient, prekeyData),
Prekey (Prekey, prekeyId, prekeyKey),
PrekeyBundle (..),
PrekeyId (PrekeyId, keyId),
)
testObject_PrekeyBundle_user_1 :: PrekeyBundle
testObject_PrekeyBundle_user_1 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000046-0000-0011-0000-007200000022")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "8"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\rOx"}
}
]
}
testObject_PrekeyBundle_user_2 :: PrekeyBundle
testObject_PrekeyBundle_user_2 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000043-0000-002b-0000-00550000002a")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_3 :: PrekeyBundle
testObject_PrekeyBundle_user_3 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000001-0000-002b-0000-002e00000010")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\n"}
}
]
}
testObject_PrekeyBundle_user_4 :: PrekeyBundle
testObject_PrekeyBundle_user_4 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000037-0000-0050-0000-005900000043")),
prekeyClients = []
}
testObject_PrekeyBundle_user_5 :: PrekeyBundle
testObject_PrekeyBundle_user_5 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000000b-0000-0075-0000-00620000001e")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "i"}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "L"}
}
]
}
testObject_PrekeyBundle_user_6 :: PrekeyBundle
testObject_PrekeyBundle_user_6 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000004c-0000-007e-0000-004300000034")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_7 :: PrekeyBundle
testObject_PrekeyBundle_user_7 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000001e-0000-0066-0000-000200000002")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "4"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "$"}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_8 :: PrekeyBundle
testObject_PrekeyBundle_user_8 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000050-0000-0050-0000-00760000005f")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_9 :: PrekeyBundle
testObject_PrekeyBundle_user_9 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000024-0000-0074-0000-000b0000001d")),
prekeyClients = []
}
testObject_PrekeyBundle_user_10 :: PrekeyBundle
testObject_PrekeyBundle_user_10 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000062-0000-003a-0000-006c0000001e")),
prekeyClients = []
}
testObject_PrekeyBundle_user_11 :: PrekeyBundle
testObject_PrekeyBundle_user_11 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000025-0000-0061-0000-005f0000000a")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "4"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ">"}
}
]
}
testObject_PrekeyBundle_user_12 :: PrekeyBundle
testObject_PrekeyBundle_user_12 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000073-0000-0034-0000-004c00000024")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "a"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "\1092897\990773-"}
}
]
}
testObject_PrekeyBundle_user_13 :: PrekeyBundle
testObject_PrekeyBundle_user_13 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000000c-0000-006a-0000-00650000007c")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_14 :: PrekeyBundle
testObject_PrekeyBundle_user_14 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000012-0000-0024-0000-006700000016")),
prekeyClients = []
}
testObject_PrekeyBundle_user_15 :: PrekeyBundle
testObject_PrekeyBundle_user_15 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000079-0000-0057-0000-004200000037")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\RS"}
}
]
}
testObject_PrekeyBundle_user_16 :: PrekeyBundle
testObject_PrekeyBundle_user_16 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000002b-0000-0032-0000-00140000006e")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "f"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "\1066568\149661?"}
}
]
}
testObject_PrekeyBundle_user_17 :: PrekeyBundle
testObject_PrekeyBundle_user_17 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000006f-0000-0036-0000-00560000002d")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_18 :: PrekeyBundle
testObject_PrekeyBundle_user_18 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000069-0000-007c-0000-000f0000004a")),
prekeyClients = []
}
testObject_PrekeyBundle_user_19 :: PrekeyBundle
testObject_PrekeyBundle_user_19 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000006f-0000-0072-0000-003e00000008")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_20 :: PrekeyBundle
testObject_PrekeyBundle_user_20 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000073-0000-0017-0000-00690000007a")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "\1014040"}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\SO"}
}
]
}
| null | https://raw.githubusercontent.com/wireapp/wire-server/c428355b7683b7b7722ea544eba314fc843ad8fa/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/PrekeyBundle_user.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>. | # LANGUAGE OverloadedLists #
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Test.Wire.API.Golden.Generated.PrekeyBundle_user where
import Data.Id (ClientId (ClientId, client), Id (Id))
import qualified Data.UUID as UUID (fromString)
import Imports (fromJust)
import Wire.API.User.Client.Prekey
( ClientPrekey (ClientPrekey, prekeyClient, prekeyData),
Prekey (Prekey, prekeyId, prekeyKey),
PrekeyBundle (..),
PrekeyId (PrekeyId, keyId),
)
testObject_PrekeyBundle_user_1 :: PrekeyBundle
testObject_PrekeyBundle_user_1 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000046-0000-0011-0000-007200000022")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "8"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\rOx"}
}
]
}
testObject_PrekeyBundle_user_2 :: PrekeyBundle
testObject_PrekeyBundle_user_2 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000043-0000-002b-0000-00550000002a")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_3 :: PrekeyBundle
testObject_PrekeyBundle_user_3 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000001-0000-002b-0000-002e00000010")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\n"}
}
]
}
testObject_PrekeyBundle_user_4 :: PrekeyBundle
testObject_PrekeyBundle_user_4 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000037-0000-0050-0000-005900000043")),
prekeyClients = []
}
testObject_PrekeyBundle_user_5 :: PrekeyBundle
testObject_PrekeyBundle_user_5 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000000b-0000-0075-0000-00620000001e")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "i"}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "L"}
}
]
}
testObject_PrekeyBundle_user_6 :: PrekeyBundle
testObject_PrekeyBundle_user_6 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000004c-0000-007e-0000-004300000034")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_7 :: PrekeyBundle
testObject_PrekeyBundle_user_7 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000001e-0000-0066-0000-000200000002")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "4"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "$"}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_8 :: PrekeyBundle
testObject_PrekeyBundle_user_8 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000050-0000-0050-0000-00760000005f")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_9 :: PrekeyBundle
testObject_PrekeyBundle_user_9 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000024-0000-0074-0000-000b0000001d")),
prekeyClients = []
}
testObject_PrekeyBundle_user_10 :: PrekeyBundle
testObject_PrekeyBundle_user_10 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000062-0000-003a-0000-006c0000001e")),
prekeyClients = []
}
testObject_PrekeyBundle_user_11 :: PrekeyBundle
testObject_PrekeyBundle_user_11 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000025-0000-0061-0000-005f0000000a")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "4"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ">"}
}
]
}
testObject_PrekeyBundle_user_12 :: PrekeyBundle
testObject_PrekeyBundle_user_12 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000073-0000-0034-0000-004c00000024")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "a"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "\1092897\990773-"}
}
]
}
testObject_PrekeyBundle_user_13 :: PrekeyBundle
testObject_PrekeyBundle_user_13 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000000c-0000-006a-0000-00650000007c")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_14 :: PrekeyBundle
testObject_PrekeyBundle_user_14 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000012-0000-0024-0000-006700000016")),
prekeyClients = []
}
testObject_PrekeyBundle_user_15 :: PrekeyBundle
testObject_PrekeyBundle_user_15 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000079-0000-0057-0000-004200000037")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\RS"}
}
]
}
testObject_PrekeyBundle_user_16 :: PrekeyBundle
testObject_PrekeyBundle_user_16 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000002b-0000-0032-0000-00140000006e")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "f"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "\1066568\149661?"}
}
]
}
testObject_PrekeyBundle_user_17 :: PrekeyBundle
testObject_PrekeyBundle_user_17 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000006f-0000-0036-0000-00560000002d")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_18 :: PrekeyBundle
testObject_PrekeyBundle_user_18 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000069-0000-007c-0000-000f0000004a")),
prekeyClients = []
}
testObject_PrekeyBundle_user_19 :: PrekeyBundle
testObject_PrekeyBundle_user_19 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "0000006f-0000-0072-0000-003e00000008")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "0"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
}
]
}
testObject_PrekeyBundle_user_20 :: PrekeyBundle
testObject_PrekeyBundle_user_20 =
PrekeyBundle
{ prekeyUser = Id (fromJust (UUID.fromString "00000073-0000-0017-0000-00690000007a")),
prekeyClients =
[ ClientPrekey
{ prekeyClient = ClientId {client = "1"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = ""}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 1}, prekeyKey = "\1014040"}
},
ClientPrekey
{ prekeyClient = ClientId {client = "2"},
prekeyData = Prekey {prekeyId = PrekeyId {keyId = 0}, prekeyKey = "\SO"}
}
]
}
|
fdc10e4d859a19a8ca3ccc80fd38439fb40ce88d2b088a0960763c512dfffe6f | sheyll/mediabus | ReorderSpec.hs | module Data.MediaBus.Conduit.ReorderSpec
( spec,
)
where
import Conduit
import Control.Monad
import Data.Conduit.List
import Data.MediaBus
import Data.Proxy
import Data.Word
import Debug.Trace
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec =
describe "reorderFramesBySeqNumC" $ do
let runC inputs =
runConduitPure
( sourceList inputs
.| annotateTypeC
(Proxy :: Proxy (Stream () TestSeqNumType () () ()))
(reorderFramesBySeqNumC 3)
.| consume
)
it "yields at least one 'Start' for each incoming 'Start'" $
property $
\inputs ->
let countStarts =
foldr
( \x n ->
case x of
MkStream (Start _) -> n + 1
MkStream (Next _) -> n
)
0
in countStarts (runC inputs) `shouldSatisfy` (>= countStarts inputs)
it "yields exactly the given input if the input is ordered and gap-free" $
let inputs = startFrame 0 : [nextFrame x | x <- [0 .. 10]]
in runC inputs `shouldBe` inputs
it "reorders out of order packets (1)" $
let inputs =
[startFrame 0, nextFrame 0, nextFrame 2, nextFrame 3, nextFrame 1]
expected =
[startFrame 0, nextFrame 0, nextFrame 1, nextFrame 2, nextFrame 3]
in runC inputs `shouldBe` expected
it "reorders out of order packets (2)" $
let inputs = [startFrame 0, nextFrame 2, nextFrame 1, nextFrame 0]
expected = [startFrame 0, nextFrame 0, nextFrame 1, nextFrame 2]
in runC inputs `shouldBe` expected
it "skips over missing frames when the queue is full" $
let inputs =
[ startFrame 0,
nextFrame 0,
nextFrame 1,
nextFrame 3,
nextFrame 4,
nextFrame 5
]
expected =
[ startFrame 0,
nextFrame 0,
nextFrame 1,
nextFrame 3,
nextFrame 4,
nextFrame 5
]
in runC inputs `shouldBe` expected
it "restarts at the incoming sequence numbering after too many frame drops" $
let inputs =
[ startFrame 10,
nextFrame 10,
nextFrame 11,
nextFrame 12,
nextFrame 0,
nextFrame 1,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
expected =
[ startFrame 10,
nextFrame 10,
nextFrame 11,
nextFrame 12,
startFrame 2,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
in runC inputs `shouldBe` expected
it
"restarts at the incoming sequence numbering after too many frame drops, AND flushes the queued elements first"
$ let inputs =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
nextFrame 0,
nextFrame 1,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
expected =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
startFrame 2,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
in runC inputs `shouldBe` expected
it "flushes and resets its internal state after every 'Start'" $
let inputs =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
startFrame 40,
nextFrame 40,
nextFrame 41,
startFrame 50,
nextFrame 0,
nextFrame 1,
startFrame 60,
nextFrame 50,
nextFrame 51,
nextFrame 52
]
expected =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
startFrame 40,
nextFrame 40,
nextFrame 41,
startFrame 50,
startFrame 60,
startFrame 52,
nextFrame 52
]
in runC inputs `shouldBe` expected
it "yields monotone increasing frames higher than the start-frame" $
property $
\inputs ->
let os = runC inputs
in unless
(isMonoIncreasingAndHigherThanStartSeqNum os)
( trace
( unlines
( (("IN: " ++) . show <$> inputs)
++ ( ("OUT: " ++) . show
<$> os
)
)
)
os
`shouldSatisfy` isMonoIncreasingAndHigherThanStartSeqNum
)
isMonoIncreasingAndHigherThanStartSeqNum ::
[Stream () TestSeqNumType () () ()] ->
Bool
isMonoIncreasingAndHigherThanStartSeqNum [] = True
isMonoIncreasingAndHigherThanStartSeqNum (MkStream (Start (MkFrameCtx () () sn ())) : rest) =
isMonoIncreasingAndHigherThanStartSeqNumN sn rest
isMonoIncreasingAndHigherThanStartSeqNum rest@(MkStream (Next (MkFrame () sn ())) : _) =
isMonoIncreasingAndHigherThanStartSeqNumN sn rest
isMonoIncreasingAndHigherThanStartSeqNumN _ [] = True
isMonoIncreasingAndHigherThanStartSeqNumN _ (MkStream (Start (MkFrameCtx () () sn ())) : rest) =
isMonoIncreasingAndHigherThanStartSeqNumN sn rest
isMonoIncreasingAndHigherThanStartSeqNumN sn (MkStream (Next (MkFrame () snFrame ())) : rest)
| snFrame >= sn = isMonoIncreasingAndHigherThanStartSeqNumN snFrame rest
| otherwise = False
startFrame :: TestSeqNumType -> Stream () TestSeqNumType () () ()
startFrame sn = MkStream (Start (MkFrameCtx () () sn ()))
nextFrame :: TestSeqNumType -> Stream () TestSeqNumType () () ()
nextFrame sn = MkStream (Next (MkFrame () sn ()))
type TestSeqNumType = Word64
| null | https://raw.githubusercontent.com/sheyll/mediabus/7a2fd3f4a4b9ab281a3f54b5c9bf43c98eb38fb9/specs/Data/MediaBus/Conduit/ReorderSpec.hs | haskell | module Data.MediaBus.Conduit.ReorderSpec
( spec,
)
where
import Conduit
import Control.Monad
import Data.Conduit.List
import Data.MediaBus
import Data.Proxy
import Data.Word
import Debug.Trace
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec =
describe "reorderFramesBySeqNumC" $ do
let runC inputs =
runConduitPure
( sourceList inputs
.| annotateTypeC
(Proxy :: Proxy (Stream () TestSeqNumType () () ()))
(reorderFramesBySeqNumC 3)
.| consume
)
it "yields at least one 'Start' for each incoming 'Start'" $
property $
\inputs ->
let countStarts =
foldr
( \x n ->
case x of
MkStream (Start _) -> n + 1
MkStream (Next _) -> n
)
0
in countStarts (runC inputs) `shouldSatisfy` (>= countStarts inputs)
it "yields exactly the given input if the input is ordered and gap-free" $
let inputs = startFrame 0 : [nextFrame x | x <- [0 .. 10]]
in runC inputs `shouldBe` inputs
it "reorders out of order packets (1)" $
let inputs =
[startFrame 0, nextFrame 0, nextFrame 2, nextFrame 3, nextFrame 1]
expected =
[startFrame 0, nextFrame 0, nextFrame 1, nextFrame 2, nextFrame 3]
in runC inputs `shouldBe` expected
it "reorders out of order packets (2)" $
let inputs = [startFrame 0, nextFrame 2, nextFrame 1, nextFrame 0]
expected = [startFrame 0, nextFrame 0, nextFrame 1, nextFrame 2]
in runC inputs `shouldBe` expected
it "skips over missing frames when the queue is full" $
let inputs =
[ startFrame 0,
nextFrame 0,
nextFrame 1,
nextFrame 3,
nextFrame 4,
nextFrame 5
]
expected =
[ startFrame 0,
nextFrame 0,
nextFrame 1,
nextFrame 3,
nextFrame 4,
nextFrame 5
]
in runC inputs `shouldBe` expected
it "restarts at the incoming sequence numbering after too many frame drops" $
let inputs =
[ startFrame 10,
nextFrame 10,
nextFrame 11,
nextFrame 12,
nextFrame 0,
nextFrame 1,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
expected =
[ startFrame 10,
nextFrame 10,
nextFrame 11,
nextFrame 12,
startFrame 2,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
in runC inputs `shouldBe` expected
it
"restarts at the incoming sequence numbering after too many frame drops, AND flushes the queued elements first"
$ let inputs =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
nextFrame 0,
nextFrame 1,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
expected =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
startFrame 2,
nextFrame 2,
nextFrame 3,
nextFrame 4
]
in runC inputs `shouldBe` expected
it "flushes and resets its internal state after every 'Start'" $
let inputs =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
startFrame 40,
nextFrame 40,
nextFrame 41,
startFrame 50,
nextFrame 0,
nextFrame 1,
startFrame 60,
nextFrame 50,
nextFrame 51,
nextFrame 52
]
expected =
[ startFrame 10,
nextFrame 13,
nextFrame 14,
startFrame 40,
nextFrame 40,
nextFrame 41,
startFrame 50,
startFrame 60,
startFrame 52,
nextFrame 52
]
in runC inputs `shouldBe` expected
it "yields monotone increasing frames higher than the start-frame" $
property $
\inputs ->
let os = runC inputs
in unless
(isMonoIncreasingAndHigherThanStartSeqNum os)
( trace
( unlines
( (("IN: " ++) . show <$> inputs)
++ ( ("OUT: " ++) . show
<$> os
)
)
)
os
`shouldSatisfy` isMonoIncreasingAndHigherThanStartSeqNum
)
isMonoIncreasingAndHigherThanStartSeqNum ::
[Stream () TestSeqNumType () () ()] ->
Bool
isMonoIncreasingAndHigherThanStartSeqNum [] = True
isMonoIncreasingAndHigherThanStartSeqNum (MkStream (Start (MkFrameCtx () () sn ())) : rest) =
isMonoIncreasingAndHigherThanStartSeqNumN sn rest
isMonoIncreasingAndHigherThanStartSeqNum rest@(MkStream (Next (MkFrame () sn ())) : _) =
isMonoIncreasingAndHigherThanStartSeqNumN sn rest
isMonoIncreasingAndHigherThanStartSeqNumN _ [] = True
isMonoIncreasingAndHigherThanStartSeqNumN _ (MkStream (Start (MkFrameCtx () () sn ())) : rest) =
isMonoIncreasingAndHigherThanStartSeqNumN sn rest
isMonoIncreasingAndHigherThanStartSeqNumN sn (MkStream (Next (MkFrame () snFrame ())) : rest)
| snFrame >= sn = isMonoIncreasingAndHigherThanStartSeqNumN snFrame rest
| otherwise = False
startFrame :: TestSeqNumType -> Stream () TestSeqNumType () () ()
startFrame sn = MkStream (Start (MkFrameCtx () () sn ()))
nextFrame :: TestSeqNumType -> Stream () TestSeqNumType () () ()
nextFrame sn = MkStream (Next (MkFrame () sn ()))
type TestSeqNumType = Word64
|
|
cee03a1a99441418d2bee25ef1a14a6ab2c7bc7a258002b5d830806098d734d3 | phronmophobic/jna-native-image | build.clj | (ns build
(:require [clojure.tools.build.api :as b]
[clojure.string :as str]))
(def lib 'com.phronemophobic.native-image/jna)
(def version "0.1.0")
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s-%s.jar" (name lib) version))
(def uber-file (format "target/%s-%s-standalone.jar" (name lib) version))
(defn clean [_]
(b/delete {:path "target"}))
(defn uber [_]
(clean nil)
(b/copy-dir {:src-dirs ["src" "resources"]
:target-dir class-dir})
(b/compile-clj {:basis basis
:src-dirs ["src"]
:class-dir class-dir})
(b/uber {:class-dir class-dir
:uber-file uber-file
:basis basis
:main 'com.phronemophobic.native-image.jna}))
| null | https://raw.githubusercontent.com/phronmophobic/jna-native-image/77a714494716933928d4fa581f9ed93ab3d32587/build.clj | clojure | (ns build
(:require [clojure.tools.build.api :as b]
[clojure.string :as str]))
(def lib 'com.phronemophobic.native-image/jna)
(def version "0.1.0")
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s-%s.jar" (name lib) version))
(def uber-file (format "target/%s-%s-standalone.jar" (name lib) version))
(defn clean [_]
(b/delete {:path "target"}))
(defn uber [_]
(clean nil)
(b/copy-dir {:src-dirs ["src" "resources"]
:target-dir class-dir})
(b/compile-clj {:basis basis
:src-dirs ["src"]
:class-dir class-dir})
(b/uber {:class-dir class-dir
:uber-file uber-file
:basis basis
:main 'com.phronemophobic.native-image.jna}))
|
|
f12c14f00c1b3edb622d50f1c7ed9896c38814f7a773bc138defc2b132c51826 | gsakkas/rite | 20060319-13:25:22-d82ce217b923933f541e5e4c291912ff.seminal.ml | type heap = (string * int) list
type exp = Int of int | Var of string
| Plus of exp * exp | Times of exp * exp
type stmt = Skip | Assign of string * exp
| Seq of stmt * stmt
| If of exp * stmt * stmt
| While of exp * stmt
| Saveheap of heap
| Restoreheap of heap
let rec lookup h str =
match h with
# # # # # # # # # # # # # # #
|(s,i)::tl -> if s=str then i else lookup tl str
let update h str i = (str,i)::h
let rec interp_e (h:heap) (e:exp) =
match e with
Int i ->i
|Var str ->lookup h str
|Plus(e1,e2) ->(interp_e h e1)+(interp_e h e2)
|Times(e1,e2)->(interp_e h e1)*(interp_e h e2)
let rec interp_s (h:heap) (s:stmt) =
match s with
Skip -> h
|Seq(s1,s2) -> let h2 = interp_s h s1 in
interp_s h2 s2
|If(e,s1,s2) -> if (interp_e h e) <> 0
then interp_s h s1
else interp_s h s2
|Assign(str,e) -> update h str (interp_e h e)
|While(e,s1) -> if (interp_e h e) <> 0
then let h2 = interp_s h s1 in
interp_s h2 s
else h
let mt_heap = []
let interp_prog s =
lookup (interp_s mt_heap s) "ans"
(******************** Test Program in IMP **************************)
# # # # # # # # # # # # # # #
let testProgram1 = Skip
let testProgram1 = Seq (testProgram1, (Assign ("x",Int 1)))
let testProgram1 = Seq (testProgram1, (Saveheap ("myheap1")))
let testProgram1 = Seq (testProgram1, (Assign ("x",Int 12)))
let testProgram1 = Seq (testProgram1, (Restoreheap ("myheap1")))
let testProgram1 = Seq (testProgram1, (Assign ("ans",Var "x")))
# # # # # # # # # # # # # # #
let testProgram2 = Skip
let testProgram2 = Seq (testProgram2, (Assign ("x",Int 1)))
let testProgram2 = Seq (testProgram2, (Saveheap ("myheap1")))
let testProgram2 = Seq (testProgram2, (Assign ("ans",Var "myheap1")))
# # # # # # # # # # # # # # # #
let testProgram3 = Skip
let testProgram3 = Seq (testProgram3, (Assign ("x",Int 1)))
let testProgram3 = Seq (testProgram3, (Saveheap ("myheap1")))
let testProgram3 = Seq (testProgram3, (Assign ("x",Int 12)))
let testProgram3 = Seq (testProgram3, (Restoreheap ("myheapnot")))
let testProgram3 = Seq (testProgram3, (Assign ("ans",Var "x")))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
######################################################
###################################################################
##########################
#################
###################################
################
##########
####################################################################################
####################################################################################
################################################################################### *)
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060319-13%3A25%3A22-d82ce217b923933f541e5e4c291912ff.seminal.ml | ocaml | ******************* Test Program in IMP ************************* | type heap = (string * int) list
type exp = Int of int | Var of string
| Plus of exp * exp | Times of exp * exp
type stmt = Skip | Assign of string * exp
| Seq of stmt * stmt
| If of exp * stmt * stmt
| While of exp * stmt
| Saveheap of heap
| Restoreheap of heap
let rec lookup h str =
match h with
# # # # # # # # # # # # # # #
|(s,i)::tl -> if s=str then i else lookup tl str
let update h str i = (str,i)::h
let rec interp_e (h:heap) (e:exp) =
match e with
Int i ->i
|Var str ->lookup h str
|Plus(e1,e2) ->(interp_e h e1)+(interp_e h e2)
|Times(e1,e2)->(interp_e h e1)*(interp_e h e2)
let rec interp_s (h:heap) (s:stmt) =
match s with
Skip -> h
|Seq(s1,s2) -> let h2 = interp_s h s1 in
interp_s h2 s2
|If(e,s1,s2) -> if (interp_e h e) <> 0
then interp_s h s1
else interp_s h s2
|Assign(str,e) -> update h str (interp_e h e)
|While(e,s1) -> if (interp_e h e) <> 0
then let h2 = interp_s h s1 in
interp_s h2 s
else h
let mt_heap = []
let interp_prog s =
lookup (interp_s mt_heap s) "ans"
# # # # # # # # # # # # # # #
let testProgram1 = Skip
let testProgram1 = Seq (testProgram1, (Assign ("x",Int 1)))
let testProgram1 = Seq (testProgram1, (Saveheap ("myheap1")))
let testProgram1 = Seq (testProgram1, (Assign ("x",Int 12)))
let testProgram1 = Seq (testProgram1, (Restoreheap ("myheap1")))
let testProgram1 = Seq (testProgram1, (Assign ("ans",Var "x")))
# # # # # # # # # # # # # # #
let testProgram2 = Skip
let testProgram2 = Seq (testProgram2, (Assign ("x",Int 1)))
let testProgram2 = Seq (testProgram2, (Saveheap ("myheap1")))
let testProgram2 = Seq (testProgram2, (Assign ("ans",Var "myheap1")))
# # # # # # # # # # # # # # # #
let testProgram3 = Skip
let testProgram3 = Seq (testProgram3, (Assign ("x",Int 1)))
let testProgram3 = Seq (testProgram3, (Saveheap ("myheap1")))
let testProgram3 = Seq (testProgram3, (Assign ("x",Int 12)))
let testProgram3 = Seq (testProgram3, (Restoreheap ("myheapnot")))
let testProgram3 = Seq (testProgram3, (Assign ("ans",Var "x")))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
######################################################
###################################################################
##########################
#################
###################################
################
##########
####################################################################################
####################################################################################
################################################################################### *)
|
a97dd583c9b0ed80fe77bc42c3d16475861aaa4e7184790a12b6f606a7141f3c | haskell/cabal | Package.hs | # LANGUAGE DeriveFunctor #
module Distribution.Solver.Modular.Package
( I(..)
, Loc(..)
, PackageId
, PackageIdentifier(..)
, PackageName, mkPackageName, unPackageName
, PkgconfigName, mkPkgconfigName, unPkgconfigName
, PI(..)
, PN
, QPV
, instI
, makeIndependent
, primaryPP
, setupPP
, showI
, showPI
, unPN
) where
import Prelude ()
import Distribution.Solver.Compat.Prelude
from Cabal
import Distribution.Pretty (prettyShow)
import Distribution.Solver.Modular.Version
import Distribution.Solver.Types.PackagePath
-- | A package name.
type PN = PackageName
-- | Unpacking a package name.
unPN :: PN -> String
unPN = unPackageName
-- | Package version. A package name plus a version number.
type PV = PackageId
-- | Qualified package version.
type QPV = Qualified PV
-- | Package id. Currently just a black-box string.
type PId = UnitId
-- | Location. Info about whether a package is installed or not, and where
-- exactly it is located. For installed packages, uniquely identifies the
package instance via its ' PId ' .
--
-- TODO: More information is needed about the repo.
data Loc = Inst PId | InRepo
deriving (Eq, Ord, Show)
-- | Instance. A version number and a location.
data I = I Ver Loc
deriving (Eq, Ord, Show)
-- | String representation of an instance.
showI :: I -> String
showI (I v InRepo) = showVer v
showI (I v (Inst uid)) = showVer v ++ "/installed" ++ extractPackageAbiHash uid
where
extractPackageAbiHash xs =
case first reverse $ break (=='-') $ reverse (prettyShow xs) of
(ys, []) -> ys
(ys, _) -> '-' : ys
-- | Package instance. A package name and an instance.
data PI qpn = PI qpn I
deriving (Eq, Ord, Show, Functor)
-- | String representation of a package instance.
showPI :: PI QPN -> String
showPI (PI qpn i) = showQPN qpn ++ "-" ++ showI i
instI :: I -> Bool
instI (I _ (Inst _)) = True
instI _ = False
-- | Is the package in the primary group of packages. This is used to
-- determine (1) if we should try to establish stanza preferences
for this goal , and ( 2 ) whether or not a user specified @--constraint@
-- should apply to this dependency (grep 'primaryPP' to see the
-- use sites). In particular this does not include packages pulled in
-- as setup deps.
--
primaryPP :: PackagePath -> Bool
primaryPP (PackagePath _ns q) = go q
where
go QualToplevel = True
go (QualBase _) = True
go (QualSetup _) = False
go (QualExe _ _) = False
-- | Is the package a dependency of a setup script. This is used to
-- establish whether or not certain constraints should apply to this
-- dependency (grep 'setupPP' to see the use sites).
--
setupPP :: PackagePath -> Bool
setupPP (PackagePath _ns (QualSetup _)) = True
setupPP (PackagePath _ns _) = False
-- | Qualify a target package with its own name so that its dependencies are not
-- required to be consistent with other targets.
makeIndependent :: PN -> QPN
makeIndependent pn = Q (PackagePath (Independent pn) QualToplevel) pn
| null | https://raw.githubusercontent.com/haskell/cabal/6896c6aa0e4804913aaba0bbbe00649e18f17bb8/cabal-install-solver/src/Distribution/Solver/Modular/Package.hs | haskell | | A package name.
| Unpacking a package name.
| Package version. A package name plus a version number.
| Qualified package version.
| Package id. Currently just a black-box string.
| Location. Info about whether a package is installed or not, and where
exactly it is located. For installed packages, uniquely identifies the
TODO: More information is needed about the repo.
| Instance. A version number and a location.
| String representation of an instance.
| Package instance. A package name and an instance.
| String representation of a package instance.
| Is the package in the primary group of packages. This is used to
determine (1) if we should try to establish stanza preferences
constraint@
should apply to this dependency (grep 'primaryPP' to see the
use sites). In particular this does not include packages pulled in
as setup deps.
| Is the package a dependency of a setup script. This is used to
establish whether or not certain constraints should apply to this
dependency (grep 'setupPP' to see the use sites).
| Qualify a target package with its own name so that its dependencies are not
required to be consistent with other targets. | # LANGUAGE DeriveFunctor #
module Distribution.Solver.Modular.Package
( I(..)
, Loc(..)
, PackageId
, PackageIdentifier(..)
, PackageName, mkPackageName, unPackageName
, PkgconfigName, mkPkgconfigName, unPkgconfigName
, PI(..)
, PN
, QPV
, instI
, makeIndependent
, primaryPP
, setupPP
, showI
, showPI
, unPN
) where
import Prelude ()
import Distribution.Solver.Compat.Prelude
from Cabal
import Distribution.Pretty (prettyShow)
import Distribution.Solver.Modular.Version
import Distribution.Solver.Types.PackagePath
type PN = PackageName
unPN :: PN -> String
unPN = unPackageName
type PV = PackageId
type QPV = Qualified PV
type PId = UnitId
package instance via its ' PId ' .
data Loc = Inst PId | InRepo
deriving (Eq, Ord, Show)
data I = I Ver Loc
deriving (Eq, Ord, Show)
showI :: I -> String
showI (I v InRepo) = showVer v
showI (I v (Inst uid)) = showVer v ++ "/installed" ++ extractPackageAbiHash uid
where
extractPackageAbiHash xs =
case first reverse $ break (=='-') $ reverse (prettyShow xs) of
(ys, []) -> ys
(ys, _) -> '-' : ys
data PI qpn = PI qpn I
deriving (Eq, Ord, Show, Functor)
showPI :: PI QPN -> String
showPI (PI qpn i) = showQPN qpn ++ "-" ++ showI i
instI :: I -> Bool
instI (I _ (Inst _)) = True
instI _ = False
primaryPP :: PackagePath -> Bool
primaryPP (PackagePath _ns q) = go q
where
go QualToplevel = True
go (QualBase _) = True
go (QualSetup _) = False
go (QualExe _ _) = False
setupPP :: PackagePath -> Bool
setupPP (PackagePath _ns (QualSetup _)) = True
setupPP (PackagePath _ns _) = False
makeIndependent :: PN -> QPN
makeIndependent pn = Q (PackagePath (Independent pn) QualToplevel) pn
|
eca6ab950a2b2377e1acae38e470d12e0a88b42cb7eb476d2a4e66b8e1d8600d | namenu/advent-of-code | day03.clj | ;; --- Day 3: Spiral Memory ---
(ns aoc.year2017.day03
(:require [aoc.util :refer [find-first manhattan-dist]]))
scales = 1 1 2 2 3 3 4 4
(def scales
(let [nat (drop 1 (range))]
(interleave nat nat)))
;; dirs = R U L D R U L D ...
(def dirs
(cycle [[1 0] [0 -1] [-1 0] [0 1]]))
(defn spiral []
(let [moves (mapcat repeat scales dirs)]
(reductions #(mapv + %1 %2) [0 0] moves)))
(def n 312051)
pt.1
(manhattan-dist [0 0] (nth (spiral) (dec n)))
pt.2
(defn neighbors [[x y]]
[[(dec x) (dec y)] [(dec x) y] [(dec x) (inc y)]
[x (dec y)] [x (inc y)]
[(inc x) (dec y)] [(inc x) y] [(inc x) (inc y)]])
(defn acc-spiral []
(letfn [(step [acc [pos & next]]
(lazy-seq
(let [v (apply + (vals (select-keys acc (neighbors pos))))]
(cons v (step (assoc acc pos v) next)))))]
(step {[0 0] 1} (next (spiral)))))
(find-first #(> % n) (acc-spiral))
| null | https://raw.githubusercontent.com/namenu/advent-of-code/83f8cf05931f814dab76696bf46fec1bb1276fac/2017/clojure/src/aoc/year2017/day03.clj | clojure | --- Day 3: Spiral Memory ---
dirs = R U L D R U L D ... | (ns aoc.year2017.day03
(:require [aoc.util :refer [find-first manhattan-dist]]))
scales = 1 1 2 2 3 3 4 4
(def scales
(let [nat (drop 1 (range))]
(interleave nat nat)))
(def dirs
(cycle [[1 0] [0 -1] [-1 0] [0 1]]))
(defn spiral []
(let [moves (mapcat repeat scales dirs)]
(reductions #(mapv + %1 %2) [0 0] moves)))
(def n 312051)
pt.1
(manhattan-dist [0 0] (nth (spiral) (dec n)))
pt.2
(defn neighbors [[x y]]
[[(dec x) (dec y)] [(dec x) y] [(dec x) (inc y)]
[x (dec y)] [x (inc y)]
[(inc x) (dec y)] [(inc x) y] [(inc x) (inc y)]])
(defn acc-spiral []
(letfn [(step [acc [pos & next]]
(lazy-seq
(let [v (apply + (vals (select-keys acc (neighbors pos))))]
(cons v (step (assoc acc pos v) next)))))]
(step {[0 0] 1} (next (spiral)))))
(find-first #(> % n) (acc-spiral))
|
5bc6efa0454837520535585fdac4b60fe335347aa60c049889ed10cf0004d2b5 | nuprl/gradual-typing-performance | data-lattice.rkt | #lang racket/base
;; Provides functions for drawing lattices that show the perf data
;; for each configuration
(require racket/contract
racket/format
racket/list
data/bit-vector
(except-in math/number-theory permutations)
pict
unstable/gui/pict)
(provide (contract-out
[make-performance-lattice
(-> (and/c (vectorof (cons/c number? number?))
power-of-two-length?)
pict?)]))
(module+ test (require rackunit))
(define (power-of-two-length? vec)
(define factors (factorize (vector-length vec)))
(and (= 1 (length factors))
(= (car (car factors)) 2)))
(define (two-expt n) (cadar (factorize n)))
(module+ test
(check-true (power-of-two-length? (vector 1 2 3 4)))
(check-false (power-of-two-length? (vector 1 2 3))))
(define (make-performance-lattice data-vec)
(define total-bits (two-expt (vector-length data-vec)))
(define pict-vec (make-vector (vector-length data-vec) #f))
(define level-picts
(for/list ([on-bits (in-range total-bits -1 -1)])
(define perms (select (- total-bits on-bits) total-bits))
(apply hc-append 10
(for/list ([perm (in-list perms)])
(define bv (apply bit-vector perm))
(define num (string->number (bit-vector->string bv) 2))
(define pict (make-point bv
(vector-ref data-vec num)
(vector-ref data-vec 0)))
(vector-set! pict-vec num pict)
pict))))
(define no-lines-yet (apply vc-append 20 level-picts))
(add-all-lines no-lines-yet pict-vec total-bits))
taken from MF 's version
(define (select i L)
(cond
[(zero? i) (list (build-list L (lambda (_) #t)))]
[(zero? L) '()]
[else (append (map (lambda (r) (cons #f r)) (select (sub1 i) (sub1 L)))
(map (lambda (r) (cons #t r)) (select i (sub1 L))))]))
;; constructs a pict for a point in the lattice, using the initial
;; configuration to normalize (for coloring)
(define (make-point bv data init-data)
(define normalized-mean (/ (car data) (car init-data)))
(define normalized-stdev (/ (cdr data) (car init-data)))
(define style (if (> normalized-mean 1.5) '(bold) null))
(define box-pict
(apply hc-append
(for/list ([bit (in-bit-vector bv)])
(rectangle/border 7 10
#:border-width 1
#:color (if bit "black" "white")
#:border-color "dark gray"))))
(vc-append (blank 1 2)
box-pict
(blank 1 5)
(text (~a (~r normalized-mean
#:precision 2)
"±"
(~r normalized-stdev
#:precision 2))
style
6)
(blank 1 2)))
;; adds lines between elements in levels
(define (add-all-lines base vec bits)
(for/fold ([pict base])
([(from-pict idx) (in-indexed (in-vector vec))])
(define masks
(for/list ([bools (in-list (select (- bits 1) bits))])
(string->number (apply string-append (map (λ (x) (if x "1" "0")) bools))
2)))
(define targets
(remove* (list idx)
(map (λ (x) (bitwise-ior x idx)) masks)))
(for/fold ([pict pict])
([target-idx targets])
(define target (vector-ref vec target-idx))
(pin-arrow-line 2 pict from-pict ct-find target cb-find
#:line-width 0.5
#:under? #t))))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/benchmarks/data-lattice.rkt | racket | Provides functions for drawing lattices that show the perf data
for each configuration
constructs a pict for a point in the lattice, using the initial
configuration to normalize (for coloring)
adds lines between elements in levels | #lang racket/base
(require racket/contract
racket/format
racket/list
data/bit-vector
(except-in math/number-theory permutations)
pict
unstable/gui/pict)
(provide (contract-out
[make-performance-lattice
(-> (and/c (vectorof (cons/c number? number?))
power-of-two-length?)
pict?)]))
(module+ test (require rackunit))
(define (power-of-two-length? vec)
(define factors (factorize (vector-length vec)))
(and (= 1 (length factors))
(= (car (car factors)) 2)))
(define (two-expt n) (cadar (factorize n)))
(module+ test
(check-true (power-of-two-length? (vector 1 2 3 4)))
(check-false (power-of-two-length? (vector 1 2 3))))
(define (make-performance-lattice data-vec)
(define total-bits (two-expt (vector-length data-vec)))
(define pict-vec (make-vector (vector-length data-vec) #f))
(define level-picts
(for/list ([on-bits (in-range total-bits -1 -1)])
(define perms (select (- total-bits on-bits) total-bits))
(apply hc-append 10
(for/list ([perm (in-list perms)])
(define bv (apply bit-vector perm))
(define num (string->number (bit-vector->string bv) 2))
(define pict (make-point bv
(vector-ref data-vec num)
(vector-ref data-vec 0)))
(vector-set! pict-vec num pict)
pict))))
(define no-lines-yet (apply vc-append 20 level-picts))
(add-all-lines no-lines-yet pict-vec total-bits))
taken from MF 's version
(define (select i L)
(cond
[(zero? i) (list (build-list L (lambda (_) #t)))]
[(zero? L) '()]
[else (append (map (lambda (r) (cons #f r)) (select (sub1 i) (sub1 L)))
(map (lambda (r) (cons #t r)) (select i (sub1 L))))]))
(define (make-point bv data init-data)
(define normalized-mean (/ (car data) (car init-data)))
(define normalized-stdev (/ (cdr data) (car init-data)))
(define style (if (> normalized-mean 1.5) '(bold) null))
(define box-pict
(apply hc-append
(for/list ([bit (in-bit-vector bv)])
(rectangle/border 7 10
#:border-width 1
#:color (if bit "black" "white")
#:border-color "dark gray"))))
(vc-append (blank 1 2)
box-pict
(blank 1 5)
(text (~a (~r normalized-mean
#:precision 2)
"±"
(~r normalized-stdev
#:precision 2))
style
6)
(blank 1 2)))
(define (add-all-lines base vec bits)
(for/fold ([pict base])
([(from-pict idx) (in-indexed (in-vector vec))])
(define masks
(for/list ([bools (in-list (select (- bits 1) bits))])
(string->number (apply string-append (map (λ (x) (if x "1" "0")) bools))
2)))
(define targets
(remove* (list idx)
(map (λ (x) (bitwise-ior x idx)) masks)))
(for/fold ([pict pict])
([target-idx targets])
(define target (vector-ref vec target-idx))
(pin-arrow-line 2 pict from-pict ct-find target cb-find
#:line-width 0.5
#:under? #t))))
|
6f3b5873c184fa242e63e9b68de8899a4294c665e1fde09fbf5ddd90cab46a1b | runexec/chp | login.clj | (ns chp.login
(:require [korma.db
:as kdb]
[korma.core
:as kc])
(:use [chp.db
:only [*db*]]
[chp.password
:only [password]]))
(kdb/defdb korma-db *db*)
(defn login?
[user
secret
& {:keys
[username-column
password-column]
:or {username-column :name
password-column :password}}]
(let [[uc pc] [(keyword username-column)
(keyword password-column)]
user {uc user}
table {:table "user"}
salt (->> (kc/where user)
(kc/select table (kc/fields [:salt]))
first
:salt)
login (assoc user
:password
(password salt secret))]
(->> (kc/where login)
(kc/select table (kc/fields [:id]))
first
boolean)))
(defn admin?
[user
& {:keys
[username-column
admin-column]
:or {username-column :name
admin-column :admin}}]
(let [uc (keyword username-column)
ac (keyword admin-column)
admin {uc user
ac true}]
(->> (kc/where admin)
(kc/select {:table "user"})
first
boolean)))
(defn login-id
[user
& {:keys [username-column]
:or {username-column :name}}]
(let [column (keyword username-column)
-user {column (str user)}]
(->> (kc/where -user)
(kc/select {:table "user"} (kc/fields [:id]))
first
:id)))
(defn login-salt
[user
& {:keys [username-column]
:or {username-column :name}}]
(let [column (keyword username-column)
-user {column (str user)}]
(->> (kc/where -user)
(kc/select {:table "user"} (kc/fields [:salt]))
first
:salt)))
(defn login-password
[user
& {:keys [username-column]
:or {username-column :name}}]
(let [column (keyword username-column)
-user {column (str user)}]
(->> (kc/where -user)
(kc/select {:table "user"} (kc/fields [:password]))
first
:password)))
| null | https://raw.githubusercontent.com/runexec/chp/9059399c46fb4106a73631c741f1e557af541a8b/src/chp/login.clj | clojure | (ns chp.login
(:require [korma.db
:as kdb]
[korma.core
:as kc])
(:use [chp.db
:only [*db*]]
[chp.password
:only [password]]))
(kdb/defdb korma-db *db*)
(defn login?
[user
secret
& {:keys
[username-column
password-column]
:or {username-column :name
password-column :password}}]
(let [[uc pc] [(keyword username-column)
(keyword password-column)]
user {uc user}
table {:table "user"}
salt (->> (kc/where user)
(kc/select table (kc/fields [:salt]))
first
:salt)
login (assoc user
:password
(password salt secret))]
(->> (kc/where login)
(kc/select table (kc/fields [:id]))
first
boolean)))
(defn admin?
[user
& {:keys
[username-column
admin-column]
:or {username-column :name
admin-column :admin}}]
(let [uc (keyword username-column)
ac (keyword admin-column)
admin {uc user
ac true}]
(->> (kc/where admin)
(kc/select {:table "user"})
first
boolean)))
(defn login-id
[user
& {:keys [username-column]
:or {username-column :name}}]
(let [column (keyword username-column)
-user {column (str user)}]
(->> (kc/where -user)
(kc/select {:table "user"} (kc/fields [:id]))
first
:id)))
(defn login-salt
[user
& {:keys [username-column]
:or {username-column :name}}]
(let [column (keyword username-column)
-user {column (str user)}]
(->> (kc/where -user)
(kc/select {:table "user"} (kc/fields [:salt]))
first
:salt)))
(defn login-password
[user
& {:keys [username-column]
:or {username-column :name}}]
(let [column (keyword username-column)
-user {column (str user)}]
(->> (kc/where -user)
(kc/select {:table "user"} (kc/fields [:password]))
first
:password)))
|
|
7000f6a6939a0a20efe86f5d7acd46e19161c2c9847b074054c3ca8faf08701e | ucsd-progsys/liquidhaskell | UnboundVarInLocSig.hs | {-@ LIQUID "--expect-error-containing=Illegal type specification for `bar`" @-}
module UnboundVarInLocSig where
{-@ foo :: x:_ -> y:_ -> {v:Int | v = x + y} @-}
foo :: Int -> Int -> Int
foo arg0 = bar
where
{-@ bar :: x:_ -> {v:Int | v = x + barg0} @-}
bar arg1 = arg0 + arg1
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/errors/UnboundVarInLocSig.hs | haskell | @ LIQUID "--expect-error-containing=Illegal type specification for `bar`" @
@ foo :: x:_ -> y:_ -> {v:Int | v = x + y} @
@ bar :: x:_ -> {v:Int | v = x + barg0} @ | module UnboundVarInLocSig where
foo :: Int -> Int -> Int
foo arg0 = bar
where
bar arg1 = arg0 + arg1
|
7dee47d7cd236c19a037ff398bb1b454a9d736b68df3025e12e1d633143a1e5a | shentufoundation/deepsea | parser.mli |
(* The type of tokens. *)
type token =
| XOR
| WITH
| UNEQUAL
| UINT of (string)
| TYPE
| TRUSTED
| TRANSFERETH
| TO
| THEN
| STRING of (string)
| STAR
| SLASH
| SIGNATURE
| SHR
| SHL
| SEMICOLON
| RPAREN
| REFINED
| RBRACKET
| RBRACE
| PLUS
| OBJECT
| MOD
| MINUS
| MATCH
| MAPPING
| LPAREN
| LOGICAL
| LIST
| LET
| LESSEQ
| LESS
| LBRACKET
| LBRACE
| LAYER
| INT of (string)
| INDEXED
| IN
| IF
| IDENT of (Astcommon.ident)
| GREATEREQ
| GREATER
| GHOST
| FOR
| FOLD
| FIRST
| FAIL
| EXTERNAL
| EVENT
| EQUAL
| EOF
| END
| EMIT
| ELSE
| DOUBLEARROW
| DOT
| DO
| DISJUNCTION
| DENY
| CONSTRUCTOR
| CONST
| CONJUNCTION
| COMMA
| COLONLESS
| COLONGREATER
| COLONCOLON
| COLON
| CLONE
| BITNOT
| BITAND
| BEGIN
| BARBAR
| BAR
| BANG
| AT
| ASSIGN
| ASSERT
| ARROW
| ARRAY
| ADDRESS
(* This exception is raised by the monolithic API functions. *)
exception Error
(* The monolithic API. *)
val file: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.p_file_structure)
| null | https://raw.githubusercontent.com/shentufoundation/deepsea/60386608f23e5e316196ac73db417007783240d8/src/Edsger/parser.mli | ocaml | The type of tokens.
This exception is raised by the monolithic API functions.
The monolithic API. |
type token =
| XOR
| WITH
| UNEQUAL
| UINT of (string)
| TYPE
| TRUSTED
| TRANSFERETH
| TO
| THEN
| STRING of (string)
| STAR
| SLASH
| SIGNATURE
| SHR
| SHL
| SEMICOLON
| RPAREN
| REFINED
| RBRACKET
| RBRACE
| PLUS
| OBJECT
| MOD
| MINUS
| MATCH
| MAPPING
| LPAREN
| LOGICAL
| LIST
| LET
| LESSEQ
| LESS
| LBRACKET
| LBRACE
| LAYER
| INT of (string)
| INDEXED
| IN
| IF
| IDENT of (Astcommon.ident)
| GREATEREQ
| GREATER
| GHOST
| FOR
| FOLD
| FIRST
| FAIL
| EXTERNAL
| EVENT
| EQUAL
| EOF
| END
| EMIT
| ELSE
| DOUBLEARROW
| DOT
| DO
| DISJUNCTION
| DENY
| CONSTRUCTOR
| CONST
| CONJUNCTION
| COMMA
| COLONLESS
| COLONGREATER
| COLONCOLON
| COLON
| CLONE
| BITNOT
| BITAND
| BEGIN
| BARBAR
| BAR
| BANG
| AT
| ASSIGN
| ASSERT
| ARROW
| ARRAY
| ADDRESS
exception Error
val file: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.p_file_structure)
|
f3690efcc1b9dd01275e00372f4ffac2662e6cfb800fb6db53e3e6644c2b7e68 | axelarge/advent-of-code | day10.clj | (ns advent-of-code.y2017.day10
(:require [advent-of-code.support :refer :all]
[clojure.string :as str]))
(def input "227,169,3,166,246,201,0,47,1,255,2,254,96,3,97,144")
(defn parse1 [steps]
(find-ints steps))
(defn parse2 [steps]
(-> (map int steps)
(concat [17 31 73 47 23])
vec))
(defn take-step [[ls offset skip] n]
(let [is (->> (range offset (+ offset n))
(map #(mod % (count ls))))]
[(reduce-kv assoc ls (zipmap is (map ls (reverse is))))
(+ offset n skip)
(inc skip)]))
(defn take-steps [size times steps]
(-> (iterate #(reduce take-step % steps)
[(vec (range size)) 0 0])
(nth times)
first))
(defn condense [ints]
(->> ints
(partition 16)
(map (partial apply bit-xor))))
(defn to-hex [ints]
(str/join (map #(format "%02x" %) ints)))
(defn solve1
([input] (solve1 256 input))
([size input]
(->> input
parse1
(take-steps size 1)
(take 2)
(apply *))))
(defn solve2 [input]
(->> input
parse2
(take-steps 256 64)
condense
to-hex))
| null | https://raw.githubusercontent.com/axelarge/advent-of-code/4c62a53ef71605780a22cf8219029453d8e1b977/src/advent_of_code/y2017/day10.clj | clojure | (ns advent-of-code.y2017.day10
(:require [advent-of-code.support :refer :all]
[clojure.string :as str]))
(def input "227,169,3,166,246,201,0,47,1,255,2,254,96,3,97,144")
(defn parse1 [steps]
(find-ints steps))
(defn parse2 [steps]
(-> (map int steps)
(concat [17 31 73 47 23])
vec))
(defn take-step [[ls offset skip] n]
(let [is (->> (range offset (+ offset n))
(map #(mod % (count ls))))]
[(reduce-kv assoc ls (zipmap is (map ls (reverse is))))
(+ offset n skip)
(inc skip)]))
(defn take-steps [size times steps]
(-> (iterate #(reduce take-step % steps)
[(vec (range size)) 0 0])
(nth times)
first))
(defn condense [ints]
(->> ints
(partition 16)
(map (partial apply bit-xor))))
(defn to-hex [ints]
(str/join (map #(format "%02x" %) ints)))
(defn solve1
([input] (solve1 256 input))
([size input]
(->> input
parse1
(take-steps size 1)
(take 2)
(apply *))))
(defn solve2 [input]
(->> input
parse2
(take-steps 256 64)
condense
to-hex))
|
|
df3f9fa2bad3b8dcb81d4a2879c22a88d84518212e62ceb35d727bcc14acb4d5 | stonebuddha/eopl | core.ml | open Syntax
type refer = int
and store = expval list
and environment = refer list
and expval =
| NumVal of int
| BoolVal of bool
| ProcVal of proc
and proc = expression * environment ref
let string_of_expval eval =
match eval with
| NumVal num -> string_of_int num
| BoolVal bool -> string_of_bool bool
| ProcVal _ -> "<proc>"
let empty_env () = []
let extend_env refer env = refer :: env
let apply_env env var = List.nth env var
type stoval =
| Evaled of expval
| Thunk of expression * environment
let empty_store () = ref []
let init_store st = st := []
let newref sval st =
let refer = List.length (!st) in
let () = st := List.append (!st) [sval] in
refer
let deref refer st = List.nth (!st) refer
let setref refer sval st =
let rec inner refer st =
if refer = 0 then
sval :: List.tl st
else
List.hd st :: inner (refer - 1) (List.tl st) in
st := inner refer (!st)
let the_store = empty_store ()
exception Interpreter_error of string * Ploc.t
let rec value_of exp env =
match exp with
| ConstExp (num, loc) -> NumVal num
| DiffExp (exp1, exp2, loc) ->
let eval1 = value_of exp1 env in
let eval2 = value_of exp2 env in
(match (eval1, eval2) with
| (NumVal num1, NumVal num2) -> NumVal (num1 - num2)
| _ -> raise (Interpreter_error ("the operands of diff should be numbers", loc)))
| IsZeroExp (exp1, loc) ->
let eval1 = value_of exp1 env in
(match eval1 with
| NumVal num1 -> BoolVal (num1 = 0)
| _ -> raise (Interpreter_error ("the operand of is_zero should be a number", loc)))
| IfExp (exp1, exp2, exp3, loc) ->
let eval1 = value_of exp1 env in
(match eval1 with
| BoolVal bool1 -> if bool1 then value_of exp2 env else value_of exp3 env
| _ -> raise (Interpreter_error ("the predicate of if should be a boolean", loc)))
| VarExp (var, loc) ->
let refer = apply_env env var in
let sval = deref refer the_store in
(match sval with
| Evaled eval -> eval
| Thunk (body, saved_env) ->
let eval = value_of body saved_env in
let () = setref refer (Evaled eval) the_store in
eval)
| LetExp (exps, body, loc) ->
let evals = List.map (fun exp1 -> value_of exp1 env) exps in
let env' = List.fold_left (fun env eval1 -> extend_env (newref (Evaled eval1) the_store) env) env evals in
value_of body env'
| ProcExp (body, loc) -> ProcVal (body, ref env)
| CallExp (rator, rand, loc) ->
let rator_val = value_of rator env in
(match rator_val with
| ProcVal proc -> let rand_ref = value_of_operand rand env in apply_procedure proc rand_ref
| _ -> raise (Interpreter_error ("the operator of call should be a procedure", loc)))
| LetrecExp (p_bodies, letrec_body, loc) ->
let saved_env = ref (empty_env ()) in
let procs = List.map (fun p_body -> ProcVal (p_body, saved_env)) p_bodies in
let env' = List.fold_left (fun env eval -> extend_env (newref (Evaled eval) the_store) env) env procs in
let () = saved_env := env' in
value_of letrec_body !saved_env
| BeginExp (exps, loc) ->
let eval1 = value_of (List.hd exps) env in
List.fold_left (fun _ exp1 -> value_of exp1 env) eval1 (List.tl exps)
| AssignExp (var, exp1, loc) ->
let refer = apply_env env var in
let eval1 = value_of exp1 env in
let () = setref refer (Evaled eval1) the_store in
NumVal 27
and value_of_operand exp env =
match exp with
| VarExp (var, loc) -> apply_env env var
| _ -> newref (Thunk (exp, env)) the_store
and apply_procedure proc arg_ref =
match proc with
| (body, saved_env) -> value_of body (extend_env arg_ref !saved_env)
let value_of_top_level top env =
match top with
| ValTop (var, exp1) ->
let eval1 = value_of exp1 env in
let () = print_endline ("val " ^ var ^ " = " ^ string_of_expval eval1 ^ ";") in
extend_env (newref (Evaled eval1) the_store) env
| FunTop (p_name, p_body) ->
let saved_env = ref (empty_env ()) in
let proc = ProcVal (p_body, saved_env) in
let () = saved_env := extend_env (newref (Evaled proc) the_store) env in
!saved_env
let value_of_program (AProgram tops) =
let () = init_store the_store in
List.fold_left (fun env top -> value_of_top_level top env) (empty_env ()) tops; ()
| null | https://raw.githubusercontent.com/stonebuddha/eopl/88ea636110421706f900e753c30240ff1ea26f67/CALL-BY-NEED/core.ml | ocaml | open Syntax
type refer = int
and store = expval list
and environment = refer list
and expval =
| NumVal of int
| BoolVal of bool
| ProcVal of proc
and proc = expression * environment ref
let string_of_expval eval =
match eval with
| NumVal num -> string_of_int num
| BoolVal bool -> string_of_bool bool
| ProcVal _ -> "<proc>"
let empty_env () = []
let extend_env refer env = refer :: env
let apply_env env var = List.nth env var
type stoval =
| Evaled of expval
| Thunk of expression * environment
let empty_store () = ref []
let init_store st = st := []
let newref sval st =
let refer = List.length (!st) in
let () = st := List.append (!st) [sval] in
refer
let deref refer st = List.nth (!st) refer
let setref refer sval st =
let rec inner refer st =
if refer = 0 then
sval :: List.tl st
else
List.hd st :: inner (refer - 1) (List.tl st) in
st := inner refer (!st)
let the_store = empty_store ()
exception Interpreter_error of string * Ploc.t
let rec value_of exp env =
match exp with
| ConstExp (num, loc) -> NumVal num
| DiffExp (exp1, exp2, loc) ->
let eval1 = value_of exp1 env in
let eval2 = value_of exp2 env in
(match (eval1, eval2) with
| (NumVal num1, NumVal num2) -> NumVal (num1 - num2)
| _ -> raise (Interpreter_error ("the operands of diff should be numbers", loc)))
| IsZeroExp (exp1, loc) ->
let eval1 = value_of exp1 env in
(match eval1 with
| NumVal num1 -> BoolVal (num1 = 0)
| _ -> raise (Interpreter_error ("the operand of is_zero should be a number", loc)))
| IfExp (exp1, exp2, exp3, loc) ->
let eval1 = value_of exp1 env in
(match eval1 with
| BoolVal bool1 -> if bool1 then value_of exp2 env else value_of exp3 env
| _ -> raise (Interpreter_error ("the predicate of if should be a boolean", loc)))
| VarExp (var, loc) ->
let refer = apply_env env var in
let sval = deref refer the_store in
(match sval with
| Evaled eval -> eval
| Thunk (body, saved_env) ->
let eval = value_of body saved_env in
let () = setref refer (Evaled eval) the_store in
eval)
| LetExp (exps, body, loc) ->
let evals = List.map (fun exp1 -> value_of exp1 env) exps in
let env' = List.fold_left (fun env eval1 -> extend_env (newref (Evaled eval1) the_store) env) env evals in
value_of body env'
| ProcExp (body, loc) -> ProcVal (body, ref env)
| CallExp (rator, rand, loc) ->
let rator_val = value_of rator env in
(match rator_val with
| ProcVal proc -> let rand_ref = value_of_operand rand env in apply_procedure proc rand_ref
| _ -> raise (Interpreter_error ("the operator of call should be a procedure", loc)))
| LetrecExp (p_bodies, letrec_body, loc) ->
let saved_env = ref (empty_env ()) in
let procs = List.map (fun p_body -> ProcVal (p_body, saved_env)) p_bodies in
let env' = List.fold_left (fun env eval -> extend_env (newref (Evaled eval) the_store) env) env procs in
let () = saved_env := env' in
value_of letrec_body !saved_env
| BeginExp (exps, loc) ->
let eval1 = value_of (List.hd exps) env in
List.fold_left (fun _ exp1 -> value_of exp1 env) eval1 (List.tl exps)
| AssignExp (var, exp1, loc) ->
let refer = apply_env env var in
let eval1 = value_of exp1 env in
let () = setref refer (Evaled eval1) the_store in
NumVal 27
and value_of_operand exp env =
match exp with
| VarExp (var, loc) -> apply_env env var
| _ -> newref (Thunk (exp, env)) the_store
and apply_procedure proc arg_ref =
match proc with
| (body, saved_env) -> value_of body (extend_env arg_ref !saved_env)
let value_of_top_level top env =
match top with
| ValTop (var, exp1) ->
let eval1 = value_of exp1 env in
let () = print_endline ("val " ^ var ^ " = " ^ string_of_expval eval1 ^ ";") in
extend_env (newref (Evaled eval1) the_store) env
| FunTop (p_name, p_body) ->
let saved_env = ref (empty_env ()) in
let proc = ProcVal (p_body, saved_env) in
let () = saved_env := extend_env (newref (Evaled proc) the_store) env in
!saved_env
let value_of_program (AProgram tops) =
let () = init_store the_store in
List.fold_left (fun env top -> value_of_top_level top env) (empty_env ()) tops; ()
|
|
c8a69962acdc5ab7ac8750bde8bb8de4842e4ef9c34e18aade32a06af012cc25 | haskell-repa/repa | Append.hs |
module Data.Array.Repa.Chain.Append
(appendSegs)
where
import Data.Array.Repa.Chain.Base
import GHC.Exts
-- | Segmented append.
appendSegs
:: forall a
. (Int# -> Int#) -- ^ Get segment lengths for 'xs' array.
-> (Int# -> Int#) -- ^ Get segment indices for 'xs' array.
^ Get data from the ' xs ' array .
-> (Int# -> Int#) -- ^ Get segment lengths for 'ys' array.
-> (Int# -> Int#) -- ^ Get segment indices for 'ys' array.
-> (Int# -> a) -- ^ Get data from the 'ys' array.
-> Int# -- ^ How many result elements to produce in total.
-> Int# -- ^ Starting segment id.
-> Int# -- ^ Starting element index within the starting segment.
-- This is the element index relative to the result array.
-> Chain a
appendSegs segLenX segIdxX elemX
segLenY segIdxY elemY
n seg_off el_off
= Chain n state next
where
Starting State -------------
-- We need to determine which vector to start reading elements from.
state
-- The result vector has no elements, so we're already done.
| n ==# 0#
= ASDo { as_takefrom = 0#
, as_seg_off = 0#
, as_xs_index = 0#
, as_ys_index = 0#
, as_next_swap = 0#
, as_remain = 0# }
-- Start reading elements from xs.
-- If the starting element index is less than the length of the
-- first 'xs' segment then we start reading elements from the
-- 'xs' array.
| el_off <# segLenX seg_off
= ASDo { as_takefrom = 0#
, as_seg_off = seg_off
, as_xs_index = segIdxX seg_off +# el_off
, as_ys_index = segIdxY seg_off
, as_next_swap = segLenX seg_off -# el_off
, as_remain = n }
-- Start reading elements from ys.
We still set as_xs_index to the first element we will read from
-- the X array, but in this case it will be for the next segment.
--
-- NOTE: *not* indicesUSegd xd ! (seg_off+1) since seg_off+1
-- might be out of bounds
| otherwise
Get the starting element offset relative to the first segment
-- of the Y array.
!el_off' = el_off -# segLenX seg_off
in ASDo
{ as_takefrom = 1#
, as_seg_off = seg_off
, as_xs_index = segIdxX seg_off +# segLenX seg_off
, as_ys_index = segIdxY seg_off +# el_off'
, as_next_swap = segLenY seg_off -# el_off'
, as_remain = n }
# INLINE next #
-- Next -----------------------
next :: Int# -> AppendState -> Step AppendState a
-- Reading from xs
next _ s@ASDo { as_takefrom = 0# }
-- Done reading xs, so read the rest of this segment from ys.
| as_next_swap s ==# 0#
= Update $ s { as_takefrom = 1#
, as_next_swap = segLenY (as_seg_off s) }
-- Emit a value from xs.
| otherwise
= Yield (inc s) (elemX (as_xs_index s))
-- Reading from ys.
next _ s
-- Done reading ys, so read the rest from the next segments xs.
| as_next_swap s ==# 0#
= let seg' = as_seg_off s +# 1#
in Update
$ s { as_takefrom = 0#
, as_seg_off = seg'
, as_next_swap = segLenX seg' }
-- Emit a value from ys
| otherwise
= Yield (inc s) (elemY (as_ys_index s))
-- Inc ---------------------------
-- Move data pointer forward, and decrease remaining and swap
inc :: AppendState -> AppendState
inc s@ASDo
{ as_takefrom = 0#
, as_xs_index = xi
, as_next_swap = swap
, as_remain = n'}
= s { as_xs_index = xi +# 1#
, as_next_swap = swap -# 1#
, as_remain = n' -# 1# }
is nonzero : reading from ys
inc s@ASDo
{ as_ys_index = yi
, as_next_swap = swap
, as_remain = n'}
= s { as_ys_index = yi +# 1#
, as_next_swap = swap -# 1#
, as_remain = n' -# 1# }
# INLINE inc #
# INLINE appendSegs #
data AppendState
= ASDo
{ -- | Which vector we're currently reading from.
-- 0 = xs, nonzero = ys
as_takefrom :: Int#
-- | Current segment id.
, as_seg_off :: Int#
-- | Current index into 'xs' data.
, as_xs_index :: Int#
-- | Current index into 'ys' data.
, as_ys_index :: Int#
-- | How many elements to emit before we swap source arrays.
, as_next_swap :: Int#
-- | How many more elements we need to emit in total.
, as_remain :: Int#
}
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/icebox/abandoned/repa-stream/Data/Array/Repa/Chain/Append.hs | haskell | | Segmented append.
^ Get segment lengths for 'xs' array.
^ Get segment indices for 'xs' array.
^ Get segment lengths for 'ys' array.
^ Get segment indices for 'ys' array.
^ Get data from the 'ys' array.
^ How many result elements to produce in total.
^ Starting segment id.
^ Starting element index within the starting segment.
This is the element index relative to the result array.
-----------
We need to determine which vector to start reading elements from.
The result vector has no elements, so we're already done.
Start reading elements from xs.
If the starting element index is less than the length of the
first 'xs' segment then we start reading elements from the
'xs' array.
Start reading elements from ys.
the X array, but in this case it will be for the next segment.
NOTE: *not* indicesUSegd xd ! (seg_off+1) since seg_off+1
might be out of bounds
of the Y array.
Next -----------------------
Reading from xs
Done reading xs, so read the rest of this segment from ys.
Emit a value from xs.
Reading from ys.
Done reading ys, so read the rest from the next segments xs.
Emit a value from ys
Inc ---------------------------
Move data pointer forward, and decrease remaining and swap
| Which vector we're currently reading from.
0 = xs, nonzero = ys
| Current segment id.
| Current index into 'xs' data.
| Current index into 'ys' data.
| How many elements to emit before we swap source arrays.
| How many more elements we need to emit in total. |
module Data.Array.Repa.Chain.Append
(appendSegs)
where
import Data.Array.Repa.Chain.Base
import GHC.Exts
appendSegs
:: forall a
^ Get data from the ' xs ' array .
-> Chain a
appendSegs segLenX segIdxX elemX
segLenY segIdxY elemY
n seg_off el_off
= Chain n state next
where
state
| n ==# 0#
= ASDo { as_takefrom = 0#
, as_seg_off = 0#
, as_xs_index = 0#
, as_ys_index = 0#
, as_next_swap = 0#
, as_remain = 0# }
| el_off <# segLenX seg_off
= ASDo { as_takefrom = 0#
, as_seg_off = seg_off
, as_xs_index = segIdxX seg_off +# el_off
, as_ys_index = segIdxY seg_off
, as_next_swap = segLenX seg_off -# el_off
, as_remain = n }
We still set as_xs_index to the first element we will read from
| otherwise
Get the starting element offset relative to the first segment
!el_off' = el_off -# segLenX seg_off
in ASDo
{ as_takefrom = 1#
, as_seg_off = seg_off
, as_xs_index = segIdxX seg_off +# segLenX seg_off
, as_ys_index = segIdxY seg_off +# el_off'
, as_next_swap = segLenY seg_off -# el_off'
, as_remain = n }
# INLINE next #
next :: Int# -> AppendState -> Step AppendState a
next _ s@ASDo { as_takefrom = 0# }
| as_next_swap s ==# 0#
= Update $ s { as_takefrom = 1#
, as_next_swap = segLenY (as_seg_off s) }
| otherwise
= Yield (inc s) (elemX (as_xs_index s))
next _ s
| as_next_swap s ==# 0#
= let seg' = as_seg_off s +# 1#
in Update
$ s { as_takefrom = 0#
, as_seg_off = seg'
, as_next_swap = segLenX seg' }
| otherwise
= Yield (inc s) (elemY (as_ys_index s))
inc :: AppendState -> AppendState
inc s@ASDo
{ as_takefrom = 0#
, as_xs_index = xi
, as_next_swap = swap
, as_remain = n'}
= s { as_xs_index = xi +# 1#
, as_next_swap = swap -# 1#
, as_remain = n' -# 1# }
is nonzero : reading from ys
inc s@ASDo
{ as_ys_index = yi
, as_next_swap = swap
, as_remain = n'}
= s { as_ys_index = yi +# 1#
, as_next_swap = swap -# 1#
, as_remain = n' -# 1# }
# INLINE inc #
# INLINE appendSegs #
data AppendState
= ASDo
as_takefrom :: Int#
, as_seg_off :: Int#
, as_xs_index :: Int#
, as_ys_index :: Int#
, as_next_swap :: Int#
, as_remain :: Int#
}
|
fe29f24ba6b184bc5b95b27ec6b73320963864fdb7f2ad447197e9598d559fac | herbelin/coq-hh | entries.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i*)
open Names
open Univ
open Term
open Sign
(*i*)
(* This module defines the entry types for global declarations. This
information is entered in the environments. This includes global
constants/axioms, mutual inductive definitions, modules and module
types *)
(*s Local entries *)
type local_entry =
| LocalDef of constr
| LocalAssum of constr
(*s Declaration of inductive types. *)
Assume the following definition in concrete syntax :
}
Inductive I1 ( x1 : X1 ) ... ( xn : Xn ) : A1 : = c11 : T11 | ... | c1n1 : T1n1
...
with Ip ( x1 : X1 ) ... ( xn : Xn ) : Ap : = cp1 : Tp1 | ... | cpnp : Tpnp .
\end{verbatim }
then , in $ i^{th}$ block , [ mind_entry_params ] is [ [ xn : Xn; ... ;x1 : X1 ] ] ;
[ mind_entry_arity ] is [ Ai ] , defined in context [ [ [ x1 : X1; ... ;xn : Xn ] ] ;
[ mind_entry_lc ] is [ Ti1; ... ;Tini ] , defined in context [ [ A'1; ... ;A'p;x1 : X1; ... ;xn : Xn ] ] where [ A'i ] is [ Ai ] generalized over [ [ x1 : X1; ... ;xn : Xn ] ] .
\begin{verbatim}
Inductive I1 (x1:X1) ... (xn:Xn) : A1 := c11 : T11 | ... | c1n1 : T1n1
...
with Ip (x1:X1) ... (xn:Xn) : Ap := cp1 : Tp1 | ... | cpnp : Tpnp.
\end{verbatim}
then, in $i^{th}$ block, [mind_entry_params] is [[xn:Xn;...;x1:X1]];
[mind_entry_arity] is [Ai], defined in context [[[x1:X1;...;xn:Xn]];
[mind_entry_lc] is [Ti1;...;Tini], defined in context [[A'1;...;A'p;x1:X1;...;xn:Xn]] where [A'i] is [Ai] generalized over [[x1:X1;...;xn:Xn]].
*)
type one_inductive_entry = {
mind_entry_typename : identifier;
mind_entry_arity : constr;
mind_entry_consnames : identifier list;
mind_entry_lc : constr list }
type mutual_inductive_entry = {
mind_entry_record : bool;
mind_entry_finite : bool;
mind_entry_params : (identifier * local_entry) list;
mind_entry_inds : one_inductive_entry list }
(*s Constants (Definition/Axiom) *)
type definition_entry = {
const_entry_body : constr;
const_entry_type : types option;
const_entry_opaque : bool;
const_entry_boxed : bool}
(* type and the inlining flag *)
type parameter_entry = types * bool
type constant_entry =
| DefinitionEntry of definition_entry
| ParameterEntry of parameter_entry
(*s Modules *)
type module_struct_entry =
MSEident of module_path
| MSEfunctor of mod_bound_id * module_struct_entry * module_struct_entry
| MSEwith of module_struct_entry * with_declaration
| MSEapply of module_struct_entry * module_struct_entry
and with_declaration =
With_Module of identifier list * module_path
| With_Definition of identifier list * constr
and module_entry =
{ mod_entry_type : module_struct_entry option;
mod_entry_expr : module_struct_entry option}
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/kernel/entries.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
This module defines the entry types for global declarations. This
information is entered in the environments. This includes global
constants/axioms, mutual inductive definitions, modules and module
types
s Local entries
s Declaration of inductive types.
s Constants (Definition/Axiom)
type and the inlining flag
s Modules | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Univ
open Term
open Sign
type local_entry =
| LocalDef of constr
| LocalAssum of constr
Assume the following definition in concrete syntax :
}
Inductive I1 ( x1 : X1 ) ... ( xn : Xn ) : A1 : = c11 : T11 | ... | c1n1 : T1n1
...
with Ip ( x1 : X1 ) ... ( xn : Xn ) : Ap : = cp1 : Tp1 | ... | cpnp : Tpnp .
\end{verbatim }
then , in $ i^{th}$ block , [ mind_entry_params ] is [ [ xn : Xn; ... ;x1 : X1 ] ] ;
[ mind_entry_arity ] is [ Ai ] , defined in context [ [ [ x1 : X1; ... ;xn : Xn ] ] ;
[ mind_entry_lc ] is [ Ti1; ... ;Tini ] , defined in context [ [ A'1; ... ;A'p;x1 : X1; ... ;xn : Xn ] ] where [ A'i ] is [ Ai ] generalized over [ [ x1 : X1; ... ;xn : Xn ] ] .
\begin{verbatim}
Inductive I1 (x1:X1) ... (xn:Xn) : A1 := c11 : T11 | ... | c1n1 : T1n1
...
with Ip (x1:X1) ... (xn:Xn) : Ap := cp1 : Tp1 | ... | cpnp : Tpnp.
\end{verbatim}
then, in $i^{th}$ block, [mind_entry_params] is [[xn:Xn;...;x1:X1]];
[mind_entry_arity] is [Ai], defined in context [[[x1:X1;...;xn:Xn]];
[mind_entry_lc] is [Ti1;...;Tini], defined in context [[A'1;...;A'p;x1:X1;...;xn:Xn]] where [A'i] is [Ai] generalized over [[x1:X1;...;xn:Xn]].
*)
type one_inductive_entry = {
mind_entry_typename : identifier;
mind_entry_arity : constr;
mind_entry_consnames : identifier list;
mind_entry_lc : constr list }
type mutual_inductive_entry = {
mind_entry_record : bool;
mind_entry_finite : bool;
mind_entry_params : (identifier * local_entry) list;
mind_entry_inds : one_inductive_entry list }
type definition_entry = {
const_entry_body : constr;
const_entry_type : types option;
const_entry_opaque : bool;
const_entry_boxed : bool}
type parameter_entry = types * bool
type constant_entry =
| DefinitionEntry of definition_entry
| ParameterEntry of parameter_entry
type module_struct_entry =
MSEident of module_path
| MSEfunctor of mod_bound_id * module_struct_entry * module_struct_entry
| MSEwith of module_struct_entry * with_declaration
| MSEapply of module_struct_entry * module_struct_entry
and with_declaration =
With_Module of identifier list * module_path
| With_Definition of identifier list * constr
and module_entry =
{ mod_entry_type : module_struct_entry option;
mod_entry_expr : module_struct_entry option}
|
9b5ec00beff9aea813931f00691d53748f2dfb3a6ac1dbc485d55135e0498343 | diku-dk/futhark | IR.hs | | A convenient re - export of basic AST modules .
module Futhark.IR
( module Futhark.IR.Prop,
module Futhark.IR.Traversals,
module Futhark.IR.Pretty,
module Futhark.IR.Syntax,
)
where
import Futhark.IR.Pretty
import Futhark.IR.Prop
import Futhark.IR.Syntax
import Futhark.IR.Traversals
| null | https://raw.githubusercontent.com/diku-dk/futhark/7c8494f809dbb1e41775471e88270068d8632407/src/Futhark/IR.hs | haskell | | A convenient re - export of basic AST modules .
module Futhark.IR
( module Futhark.IR.Prop,
module Futhark.IR.Traversals,
module Futhark.IR.Pretty,
module Futhark.IR.Syntax,
)
where
import Futhark.IR.Pretty
import Futhark.IR.Prop
import Futhark.IR.Syntax
import Futhark.IR.Traversals
|
|
bcb67758c25026990c568758cf7f10a24c17f9f8c0682ea6c95f5b5ee41cd953 | kumarshantanu/espejito | core.cljc | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns espejito.core
#?(:cljs (:require-macros espejito.core))
(:require
#?(:cljs [goog.string :as gstring])
#?(:cljs [goog.string.format])
#?(:cljs [cljs.pprint :include-macros true :as pp]
:clj [clojure.pprint :as pp])
[espejito.internal :as i]))
(def ^:dynamic *metrics* nil)
(defmacro measure
"Use this at layer boundaries in code. Not recommended for tight loops - may cause out-of-memory situation!"
[name & body]
(let [esym (gensym "ex")]
`(if (some? *metrics*)
(let [start# (i/nanos)
children-metrics# (transient [])]
(try
(let [result# (binding [*metrics* children-metrics#]
~@body)]
(conj! *metrics* [~name (i/nanos start#) nil
(persistent! children-metrics#)])
result#)
(catch ~(if (:ns &env) `js/Error `Throwable) ~esym
(conj! *metrics* [~name (i/nanos start#) ~(if (:ns &env)
`(if-let [ctor# (.-constructor ~esym)]
(.-name ctor#)
"unknown")
`(.getName ^Class (class ~esym)))
(persistent! children-metrics#)])
(throw ~esym))))
(do
~@body))))
(defn wrap-measure
"Wrap given function such that it measures latency when invoked."
[f measure-name]
(fn espejito-measured [& args]
(measure measure-name
(apply f args))))
(defn print-table
"Print the report in a tabular format. Argument table-printer is an arity-2 fn that accepts header and rows."
([nested-metrics]
(print-table 50 nested-metrics))
([^long name-column-width nested-metrics]
(print-table pp/print-table name-column-width nested-metrics))
([table-printer ^long name-column-width nested-metrics]
(if-let [flat-metrics (seq (i/flatten-children-report nested-metrics))]
(let [total-ns (:cumulative-latency-ns (first flat-metrics))]
(->> flat-metrics
(mapv (fn [{:keys [name level cumulative-latency-ns individual-latency-ns] :as m}]
(assoc m
:name (i/indent-name name-column-width level name)
:cumulative (i/human-readable-latency cumulative-latency-ns)
:cumul-% (#?(:cljs gstring/format :clj format) "%.2f %%" (i/percent cumulative-latency-ns total-ns))
:individual (i/human-readable-latency individual-latency-ns)
:indiv-% (#?(:cljs gstring/format :clj format) "%.2f %%" (i/percent individual-latency-ns total-ns)))))
(table-printer [:name :cumulative :cumul-% :individual :indiv-% :thrown?])))
(println "\nNo data to report!"))))
(defmacro report
"Use this at the outermost periphery of the code."
[f & body]
`(binding [*metrics* (transient [])]
(try
~@body
(finally
(~f (persistent! *metrics*)))))) | null | https://raw.githubusercontent.com/kumarshantanu/espejito/40513bd7cfac8112dfe182ab616e03c93f668f7a/src/espejito/core.cljc | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) . All rights reserved .
(ns espejito.core
#?(:cljs (:require-macros espejito.core))
(:require
#?(:cljs [goog.string :as gstring])
#?(:cljs [goog.string.format])
#?(:cljs [cljs.pprint :include-macros true :as pp]
:clj [clojure.pprint :as pp])
[espejito.internal :as i]))
(def ^:dynamic *metrics* nil)
(defmacro measure
"Use this at layer boundaries in code. Not recommended for tight loops - may cause out-of-memory situation!"
[name & body]
(let [esym (gensym "ex")]
`(if (some? *metrics*)
(let [start# (i/nanos)
children-metrics# (transient [])]
(try
(let [result# (binding [*metrics* children-metrics#]
~@body)]
(conj! *metrics* [~name (i/nanos start#) nil
(persistent! children-metrics#)])
result#)
(catch ~(if (:ns &env) `js/Error `Throwable) ~esym
(conj! *metrics* [~name (i/nanos start#) ~(if (:ns &env)
`(if-let [ctor# (.-constructor ~esym)]
(.-name ctor#)
"unknown")
`(.getName ^Class (class ~esym)))
(persistent! children-metrics#)])
(throw ~esym))))
(do
~@body))))
(defn wrap-measure
"Wrap given function such that it measures latency when invoked."
[f measure-name]
(fn espejito-measured [& args]
(measure measure-name
(apply f args))))
(defn print-table
"Print the report in a tabular format. Argument table-printer is an arity-2 fn that accepts header and rows."
([nested-metrics]
(print-table 50 nested-metrics))
([^long name-column-width nested-metrics]
(print-table pp/print-table name-column-width nested-metrics))
([table-printer ^long name-column-width nested-metrics]
(if-let [flat-metrics (seq (i/flatten-children-report nested-metrics))]
(let [total-ns (:cumulative-latency-ns (first flat-metrics))]
(->> flat-metrics
(mapv (fn [{:keys [name level cumulative-latency-ns individual-latency-ns] :as m}]
(assoc m
:name (i/indent-name name-column-width level name)
:cumulative (i/human-readable-latency cumulative-latency-ns)
:cumul-% (#?(:cljs gstring/format :clj format) "%.2f %%" (i/percent cumulative-latency-ns total-ns))
:individual (i/human-readable-latency individual-latency-ns)
:indiv-% (#?(:cljs gstring/format :clj format) "%.2f %%" (i/percent individual-latency-ns total-ns)))))
(table-printer [:name :cumulative :cumul-% :individual :indiv-% :thrown?])))
(println "\nNo data to report!"))))
(defmacro report
"Use this at the outermost periphery of the code."
[f & body]
`(binding [*metrics* (transient [])]
(try
~@body
(finally
(~f (persistent! *metrics*)))))) |
1287ec7c8e2a1c31049faa7960f46d1c0ede2c931668257fbeebf832e26f6a84 | overtone/overtone | tuning.clj | (ns
^{:doc "Functions that define tuning systems from various musical traditions and theories."
:author "Jeff Rose"}
overtone.music.tuning
(:use [overtone.music pitch]))
;; TODO: Not only should we pre-compute the frequency values for standard tunings,
;; but it would be cool to let people explore different tunings while creating
;; new synth instruments. So, if they have a base frequency chosen we should be
;; able to generate tunings, scales, and arpeggios to let them hear their
instrument in " western mode " , " arabic mode " , " indian mode " , " chinese mode " , etc .
Diatonic Just -- > Indian music
;; Equal Temperament
;;
;; The octave is divided into a fixed number of notes, where the ratio of
one note to the next is constant . Typically the A at 440hz is used as the
;; stationary point around which all other notes can be calculated.
12 - tone equal temperament -- > Western music
ratio = ( Math / pow 2 ( / 1 12 ) ) = > 1.0594630943592953
24 - tone equal temperament -- > Arabic music
ratio = ( Math / pow 2 ( / 1 24 ) ) = > 1.029302236643492
| null | https://raw.githubusercontent.com/overtone/overtone/02f8cdd2817bf810ff390b6f91d3e84d61afcc85/src/overtone/music/tuning.clj | clojure | TODO: Not only should we pre-compute the frequency values for standard tunings,
but it would be cool to let people explore different tunings while creating
new synth instruments. So, if they have a base frequency chosen we should be
able to generate tunings, scales, and arpeggios to let them hear their
Equal Temperament
The octave is divided into a fixed number of notes, where the ratio of
stationary point around which all other notes can be calculated. | (ns
^{:doc "Functions that define tuning systems from various musical traditions and theories."
:author "Jeff Rose"}
overtone.music.tuning
(:use [overtone.music pitch]))
instrument in " western mode " , " arabic mode " , " indian mode " , " chinese mode " , etc .
Diatonic Just -- > Indian music
one note to the next is constant . Typically the A at 440hz is used as the
12 - tone equal temperament -- > Western music
ratio = ( Math / pow 2 ( / 1 12 ) ) = > 1.0594630943592953
24 - tone equal temperament -- > Arabic music
ratio = ( Math / pow 2 ( / 1 24 ) ) = > 1.029302236643492
|
639ab4b44abe833eaf5f7ca6f66ce89ac9ee097ba7410558531ee50446a90db1 | rollacaster/sketches | reverse_roots.cljs | (ns sketches.rac-sketches.reverse-roots
(:require [quil.core :as q :include-macros true]
[quil.middleware :as md]
[sketches.vector :as v]
[sketches.mover :as m]))
(defn create-particle []
{:acceleration [0 0]
:velocity [0 0]
:location [(/ (q/width) 2) (q/height)]
:lifespan 255})
(defn setup []
{:particles ()})
(defn update-particle [particle]
(let [levity [0 -0.01]
wind [(q/random -0.1 0.1) 0]]
(-> particle
(m/update-mover (v/add levity wind))
(update :lifespan dec))))
(defn update-state [{:keys [particles]}]
(if (= (mod (q/frame-count) 500) 0)
{:particles ()}
{:particles
(->> (conj particles (create-particle))
(filter (fn [{:keys [lifespan]}] (>= lifespan 0)))
(map update-particle))}))
(defn draw-particle [{[x y] :location :keys [lifespan]}]
(q/fill 255 lifespan)
(q/ellipse x y
(q/map-range lifespan 0 255 0 32)
(q/map-range lifespan 0 255 0 32)))
(defn draw [{:keys [particles]}]
(when (= (mod (q/frame-count) 500) 0)
(q/clear))
(doall (map draw-particle particles)))
(defn run [host]
(q/defsketch reverse-roots
:host host
:setup setup
:draw draw
:update update-state
:middleware [md/fun-mode]
:size [300 300]))
| null | https://raw.githubusercontent.com/rollacaster/sketches/ba79fccf2a37139de9193ed2ea7a6cc04b63fad0/src/sketches/rac_sketches/reverse_roots.cljs | clojure | (ns sketches.rac-sketches.reverse-roots
(:require [quil.core :as q :include-macros true]
[quil.middleware :as md]
[sketches.vector :as v]
[sketches.mover :as m]))
(defn create-particle []
{:acceleration [0 0]
:velocity [0 0]
:location [(/ (q/width) 2) (q/height)]
:lifespan 255})
(defn setup []
{:particles ()})
(defn update-particle [particle]
(let [levity [0 -0.01]
wind [(q/random -0.1 0.1) 0]]
(-> particle
(m/update-mover (v/add levity wind))
(update :lifespan dec))))
(defn update-state [{:keys [particles]}]
(if (= (mod (q/frame-count) 500) 0)
{:particles ()}
{:particles
(->> (conj particles (create-particle))
(filter (fn [{:keys [lifespan]}] (>= lifespan 0)))
(map update-particle))}))
(defn draw-particle [{[x y] :location :keys [lifespan]}]
(q/fill 255 lifespan)
(q/ellipse x y
(q/map-range lifespan 0 255 0 32)
(q/map-range lifespan 0 255 0 32)))
(defn draw [{:keys [particles]}]
(when (= (mod (q/frame-count) 500) 0)
(q/clear))
(doall (map draw-particle particles)))
(defn run [host]
(q/defsketch reverse-roots
:host host
:setup setup
:draw draw
:update update-state
:middleware [md/fun-mode]
:size [300 300]))
|
|
f37db8eb95a33da2c0450ac088fc7d3da53851326b20ec217653959a13894472 | TrustInSoft/tis-interpreter | binary_cache.mli | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** Very low-level abstract functorial caches. Do not use them unless
you understand what happens in this module, and do not forget that
those caches are not aware of projects. *)
val memory_footprint_var_name: string
val cache_size: int
(** Size of the caches. Controlled by environment variable
[memory_footprint_var_name]. *)
module type Cacheable = sig
type t
val hash : t -> int
val sentinel : t
val equal : t -> t -> bool
end
module type Result = sig
type t
val sentinel : t
end
module Symmetric_Binary(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> H.t -> R.t) -> H.t -> H.t -> R.t
end
module Binary_Predicate(H0 : Cacheable)(H1 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> bool) -> H0.t -> H1.t -> bool
end
module Symmetric_Binary_Predicate(H0 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H0.t -> bool) -> H0.t -> H0.t -> bool
end
module Arity_One(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> R.t) -> H.t -> R.t
end
module Arity_Two(H0 : Cacheable)(H1 : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> R.t) -> H0.t -> H1.t -> R.t
end
module Arity_Three(H0 : Cacheable)(H1 : Cacheable)(H2 : Cacheable)(R : Result):
sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> H2.t -> R.t) -> H0.t -> H1.t -> H2.t -> R.t
end
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/libraries/utils/binary_cache.mli | 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.
************************************************************************
* Very low-level abstract functorial caches. Do not use them unless
you understand what happens in this module, and do not forget that
those caches are not aware of projects.
* Size of the caches. Controlled by environment variable
[memory_footprint_var_name].
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
val memory_footprint_var_name: string
val cache_size: int
module type Cacheable = sig
type t
val hash : t -> int
val sentinel : t
val equal : t -> t -> bool
end
module type Result = sig
type t
val sentinel : t
end
module Symmetric_Binary(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> H.t -> R.t) -> H.t -> H.t -> R.t
end
module Binary_Predicate(H0 : Cacheable)(H1 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> bool) -> H0.t -> H1.t -> bool
end
module Symmetric_Binary_Predicate(H0 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H0.t -> bool) -> H0.t -> H0.t -> bool
end
module Arity_One(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> R.t) -> H.t -> R.t
end
module Arity_Two(H0 : Cacheable)(H1 : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> R.t) -> H0.t -> H1.t -> R.t
end
module Arity_Three(H0 : Cacheable)(H1 : Cacheable)(H2 : Cacheable)(R : Result):
sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> H2.t -> R.t) -> H0.t -> H1.t -> H2.t -> R.t
end
|
1ae19dec2a3205d1a4288227bed89818f4e8d8abfc7aa69a0c6c0e2fec494faa | nvim-treesitter/nvim-treesitter | indents.scm | ; inherits: css
[
(mixin_statement)
(while_statement)
(each_statement)
] @indent
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/ddc0f1b606472b6a1ab85ee9becfd4877507627d/queries/scss/indents.scm | scheme | inherits: css |
[
(mixin_statement)
(while_statement)
(each_statement)
] @indent
|
219d32bb8bbdd47a468f925ed96a91d6be400d8e0d9c9282d4cac9ef31d0d633 | wertercatt/mrifk | Mrifk_grammar.hs |
Mrifk , a decompiler for Glulx story files .
Copyright 2004 .
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You can read the GNU General Public License at this URL :
Mrifk, a decompiler for Glulx story files.
Copyright 2004 Ben Rudiak-Gould.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You can read the GNU General Public License at this URL:
-}
module Mrifk_grammar (
GrammarLine(..), GrammarToken(..),
verbs, actionRoutines,
DictWordTag(..),
dictionary,
dictWordAt, isDictWord
) where
import Mrifk_storyfile
import Mrifk_memmap
import Data.Char (chr)
import Control.Monad
import Data.Array
import Data.Bits
import Data.Maybe (isJust)
import Numeric (showHex)
-- words after verb action reverse
data GrammarLine = GrammarLine [GrammarToken] Int Bool
deriving Show
verbs :: [([String],[GrammarLine])]
verbs = reverse (zip verbWords grammarEntries)
verbWords =
[[x | (x,_,tags) <- elems dictionary, DictVerb n <- tags, n == n']
| n' <- [255,254..1]]
grammarEntries :: [[GrammarLine]]
actionRoutines :: [Int]
dictionary :: Array Int (String,String,[DictWordTag])
numEntries,entryBaseAddr,entryLength :: Int
(grammarEntries, actionRoutines,
(dictionary,numEntries,entryBaseAddr,entryLength)) =
evalFrom informGrammarTable parseGV2
data GrammarToken = ElementaryToken String | Preposition String
| Attribute Int | ParseRoutine String Int
| Alternatives [GrammarToken]
deriving (Show,Eq,Ord)
{-----------}
parseGV2 =
do numVerbs <- getDword
verbGrammars <- replicateM numVerbs getDword
entries <- mapM parseGV2Verb verbGrammars
numActionRoutines <- getDword
actionRoutines <- replicateM numActionRoutines getDword
dictionary <- parseDictionary
return (entries, actionRoutines, dictionary)
parseGV2Verb addr =
do pos <- getPos
if pos == addr then
do numLines <- getUByte
replicateM numLines parseGV2Line
else
error ("Grammar table not contiguous: next pointer is 0x" ++ showHex addr (", but expected 0x" ++ showHex pos ""))
parseGV2Line = do
actionNum <- getUWord
flags <- getUByte
let reverseParams = testBit flags 0
tokens <- parseGV2Tokens
return $ GrammarLine (groupGV2Tokens tokens) actionNum reverseParams
parseGV2Tokens = do
tokenType <- getUByte
if tokenType == 15
then return []
else do
tokenData <- getDword
tokens <- parseGV2Tokens
return ((tokenType .&. 0x30,parseGV2Token (tokenType .&. 15) tokenData) : tokens)
parseGV2Token 1 d = ElementaryToken (elementaryTokenTypes !! d)
parseGV2Token 2 d = Preposition (dictWordAt d)
parseGV2Token 3 d = ParseRoutine "noun=" d
parseGV2Token 4 d = Attribute d
parseGV2Token 5 d = ParseRoutine "scope=" d
parseGV2Token 6 d = ParseRoutine "" d
elementaryTokenTypes =
["noun", "held", "multi", "multiheld", "multiexcept",
"multiinside", "creature", "special", "number", "topic"]
groupGV2Tokens ((0,x):rest) =
x : groupGV2Tokens rest
groupGV2Tokens ((32,x):rest) =
Alternatives (x : map snd xs) : groupGV2Tokens rest'
where (xs,rest') = break (\(n,_) -> not (testBit n 4)) rest
groupGV2Tokens ((n,x):rest) = error (show n)
groupGV2Tokens [] = []
{---------------}
-- Dictionary
data DictWordTag
= DictVerb Int | DictPrep
| DictNoun | DictPlural | DictMeta
| DictMaybeTruncated
deriving (Show,Eq)
parseDictionary = do
numWords <- getDword
pos <- getPos
case filter (possibleDictLength pos numWords) [8..100] of
[] -> error "Unable to determine dictionary word length"
(len:_) ->
do words <- replicateM numWords (getDictWord len)
return (listArray (0,numWords-1) words, numWords, pos, len)
getDictWord len =
do _ <- getUByte -- 0x60, already checked
wordBytes <- replicateM (len-7) getUByte
let word = map chr (takeWhile (/= 0) wordBytes)
truncated = if last wordBytes == 0 then [] else [DictMaybeTruncated]
flags <- getUWord
verbNum <- getUWord
unused <- getUWord
let tags = truncated ++ parseFlags flags verbNum
return (mungeDictWord word tags, word, tags)
parseFlags flags verbNum =
(if testBit flags 0 then [DictVerb verbNum] else [])
++ (if testBit flags 3 then [DictPrep] else [])
++ (if testBit flags 7 then [DictNoun] else [])
++ (if testBit flags 2 then [DictPlural] else [])
++ (if testBit flags 1 then [DictMeta] else [])
mungeDictWord word tags = word' ++ attr
where word' = {-sfFullDictWord-} word
attr | '/' `elem` word' = ""
| DictPlural `elem` tags = "//p"
| length word == 1 = "//"
| otherwise = ""
possibleDictLength pos numWords len =
(pos + numWords * len <= snd wholeFile)
&& all (== 0x60) (map byteAt (take numWords [pos,pos+len..]))
dictWordAt :: Int -> String
dictWordAt addr =
case addrToDictWordIndex addr of
Just n -> case dictionary!n of (word,_,_) -> word
Nothing -> "unknownDictWord" ++ show addr
addrToDictWordIndex addr
| addr < entryBaseAddr = Nothing
| otherwise =
case (addr - entryBaseAddr) `divMod` entryLength of
(d,0) -> if d < numEntries then Just d else Nothing
(_,_) -> Nothing
isDictWord addr = isJust (addrToDictWordIndex addr)
| null | https://raw.githubusercontent.com/wertercatt/mrifk/48687e5b6881cf41d4828cca2ec5dec1c5f4cad3/Mrifk_grammar.hs | haskell | words after verb action reverse
---------
-------------
Dictionary
0x60, already checked
sfFullDictWord |
Mrifk , a decompiler for Glulx story files .
Copyright 2004 .
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You can read the GNU General Public License at this URL :
Mrifk, a decompiler for Glulx story files.
Copyright 2004 Ben Rudiak-Gould.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You can read the GNU General Public License at this URL:
-}
module Mrifk_grammar (
GrammarLine(..), GrammarToken(..),
verbs, actionRoutines,
DictWordTag(..),
dictionary,
dictWordAt, isDictWord
) where
import Mrifk_storyfile
import Mrifk_memmap
import Data.Char (chr)
import Control.Monad
import Data.Array
import Data.Bits
import Data.Maybe (isJust)
import Numeric (showHex)
data GrammarLine = GrammarLine [GrammarToken] Int Bool
deriving Show
verbs :: [([String],[GrammarLine])]
verbs = reverse (zip verbWords grammarEntries)
verbWords =
[[x | (x,_,tags) <- elems dictionary, DictVerb n <- tags, n == n']
| n' <- [255,254..1]]
grammarEntries :: [[GrammarLine]]
actionRoutines :: [Int]
dictionary :: Array Int (String,String,[DictWordTag])
numEntries,entryBaseAddr,entryLength :: Int
(grammarEntries, actionRoutines,
(dictionary,numEntries,entryBaseAddr,entryLength)) =
evalFrom informGrammarTable parseGV2
data GrammarToken = ElementaryToken String | Preposition String
| Attribute Int | ParseRoutine String Int
| Alternatives [GrammarToken]
deriving (Show,Eq,Ord)
parseGV2 =
do numVerbs <- getDword
verbGrammars <- replicateM numVerbs getDword
entries <- mapM parseGV2Verb verbGrammars
numActionRoutines <- getDword
actionRoutines <- replicateM numActionRoutines getDword
dictionary <- parseDictionary
return (entries, actionRoutines, dictionary)
parseGV2Verb addr =
do pos <- getPos
if pos == addr then
do numLines <- getUByte
replicateM numLines parseGV2Line
else
error ("Grammar table not contiguous: next pointer is 0x" ++ showHex addr (", but expected 0x" ++ showHex pos ""))
parseGV2Line = do
actionNum <- getUWord
flags <- getUByte
let reverseParams = testBit flags 0
tokens <- parseGV2Tokens
return $ GrammarLine (groupGV2Tokens tokens) actionNum reverseParams
parseGV2Tokens = do
tokenType <- getUByte
if tokenType == 15
then return []
else do
tokenData <- getDword
tokens <- parseGV2Tokens
return ((tokenType .&. 0x30,parseGV2Token (tokenType .&. 15) tokenData) : tokens)
parseGV2Token 1 d = ElementaryToken (elementaryTokenTypes !! d)
parseGV2Token 2 d = Preposition (dictWordAt d)
parseGV2Token 3 d = ParseRoutine "noun=" d
parseGV2Token 4 d = Attribute d
parseGV2Token 5 d = ParseRoutine "scope=" d
parseGV2Token 6 d = ParseRoutine "" d
elementaryTokenTypes =
["noun", "held", "multi", "multiheld", "multiexcept",
"multiinside", "creature", "special", "number", "topic"]
groupGV2Tokens ((0,x):rest) =
x : groupGV2Tokens rest
groupGV2Tokens ((32,x):rest) =
Alternatives (x : map snd xs) : groupGV2Tokens rest'
where (xs,rest') = break (\(n,_) -> not (testBit n 4)) rest
groupGV2Tokens ((n,x):rest) = error (show n)
groupGV2Tokens [] = []
data DictWordTag
= DictVerb Int | DictPrep
| DictNoun | DictPlural | DictMeta
| DictMaybeTruncated
deriving (Show,Eq)
parseDictionary = do
numWords <- getDword
pos <- getPos
case filter (possibleDictLength pos numWords) [8..100] of
[] -> error "Unable to determine dictionary word length"
(len:_) ->
do words <- replicateM numWords (getDictWord len)
return (listArray (0,numWords-1) words, numWords, pos, len)
getDictWord len =
wordBytes <- replicateM (len-7) getUByte
let word = map chr (takeWhile (/= 0) wordBytes)
truncated = if last wordBytes == 0 then [] else [DictMaybeTruncated]
flags <- getUWord
verbNum <- getUWord
unused <- getUWord
let tags = truncated ++ parseFlags flags verbNum
return (mungeDictWord word tags, word, tags)
parseFlags flags verbNum =
(if testBit flags 0 then [DictVerb verbNum] else [])
++ (if testBit flags 3 then [DictPrep] else [])
++ (if testBit flags 7 then [DictNoun] else [])
++ (if testBit flags 2 then [DictPlural] else [])
++ (if testBit flags 1 then [DictMeta] else [])
mungeDictWord word tags = word' ++ attr
attr | '/' `elem` word' = ""
| DictPlural `elem` tags = "//p"
| length word == 1 = "//"
| otherwise = ""
possibleDictLength pos numWords len =
(pos + numWords * len <= snd wholeFile)
&& all (== 0x60) (map byteAt (take numWords [pos,pos+len..]))
dictWordAt :: Int -> String
dictWordAt addr =
case addrToDictWordIndex addr of
Just n -> case dictionary!n of (word,_,_) -> word
Nothing -> "unknownDictWord" ++ show addr
addrToDictWordIndex addr
| addr < entryBaseAddr = Nothing
| otherwise =
case (addr - entryBaseAddr) `divMod` entryLength of
(d,0) -> if d < numEntries then Just d else Nothing
(_,_) -> Nothing
isDictWord addr = isJust (addrToDictWordIndex addr)
|
46ab7d0dfe2d2f5105d6ae8c85adb5e0040aaa7be3b6bb617ac5db1a562d23d0 | DOBRO/uef-lib | uef_num_tests.erl | Copyright ( c ) 2019 - 2022 , < > . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(uef_num_tests).
-include_lib("eunit/include/eunit.hrl").
%%%------------------------------------------------------------------------------
%%% Tests
%%%------------------------------------------------------------------------------
round_number_test_() ->
[
?_assertEqual(1.0, uef_num:round_price(1)),
?_assertEqual(1.01, uef_num:round_price(1.01)),
?_assertEqual(1.01, uef_num:round_price(1.015)),
?_assertEqual(1.02, uef_num:round_price(1.025)),
?_assertEqual(1.02, uef_num:round_price(1.0155)),
?_assertEqual(1.015, uef_num:round_number(1.015, 3)),
?_assertEqual(2.0, uef_num:round_number(1.9999, 1)),
?_assertEqual(2.0, uef_num:round_number(1.9999, 2)),
?_assertEqual(1.9999, uef_num:round_number(1.9999, 4)),
?_assertEqual(-1.9999, uef_num:round_number(-1.9999, 4)),
?_assertEqual(-2.0, uef_num:round_number(-1.9999, 3)),
?_assertEqual(10000.0, uef_num:round_number(9999.999999, 5))
].
popcount_test_() ->
[
?_assertEqual(0, uef_num:popcount(0)),
?_assertEqual(3, uef_num:popcount(7)),
?_assertEqual(1, uef_num:popcount(8)),
?_assertEqual(1, uef_num:popcount(8)),
?_assertEqual(1, uef_num:popcount(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(1, uef_num:popcount(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(8, uef_num:popcount(2#0000000100000001000000010000000100000001000000010000000100000001)),
?_assertEqual(8, uef_num:popcount(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(16, uef_num:popcount(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(64, uef_num:popcount(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, -1}, uef_num:popcount(-1)),
?_assertError({badarg, 1.0}, uef_num:popcount(1.0)),
?_assertError({badarg, 0.0}, uef_num:popcount(0.0))
].
msb_pos_test_() ->
[
?_assertEqual(1, uef_num:msb_pos(2#1)),
?_assertEqual(1, uef_num:msb_pos(2#01)),
?_assertEqual(2, uef_num:msb_pos(2#10)),
?_assertEqual(3, uef_num:msb_pos(2#100)),
?_assertEqual(3, uef_num:msb_pos(2#0100)),
?_assertEqual(3, uef_num:msb_pos(2#111)),
?_assertEqual(3, uef_num:msb_pos(2#0111)),
?_assertEqual(1, uef_num:msb_pos(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(64, uef_num:msb_pos(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(57, uef_num:msb_pos(2#0000000100000001000000010000000100000001000000010000000100000001)),
?_assertEqual(8, uef_num:msb_pos(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(64, uef_num:msb_pos(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(64, uef_num:msb_pos(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, 0}, uef_num:msb_pos(0)),
?_assertError({badarg, -1}, uef_num:msb_pos(-1)),
?_assertError({badarg, 1.0}, uef_num:msb_pos(1.0)),
?_assertError({badarg, 0.0}, uef_num:msb_pos(0.0))
].
lsb_pos_test_() ->
[
?_assertEqual(1, uef_num:lsb_pos(1)),
?_assertEqual(1, uef_num:lsb_pos(2#01)),
?_assertEqual(2, uef_num:lsb_pos(2#10)),
?_assertEqual(3, uef_num:lsb_pos(2#100)),
?_assertEqual(3, uef_num:lsb_pos(2#0100)),
?_assertEqual(1, uef_num:lsb_pos(2#111)),
?_assertEqual(1, uef_num:lsb_pos(2#0111)),
?_assertEqual(4, uef_num:lsb_pos(2#0101000)),
?_assertEqual(1, uef_num:lsb_pos(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(64, uef_num:lsb_pos(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(9, uef_num:lsb_pos(2#0000000100000001000000010000000100000001000000010000000100000000)),
?_assertEqual(1, uef_num:lsb_pos(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(1, uef_num:lsb_pos(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(1, uef_num:lsb_pos(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, 0}, uef_num:lsb_pos(0)),
?_assertError({badarg, -1}, uef_num:lsb_pos(-1)),
?_assertError({badarg, 1.0}, uef_num:lsb_pos(1.0)),
?_assertError({badarg, 0.0}, uef_num:lsb_pos(0.0))
].
ctz_test_() ->
[
?_assertEqual(0, uef_num:ctz(1)),
?_assertEqual(0, uef_num:ctz(2#01)),
?_assertEqual(1, uef_num:ctz(2#10)),
?_assertEqual(2, uef_num:ctz(2#100)),
?_assertEqual(2, uef_num:ctz(2#0100)),
?_assertEqual(0, uef_num:ctz(2#111)),
?_assertEqual(0, uef_num:ctz(2#0111)),
?_assertEqual(3, uef_num:ctz(2#0101000)),
?_assertEqual(0, uef_num:ctz(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(63, uef_num:ctz(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(8, uef_num:ctz(2#0000000100000001000000010000000100000001000000010000000100000000)),
?_assertEqual(0, uef_num:ctz(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(0, uef_num:ctz(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(0, uef_num:ctz(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, 0}, uef_num:ctz(0)),
?_assertError({badarg, -1}, uef_num:ctz(-1)),
?_assertError({badarg, 1.0}, uef_num:ctz(1.0)),
?_assertError({badarg, 0.0}, uef_num:ctz(0.0))
].
| null | https://raw.githubusercontent.com/DOBRO/uef-lib/765d28837584bcfced1aae5d5f831972ec0254bb/test/uef_num_tests.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------
Tests
------------------------------------------------------------------------------ | Copyright ( c ) 2019 - 2022 , < > . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(uef_num_tests).
-include_lib("eunit/include/eunit.hrl").
round_number_test_() ->
[
?_assertEqual(1.0, uef_num:round_price(1)),
?_assertEqual(1.01, uef_num:round_price(1.01)),
?_assertEqual(1.01, uef_num:round_price(1.015)),
?_assertEqual(1.02, uef_num:round_price(1.025)),
?_assertEqual(1.02, uef_num:round_price(1.0155)),
?_assertEqual(1.015, uef_num:round_number(1.015, 3)),
?_assertEqual(2.0, uef_num:round_number(1.9999, 1)),
?_assertEqual(2.0, uef_num:round_number(1.9999, 2)),
?_assertEqual(1.9999, uef_num:round_number(1.9999, 4)),
?_assertEqual(-1.9999, uef_num:round_number(-1.9999, 4)),
?_assertEqual(-2.0, uef_num:round_number(-1.9999, 3)),
?_assertEqual(10000.0, uef_num:round_number(9999.999999, 5))
].
popcount_test_() ->
[
?_assertEqual(0, uef_num:popcount(0)),
?_assertEqual(3, uef_num:popcount(7)),
?_assertEqual(1, uef_num:popcount(8)),
?_assertEqual(1, uef_num:popcount(8)),
?_assertEqual(1, uef_num:popcount(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(1, uef_num:popcount(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(8, uef_num:popcount(2#0000000100000001000000010000000100000001000000010000000100000001)),
?_assertEqual(8, uef_num:popcount(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(16, uef_num:popcount(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(64, uef_num:popcount(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, -1}, uef_num:popcount(-1)),
?_assertError({badarg, 1.0}, uef_num:popcount(1.0)),
?_assertError({badarg, 0.0}, uef_num:popcount(0.0))
].
msb_pos_test_() ->
[
?_assertEqual(1, uef_num:msb_pos(2#1)),
?_assertEqual(1, uef_num:msb_pos(2#01)),
?_assertEqual(2, uef_num:msb_pos(2#10)),
?_assertEqual(3, uef_num:msb_pos(2#100)),
?_assertEqual(3, uef_num:msb_pos(2#0100)),
?_assertEqual(3, uef_num:msb_pos(2#111)),
?_assertEqual(3, uef_num:msb_pos(2#0111)),
?_assertEqual(1, uef_num:msb_pos(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(64, uef_num:msb_pos(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(57, uef_num:msb_pos(2#0000000100000001000000010000000100000001000000010000000100000001)),
?_assertEqual(8, uef_num:msb_pos(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(64, uef_num:msb_pos(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(64, uef_num:msb_pos(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, 0}, uef_num:msb_pos(0)),
?_assertError({badarg, -1}, uef_num:msb_pos(-1)),
?_assertError({badarg, 1.0}, uef_num:msb_pos(1.0)),
?_assertError({badarg, 0.0}, uef_num:msb_pos(0.0))
].
lsb_pos_test_() ->
[
?_assertEqual(1, uef_num:lsb_pos(1)),
?_assertEqual(1, uef_num:lsb_pos(2#01)),
?_assertEqual(2, uef_num:lsb_pos(2#10)),
?_assertEqual(3, uef_num:lsb_pos(2#100)),
?_assertEqual(3, uef_num:lsb_pos(2#0100)),
?_assertEqual(1, uef_num:lsb_pos(2#111)),
?_assertEqual(1, uef_num:lsb_pos(2#0111)),
?_assertEqual(4, uef_num:lsb_pos(2#0101000)),
?_assertEqual(1, uef_num:lsb_pos(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(64, uef_num:lsb_pos(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(9, uef_num:lsb_pos(2#0000000100000001000000010000000100000001000000010000000100000000)),
?_assertEqual(1, uef_num:lsb_pos(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(1, uef_num:lsb_pos(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(1, uef_num:lsb_pos(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, 0}, uef_num:lsb_pos(0)),
?_assertError({badarg, -1}, uef_num:lsb_pos(-1)),
?_assertError({badarg, 1.0}, uef_num:lsb_pos(1.0)),
?_assertError({badarg, 0.0}, uef_num:lsb_pos(0.0))
].
ctz_test_() ->
[
?_assertEqual(0, uef_num:ctz(1)),
?_assertEqual(0, uef_num:ctz(2#01)),
?_assertEqual(1, uef_num:ctz(2#10)),
?_assertEqual(2, uef_num:ctz(2#100)),
?_assertEqual(2, uef_num:ctz(2#0100)),
?_assertEqual(0, uef_num:ctz(2#111)),
?_assertEqual(0, uef_num:ctz(2#0111)),
?_assertEqual(3, uef_num:ctz(2#0101000)),
?_assertEqual(0, uef_num:ctz(2#0000000000000000000000000000000000000000000000000000000000000001)),
?_assertEqual(63, uef_num:ctz(2#1000000000000000000000000000000000000000000000000000000000000000)),
?_assertEqual(8, uef_num:ctz(2#0000000100000001000000010000000100000001000000010000000100000000)),
?_assertEqual(0, uef_num:ctz(2#0000000000000000000000000000000000000000000000000000000011111111)),
?_assertEqual(0, uef_num:ctz(2#1111111100000000000000000000000000000000000000000000000011111111)),
?_assertEqual(0, uef_num:ctz(2#1111111111111111111111111111111111111111111111111111111111111111)),
?_assertError({badarg, 0}, uef_num:ctz(0)),
?_assertError({badarg, -1}, uef_num:ctz(-1)),
?_assertError({badarg, 1.0}, uef_num:ctz(1.0)),
?_assertError({badarg, 0.0}, uef_num:ctz(0.0))
].
|
6d0848725bc8d1ca3b0ffaa570fb5fef9e074eb89b66e37428ac8e3250e3b408 | shirok/Gauche | 219.scm | ;;
;; SRFI-219 - Define higher-order lambda
;;
The feature is natively supported in Gauche . This is for the portable code .
NB : SRFI-219 exports null#define , for the portable code using SRFI-219
;; most likely expects it.
(define-module srfi.219
(define-syntax vanilla-define (with-module null define))
(export (rename vanilla-define define)))
| null | https://raw.githubusercontent.com/shirok/Gauche/e606bfe5a94b100d5807bca9c2bb95df94f60aa6/lib/srfi/219.scm | scheme |
SRFI-219 - Define higher-order lambda
most likely expects it. |
The feature is natively supported in Gauche . This is for the portable code .
NB : SRFI-219 exports null#define , for the portable code using SRFI-219
(define-module srfi.219
(define-syntax vanilla-define (with-module null define))
(export (rename vanilla-define define)))
|
c252b88e6581b08436f9127043901aadfecf903f6b8e40443b149c34fb0f25f5 | dsheets/gloc | glol_js.ml | open Js
open Json
open Dom_html
open Glo_lib
external reg : string -> ('a -> 'b) -> unit = "register_ocaml_fn"
let addr_of_js j = match (Optdef.to_option (array_get j 0),
Optdef.to_option (array_get j 1)) with
| (Some s, Some i) -> (to_string s,
int_of_float (float_of_number (Unsafe.coerce i)))
| _ -> raise (Failure "not enough fields in addr")
in
let string_of_js_exc e = string (Glol.string_of_error begin
match to_string (e##name) with
| "MissingMacro" ->
Glol.MissingMacro (addr_of_js e##addr, to_string e##macro)
| "MissingSymbol" ->
Glol.MissingSymbol (addr_of_js e##addr, to_string e##symbol)
| "NotFound" ->
Failure ("NotFound: "^(to_string e##key))
| "CircularDependency" ->
let addrs = Array.to_list (to_array e##addrs) in
Glol.CircularDependency (List.map addr_of_js addrs)
| "SymbolConflict" ->
Glol.SymbolConflict (to_string (e##sym_a_),
to_string (e##sym_b_),
addr_of_js (e##addr_a_),
addr_of_js (e##addr_b_))
| "UnknownBehavior" ->
Glol.UnknownBehavior (addr_of_js e##addr, to_string e##behavior)
| "UnknownGloVersion" ->
let v = to_array e##version in
Glol.UnknownGloVersion (to_string e##path, (v.(0),v.(1),v.(2)))
| n -> Failure ("unknown error "^n)
end)
in
let link prologue syms glom_s =
let gloms = to_string glom_s in
let glom = glom_of_string gloms in
string (Glol.link (to_string prologue)
(List.map to_string (Array.to_list (to_array syms)))
(Glol.flatten "" glom))
in
reg "link" link;
reg "string_of_error" (fun e -> string (Glol.string_of_error e));
reg "string_of_js_exc" string_of_js_exc
| null | https://raw.githubusercontent.com/dsheets/gloc/d5917c072ec314ae93a61344da2407f520fac1b5/src/glol_js.ml | ocaml | open Js
open Json
open Dom_html
open Glo_lib
external reg : string -> ('a -> 'b) -> unit = "register_ocaml_fn"
let addr_of_js j = match (Optdef.to_option (array_get j 0),
Optdef.to_option (array_get j 1)) with
| (Some s, Some i) -> (to_string s,
int_of_float (float_of_number (Unsafe.coerce i)))
| _ -> raise (Failure "not enough fields in addr")
in
let string_of_js_exc e = string (Glol.string_of_error begin
match to_string (e##name) with
| "MissingMacro" ->
Glol.MissingMacro (addr_of_js e##addr, to_string e##macro)
| "MissingSymbol" ->
Glol.MissingSymbol (addr_of_js e##addr, to_string e##symbol)
| "NotFound" ->
Failure ("NotFound: "^(to_string e##key))
| "CircularDependency" ->
let addrs = Array.to_list (to_array e##addrs) in
Glol.CircularDependency (List.map addr_of_js addrs)
| "SymbolConflict" ->
Glol.SymbolConflict (to_string (e##sym_a_),
to_string (e##sym_b_),
addr_of_js (e##addr_a_),
addr_of_js (e##addr_b_))
| "UnknownBehavior" ->
Glol.UnknownBehavior (addr_of_js e##addr, to_string e##behavior)
| "UnknownGloVersion" ->
let v = to_array e##version in
Glol.UnknownGloVersion (to_string e##path, (v.(0),v.(1),v.(2)))
| n -> Failure ("unknown error "^n)
end)
in
let link prologue syms glom_s =
let gloms = to_string glom_s in
let glom = glom_of_string gloms in
string (Glol.link (to_string prologue)
(List.map to_string (Array.to_list (to_array syms)))
(Glol.flatten "" glom))
in
reg "link" link;
reg "string_of_error" (fun e -> string (Glol.string_of_error e));
reg "string_of_js_exc" string_of_js_exc
|
|
6acc6363f4f6bb47c7b4f5808dee4719ed54fff708785e21ace13d0937ebabf0 | funcool/suricatta | dsl_test.clj | (ns suricatta.dsl-test
(:require [clojure.test :refer :all]
[suricatta.core :as sc]
[suricatta.dsl.alpha :as dsl]))
(deftest select-statement-1
(let [qq (-> (dsl/select)
(dsl/from "posts" "p")
(dsl/join "authors" "a" "p.author_id = a.id")
(dsl/field "p.*")
(dsl/field "a.slug" "author_slug")
(dsl/limit 10))]
(is (= (dsl/fmt qq)
["SELECT p.*, a.slug author_slug FROM posts p INNER JOIN authors a ON (p.author_id = a.id) "]))))
(deftest select-statement-2
(let [qq (-> (dsl/select)
(dsl/from "posts" "p")
(dsl/field "p.id" "post_id")
(dsl/where "p.category = ?" "offtopic"))]
(is (= (dsl/fmt qq)
["SELECT p.id post_id FROM posts p WHERE (p.category = ?)" "offtopic"]))))
(deftest update-statement-1
(let [qq (-> (dsl/update "users" "u")
(dsl/set "u.username" "foobar")
(dsl/set "u.email" "")
(dsl/where "u.id = ? AND u.deleted_at IS null" 555))]
(is (= (dsl/fmt qq)
["UPDATE users u SET u.username = ?, u.email = ? WHERE (u.id = ? AND u.deleted_at IS null)" "foobar" "" 555]))))
| null | https://raw.githubusercontent.com/funcool/suricatta/58e5d2080815aee19ee0893f8ed1b04043525c81/test/suricatta/dsl_test.clj | clojure | (ns suricatta.dsl-test
(:require [clojure.test :refer :all]
[suricatta.core :as sc]
[suricatta.dsl.alpha :as dsl]))
(deftest select-statement-1
(let [qq (-> (dsl/select)
(dsl/from "posts" "p")
(dsl/join "authors" "a" "p.author_id = a.id")
(dsl/field "p.*")
(dsl/field "a.slug" "author_slug")
(dsl/limit 10))]
(is (= (dsl/fmt qq)
["SELECT p.*, a.slug author_slug FROM posts p INNER JOIN authors a ON (p.author_id = a.id) "]))))
(deftest select-statement-2
(let [qq (-> (dsl/select)
(dsl/from "posts" "p")
(dsl/field "p.id" "post_id")
(dsl/where "p.category = ?" "offtopic"))]
(is (= (dsl/fmt qq)
["SELECT p.id post_id FROM posts p WHERE (p.category = ?)" "offtopic"]))))
(deftest update-statement-1
(let [qq (-> (dsl/update "users" "u")
(dsl/set "u.username" "foobar")
(dsl/set "u.email" "")
(dsl/where "u.id = ? AND u.deleted_at IS null" 555))]
(is (= (dsl/fmt qq)
["UPDATE users u SET u.username = ?, u.email = ? WHERE (u.id = ? AND u.deleted_at IS null)" "foobar" "" 555]))))
|
|
d09ad4dfafea6f194c97e82d21198fa745c88635df55d41198995153dfaabade | scrive/consumers | Utils.hs | module Database.PostgreSQL.Consumers.Utils (
finalize
, ThrownFrom(..)
, stopExecution
, forkP
, gforkP
) where
import Control.Concurrent.Lifted
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.Trans.Control
import Data.Typeable
import Prelude
import qualified Control.Concurrent.Thread.Group.Lifted as TG
import qualified Control.Concurrent.Thread.Lifted as T
import qualified Control.Exception.Lifted as E
-- | Run an action 'm' that returns a finalizer and perform the
-- returned finalizer after the action 'action' completes.
finalize :: (MonadMask m, MonadBase IO m) => m (m ()) -> m a -> m a
finalize m action = do
finalizer <- newEmptyMVar
flip finally (tryTakeMVar finalizer >>= maybe (return ()) id) $ do
putMVar finalizer =<< m
action
----------------------------------------
-- | Exception thrown to a thread to stop its execution.
All exceptions other than ' StopExecution ' thrown to
-- threads spawned by 'forkP' and 'gforkP' are propagated
-- back to the parent thread.
data StopExecution = StopExecution
deriving (Show, Typeable)
instance Exception StopExecution
-- | Exception thrown from a child thread.
data ThrownFrom = ThrownFrom String SomeException
deriving (Show, Typeable)
instance Exception ThrownFrom
-- | Stop execution of a thread.
stopExecution :: MonadBase IO m => ThreadId -> m ()
stopExecution = flip throwTo StopExecution
----------------------------------------
-- | Modified version of 'fork' that propagates
-- thrown exceptions to the parent thread.
forkP :: MonadBaseControl IO m => String -> m () -> m ThreadId
forkP = forkImpl fork
-- | Modified version of 'TG.fork' that propagates
-- thrown exceptions to the parent thread.
gforkP :: MonadBaseControl IO m
=> TG.ThreadGroup
-> String
-> m ()
-> m (ThreadId, m (T.Result ()))
gforkP = forkImpl . TG.fork
----------------------------------------
forkImpl :: MonadBaseControl IO m
=> (m () -> m a)
-> String
-> m ()
-> m a
forkImpl ffork tname m = E.mask $ \release -> do
parent <- myThreadId
ffork $ release m `E.catches` [
E.Handler $ \StopExecution -> return ()
, E.Handler $ (throwTo parent . ThrownFrom tname)
]
| null | https://raw.githubusercontent.com/scrive/consumers/77d4ec2ad45eb8a46a8399b8630597fb4b03db97/src/Database/PostgreSQL/Consumers/Utils.hs | haskell | | Run an action 'm' that returns a finalizer and perform the
returned finalizer after the action 'action' completes.
--------------------------------------
| Exception thrown to a thread to stop its execution.
threads spawned by 'forkP' and 'gforkP' are propagated
back to the parent thread.
| Exception thrown from a child thread.
| Stop execution of a thread.
--------------------------------------
| Modified version of 'fork' that propagates
thrown exceptions to the parent thread.
| Modified version of 'TG.fork' that propagates
thrown exceptions to the parent thread.
-------------------------------------- | module Database.PostgreSQL.Consumers.Utils (
finalize
, ThrownFrom(..)
, stopExecution
, forkP
, gforkP
) where
import Control.Concurrent.Lifted
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.Trans.Control
import Data.Typeable
import Prelude
import qualified Control.Concurrent.Thread.Group.Lifted as TG
import qualified Control.Concurrent.Thread.Lifted as T
import qualified Control.Exception.Lifted as E
finalize :: (MonadMask m, MonadBase IO m) => m (m ()) -> m a -> m a
finalize m action = do
finalizer <- newEmptyMVar
flip finally (tryTakeMVar finalizer >>= maybe (return ()) id) $ do
putMVar finalizer =<< m
action
All exceptions other than ' StopExecution ' thrown to
data StopExecution = StopExecution
deriving (Show, Typeable)
instance Exception StopExecution
data ThrownFrom = ThrownFrom String SomeException
deriving (Show, Typeable)
instance Exception ThrownFrom
stopExecution :: MonadBase IO m => ThreadId -> m ()
stopExecution = flip throwTo StopExecution
forkP :: MonadBaseControl IO m => String -> m () -> m ThreadId
forkP = forkImpl fork
gforkP :: MonadBaseControl IO m
=> TG.ThreadGroup
-> String
-> m ()
-> m (ThreadId, m (T.Result ()))
gforkP = forkImpl . TG.fork
forkImpl :: MonadBaseControl IO m
=> (m () -> m a)
-> String
-> m ()
-> m a
forkImpl ffork tname m = E.mask $ \release -> do
parent <- myThreadId
ffork $ release m `E.catches` [
E.Handler $ \StopExecution -> return ()
, E.Handler $ (throwTo parent . ThrownFrom tname)
]
|
70f61dd60acd6a3e81aa30eec80bf4e8eddd9d89423e50e90f9014b2ff850e52 | TrustInSoft/tis-interpreter | mergecil.mli | Modified by TrustInSoft
(****************************************************************************)
(* *)
Copyright ( C ) 2001 - 2003
< >
(* Scott McPeak <> *)
< >
< >
(* All rights reserved. *)
(* *)
(* Redistribution and use in source and binary forms, with or without *)
(* modification, are permitted provided that the following conditions *)
(* are met: *)
(* *)
1 . Redistributions of source code must retain the above copyright
(* notice, this list of conditions and the following disclaimer. *)
(* *)
2 . 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. *)
(* *)
3 . The names of the contributors may not be used to endorse or
(* promote products derived from this software without specific prior *)
(* written permission. *)
(* *)
(* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *)
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
(* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *)
(* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *)
COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
(* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *)
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN *)
(* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *)
(* POSSIBILITY OF SUCH DAMAGE. *)
(* *)
File modified by CEA ( Commissariat à l'énergie atomique et aux
(* énergies alternatives) *)
and INRIA ( Institut National de Recherche en Informatique
(* et Automatique). *)
(****************************************************************************)
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . 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 .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
(** Merge a number of CIL files *)
val merge: Cil_types.file list -> string -> Cil_types.file
(*
val translate_vinfo : Cil_types.varinfo -> Cil_types.varinfo
val translate_typinfo :Cil_types.typeinfo -> Cil_types.typeinfo
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/kernel_internals/typing/mergecil.mli | ocaml | **************************************************************************
Scott McPeak <>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
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.
énergies alternatives)
et Automatique).
**************************************************************************
* Merge a number of CIL files
val translate_vinfo : Cil_types.varinfo -> Cil_types.varinfo
val translate_typinfo :Cil_types.typeinfo -> Cil_types.typeinfo
| Modified by TrustInSoft
Copyright ( C ) 2001 - 2003
< >
< >
< >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . The names of the contributors may not be used to endorse or
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
File modified by CEA ( Commissariat à l'énergie atomique et aux
and INRIA ( Institut National de Recherche en Informatique
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . 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 .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
val merge: Cil_types.file list -> string -> Cil_types.file
|
181aac4edaa748a427f7e19202ef03c34ebe9f2faf82fa56e94dd576db6a4f00 | AshleyYakeley/Truth | Unifier.hs | module Test.Unifier
( testUnifier
) where
import Data.Shim
import Debug.Trace.Null
import Language.Expression.Common
import Language.Expression.Dolan.Test
import Pinafore
import Pinafore.Language.API
import Pinafore.Test
import Shapes
import Test.RunScript
type PinaforeBisubstitution = Bisubstitution QGroundType (QPolyShim Type) (UnifierM QGroundType)
pinaforeBisubstitutes :: [PinaforeBisubstitution] -> QValue -> QInterpreter QValue
pinaforeBisubstitutes bisubs val = do
liftIO $ traceIO $ "bisubstitute: before: " <> showValType val
val' <- runUnifierM @QGroundType $ unEndoM (bisubstitutes @QGroundType bisubs) val
liftIO $ traceIO $ "bisubstitute: after: " <> showValType val'
return val'
testSourceScoped :: Text -> QInterpreter () -> TestTree
testSourceScoped name action = testTree (unpack name) $ runTester defaultTester $ testerLiftInterpreter action
showValType :: QValue -> String
showValType (MkSomeOf (MkShimWit t _) _) = show t
testUnifyToType ::
forall t. HasQType 'Negative t
=> QInterpreter QValue
-> [PinaforeBisubstitution]
-> (t -> IO ())
-> TestTree
testUnifyToType mval bisubs checkVal =
testSourceScoped (toText $ "unify to " <> qNegativeTypeDescription @t) $ do
val <- mval
liftIO $ traceIO $ "original type: " <> showValType val
val' <- pinaforeBisubstitutes bisubs val
liftIO $ traceIO $ "bisub type: " <> showValType val'
found <- qUnifyValue @t val'
liftIO $ checkVal found
testInterpret ::
forall t. HasQType 'Negative t
=> Text
-> (t -> Tester ())
-> ScriptTestTree
testInterpret expr checkVal =
testExpression @t expr expr $ \interpret -> do
found <- interpret
checkVal found
op1 :: X -> (X -> X) -> X
op1 v r = r $ r v
op2 :: X -> (X -> Text) -> (X -> X) -> Text
op2 v withVal r = withVal $ r $ r v
op2Text :: Text -> (Text -> Text) -> (Text -> Text) -> Text
op2Text v withVal r = withVal $ r $ r v
op3 :: X -> (X -> Action ()) -> (X -> X) -> Action ()
op3 v withVal r = withVal $ r $ r v
op4 :: (X -> Text) -> (X -> X) -> X -> Text
op4 withVal r v = withVal $ r $ r v
idText :: Text -> Text
idText = id
testLib :: LibraryModule context
testLib = let
testSameT :: Text -> Text -> Action ()
testSameT expected found =
if expected == found
then return ()
else fail "different"
testSameI :: Integer -> Integer -> Action ()
testSameI expected found =
if expected == found
then return ()
else fail "different"
in MkLibraryModule "TEST" $
headingBDT "TEST" "" $
[ valBDT "idText" "TEST" idText
, valBDT "testSameT" "TEST" testSameT
, valBDT "testSameI" "TEST" testSameI
, valBDT "op1" "TEST" op1
, valBDT "op2" "TEST" op2
, valBDT "op3" "TEST" op3
, valBDT "op4" "TEST" op4
]
testUnifier :: TestTree
testUnifier =
testTree
"unifier"
[ testTree
"unifier"
[ testTree
"op1"
[ testTree
"unify"
[ testUnifyToType @(Text -> (Text -> Text) -> Text) (return $ jmToValue op1) [] $ \found ->
assertEqual "" "PQPQPQ" $ found "PQPQPQ" id
, testUnifyToType @(X -> (X -> X) -> X) (return $ jmToValue op1) [] $ \found ->
assignUVarT @Text (MkSymbolType @"x") $
assertEqual "" "PQPQPQ" $ unVar $ found (MkVar "PQPQPQ") id
, testUnifyToType @(A -> (A -> A) -> A) (return $ jmToValue op1) [] $ \found ->
assignUVarT @Text (MkSymbolType @"a") $
assertEqual "" "PQPQPQ" $ unVar $ found (MkVar "PQPQPQ") id
]
, runScriptTestTree $
tLibrary testLib $
tDecls ["import \"TEST\""] $
tGroup
"interpret"
[ testInterpret @(A -> (A -> A) -> A) "op1" $ \found ->
assignUVarT @Text (MkSymbolType @"a") $
liftIO $ assertEqual "" "PQPQPQ" $ unVar $ found (MkVar "PQPQPQ") id
, testInterpret @(Text -> (Text -> Text) -> Text) "op1" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found "PQPQPQ" id
, testInterpret @((Text -> Text) -> Text) "op1 \"PQPQPQ\"" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id
, testInterpret @Text "op1 \"PQPQPQ\" id.Function" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" found
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op1 \"PQPQPQ\" idText"
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op1 \"PQPQPQ\" id.Function"
]
]
, testTree
"op2"
[ testTree
"unify"
[ testUnifyToType
@(Text -> (Text -> Text) -> (Text -> Text) -> Text)
(return $ jmToValue op2)
[] $ \found -> assertEqual "" "PQPQPQ" $ found "PQPQPQ" id id
, testUnifyToType @(A -> (A -> Text) -> (A -> A) -> Text) (return $ jmToValue op2) [] $ \found ->
assignUVarT @Text (MkSymbolType @"a") $
assertEqual "" "PQPQPQ" $ found (MkVar "PQPQPQ") unVar id
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
qEvalExpr expr1
checkVal found = assertEqual "" "PQPQPQ" $ found idText id
in testUnifyToType @((Text -> Text) -> (Text -> Text) -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2Text) (qConstExpr @Text "PQPQPQ")
expr2 <- qApplyExpr expr1 (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found id
in testUnifyToType @((Text -> Text) -> Text) makeVal [] checkVal
, testSourceScoped "value1" $ do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
val1 <- qEvalExpr expr1
found1 <- qUnifyValue @((Text -> Text) -> (Text -> Text) -> Text) val1
liftIO $ assertEqual "found1" "PQPQPQ" $ found1 idText id
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
val1 <- qEvalExpr expr1
expr2 <- qApplyExpr (qConstExprAny val1) (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found id
in testUnifyToType @((Text -> Text) -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
expr2 <- qApplyExpr expr1 (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found id
in testUnifyToType @((Text -> Text) -> Text) makeVal [] checkVal
]
, runScriptTestTree $
tLibrary testLib $
tDecls ["import \"TEST\""] $
tGroup
"interpret"
[ testInterpret @(Text -> (Text -> Text) -> (Text -> Text) -> Text) "op2" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found "PQPQPQ" id id
, testInterpret @((Text -> Text) -> (Text -> Text) -> Text) "op2 \"PQPQPQ\"" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id id
, testInterpret @((Text -> Text) -> Text) "op2 \"PQPQPQ\" id.Function" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id
, testInterpret @((Text -> Text) -> Text) "op2 \"PQPQPQ\" idText" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id
, testInterpret @Text "op2 \"PQPQPQ\" id.Function idText" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" found
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op2 \"PQPQPQ\" id.Function idText"
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op2 \"PQPQPQ\" id.Function id.Function"
]
]
, testTree
"op3"
[ testTree @[TestTree] "unify" []
, runScriptTestTree $
tLibrary testLib $
tDecls ["import \"TEST\""] $
tGroup
"interpret"
[ testExpectSuccess "testSameT \"PQPQPQ\" \"PQPQPQ\""
, testExpectSuccess "op3 \"PQPQPQ\" (testSameT \"PQPQPQ\") idText"
, testExpectSuccess "op3 \"PQPQPQ\" (testSameT \"PQPQPQ\") id.Function"
, testExpectSuccess "op3 10 (testSameI 10) id.Function"
]
]
, testTree
"op4"
[ testTree
"unify"
[ let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op4) (qConstExpr idText)
qEvalExpr expr1
checkVal found = assertEqual "" "PQPQPQ" $ found idText "PQPQPQ"
in testUnifyToType @((Text -> Text) -> Text -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op4) (qConstExpr idText)
expr2 <- qApplyExpr expr1 (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found "PQPQPQ"
in testUnifyToType @(Text -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op4) (qConstExpr idText)
expr2 <- qApplyExpr expr1 (qConstExpr idText)
expr3 <- qApplyExpr expr2 (qConstExpr @Text "PQPQPQ")
qEvalExpr expr3
checkVal found = assertEqual "" "PQPQPQ" found
in testUnifyToType @Text makeVal [] checkVal
]
]
]
, testTree
"subtype"
[ testTree "t8" $
runTester defaultTester $ do
action <-
testerLiftInterpreter $ do
a1Expr <-
return $
qConstExpr ((>>=) newMemListModel :: (LangListModel '( A, A) -> Action B) -> Action B)
a2Expr <-
return $
qConstExpr (return :: LangListModel '( A, A) -> Action (LangListModel '( A, A)))
actionExpr <- qApplyExpr a1Expr a2Expr
actionVal <- qEvalExpr actionExpr
qUnifyValue @(Action (LangWholeModel '( [Integer], [Integer]))) actionVal
testerLiftAction $ do
wr <- action
langWholeModelSet wr $ Known [10, 20]
l <- langWholeModelGet wr
if l == [10, 20]
then return ()
else fail $ "different: " <> show l
, testTree "t5" $
runTester defaultTester $ do
r <- testerLiftAction $ newMemListModel @A
(_r' :: LangListModel '( Integer, Integer), wr' :: LangWholeModel '( [Integer], [Integer])) <-
testerLiftInterpreter $ do
convertExpr <- parseTopExpression "fn r => (r,r)"
convertVal <- qEvalExpr convertExpr
convert <- qUnifyValueToFree convertVal
return $ convert r
testerLiftAction $ langWholeModelSet wr' $ Known [10, 20]
l <- testerLiftAction $ langWholeModelGet wr'
if l == [10, 20]
then return ()
else fail "different"
, testTree "t4" $
runTester defaultTester $ do
r <- testerLiftAction $ newMemListModel @A
action <-
testerLiftInterpreter $ do
bodyExpr <-
parseTopExpression
"fn r => do r :=.WholeModel [10,20]; set.ListModel 0 25 r; get.WholeModel r end"
bodyVal <- qEvalExpr bodyExpr
body <- qUnifyValueToFree bodyVal
return $ body r
l :: [Integer] <- testerLiftAction action
if l == [25, 20]
then return ()
else fail "different"
, testTree "t3" $
runTester defaultTester $ do
r <- testerLiftAction $ newMemListModel @A
action <-
testerLiftInterpreter $ do
bodyExpr <-
parseTopExpression
"fn r => do r :=.WholeModel [10,20]; set.ListModel 0 25 r; get.WholeModel r end"
actionExpr <- qApplyExpr bodyExpr (qConstExpr r)
actionVal <- qEvalExpr actionExpr
qUnifyValue actionVal
l :: [Integer] <- testerLiftAction action
if l == [25, 20]
then return ()
else fail "different"
, testTree "t2" $
runTester defaultTester $ do
action <-
testerLiftInterpreter $ do
expr <-
parseTopExpression
"do r <- newMem.ListModel: Action (ListModel a); r :=.WholeModel [10,20]; ir <- item.ListModel True 0 r; ir :=.WholeModel 25; get.WholeModel r end"
val <- qEvalExpr expr
qUnifyValue val
l :: [Integer] <- testerLiftAction action
if l == [25, 20]
then return ()
else fail "different"
, testTree "t1" $
runTester defaultTester $ do
action <-
testerLiftInterpreter $ do
expr <-
parseTopExpression
"do r <- newMem.ListModel: Action (ListModel a); r :=.WholeModel [10,20]; ir <- item.ListModel True 0 r; ir :=.WholeModel 25; l <- get.WholeModel r; if l ==.Entity [25,20] then return.Action () else fail.Action \"different\"; end"
val <- qEvalExpr expr
qUnifyValue val
testerLiftAction action
, runScriptTestTree $
testExpectSuccess
"do r <- newMem.ListModel; r :=.WholeModel [10,20]; ir <- item.ListModel True 0 r; ir :=.WholeModel 25; l <- get.WholeModel r; if l ==.Entity [25,20] then return.Action () else fail.Action \"different\"; end"
]
]
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/4440fb14943e8a6ff02e760261918b1c9c535e3f/Pinafore/pinafore-language/test/Test/Unifier.hs | haskell | module Test.Unifier
( testUnifier
) where
import Data.Shim
import Debug.Trace.Null
import Language.Expression.Common
import Language.Expression.Dolan.Test
import Pinafore
import Pinafore.Language.API
import Pinafore.Test
import Shapes
import Test.RunScript
type PinaforeBisubstitution = Bisubstitution QGroundType (QPolyShim Type) (UnifierM QGroundType)
pinaforeBisubstitutes :: [PinaforeBisubstitution] -> QValue -> QInterpreter QValue
pinaforeBisubstitutes bisubs val = do
liftIO $ traceIO $ "bisubstitute: before: " <> showValType val
val' <- runUnifierM @QGroundType $ unEndoM (bisubstitutes @QGroundType bisubs) val
liftIO $ traceIO $ "bisubstitute: after: " <> showValType val'
return val'
testSourceScoped :: Text -> QInterpreter () -> TestTree
testSourceScoped name action = testTree (unpack name) $ runTester defaultTester $ testerLiftInterpreter action
showValType :: QValue -> String
showValType (MkSomeOf (MkShimWit t _) _) = show t
testUnifyToType ::
forall t. HasQType 'Negative t
=> QInterpreter QValue
-> [PinaforeBisubstitution]
-> (t -> IO ())
-> TestTree
testUnifyToType mval bisubs checkVal =
testSourceScoped (toText $ "unify to " <> qNegativeTypeDescription @t) $ do
val <- mval
liftIO $ traceIO $ "original type: " <> showValType val
val' <- pinaforeBisubstitutes bisubs val
liftIO $ traceIO $ "bisub type: " <> showValType val'
found <- qUnifyValue @t val'
liftIO $ checkVal found
testInterpret ::
forall t. HasQType 'Negative t
=> Text
-> (t -> Tester ())
-> ScriptTestTree
testInterpret expr checkVal =
testExpression @t expr expr $ \interpret -> do
found <- interpret
checkVal found
op1 :: X -> (X -> X) -> X
op1 v r = r $ r v
op2 :: X -> (X -> Text) -> (X -> X) -> Text
op2 v withVal r = withVal $ r $ r v
op2Text :: Text -> (Text -> Text) -> (Text -> Text) -> Text
op2Text v withVal r = withVal $ r $ r v
op3 :: X -> (X -> Action ()) -> (X -> X) -> Action ()
op3 v withVal r = withVal $ r $ r v
op4 :: (X -> Text) -> (X -> X) -> X -> Text
op4 withVal r v = withVal $ r $ r v
idText :: Text -> Text
idText = id
testLib :: LibraryModule context
testLib = let
testSameT :: Text -> Text -> Action ()
testSameT expected found =
if expected == found
then return ()
else fail "different"
testSameI :: Integer -> Integer -> Action ()
testSameI expected found =
if expected == found
then return ()
else fail "different"
in MkLibraryModule "TEST" $
headingBDT "TEST" "" $
[ valBDT "idText" "TEST" idText
, valBDT "testSameT" "TEST" testSameT
, valBDT "testSameI" "TEST" testSameI
, valBDT "op1" "TEST" op1
, valBDT "op2" "TEST" op2
, valBDT "op3" "TEST" op3
, valBDT "op4" "TEST" op4
]
testUnifier :: TestTree
testUnifier =
testTree
"unifier"
[ testTree
"unifier"
[ testTree
"op1"
[ testTree
"unify"
[ testUnifyToType @(Text -> (Text -> Text) -> Text) (return $ jmToValue op1) [] $ \found ->
assertEqual "" "PQPQPQ" $ found "PQPQPQ" id
, testUnifyToType @(X -> (X -> X) -> X) (return $ jmToValue op1) [] $ \found ->
assignUVarT @Text (MkSymbolType @"x") $
assertEqual "" "PQPQPQ" $ unVar $ found (MkVar "PQPQPQ") id
, testUnifyToType @(A -> (A -> A) -> A) (return $ jmToValue op1) [] $ \found ->
assignUVarT @Text (MkSymbolType @"a") $
assertEqual "" "PQPQPQ" $ unVar $ found (MkVar "PQPQPQ") id
]
, runScriptTestTree $
tLibrary testLib $
tDecls ["import \"TEST\""] $
tGroup
"interpret"
[ testInterpret @(A -> (A -> A) -> A) "op1" $ \found ->
assignUVarT @Text (MkSymbolType @"a") $
liftIO $ assertEqual "" "PQPQPQ" $ unVar $ found (MkVar "PQPQPQ") id
, testInterpret @(Text -> (Text -> Text) -> Text) "op1" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found "PQPQPQ" id
, testInterpret @((Text -> Text) -> Text) "op1 \"PQPQPQ\"" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id
, testInterpret @Text "op1 \"PQPQPQ\" id.Function" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" found
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op1 \"PQPQPQ\" idText"
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op1 \"PQPQPQ\" id.Function"
]
]
, testTree
"op2"
[ testTree
"unify"
[ testUnifyToType
@(Text -> (Text -> Text) -> (Text -> Text) -> Text)
(return $ jmToValue op2)
[] $ \found -> assertEqual "" "PQPQPQ" $ found "PQPQPQ" id id
, testUnifyToType @(A -> (A -> Text) -> (A -> A) -> Text) (return $ jmToValue op2) [] $ \found ->
assignUVarT @Text (MkSymbolType @"a") $
assertEqual "" "PQPQPQ" $ found (MkVar "PQPQPQ") unVar id
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
qEvalExpr expr1
checkVal found = assertEqual "" "PQPQPQ" $ found idText id
in testUnifyToType @((Text -> Text) -> (Text -> Text) -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2Text) (qConstExpr @Text "PQPQPQ")
expr2 <- qApplyExpr expr1 (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found id
in testUnifyToType @((Text -> Text) -> Text) makeVal [] checkVal
, testSourceScoped "value1" $ do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
val1 <- qEvalExpr expr1
found1 <- qUnifyValue @((Text -> Text) -> (Text -> Text) -> Text) val1
liftIO $ assertEqual "found1" "PQPQPQ" $ found1 idText id
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
val1 <- qEvalExpr expr1
expr2 <- qApplyExpr (qConstExprAny val1) (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found id
in testUnifyToType @((Text -> Text) -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op2) (qConstExpr @Text "PQPQPQ")
expr2 <- qApplyExpr expr1 (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found id
in testUnifyToType @((Text -> Text) -> Text) makeVal [] checkVal
]
, runScriptTestTree $
tLibrary testLib $
tDecls ["import \"TEST\""] $
tGroup
"interpret"
[ testInterpret @(Text -> (Text -> Text) -> (Text -> Text) -> Text) "op2" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found "PQPQPQ" id id
, testInterpret @((Text -> Text) -> (Text -> Text) -> Text) "op2 \"PQPQPQ\"" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id id
, testInterpret @((Text -> Text) -> Text) "op2 \"PQPQPQ\" id.Function" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id
, testInterpret @((Text -> Text) -> Text) "op2 \"PQPQPQ\" idText" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" $ found id
, testInterpret @Text "op2 \"PQPQPQ\" id.Function idText" $ \found ->
liftIO $ assertEqual "" "PQPQPQ" found
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op2 \"PQPQPQ\" id.Function idText"
, testExpectSuccess "testSameT \"PQPQPQ\" $.Function op2 \"PQPQPQ\" id.Function id.Function"
]
]
, testTree
"op3"
[ testTree @[TestTree] "unify" []
, runScriptTestTree $
tLibrary testLib $
tDecls ["import \"TEST\""] $
tGroup
"interpret"
[ testExpectSuccess "testSameT \"PQPQPQ\" \"PQPQPQ\""
, testExpectSuccess "op3 \"PQPQPQ\" (testSameT \"PQPQPQ\") idText"
, testExpectSuccess "op3 \"PQPQPQ\" (testSameT \"PQPQPQ\") id.Function"
, testExpectSuccess "op3 10 (testSameI 10) id.Function"
]
]
, testTree
"op4"
[ testTree
"unify"
[ let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op4) (qConstExpr idText)
qEvalExpr expr1
checkVal found = assertEqual "" "PQPQPQ" $ found idText "PQPQPQ"
in testUnifyToType @((Text -> Text) -> Text -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op4) (qConstExpr idText)
expr2 <- qApplyExpr expr1 (qConstExpr idText)
qEvalExpr expr2
checkVal found = assertEqual "" "PQPQPQ" $ found "PQPQPQ"
in testUnifyToType @(Text -> Text) makeVal [] checkVal
, let
makeVal :: QInterpreter QValue
makeVal = do
expr1 <- qApplyExpr (qConstExpr op4) (qConstExpr idText)
expr2 <- qApplyExpr expr1 (qConstExpr idText)
expr3 <- qApplyExpr expr2 (qConstExpr @Text "PQPQPQ")
qEvalExpr expr3
checkVal found = assertEqual "" "PQPQPQ" found
in testUnifyToType @Text makeVal [] checkVal
]
]
]
, testTree
"subtype"
[ testTree "t8" $
runTester defaultTester $ do
action <-
testerLiftInterpreter $ do
a1Expr <-
return $
qConstExpr ((>>=) newMemListModel :: (LangListModel '( A, A) -> Action B) -> Action B)
a2Expr <-
return $
qConstExpr (return :: LangListModel '( A, A) -> Action (LangListModel '( A, A)))
actionExpr <- qApplyExpr a1Expr a2Expr
actionVal <- qEvalExpr actionExpr
qUnifyValue @(Action (LangWholeModel '( [Integer], [Integer]))) actionVal
testerLiftAction $ do
wr <- action
langWholeModelSet wr $ Known [10, 20]
l <- langWholeModelGet wr
if l == [10, 20]
then return ()
else fail $ "different: " <> show l
, testTree "t5" $
runTester defaultTester $ do
r <- testerLiftAction $ newMemListModel @A
(_r' :: LangListModel '( Integer, Integer), wr' :: LangWholeModel '( [Integer], [Integer])) <-
testerLiftInterpreter $ do
convertExpr <- parseTopExpression "fn r => (r,r)"
convertVal <- qEvalExpr convertExpr
convert <- qUnifyValueToFree convertVal
return $ convert r
testerLiftAction $ langWholeModelSet wr' $ Known [10, 20]
l <- testerLiftAction $ langWholeModelGet wr'
if l == [10, 20]
then return ()
else fail "different"
, testTree "t4" $
runTester defaultTester $ do
r <- testerLiftAction $ newMemListModel @A
action <-
testerLiftInterpreter $ do
bodyExpr <-
parseTopExpression
"fn r => do r :=.WholeModel [10,20]; set.ListModel 0 25 r; get.WholeModel r end"
bodyVal <- qEvalExpr bodyExpr
body <- qUnifyValueToFree bodyVal
return $ body r
l :: [Integer] <- testerLiftAction action
if l == [25, 20]
then return ()
else fail "different"
, testTree "t3" $
runTester defaultTester $ do
r <- testerLiftAction $ newMemListModel @A
action <-
testerLiftInterpreter $ do
bodyExpr <-
parseTopExpression
"fn r => do r :=.WholeModel [10,20]; set.ListModel 0 25 r; get.WholeModel r end"
actionExpr <- qApplyExpr bodyExpr (qConstExpr r)
actionVal <- qEvalExpr actionExpr
qUnifyValue actionVal
l :: [Integer] <- testerLiftAction action
if l == [25, 20]
then return ()
else fail "different"
, testTree "t2" $
runTester defaultTester $ do
action <-
testerLiftInterpreter $ do
expr <-
parseTopExpression
"do r <- newMem.ListModel: Action (ListModel a); r :=.WholeModel [10,20]; ir <- item.ListModel True 0 r; ir :=.WholeModel 25; get.WholeModel r end"
val <- qEvalExpr expr
qUnifyValue val
l :: [Integer] <- testerLiftAction action
if l == [25, 20]
then return ()
else fail "different"
, testTree "t1" $
runTester defaultTester $ do
action <-
testerLiftInterpreter $ do
expr <-
parseTopExpression
"do r <- newMem.ListModel: Action (ListModel a); r :=.WholeModel [10,20]; ir <- item.ListModel True 0 r; ir :=.WholeModel 25; l <- get.WholeModel r; if l ==.Entity [25,20] then return.Action () else fail.Action \"different\"; end"
val <- qEvalExpr expr
qUnifyValue val
testerLiftAction action
, runScriptTestTree $
testExpectSuccess
"do r <- newMem.ListModel; r :=.WholeModel [10,20]; ir <- item.ListModel True 0 r; ir :=.WholeModel 25; l <- get.WholeModel r; if l ==.Entity [25,20] then return.Action () else fail.Action \"different\"; end"
]
]
|
|
2ffd5d7e99ec7b01ad0b2ef694d0042fb4cdf1ab544e6f0710dbe4848b192388 | ghc/packages-Cabal | Q.hs | module Q where
import P
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/NewBuild/T4405/q/Q.hs | haskell | module Q where
import P
|
|
230fadc7742c942306aee6cfcbbfdcd9c7d967e86ee1e45c1f2e1edcfd18557d | WormBase/wormbase_rest | current_genes.clj | (ns rest-api.classes.gene-class.widgets.current-genes
(:require
[clojure.string :as str]
[rest-api.classes.generic-fields :as generic]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(defn current-genes [g]
{:data (some->> (:gene/_gene-class g)
(map (fn [o]
(let [species-name (:species/id (:gene/species o))]
{:sequence (when-let [sn (:gene/sequence-name o)]
{:id sn
:label sn
:class "gene_name"
:taxonomy "all"})
:species_name species-name
:species (when-let [[genus species] (str/split species-name #" ")]
{:genus genus
:species species})
:locus (pack-obj o)})))
(group-by :species_name))
:description "genes assigned to the gene class, organized by species"})
(def widget
{:name generic/name-field
:current_genes current-genes})
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/gene_class/widgets/current_genes.clj | clojure | (ns rest-api.classes.gene-class.widgets.current-genes
(:require
[clojure.string :as str]
[rest-api.classes.generic-fields :as generic]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(defn current-genes [g]
{:data (some->> (:gene/_gene-class g)
(map (fn [o]
(let [species-name (:species/id (:gene/species o))]
{:sequence (when-let [sn (:gene/sequence-name o)]
{:id sn
:label sn
:class "gene_name"
:taxonomy "all"})
:species_name species-name
:species (when-let [[genus species] (str/split species-name #" ")]
{:genus genus
:species species})
:locus (pack-obj o)})))
(group-by :species_name))
:description "genes assigned to the gene class, organized by species"})
(def widget
{:name generic/name-field
:current_genes current-genes})
|
|
e86f8db50677b2dd181dc6525ce0deecac6aea846e519e46ffde464f95bf553e | openlilylib/lilypond-export | api.scm | ; -*- master: export-example.ly;
;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
;% %
;% This file is part of openLilyLib, %
;% =========== %
% the community library project for GNU LilyPond %
% ( ) %
;% ----------- %
;% %
;% Library: lilypond-export %
;% =============== %
;% %
% export foreign file formats with
;% %
;% lilypond-export 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. %
;% %
;% lilypond-export 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 openLilyLib. If not, see </>. %
;% %
% openLilyLib is maintained by , %
% lilypond - export is maintained by Jan - Peter Voigt , %
;% %
% Copyright Jan - , , 2017 %
;% %
;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TODO ties , slurs , grace notes , bar lines
(define-module (lilypond-export api))
(use-modules
(oll-core tree)
(oll-core internal music-tools)
(lilypond-export lily)
(lilypond-export MusicXML)
(lilypond-export Humdrum)
(lily))
(re-export exportLilyPond)
(re-export exportMusicXML)
(re-export exportHumdrum)
; create duration from moment
(define-public (moment->duration mom)
(ly:make-duration
(ly:intlog2 (ly:moment-main-denominator mom)) 0
(ly:moment-main-numerator mom)
))
; names of used context-properties
(define ctprop::voice-context-count 'voice-context-count)
(define ctprop::staff-context-count 'staff-context-count)
(define ctprop::lyric-context-count 'lyric-context-count)
(define ctprop::voice-id 'voice-id)
(define ctprop::staff-id 'staff-id)
(define ctprop::lyric-id 'lyric-id)
(define ctprop::music-export 'music-export)
(define ctprop::export-step 'music-export-step)
(define ctprop::lyrics 'lyric-events)
; The use of '@@' indicates bad code style! But how else can we add context properties in external code?
; add used context-properties
((@@ (lily) translator-property-description) ctprop::voice-context-count integer? "Count voice contexts")
((@@ (lily) translator-property-description) ctprop::staff-context-count integer? "Count staff contexts")
((@@ (lily) translator-property-description) ctprop::lyric-context-count integer? "Count staff contexts")
((@@ (lily) translator-property-description) ctprop::voice-id integer? "Voice ID")
((@@ (lily) translator-property-description) ctprop::staff-id integer? "Staff ID")
((@@ (lily) translator-property-description) ctprop::lyric-id integer? "Staff ID")
((@@ (lily) translator-property-description) ctprop::music-export tree? "Music export store")
((@@ (lily) translator-property-description) ctprop::export-step tree? "Music export step store")
((@@ (lily) translator-property-description) ctprop::lyrics list? "current lyric events")
; combine note-events to event-chord
(define (combine-notes current music)
(define (artic-type music) (ly:music-property music 'articulation-type))
(if (not (equal? (ly:music-length current)(ly:music-length music)))
(ly:warning "durations differ: ~A ~A" current music))
(cond
; only take rests, if there is no music
( and ( ly : music ? current)(eq ? ' ( ly : music - property music ' name ) ) )
(if (ly:music? current) current music))
; if we already have an event-chord, add note-event
((music-is? current 'EventChord) ;(and (ly:music? current)(eq? 'EventChord (ly:music-property current 'name)))
(let* ((elements (ly:music-property current 'elements))
(artics (ly:music-property music 'articulations))
(an1 (filter symbol? (map artic-type elements))))
; reset articulations and place them in the event-chord
(ly:music-set-property! music 'articulations '())
; add element and alement articulations to event-chord
(ly:music-set-property! current 'elements `(,@elements ,music ,@artics))
current
))
; if current is rest, override it with music
( and ( ly : music ? current)(eq ? ' ( ly : music - property current ' name ) ) )
music)
create event - chord with two note - events
((ly:music? current)
(let* ((artics1 (ly:music-property current 'articulations))
(artics2 (ly:music-property music 'articulations))
(an1 (filter symbol? (map artic-type artics1))))
(ly:music-set-property! current 'articulations '())
(ly:music-set-property! music 'articulations '())
(make-music 'EventChord 'elements
`(,current ,music ,@artics1
,@(filter (lambda (v) (not (memv (ly:music-property v 'articulation-type) an1))) artics2))
'duration (ly:music-property music 'duration)
)))
(else music))
)
; engraver to collect all note- and rest-events
(define-public collectVoice
(lambda (context)
(let ((id 0)
; beam- and tuplet-closing is always a step late ...
(beam-time '(#f . #f))
(tuplet-time '(#f . #f)))
; search for music-cause of grob
(define (grob-cause grob)
(cond
((ly:grob? grob) (grob-cause (ly:grob-property grob 'cause)))
((ly:music? grob) grob)
((ly:stream-event? grob) (grob-cause (ly:event-property grob 'music-cause)))
(else #f)
))
(make-engraver
((initialize trans)
(let* ((staff-context (ly:context-find context 'Staff))
(stvc (ly:context-property staff-context ctprop::voice-context-count 0))) ; How many voices are in the staff
(set! stvc (1+ stvc))
(ly:context-set-property! staff-context ctprop::voice-context-count stvc)
(set! id stvc)
(ly:context-set-property! context ctprop::voice-id id)
(ly:message "init Voice ~A/~A (~A)" (ly:context-property context ctprop::staff-id) (ly:context-id context) id)
export tree for one timestep
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))
))
((start-translation-timestep trans)
; clear lyrics
(ly:context-unset-property context ctprop::lyrics)
; export tree for this timestep
(if (not (tree? (ly:context-property context ctprop::export-step)))
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))))
((stop-translation-timestep trans)
(let ((step (ly:context-property context ctprop::export-step)) ; export tree for this timestep
(musicexport (ly:context-property context ctprop::music-export)) ; global export tree
(bar (ly:context-property context 'currentBarNumber 1)) ; current bar number
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))) ; current measure position
(ly:context-unset-property context ctprop::export-step)
; detect upbeat (partial)
(if (ly:moment<? moment (ly:make-moment 0))
(set! bar (1- bar)))
; if we have a tree for this timestep (why should'nt we?)
(if (tree? step)
; copy to global export tree
(tree-walk step '()
(lambda (path xkey value) ; path in tree, key of current node, value of current node
(tree-set! musicexport `(,bar ,moment ,@path) value)
) '(empty . #f)))
))
(listeners
((StreamEvent engraver event) ; listen to any event
(let ((musicexport (ly:context-property context ctprop::music-export))
(musicstep (ly:context-property context ctprop::export-step))
(music (ly:event-property event 'music-cause))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0))))
; notes and rests are stored in the tree under measeure/moment/staff/voice
TODO MultiMeasureRests , Upbeats
(if (and (ly:music? music) (= 0 (ly:moment-grace moment))) ; Drop grace notes!
(let* ((path (list bar moment
(ly:context-property context ctprop::staff-id)
(ly:context-property context ctprop::voice-id)))
(steppath (cddr path))
(notes (tree-get musicstep steppath)))
(ly:music-set-property! music 'timestamp (cons bar moment))
(cond
((memq (ly:music-property music 'name) '(NoteEvent RestEvent))
(let ((dur (ly:event-property event 'duration)))
track shortest duration ( musicXML / MEI divisions )
(let ((shortdur (tree-get musicexport '(division-dur))))
(if (and (ly:duration? dur)(or (not shortdur) (ly:duration<? dur shortdur)))
(tree-set! musicexport '(division-dur) dur))
)
; if we already have a note, combine it to a eventchord
(if (ly:music? notes) (set! music (combine-notes notes music)))
; tuplets
(let ((scale (ly:duration-scale dur)))
(if (not (integer? scale))
(let ((num (numerator scale))
(den (denominator scale)))
;(ly:message "scale ~A/~A" num den)
(tree-set! musicstep `(,@steppath scale) scale)
)))
; remember current time
(ly:event-set-property! event 'timestamp (cons bar moment))
; track time for beams
(if (not (and
(pair? (cdr beam-time))
(equal? (cadr beam-time) bar)
(equal? (cddr beam-time) moment)))
(set! beam-time (cons (cdr beam-time) (cons bar moment))))
; track time for tuplets
(if (not (and
(pair? (cdr tuplet-time))
(equal? (cadr tuplet-time) bar)
(equal? (cddr tuplet-time) moment)))
(set! tuplet-time (cons (cdr tuplet-time) (cons bar moment))))
; store music
(tree-set! musicstep steppath music)))
((eq? (ly:music-property music 'name) 'TupletSpanEvent)
(let ((timestamp (ly:music-property music 'timestamp))
(num (ly:music-property music 'numerator))
(den (ly:music-property music 'denominator))
(dir (ly:music-property music 'span-direction)))
;(ly:message "tuplet ~A:~A ~A ~A ~A" num den timestamp (cons bar moment) dir)
(cond
((and (= -1 dir)(integer? num)(integer? den))
(tree-set! musicstep `(,@steppath tuplet) `(start . ,(/ num den))))
((= 1 dir)
(let ((tup-time (cdr tuplet-time)))
;(ly:message "tuplet time ~A ~A" tup-time (cons bar moment))
(tree-set! musicexport `(,(car tup-time) ,(cdr tup-time) ,@steppath tuplet) `(stop . #f))
))
)))
)))
))
)
(acknowledgers
; store accidental
((accidental-interface engraver grob source-engraver)
(let ((musicexport (ly:context-property context ctprop::music-export))
(bar (ly:context-property context 'currentBarNumber 1))
(staff-id (ly:context-property context ctprop::staff-id))
(voice-id (ly:context-property context ctprop::voice-id))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0))))
(tree-set! musicexport (list bar moment staff-id voice-id 'accidental) (accidental-interface::calc-alteration grob))
))
; store stem direction
((stem-interface engraver grob source-engraver)
(let ((musicstep (ly:context-property context ctprop::export-step))
(staff-id (ly:context-property context ctprop::staff-id))
(voice-id (ly:context-property context ctprop::voice-id)))
(ly:message "stem info ~A" (map car (ly:grob-properties grob)))
(tree-set! musicstep `(,staff-id ,voice-id stem dir) (ly:grob-properties grob)) ;(ly:stem::calc-direction grob))
))
)
; store beam span
(end-acknowledgers
((beam-interface engraver grob source-engraver)
(let ((musicexport (ly:context-property context ctprop::music-export))
( musicstep ( ly : context - property context ctprop::export - step ) )
(staff-id (ly:context-property context ctprop::staff-id))
(voice-id (ly:context-property context ctprop::voice-id))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))
(cause (grob-cause grob)))
; we stored the start-time inside the causing music-event
we stored the end - time in beam - time one timestep before this one
(cond
((music-is? cause 'NoteEvent)
(let ((start-timestamp (ly:music-property cause 'timestamp))
(end-timestamp (car beam-time)))
(if (not (null? start-timestamp)) ; this skips grace notes
(tree-set! musicexport (list (car start-timestamp) (cdr start-timestamp) staff-id voice-id 'beam) 'start) )
(if (not (null? end-timestamp)) ; this skips grace notes
(tree-set! musicexport (list (car end-timestamp) (cdr end-timestamp) staff-id voice-id 'beam) 'end))
;(ly:message "beam ~A ~A" start-timestamp end-timestamp)
))
((music-is? cause 'BeamEvent)
(let ((start-timestamp (ly:music-property cause 'timestamp))
(end-timestamp (cons bar moment)))
(tree-set! musicexport (list (car start-timestamp) (cdr start-timestamp) staff-id voice-id 'beam) 'start)
(tree-set! musicexport (list (car end-timestamp) (cdr end-timestamp) staff-id voice-id 'beam) 'end)
;(ly:message "beam ~A ~A" start-timestamp end-timestamp)
))
; this should'nt appear!
(else (ly:message "Beam? ~A" cause))
)
))
)
))))
; collect lyrics
(define-public collectLyrics
(let ((id 0))
(lambda (context)
(make-engraver
((initialize trans)
(let* ((score-context (ly:context-find context 'Score))
(lyric-count (ly:context-property score-context ctprop::lyric-context-count)))
(if (integer? lyric-count)
(set! lyric-count (1+ lyric-count))
(set! lyric-count 1))
(set! id lyric-count)
; export tree for the current timestamp
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))
))
((start-translation-timestep trans)
(if (not (tree? (ly:context-property context ctprop::export-step)))
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))))
((stop-translation-timestep trans)
(let ((step (ly:context-property context ctprop::export-step))
(musicexport (ly:context-property context ctprop::music-export))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0))))
(ly:context-set-property! context ctprop::export-step #f)
(if (ly:moment<? moment (ly:make-moment 0))
(set! bar (1- bar)))
(if (tree? step)
(tree-walk step '()
(lambda (path xkey value)
(tree-set! musicexport `(,bar ,moment ,@path) value)
) '(empty . #f)))
))
(listeners
((lyric-event engraver event)
(let ((musicexport (ly:context-property context ctprop::music-export))
(musicstep (ly:context-property context ctprop::export-step))
(text (ly:event-property event 'text))
; we need the associated voice context
(voice (ly:context-property context 'associatedVoiceContext)))
(if (ly:context? voice)
(let* ((staff-id (ly:context-property voice ctprop::staff-id))
(voice-id (ly:context-property voice ctprop::voice-id))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))
(lpath (list staff-id voice-id 'lyrics))
(lyrics (ly:context-property voice ctprop::lyrics)))
; create/extend list of lyric events found for the associated voice context
(set! lyrics (if (list? lyrics) `(,@lyrics ,text) (list text)))
(tree-set! musicstep lpath lyrics)
(ly:context-set-property! voice ctprop::lyrics lyrics))
; TODO if we have no associated voice context, what shall we do?
(ly:message "syl ~A" text))
))
)
))))
engraver to group voices in one staff
(define-public collectStaff
(lambda (context)
(let ((id 0))
(make-engraver
((initialize trans)
TODO StaffGroup hierarchy ! - > ly : context - property - where - defined !
(let* ((parent-context (ly:context-find context 'Score)) ;(ly:context-parent context)) ; look in parent context for current staff count
(psc (ly:context-property parent-context ctprop::staff-context-count 0)))
(set! psc (1+ psc))
(ly:context-set-property! parent-context ctprop::staff-context-count psc)
(set! id psc)
(ly:context-set-property! context ctprop::staff-id id)
(ly:message "init Staff ~A" id)
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))
))
((start-translation-timestep trans)
(if (not (tree? (ly:context-property context ctprop::export-step)))
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))))
((stop-translation-timestep trans)
(let ((step (ly:context-property context ctprop::export-step))
(musicexport (ly:context-property context ctprop::music-export))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))
(mlen (ly:context-property context 'measureLength))
(barline (ly:context-property context 'whichBar)))
(ly:context-set-property! context ctprop::export-step #f) ; reset step store
(if (ly:moment<? moment (ly:make-moment 0))
(begin
(set! bar (1- bar)) ; upbeat / partial
;(set! moment (ly:moment-add mlen moment))
))
(tree-set! musicexport (list bar moment 'mlength) mlen)
(tree-set! musicexport (list bar moment id 'mlength) mlen)
(if (tree? step)
(tree-walk step '()
(lambda (path xkey value)
(tree-set! musicexport `(,bar ,moment ,@path) value)
) '(empty . #f)))
(if (and (string? barline)(not (equal? "" barline))(not (equal? "|" barline)))
(begin
(tree-set! musicexport (list bar moment 'barline) barline)
(tree-set! musicexport (list bar moment id 'barline) barline)
))
))
(listeners
((SetProperty engraver event)
(let ((musicstep (ly:context-property context ctprop::export-step))
(sym (ly:event-property event 'symbol))
(val (ly:event-property event 'value))
(staff-id (ly:context-property context ctprop::staff-id)))
; detect clefs
(if (memq sym '(clefGlyph clefPosition clefTransposition))
(tree-set! musicstep (list staff-id sym) val))
))
; detect key changes
((key-change-event engraver event)
(let ((musicstep (ly:context-property context ctprop::export-step))
(music (ly:event-property event 'music-cause))
(staff-id (ly:context-property context ctprop::staff-id)))
(tree-set! musicstep (list staff-id 'keysig) music)
))
; detect time signatures
((time-signature-event engraver event)
(let ((musicstep (ly:context-property context ctprop::export-step))
(staff-id (ly:context-property context ctprop::staff-id)))
(tree-set! musicstep (list staff-id 'timesig)
(cons (ly:event-property event 'numerator)(ly:event-property event 'denominator)))
(tree-set! musicstep `(timesig)
(cons (ly:event-property event 'numerator)(ly:event-property event 'denominator)))
))
)
))))
; create score-export-engraver
(define-public scoreExporter
; engraver to export tree in foreign format
(define-scheme-function (options)(list?)
(let* ((exporter (ly:assoc-get 'exporter options exportHumdrum #f))
(suffix (ly:assoc-get 'filesuffix options (object-property exporter 'file-suffix) #f))
(filename (ly:assoc-get 'filename options
(format "~A.~A"
(ly:assoc-get 'filebase options (ly:parser-output-name) #f)
(if (string? suffix) suffix
(begin
(ly:input-warning (*location*) "no file suffix given!")
"dat"))) #f)))
(lambda (context)
(make-engraver
((initialize trans)
(ly:message "init ~A: \"~A\"" (procedure-name exporter) filename)
(ly:context-set-property! context ctprop::music-export (tree-create ctprop::music-export))
)
((finalize trans)
(let ((musicexport (ly:context-property context ctprop::music-export)))
; when score is finished, score is exported
(tree-set! musicexport '(finaltime)
(cons (ly:context-property context 'currentBarNumber) (ly:context-property context 'measurePosition)))
( for - each ( lambda ( sym ) ( ly : message " ~A : ~A " ( tree - get musicexport ( list ) ) ) )
; (filter symbol? (tree-get-keys musicexport '())))
( tree - display musicexport )
(exporter musicexport filename)
))
))
)))
; create output-definition (layout) with file exporter
(define-public FileExport
(define-scheme-function (options)(list?)
#{
\layout {
\context {
\Voice
\consists #collectVoice
}
\context {
\Staff
\consists #collectStaff
}
\context {
\Lyrics
\consists #collectLyrics
}
\context {
\Score
\consists \scoreExporter #options
}
}
#}))
| null | https://raw.githubusercontent.com/openlilylib/lilypond-export/c1b5ec0e5140d9cb8c3e7f43ade7b3cde1620dd4/api.scm | scheme | -*- master: export-example.ly;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This file is part of openLilyLib, %
% =========== %
% ----------- %
% %
% Library: lilypond-export %
% =============== %
% %
% %
% lilypond-export is free software: you can redistribute it and/or modify %
% (at your option) any later version. %
% %
% lilypond-export is distributed in the hope that it will be useful, %
% but WITHOUT ANY WARRANTY; without even the implied warranty of %
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %
% GNU General Public License for more details. %
% %
% along with openLilyLib. If not, see </>. %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
create duration from moment
names of used context-properties
The use of '@@' indicates bad code style! But how else can we add context properties in external code?
add used context-properties
combine note-events to event-chord
only take rests, if there is no music
if we already have an event-chord, add note-event
(and (ly:music? current)(eq? 'EventChord (ly:music-property current 'name)))
reset articulations and place them in the event-chord
add element and alement articulations to event-chord
if current is rest, override it with music
engraver to collect all note- and rest-events
beam- and tuplet-closing is always a step late ...
search for music-cause of grob
How many voices are in the staff
clear lyrics
export tree for this timestep
export tree for this timestep
global export tree
current bar number
current measure position
detect upbeat (partial)
if we have a tree for this timestep (why should'nt we?)
copy to global export tree
path in tree, key of current node, value of current node
listen to any event
notes and rests are stored in the tree under measeure/moment/staff/voice
Drop grace notes!
if we already have a note, combine it to a eventchord
tuplets
(ly:message "scale ~A/~A" num den)
remember current time
track time for beams
track time for tuplets
store music
(ly:message "tuplet ~A:~A ~A ~A ~A" num den timestamp (cons bar moment) dir)
(ly:message "tuplet time ~A ~A" tup-time (cons bar moment))
store accidental
store stem direction
(ly:stem::calc-direction grob))
store beam span
we stored the start-time inside the causing music-event
this skips grace notes
this skips grace notes
(ly:message "beam ~A ~A" start-timestamp end-timestamp)
(ly:message "beam ~A ~A" start-timestamp end-timestamp)
this should'nt appear!
collect lyrics
export tree for the current timestamp
we need the associated voice context
create/extend list of lyric events found for the associated voice context
TODO if we have no associated voice context, what shall we do?
(ly:context-parent context)) ; look in parent context for current staff count
reset step store
upbeat / partial
(set! moment (ly:moment-add mlen moment))
detect clefs
detect key changes
detect time signatures
create score-export-engraver
engraver to export tree in foreign format
when score is finished, score is exported
(filter symbol? (tree-get-keys musicexport '())))
create output-definition (layout) with file exporter | % the community library project for GNU LilyPond %
% ( ) %
% export foreign file formats with
% it under the terms of the GNU General Public License as published by %
% the Free Software Foundation , either version 3 of the License , or %
% You should have received a copy of the GNU General Public License %
% openLilyLib is maintained by , %
% lilypond - export is maintained by Jan - Peter Voigt , %
% Copyright Jan - , , 2017 %
% TODO ties , slurs , grace notes , bar lines
(define-module (lilypond-export api))
(use-modules
(oll-core tree)
(oll-core internal music-tools)
(lilypond-export lily)
(lilypond-export MusicXML)
(lilypond-export Humdrum)
(lily))
(re-export exportLilyPond)
(re-export exportMusicXML)
(re-export exportHumdrum)
(define-public (moment->duration mom)
(ly:make-duration
(ly:intlog2 (ly:moment-main-denominator mom)) 0
(ly:moment-main-numerator mom)
))
(define ctprop::voice-context-count 'voice-context-count)
(define ctprop::staff-context-count 'staff-context-count)
(define ctprop::lyric-context-count 'lyric-context-count)
(define ctprop::voice-id 'voice-id)
(define ctprop::staff-id 'staff-id)
(define ctprop::lyric-id 'lyric-id)
(define ctprop::music-export 'music-export)
(define ctprop::export-step 'music-export-step)
(define ctprop::lyrics 'lyric-events)
((@@ (lily) translator-property-description) ctprop::voice-context-count integer? "Count voice contexts")
((@@ (lily) translator-property-description) ctprop::staff-context-count integer? "Count staff contexts")
((@@ (lily) translator-property-description) ctprop::lyric-context-count integer? "Count staff contexts")
((@@ (lily) translator-property-description) ctprop::voice-id integer? "Voice ID")
((@@ (lily) translator-property-description) ctprop::staff-id integer? "Staff ID")
((@@ (lily) translator-property-description) ctprop::lyric-id integer? "Staff ID")
((@@ (lily) translator-property-description) ctprop::music-export tree? "Music export store")
((@@ (lily) translator-property-description) ctprop::export-step tree? "Music export step store")
((@@ (lily) translator-property-description) ctprop::lyrics list? "current lyric events")
(define (combine-notes current music)
(define (artic-type music) (ly:music-property music 'articulation-type))
(if (not (equal? (ly:music-length current)(ly:music-length music)))
(ly:warning "durations differ: ~A ~A" current music))
(cond
( and ( ly : music ? current)(eq ? ' ( ly : music - property music ' name ) ) )
(if (ly:music? current) current music))
(let* ((elements (ly:music-property current 'elements))
(artics (ly:music-property music 'articulations))
(an1 (filter symbol? (map artic-type elements))))
(ly:music-set-property! music 'articulations '())
(ly:music-set-property! current 'elements `(,@elements ,music ,@artics))
current
))
( and ( ly : music ? current)(eq ? ' ( ly : music - property current ' name ) ) )
music)
create event - chord with two note - events
((ly:music? current)
(let* ((artics1 (ly:music-property current 'articulations))
(artics2 (ly:music-property music 'articulations))
(an1 (filter symbol? (map artic-type artics1))))
(ly:music-set-property! current 'articulations '())
(ly:music-set-property! music 'articulations '())
(make-music 'EventChord 'elements
`(,current ,music ,@artics1
,@(filter (lambda (v) (not (memv (ly:music-property v 'articulation-type) an1))) artics2))
'duration (ly:music-property music 'duration)
)))
(else music))
)
(define-public collectVoice
(lambda (context)
(let ((id 0)
(beam-time '(#f . #f))
(tuplet-time '(#f . #f)))
(define (grob-cause grob)
(cond
((ly:grob? grob) (grob-cause (ly:grob-property grob 'cause)))
((ly:music? grob) grob)
((ly:stream-event? grob) (grob-cause (ly:event-property grob 'music-cause)))
(else #f)
))
(make-engraver
((initialize trans)
(let* ((staff-context (ly:context-find context 'Staff))
(set! stvc (1+ stvc))
(ly:context-set-property! staff-context ctprop::voice-context-count stvc)
(set! id stvc)
(ly:context-set-property! context ctprop::voice-id id)
(ly:message "init Voice ~A/~A (~A)" (ly:context-property context ctprop::staff-id) (ly:context-id context) id)
export tree for one timestep
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))
))
((start-translation-timestep trans)
(ly:context-unset-property context ctprop::lyrics)
(if (not (tree? (ly:context-property context ctprop::export-step)))
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))))
((stop-translation-timestep trans)
(ly:context-unset-property context ctprop::export-step)
(if (ly:moment<? moment (ly:make-moment 0))
(set! bar (1- bar)))
(if (tree? step)
(tree-walk step '()
(tree-set! musicexport `(,bar ,moment ,@path) value)
) '(empty . #f)))
))
(listeners
(let ((musicexport (ly:context-property context ctprop::music-export))
(musicstep (ly:context-property context ctprop::export-step))
(music (ly:event-property event 'music-cause))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0))))
TODO MultiMeasureRests , Upbeats
(let* ((path (list bar moment
(ly:context-property context ctprop::staff-id)
(ly:context-property context ctprop::voice-id)))
(steppath (cddr path))
(notes (tree-get musicstep steppath)))
(ly:music-set-property! music 'timestamp (cons bar moment))
(cond
((memq (ly:music-property music 'name) '(NoteEvent RestEvent))
(let ((dur (ly:event-property event 'duration)))
track shortest duration ( musicXML / MEI divisions )
(let ((shortdur (tree-get musicexport '(division-dur))))
(if (and (ly:duration? dur)(or (not shortdur) (ly:duration<? dur shortdur)))
(tree-set! musicexport '(division-dur) dur))
)
(if (ly:music? notes) (set! music (combine-notes notes music)))
(let ((scale (ly:duration-scale dur)))
(if (not (integer? scale))
(let ((num (numerator scale))
(den (denominator scale)))
(tree-set! musicstep `(,@steppath scale) scale)
)))
(ly:event-set-property! event 'timestamp (cons bar moment))
(if (not (and
(pair? (cdr beam-time))
(equal? (cadr beam-time) bar)
(equal? (cddr beam-time) moment)))
(set! beam-time (cons (cdr beam-time) (cons bar moment))))
(if (not (and
(pair? (cdr tuplet-time))
(equal? (cadr tuplet-time) bar)
(equal? (cddr tuplet-time) moment)))
(set! tuplet-time (cons (cdr tuplet-time) (cons bar moment))))
(tree-set! musicstep steppath music)))
((eq? (ly:music-property music 'name) 'TupletSpanEvent)
(let ((timestamp (ly:music-property music 'timestamp))
(num (ly:music-property music 'numerator))
(den (ly:music-property music 'denominator))
(dir (ly:music-property music 'span-direction)))
(cond
((and (= -1 dir)(integer? num)(integer? den))
(tree-set! musicstep `(,@steppath tuplet) `(start . ,(/ num den))))
((= 1 dir)
(let ((tup-time (cdr tuplet-time)))
(tree-set! musicexport `(,(car tup-time) ,(cdr tup-time) ,@steppath tuplet) `(stop . #f))
))
)))
)))
))
)
(acknowledgers
((accidental-interface engraver grob source-engraver)
(let ((musicexport (ly:context-property context ctprop::music-export))
(bar (ly:context-property context 'currentBarNumber 1))
(staff-id (ly:context-property context ctprop::staff-id))
(voice-id (ly:context-property context ctprop::voice-id))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0))))
(tree-set! musicexport (list bar moment staff-id voice-id 'accidental) (accidental-interface::calc-alteration grob))
))
((stem-interface engraver grob source-engraver)
(let ((musicstep (ly:context-property context ctprop::export-step))
(staff-id (ly:context-property context ctprop::staff-id))
(voice-id (ly:context-property context ctprop::voice-id)))
(ly:message "stem info ~A" (map car (ly:grob-properties grob)))
))
)
(end-acknowledgers
((beam-interface engraver grob source-engraver)
(let ((musicexport (ly:context-property context ctprop::music-export))
( musicstep ( ly : context - property context ctprop::export - step ) )
(staff-id (ly:context-property context ctprop::staff-id))
(voice-id (ly:context-property context ctprop::voice-id))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))
(cause (grob-cause grob)))
we stored the end - time in beam - time one timestep before this one
(cond
((music-is? cause 'NoteEvent)
(let ((start-timestamp (ly:music-property cause 'timestamp))
(end-timestamp (car beam-time)))
(tree-set! musicexport (list (car start-timestamp) (cdr start-timestamp) staff-id voice-id 'beam) 'start) )
(tree-set! musicexport (list (car end-timestamp) (cdr end-timestamp) staff-id voice-id 'beam) 'end))
))
((music-is? cause 'BeamEvent)
(let ((start-timestamp (ly:music-property cause 'timestamp))
(end-timestamp (cons bar moment)))
(tree-set! musicexport (list (car start-timestamp) (cdr start-timestamp) staff-id voice-id 'beam) 'start)
(tree-set! musicexport (list (car end-timestamp) (cdr end-timestamp) staff-id voice-id 'beam) 'end)
))
(else (ly:message "Beam? ~A" cause))
)
))
)
))))
(define-public collectLyrics
(let ((id 0))
(lambda (context)
(make-engraver
((initialize trans)
(let* ((score-context (ly:context-find context 'Score))
(lyric-count (ly:context-property score-context ctprop::lyric-context-count)))
(if (integer? lyric-count)
(set! lyric-count (1+ lyric-count))
(set! lyric-count 1))
(set! id lyric-count)
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))
))
((start-translation-timestep trans)
(if (not (tree? (ly:context-property context ctprop::export-step)))
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))))
((stop-translation-timestep trans)
(let ((step (ly:context-property context ctprop::export-step))
(musicexport (ly:context-property context ctprop::music-export))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0))))
(ly:context-set-property! context ctprop::export-step #f)
(if (ly:moment<? moment (ly:make-moment 0))
(set! bar (1- bar)))
(if (tree? step)
(tree-walk step '()
(lambda (path xkey value)
(tree-set! musicexport `(,bar ,moment ,@path) value)
) '(empty . #f)))
))
(listeners
((lyric-event engraver event)
(let ((musicexport (ly:context-property context ctprop::music-export))
(musicstep (ly:context-property context ctprop::export-step))
(text (ly:event-property event 'text))
(voice (ly:context-property context 'associatedVoiceContext)))
(if (ly:context? voice)
(let* ((staff-id (ly:context-property voice ctprop::staff-id))
(voice-id (ly:context-property voice ctprop::voice-id))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))
(lpath (list staff-id voice-id 'lyrics))
(lyrics (ly:context-property voice ctprop::lyrics)))
(set! lyrics (if (list? lyrics) `(,@lyrics ,text) (list text)))
(tree-set! musicstep lpath lyrics)
(ly:context-set-property! voice ctprop::lyrics lyrics))
(ly:message "syl ~A" text))
))
)
))))
engraver to group voices in one staff
(define-public collectStaff
(lambda (context)
(let ((id 0))
(make-engraver
((initialize trans)
TODO StaffGroup hierarchy ! - > ly : context - property - where - defined !
(psc (ly:context-property parent-context ctprop::staff-context-count 0)))
(set! psc (1+ psc))
(ly:context-set-property! parent-context ctprop::staff-context-count psc)
(set! id psc)
(ly:context-set-property! context ctprop::staff-id id)
(ly:message "init Staff ~A" id)
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))
))
((start-translation-timestep trans)
(if (not (tree? (ly:context-property context ctprop::export-step)))
(ly:context-set-property! context ctprop::export-step (tree-create 'timestep))))
((stop-translation-timestep trans)
(let ((step (ly:context-property context ctprop::export-step))
(musicexport (ly:context-property context ctprop::music-export))
(bar (ly:context-property context 'currentBarNumber 1))
(moment (ly:context-property context 'measurePosition (ly:make-moment 0)))
(mlen (ly:context-property context 'measureLength))
(barline (ly:context-property context 'whichBar)))
(if (ly:moment<? moment (ly:make-moment 0))
(begin
))
(tree-set! musicexport (list bar moment 'mlength) mlen)
(tree-set! musicexport (list bar moment id 'mlength) mlen)
(if (tree? step)
(tree-walk step '()
(lambda (path xkey value)
(tree-set! musicexport `(,bar ,moment ,@path) value)
) '(empty . #f)))
(if (and (string? barline)(not (equal? "" barline))(not (equal? "|" barline)))
(begin
(tree-set! musicexport (list bar moment 'barline) barline)
(tree-set! musicexport (list bar moment id 'barline) barline)
))
))
(listeners
((SetProperty engraver event)
(let ((musicstep (ly:context-property context ctprop::export-step))
(sym (ly:event-property event 'symbol))
(val (ly:event-property event 'value))
(staff-id (ly:context-property context ctprop::staff-id)))
(if (memq sym '(clefGlyph clefPosition clefTransposition))
(tree-set! musicstep (list staff-id sym) val))
))
((key-change-event engraver event)
(let ((musicstep (ly:context-property context ctprop::export-step))
(music (ly:event-property event 'music-cause))
(staff-id (ly:context-property context ctprop::staff-id)))
(tree-set! musicstep (list staff-id 'keysig) music)
))
((time-signature-event engraver event)
(let ((musicstep (ly:context-property context ctprop::export-step))
(staff-id (ly:context-property context ctprop::staff-id)))
(tree-set! musicstep (list staff-id 'timesig)
(cons (ly:event-property event 'numerator)(ly:event-property event 'denominator)))
(tree-set! musicstep `(timesig)
(cons (ly:event-property event 'numerator)(ly:event-property event 'denominator)))
))
)
))))
(define-public scoreExporter
(define-scheme-function (options)(list?)
(let* ((exporter (ly:assoc-get 'exporter options exportHumdrum #f))
(suffix (ly:assoc-get 'filesuffix options (object-property exporter 'file-suffix) #f))
(filename (ly:assoc-get 'filename options
(format "~A.~A"
(ly:assoc-get 'filebase options (ly:parser-output-name) #f)
(if (string? suffix) suffix
(begin
(ly:input-warning (*location*) "no file suffix given!")
"dat"))) #f)))
(lambda (context)
(make-engraver
((initialize trans)
(ly:message "init ~A: \"~A\"" (procedure-name exporter) filename)
(ly:context-set-property! context ctprop::music-export (tree-create ctprop::music-export))
)
((finalize trans)
(let ((musicexport (ly:context-property context ctprop::music-export)))
(tree-set! musicexport '(finaltime)
(cons (ly:context-property context 'currentBarNumber) (ly:context-property context 'measurePosition)))
( for - each ( lambda ( sym ) ( ly : message " ~A : ~A " ( tree - get musicexport ( list ) ) ) )
( tree - display musicexport )
(exporter musicexport filename)
))
))
)))
(define-public FileExport
(define-scheme-function (options)(list?)
#{
\layout {
\context {
\Voice
\consists #collectVoice
}
\context {
\Staff
\consists #collectStaff
}
\context {
\Lyrics
\consists #collectLyrics
}
\context {
\Score
\consists \scoreExporter #options
}
}
#}))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.