_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 |
|---|---|---|---|---|---|---|---|---|
483dc9a2a0bede52fc7c35ac6c7b082ed99801fadee6096fe81b671059259395 | elaforge/karya | Mridangam2015.hs | Copyright 2018
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
module Solkattu.Score.Mridangam2015 where
import Prelude hiding ((.), repeat)
import qualified Solkattu.Tala as Tala
import Solkattu.Dsl.Mridangam
c_1 :: Korvai
c_1 = akash $ date 2015 1 1 $ tekha $
comment "rupak hindustani = 2 * misra chapu" $
korvaiS Tala.misra_chapu
[ sd $ i. __.i. __.n. __.od.__. n.__.od.__. n. __
, sd $ p&i.k.p&i.__.n.k .od.o&k.p&n.k.od.o&k.p&n.k
, sd $ od.__.k.od.__.k .od.o&k.p&n.k.od.o&k.p&n.k
, sd $ on.su (kt.o.k).on.on.su (kt.p.k).n.su (kt.p.k).on.on.su (kt.o.k)
]
c_2 :: Korvai
c_2 = akash $ date 2015 1 1 $ tekha $
korvaiS adi $ map (nadai 6 • sd)
[ r2 $ r2 (n.d.n.n.d.k) & (o.__.o.o.p.__ . __.__.o.o.__.__)
, r3 (on.ktpk.p&n.ktok) . on.p&n.__.on.p&n.__
]
where
ktpk = su (k.t.p.k)
ktok = su (k.t.o.k)
c_3 :: Korvai
c_3 = akash $ date 2015 1 1 $ tekha $ comment "14 beats" $
korvaiS Tala.misra_chapu
[ sd $ on.od.__.on.on.od.__.n.p&d.__.on.on.od.__
, sd $ r2 (n.d.l.n.l.d.l) & (o.__3.o.__.o.__.p.__3.o.__.o.__)
, sarvaD_ 5 . r2 (nadai 6 (n.p.kt.pk))
]
akash1 :: Korvai
akash1 = akash $ date 2015 1 1 $ korvaiS adi
[ r2 $ rh & "o__o_oo_" . rh & "p__p_p__"
, rh & "o__o_oo_" . su ktpk . "ndldnl" & "_p_p"
. fill . su ktpk . "ndldnl" & "_p_p"
]
where
fill = g $ od.k.k.od.k.k.od.__
rh = "dlndldnl"
akash :: Korvai -> Korvai
akash = source "akash"
tekha :: Korvai -> Korvai
tekha = withType "tekha"
| null | https://raw.githubusercontent.com/elaforge/karya/09c596b065ea493e8aebc7014e371de17e6d85de/Solkattu/Score/Mridangam2015.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt | Copyright 2018
module Solkattu.Score.Mridangam2015 where
import Prelude hiding ((.), repeat)
import qualified Solkattu.Tala as Tala
import Solkattu.Dsl.Mridangam
c_1 :: Korvai
c_1 = akash $ date 2015 1 1 $ tekha $
comment "rupak hindustani = 2 * misra chapu" $
korvaiS Tala.misra_chapu
[ sd $ i. __.i. __.n. __.od.__. n.__.od.__. n. __
, sd $ p&i.k.p&i.__.n.k .od.o&k.p&n.k.od.o&k.p&n.k
, sd $ od.__.k.od.__.k .od.o&k.p&n.k.od.o&k.p&n.k
, sd $ on.su (kt.o.k).on.on.su (kt.p.k).n.su (kt.p.k).on.on.su (kt.o.k)
]
c_2 :: Korvai
c_2 = akash $ date 2015 1 1 $ tekha $
korvaiS adi $ map (nadai 6 • sd)
[ r2 $ r2 (n.d.n.n.d.k) & (o.__.o.o.p.__ . __.__.o.o.__.__)
, r3 (on.ktpk.p&n.ktok) . on.p&n.__.on.p&n.__
]
where
ktpk = su (k.t.p.k)
ktok = su (k.t.o.k)
c_3 :: Korvai
c_3 = akash $ date 2015 1 1 $ tekha $ comment "14 beats" $
korvaiS Tala.misra_chapu
[ sd $ on.od.__.on.on.od.__.n.p&d.__.on.on.od.__
, sd $ r2 (n.d.l.n.l.d.l) & (o.__3.o.__.o.__.p.__3.o.__.o.__)
, sarvaD_ 5 . r2 (nadai 6 (n.p.kt.pk))
]
akash1 :: Korvai
akash1 = akash $ date 2015 1 1 $ korvaiS adi
[ r2 $ rh & "o__o_oo_" . rh & "p__p_p__"
, rh & "o__o_oo_" . su ktpk . "ndldnl" & "_p_p"
. fill . su ktpk . "ndldnl" & "_p_p"
]
where
fill = g $ od.k.k.od.k.k.od.__
rh = "dlndldnl"
akash :: Korvai -> Korvai
akash = source "akash"
tekha :: Korvai -> Korvai
tekha = withType "tekha"
|
52c4f960b7ac2b0efdd092754b651ccfaa3695c12207f2777f2c4a0fc4db8b44 | yaxu/embedded | diagram.hs | # LANGUAGE NoMonomorphismRestriction #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE TypeFamilies #-}
import qualified Diagrams.Prelude as D
import Diagrams.Backend.SVG.CmdLine
import Sound.Tidal.Context
-- or:
import Diagrams . Backend.xxx . CmdLine
-- where xxx is the backend you would like to use.
myCircle :: D.Diagram D.B
myCircle = D.circle 1
eff = (D.text "F" <> D.square 1) # D.fontSize (D.local 1)
let (##) = (D.#)
example :: D.Diagram D.B
example = D.hcat
[eff, eff ## D.scale 2, eff ## D.scaleX 2, eff ## D.scaleY 2, eff ## D.rotateBy (1/12)]
main = mainWith example
| null | https://raw.githubusercontent.com/yaxu/embedded/a6402576fe12fb8ec3f5974bbc2fff640f2f221c/tidal/diagram.hs | haskell | # LANGUAGE TypeFamilies #
or:
where xxx is the backend you would like to use. | # LANGUAGE NoMonomorphismRestriction #
# LANGUAGE FlexibleContexts #
import qualified Diagrams.Prelude as D
import Diagrams.Backend.SVG.CmdLine
import Sound.Tidal.Context
import Diagrams . Backend.xxx . CmdLine
myCircle :: D.Diagram D.B
myCircle = D.circle 1
eff = (D.text "F" <> D.square 1) # D.fontSize (D.local 1)
let (##) = (D.#)
example :: D.Diagram D.B
example = D.hcat
[eff, eff ## D.scale 2, eff ## D.scaleX 2, eff ## D.scaleY 2, eff ## D.rotateBy (1/12)]
main = mainWith example
|
4601bf417f9c626dec067ec556103352cc56cafd83053a5f2c502daac9efacdd | webnf/webnf | middleware.clj | (ns webnf.middleware
(:require
[webnf.base :refer [autoload]]
[clojure.tools.logging :as log]))
(autoload webnf.middleware.browser-http/wrap-browser-http)
(autoload webnf.middleware.pretty-exception/wrap-pretty-exception)
| null | https://raw.githubusercontent.com/webnf/webnf/6a2ccaa755e6e40528eb13a5c36bae16ba4947e7/handler/src/clj/webnf/middleware.clj | clojure | (ns webnf.middleware
(:require
[webnf.base :refer [autoload]]
[clojure.tools.logging :as log]))
(autoload webnf.middleware.browser-http/wrap-browser-http)
(autoload webnf.middleware.pretty-exception/wrap-pretty-exception)
| |
1720bcf3645ad4b13f56ee2fa423c760d86e34fe93ecb0e478aadcf87733a004 | gethop-dev/hop-cli | persistence.clj | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
;; file, You can obtain one at /
{{=<< >>=}}
(ns <<project.name>>.boundary.port.persistence)
;; (defprotocol SomeProtocolName
;; (some-method-name [db logger other-method-params...]))
| null | https://raw.githubusercontent.com/gethop-dev/hop-cli/c7b848915ff268aa41ff9a61a62c614f58ecbeb9/resources/bootstrap/profiles/persistence/sql/app/src/%7B%7Bproject.files-name%7D%7D/boundary/port/persistence.clj | clojure | file, You can obtain one at /
(defprotocol SomeProtocolName
(some-method-name [db logger other-method-params...])) | 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
{{=<< >>=}}
(ns <<project.name>>.boundary.port.persistence)
|
caea0f9fb1fabaf8eb1b78d9f27a1a1fc78c0dd15bf6871afddfc2b945024ddf | sirherrbatka/cl-progress-bar | docstrings.lisp | (in-package #:cl-progress-bar)
(docs:define-docs
:formatter docs.ext:rich-aggregating-formatter
(variable *progress-bar*
(:description "Current progress bar or NIL if there is no progress bar active. Should not be manipulated manually."))
(variable *progress-bar-enabled*
(:description "Boolean. T if progress bar should be outputed."))
(function with-progress-bar
(:description "Macro. Build active progress bar. Requires size and description that will be printed out to the REPL. If *progress-bar-endabled* is nil or there is another progress bar active already progress bar will not be shown."
:arguments-and-values ((steps-count "Total number of steps that are expected before finish is reached.")
(description "FORMAT formula that should be printed when starting process.")
(desc-args "Arguments to FORMAT, should be compatible with description formula."))
:notes "Because with-progress-bar handles cases where another progress-bar is active it is generally safe to nest code with this macro on call stack. However, top level with-progress-bar should contain correct steps-count."))
(function update
(:description "Notify progress bar about step completion."
:arguments-and-values ((unit-count "How many steps has been finished?")
(progress-bar "Instance of progress-bar. Usually should be left with default (namely: *progress-bar*)."))
:thread-safety "This function is thread safe.")))
| null | https://raw.githubusercontent.com/sirherrbatka/cl-progress-bar/9374170858663c8fe829e9fb5a29bd2cb48d95ae/src/docstrings.lisp | lisp | (in-package #:cl-progress-bar)
(docs:define-docs
:formatter docs.ext:rich-aggregating-formatter
(variable *progress-bar*
(:description "Current progress bar or NIL if there is no progress bar active. Should not be manipulated manually."))
(variable *progress-bar-enabled*
(:description "Boolean. T if progress bar should be outputed."))
(function with-progress-bar
(:description "Macro. Build active progress bar. Requires size and description that will be printed out to the REPL. If *progress-bar-endabled* is nil or there is another progress bar active already progress bar will not be shown."
:arguments-and-values ((steps-count "Total number of steps that are expected before finish is reached.")
(description "FORMAT formula that should be printed when starting process.")
(desc-args "Arguments to FORMAT, should be compatible with description formula."))
:notes "Because with-progress-bar handles cases where another progress-bar is active it is generally safe to nest code with this macro on call stack. However, top level with-progress-bar should contain correct steps-count."))
(function update
(:description "Notify progress bar about step completion."
:arguments-and-values ((unit-count "How many steps has been finished?")
(progress-bar "Instance of progress-bar. Usually should be left with default (namely: *progress-bar*)."))
:thread-safety "This function is thread safe.")))
| |
d40f441a6c3d63053a732ae4da6a8da4f9fee377a2eab78cf956c29b257a511b | issuu/ocaml-protoc-plugin | emit.ml | open StdLabels
open Parameters
open Spec.Descriptor.Google.Protobuf
module IntSet = Set.Make(struct type t = int let compare = compare end)
let sprintf = Printf.sprintf
(** Slightly overloaded name here.
Its also used for all other types which would go into a module *)
type module' = {
module_name : string;
signature : Code.t;
implementation : Code.t;
}
(* Enums are not mangled - Maybe they should be lowercased though. *)
let emit_enum_type ~scope ~params
EnumDescriptorProto.{name; value = values; options = _; reserved_range = _; reserved_name = _}
: module' =
let name = Option.value_exn ~message:"Enums must have a name" name in
let module_name = Scope.get_name scope name in
let signature = Code.init () in
let implementation = Code.init () in
let scope = Scope.push scope name in
let t = Code.init () in
Code.emit t `None "type t = %s %s"
(List.map ~f:(fun EnumValueDescriptorProto.{name; _} -> Scope.get_name_exn scope name) values
|> String.concat ~sep:" | "
)
params.Parameters.annot;
Code.append signature t;
Code.append implementation t;
Code.emit signature `None "val to_int: t -> int";
Code.emit signature `None "val from_int: int -> (t, [> Runtime'.Result.error]) result";
Code.emit implementation `Begin "let to_int = function";
List.iter ~f:(fun EnumValueDescriptorProto.{name; number; _} ->
Code.emit implementation `None "| %s -> %d" (Scope.get_name_exn scope name) (Option.value_exn number)
) values;
Code.emit implementation `End "";
Code.emit implementation `Begin "let from_int = function";
let _ =
List.fold_left ~init:IntSet.empty ~f:(fun seen EnumValueDescriptorProto.{name; number; _} ->
let idx = (Option.value_exn ~message:"All enum descriptions must have a value" number) in
match IntSet.mem idx seen with
| true -> seen
| false ->
Code.emit implementation `None "| %d -> Ok %s" idx (Scope.get_name_exn scope name);
IntSet.add idx seen
) values
in
Code.emit implementation `None "| n -> Error (`Unknown_enum_value n)";
Code.emit implementation `End "";
{module_name; signature; implementation}
let emit_service_type scope ServiceDescriptorProto.{ name; method' = methods; _ } =
let emit_method t local_scope scope MethodDescriptorProto.{ name; input_type; output_type; _} =
let name = Option.value_exn name in
let uncapitalized_name = String.uncapitalize_ascii name |> Scope.Local.get_unique_name local_scope in
(* To keep symmetry, only ensure that lowercased names are unique
so that the upper case names are aswell. We should remove this
mapping if/when we deprecate the old API *)
let capitalized_name = String.capitalize_ascii uncapitalized_name in
let service_name = Scope.get_proto_path scope in
let input = Scope.get_scoped_name scope input_type in
let input_t = Scope.get_scoped_name scope ~postfix:"t" input_type in
let output = Scope.get_scoped_name scope output_type in
let output_t = Scope.get_scoped_name scope ~postfix:"t" output_type in
Code.emit t `Begin "module %s = struct" capitalized_name;
Code.emit t `None "let name = \"/%s/%s\"" service_name name;
Code.emit t `None "module Request = %s" input;
Code.emit t `None "module Response = %s" output;
Code.emit t `End "end";
Code.emit t `Begin "let %s = " uncapitalized_name;
Code.emit t `None "(module %s : Runtime'.Service.Message with type t = %s ), "
input
input_t;
Code.emit t `None "(module %s : Runtime'.Service.Message with type t = %s )"
output
output_t;
Code.emit t `End "";
()
in
let name = Option.value_exn ~message:"Service definitions must have a name" name in
let t = Code.init () in
Code.emit t `Begin "module %s = struct" (Scope.get_name scope name);
let local_scope = Scope.Local.init () in
List.iter ~f:(emit_method t local_scope (Scope.push scope name)) methods;
Code.emit t `End "end";
t
let emit_extension ~scope ~params field =
let FieldDescriptorProto.{ name; extendee; _ } = field in
let name = Option.value_exn ~message:"Extensions must have a name" name in
let module_name = (Scope.get_name scope name) in
let extendee_type = Scope.get_scoped_name scope ~postfix:"t" extendee in
let extendee_field = Scope.get_scoped_name scope ~postfix:"extensions'" extendee in
(* Create the type of the type' / type_name *)
let t =
let params = Parameters.{params with singleton_record = false} in
Types.make ~params ~syntax:`Proto2 ~is_cyclic:false ~scope ~is_map_entry:false ~has_extensions:false ~fields:[field] []
in
let signature = Code.init () in
let implementation = Code.init () in
Code.append implementation signature;
Code.emit signature `None "type t = %s %s" t.type' params.annot;
Code.emit signature `None "val get: %s -> (%s, [> Runtime'.Result.error]) result" extendee_type t.type';
Code.emit signature `None "val set: %s -> %s -> %s" extendee_type t.type' extendee_type;
Code.emit implementation `None "type t = %s %s" t.type' params.annot;
Code.emit implementation `None "let get extendee = Runtime'.Extensions.get %s (extendee.%s) |> Runtime'.Result.open_error" t.deserialize_spec extendee_field ;
Code.emit implementation `Begin "let set extendee t =";
Code.emit implementation `None "let extensions' = Runtime'.Extensions.set (%s) (extendee.%s) t in" t.serialize_spec extendee_field;
Code.emit implementation `None "{ extendee with %s = extensions' }" extendee_field;
Code.emit implementation `End "";
{ module_name; signature; implementation }
let is_map_entry = function
| Some MessageOptions.{ map_entry = Some true; _ } -> true
| _ -> false
(** Emit the nested types. *)
let emit_sub dest ~is_implementation ~is_first {module_name; signature; implementation} =
let () =
match is_first with
| true -> Code.emit dest `Begin "module rec %s : sig" module_name
| false -> Code.emit dest `Begin "and %s : sig" module_name
in
Code.append dest signature;
let () =
match is_implementation with
| false -> ()
| true ->
Code.emit dest `EndBegin "end = struct ";
Code.append dest implementation
in
Code.emit dest `End "end";
()
let rec emit_nested_types ~syntax ~signature ~implementation ?(is_first = true) nested_types =
match nested_types with
| [] -> ()
| sub :: subs ->
emit_sub ~is_implementation:false signature ~is_first sub;
emit_sub ~is_implementation:true implementation ~is_first sub;
emit_nested_types ~syntax ~signature ~implementation ~is_first:false subs
(* Emit a message plus all its subtypes.
Why is this not being called recursively, but rather calling sub functions which never returns
*)
let rec emit_message ~params ~syntax scope
DescriptorProto.{ name; field = fields; extension = extensions;
nested_type = nested_types; enum_type = enum_types;
extension_range = extension_ranges; oneof_decl = oneof_decls; options;
reserved_range = _; reserved_name = _ } : module' =
let signature = Code.init () in
let implementation = Code.init () in
let has_extensions = not (extension_ranges = []) in
(* Ignore empty modules *)
let module_name, scope =
match name with
| None -> "", scope
| Some name ->
let module_name = Scope.get_name scope name in
module_name, Scope.push scope name
in
List.map ~f:(emit_enum_type ~scope ~params) enum_types
@ List.map ~f:(emit_message ~params ~syntax scope) nested_types
@ List.map ~f:(emit_extension ~scope ~params) extensions
|> emit_nested_types ~syntax ~signature ~implementation;
let () =
match name with
| Some _name ->
let is_map_entry = is_map_entry options in
let is_cyclic = Scope.is_cyclic scope in
let extension_ranges =
extension_ranges
|> List.map ~f:(function
| DescriptorProto.ExtensionRange.{ start = Some start; end' = Some end'; _ } -> (start, end')
| _ -> failwith "Extension ranges must be defined"
)
|> List.map ~f:(fun (s, e) -> sprintf "(%d, %d)" s e)
|> String.concat ~sep:"; "
|> sprintf "[%s]"
in
let Types.{ type'; constructor; apply; deserialize_spec; serialize_spec; default_constructor_sig; default_constructor_impl } =
Types.make ~params ~syntax ~is_cyclic ~is_map_entry ~has_extensions ~scope ~fields oneof_decls
in
ignore (default_constructor_sig, default_constructor_impl);
Code.emit signature `None "val name': unit -> string";
Code.emit signature `None "type t = %s %s" type' params.annot;
Code.emit signature `None "val make : %s" default_constructor_sig;
Code.emit signature `None "val to_proto: t -> Runtime'.Writer.t";
Code.emit signature `None "val from_proto: Runtime'.Reader.t -> (t, [> Runtime'.Result.error]) result";
Code.emit implementation `None "let name' () = \"%s\"" (Scope.get_current_scope scope);
Code.emit implementation `None "type t = %s%s" type' params.annot;
Code.emit implementation `Begin "let make =";
Code.emit implementation `None "%s" default_constructor_impl;
Code.emit implementation `End "";
Code.emit implementation `Begin "let to_proto =";
Code.emit implementation `None "let apply = %s in" apply;
Code.emit implementation `None "let spec = %s in" serialize_spec;
Code.emit implementation `None "let serialize = Runtime'.Serialize.serialize %s (spec) in" extension_ranges;
Code.emit implementation `None "fun t -> apply ~f:serialize t";
Code.emit implementation `End "";
Code.emit implementation `Begin "let from_proto =";
Code.emit implementation `None "let constructor = %s in" constructor;
Code.emit implementation `None "let spec = %s in" deserialize_spec;
Code.emit implementation `None "let deserialize = Runtime'.Deserialize.deserialize %s spec constructor in" extension_ranges;
Code.emit implementation `None "fun writer -> deserialize writer |> Runtime'.Result.open_error";
Code.emit implementation `End "";
| None -> ()
in
{module_name; signature; implementation}
let rec wrap_packages ~params ~syntax scope message_type services = function
| [] ->
let {module_name = _; implementation; _} = emit_message ~params ~syntax scope message_type in
List.iter ~f:(fun service ->
Code.append implementation (emit_service_type scope service)
) services;
implementation
| package :: packages ->
let implementation = Code.init () in
let package_name = Scope.get_name scope package in
let scope = Scope.push scope package in
Code.emit implementation `Begin "module %s = struct" package_name;
Code.append implementation (wrap_packages ~params ~syntax scope message_type services packages);
Code.emit implementation `End "end";
implementation
let parse_proto_file ~params scope
FileDescriptorProto.{ name; package; dependency = dependencies; public_dependency = _;
weak_dependency = _; message_type = message_types;
enum_type = enum_types; service = services; extension;
options = _; source_code_info = _; syntax; }
=
let name = Option.value_exn ~message:"All files must have a name" name |> String.map ~f:(function '-' -> '_' | c -> c) in
let syntax = match syntax with
| None | Some "proto2" -> `Proto2
| Some "proto3" -> `Proto3
| _ -> failwith "Unsupported syntax"
in
let message_type =
DescriptorProto.{name = None; nested_type=message_types; enum_type = enum_types;
field = []; extension; extension_range = []; oneof_decl = [];
options = None; reserved_range = []; reserved_name = []; }
in
let implementation = Code.init () in
Code.emit implementation `None "(************************************************)";
Code.emit implementation `None "(* AUTOGENERATED FILE - DO NOT EDIT! *)";
Code.emit implementation `None "(************************************************)";
Code.emit implementation `None "(* Generated by: ocaml-protoc-plugin *)";
Code.emit implementation `None "(* -protoc-plugin *)";
Code.emit implementation `None "(************************************************)";
Code.emit implementation `None "(*";
Code.emit implementation `None " Source: %s" name;
Code.emit implementation `None " Syntax: %s" (match syntax with `Proto2 -> "proto2" | `Proto3 -> "proto3");
Code.emit implementation `None " Parameters:";
Code.emit implementation `None " debug=%b" params.debug;
Code.emit implementation `None " annot='%s'" params.annot;
Code.emit implementation `None " opens=[%s]" (String.concat ~sep:"; " params.opens);
Code.emit implementation `None " int64_as_int=%b" params.int64_as_int;
Code.emit implementation `None " int32_as_int=%b" params.int32_as_int;
Code.emit implementation `None " fixed_as_int=%b" params.fixed_as_int;
Code.emit implementation `None " singleton_record=%b" params.singleton_record;
Code.emit implementation `None "*)";
Code.emit implementation `None "";
Code.emit implementation `None "open Ocaml_protoc_plugin.Runtime [@@warning \"-33\"]";
List.iter ~f:(Code.emit implementation `None "open %s [@@warning \"-33\"]" ) params.opens;
let _ = match dependencies with
| [] -> ()
| dependencies ->
Code.emit implementation `None "(**/**)";
Code.emit implementation `Begin "module %s = struct" Scope.import_module_name;
List.iter ~f:(fun proto_file ->
let module_name = Scope.module_name_of_proto proto_file in
Code.emit implementation `None "module %s = %s" module_name module_name;
) dependencies;
Code.emit implementation `End "end";
Code.emit implementation `None "(**/**)";
in
wrap_packages ~params ~syntax scope message_type services (Option.value_map ~default:[] ~f:(String.split_on_char ~sep:'.') package)
|> Code.append implementation;
let out_name =
Filename.remove_extension name
|> sprintf "%s.ml"
in
out_name, implementation
| null | https://raw.githubusercontent.com/issuu/ocaml-protoc-plugin/2dd1706f08847e12b91ca4b175ddb4fd527fb20c/src/plugin/emit.ml | ocaml | * Slightly overloaded name here.
Its also used for all other types which would go into a module
Enums are not mangled - Maybe they should be lowercased though.
To keep symmetry, only ensure that lowercased names are unique
so that the upper case names are aswell. We should remove this
mapping if/when we deprecate the old API
Create the type of the type' / type_name
* Emit the nested types.
Emit a message plus all its subtypes.
Why is this not being called recursively, but rather calling sub functions which never returns
Ignore empty modules | open StdLabels
open Parameters
open Spec.Descriptor.Google.Protobuf
module IntSet = Set.Make(struct type t = int let compare = compare end)
let sprintf = Printf.sprintf
type module' = {
module_name : string;
signature : Code.t;
implementation : Code.t;
}
let emit_enum_type ~scope ~params
EnumDescriptorProto.{name; value = values; options = _; reserved_range = _; reserved_name = _}
: module' =
let name = Option.value_exn ~message:"Enums must have a name" name in
let module_name = Scope.get_name scope name in
let signature = Code.init () in
let implementation = Code.init () in
let scope = Scope.push scope name in
let t = Code.init () in
Code.emit t `None "type t = %s %s"
(List.map ~f:(fun EnumValueDescriptorProto.{name; _} -> Scope.get_name_exn scope name) values
|> String.concat ~sep:" | "
)
params.Parameters.annot;
Code.append signature t;
Code.append implementation t;
Code.emit signature `None "val to_int: t -> int";
Code.emit signature `None "val from_int: int -> (t, [> Runtime'.Result.error]) result";
Code.emit implementation `Begin "let to_int = function";
List.iter ~f:(fun EnumValueDescriptorProto.{name; number; _} ->
Code.emit implementation `None "| %s -> %d" (Scope.get_name_exn scope name) (Option.value_exn number)
) values;
Code.emit implementation `End "";
Code.emit implementation `Begin "let from_int = function";
let _ =
List.fold_left ~init:IntSet.empty ~f:(fun seen EnumValueDescriptorProto.{name; number; _} ->
let idx = (Option.value_exn ~message:"All enum descriptions must have a value" number) in
match IntSet.mem idx seen with
| true -> seen
| false ->
Code.emit implementation `None "| %d -> Ok %s" idx (Scope.get_name_exn scope name);
IntSet.add idx seen
) values
in
Code.emit implementation `None "| n -> Error (`Unknown_enum_value n)";
Code.emit implementation `End "";
{module_name; signature; implementation}
let emit_service_type scope ServiceDescriptorProto.{ name; method' = methods; _ } =
let emit_method t local_scope scope MethodDescriptorProto.{ name; input_type; output_type; _} =
let name = Option.value_exn name in
let uncapitalized_name = String.uncapitalize_ascii name |> Scope.Local.get_unique_name local_scope in
let capitalized_name = String.capitalize_ascii uncapitalized_name in
let service_name = Scope.get_proto_path scope in
let input = Scope.get_scoped_name scope input_type in
let input_t = Scope.get_scoped_name scope ~postfix:"t" input_type in
let output = Scope.get_scoped_name scope output_type in
let output_t = Scope.get_scoped_name scope ~postfix:"t" output_type in
Code.emit t `Begin "module %s = struct" capitalized_name;
Code.emit t `None "let name = \"/%s/%s\"" service_name name;
Code.emit t `None "module Request = %s" input;
Code.emit t `None "module Response = %s" output;
Code.emit t `End "end";
Code.emit t `Begin "let %s = " uncapitalized_name;
Code.emit t `None "(module %s : Runtime'.Service.Message with type t = %s ), "
input
input_t;
Code.emit t `None "(module %s : Runtime'.Service.Message with type t = %s )"
output
output_t;
Code.emit t `End "";
()
in
let name = Option.value_exn ~message:"Service definitions must have a name" name in
let t = Code.init () in
Code.emit t `Begin "module %s = struct" (Scope.get_name scope name);
let local_scope = Scope.Local.init () in
List.iter ~f:(emit_method t local_scope (Scope.push scope name)) methods;
Code.emit t `End "end";
t
let emit_extension ~scope ~params field =
let FieldDescriptorProto.{ name; extendee; _ } = field in
let name = Option.value_exn ~message:"Extensions must have a name" name in
let module_name = (Scope.get_name scope name) in
let extendee_type = Scope.get_scoped_name scope ~postfix:"t" extendee in
let extendee_field = Scope.get_scoped_name scope ~postfix:"extensions'" extendee in
let t =
let params = Parameters.{params with singleton_record = false} in
Types.make ~params ~syntax:`Proto2 ~is_cyclic:false ~scope ~is_map_entry:false ~has_extensions:false ~fields:[field] []
in
let signature = Code.init () in
let implementation = Code.init () in
Code.append implementation signature;
Code.emit signature `None "type t = %s %s" t.type' params.annot;
Code.emit signature `None "val get: %s -> (%s, [> Runtime'.Result.error]) result" extendee_type t.type';
Code.emit signature `None "val set: %s -> %s -> %s" extendee_type t.type' extendee_type;
Code.emit implementation `None "type t = %s %s" t.type' params.annot;
Code.emit implementation `None "let get extendee = Runtime'.Extensions.get %s (extendee.%s) |> Runtime'.Result.open_error" t.deserialize_spec extendee_field ;
Code.emit implementation `Begin "let set extendee t =";
Code.emit implementation `None "let extensions' = Runtime'.Extensions.set (%s) (extendee.%s) t in" t.serialize_spec extendee_field;
Code.emit implementation `None "{ extendee with %s = extensions' }" extendee_field;
Code.emit implementation `End "";
{ module_name; signature; implementation }
let is_map_entry = function
| Some MessageOptions.{ map_entry = Some true; _ } -> true
| _ -> false
let emit_sub dest ~is_implementation ~is_first {module_name; signature; implementation} =
let () =
match is_first with
| true -> Code.emit dest `Begin "module rec %s : sig" module_name
| false -> Code.emit dest `Begin "and %s : sig" module_name
in
Code.append dest signature;
let () =
match is_implementation with
| false -> ()
| true ->
Code.emit dest `EndBegin "end = struct ";
Code.append dest implementation
in
Code.emit dest `End "end";
()
let rec emit_nested_types ~syntax ~signature ~implementation ?(is_first = true) nested_types =
match nested_types with
| [] -> ()
| sub :: subs ->
emit_sub ~is_implementation:false signature ~is_first sub;
emit_sub ~is_implementation:true implementation ~is_first sub;
emit_nested_types ~syntax ~signature ~implementation ~is_first:false subs
let rec emit_message ~params ~syntax scope
DescriptorProto.{ name; field = fields; extension = extensions;
nested_type = nested_types; enum_type = enum_types;
extension_range = extension_ranges; oneof_decl = oneof_decls; options;
reserved_range = _; reserved_name = _ } : module' =
let signature = Code.init () in
let implementation = Code.init () in
let has_extensions = not (extension_ranges = []) in
let module_name, scope =
match name with
| None -> "", scope
| Some name ->
let module_name = Scope.get_name scope name in
module_name, Scope.push scope name
in
List.map ~f:(emit_enum_type ~scope ~params) enum_types
@ List.map ~f:(emit_message ~params ~syntax scope) nested_types
@ List.map ~f:(emit_extension ~scope ~params) extensions
|> emit_nested_types ~syntax ~signature ~implementation;
let () =
match name with
| Some _name ->
let is_map_entry = is_map_entry options in
let is_cyclic = Scope.is_cyclic scope in
let extension_ranges =
extension_ranges
|> List.map ~f:(function
| DescriptorProto.ExtensionRange.{ start = Some start; end' = Some end'; _ } -> (start, end')
| _ -> failwith "Extension ranges must be defined"
)
|> List.map ~f:(fun (s, e) -> sprintf "(%d, %d)" s e)
|> String.concat ~sep:"; "
|> sprintf "[%s]"
in
let Types.{ type'; constructor; apply; deserialize_spec; serialize_spec; default_constructor_sig; default_constructor_impl } =
Types.make ~params ~syntax ~is_cyclic ~is_map_entry ~has_extensions ~scope ~fields oneof_decls
in
ignore (default_constructor_sig, default_constructor_impl);
Code.emit signature `None "val name': unit -> string";
Code.emit signature `None "type t = %s %s" type' params.annot;
Code.emit signature `None "val make : %s" default_constructor_sig;
Code.emit signature `None "val to_proto: t -> Runtime'.Writer.t";
Code.emit signature `None "val from_proto: Runtime'.Reader.t -> (t, [> Runtime'.Result.error]) result";
Code.emit implementation `None "let name' () = \"%s\"" (Scope.get_current_scope scope);
Code.emit implementation `None "type t = %s%s" type' params.annot;
Code.emit implementation `Begin "let make =";
Code.emit implementation `None "%s" default_constructor_impl;
Code.emit implementation `End "";
Code.emit implementation `Begin "let to_proto =";
Code.emit implementation `None "let apply = %s in" apply;
Code.emit implementation `None "let spec = %s in" serialize_spec;
Code.emit implementation `None "let serialize = Runtime'.Serialize.serialize %s (spec) in" extension_ranges;
Code.emit implementation `None "fun t -> apply ~f:serialize t";
Code.emit implementation `End "";
Code.emit implementation `Begin "let from_proto =";
Code.emit implementation `None "let constructor = %s in" constructor;
Code.emit implementation `None "let spec = %s in" deserialize_spec;
Code.emit implementation `None "let deserialize = Runtime'.Deserialize.deserialize %s spec constructor in" extension_ranges;
Code.emit implementation `None "fun writer -> deserialize writer |> Runtime'.Result.open_error";
Code.emit implementation `End "";
| None -> ()
in
{module_name; signature; implementation}
let rec wrap_packages ~params ~syntax scope message_type services = function
| [] ->
let {module_name = _; implementation; _} = emit_message ~params ~syntax scope message_type in
List.iter ~f:(fun service ->
Code.append implementation (emit_service_type scope service)
) services;
implementation
| package :: packages ->
let implementation = Code.init () in
let package_name = Scope.get_name scope package in
let scope = Scope.push scope package in
Code.emit implementation `Begin "module %s = struct" package_name;
Code.append implementation (wrap_packages ~params ~syntax scope message_type services packages);
Code.emit implementation `End "end";
implementation
let parse_proto_file ~params scope
FileDescriptorProto.{ name; package; dependency = dependencies; public_dependency = _;
weak_dependency = _; message_type = message_types;
enum_type = enum_types; service = services; extension;
options = _; source_code_info = _; syntax; }
=
let name = Option.value_exn ~message:"All files must have a name" name |> String.map ~f:(function '-' -> '_' | c -> c) in
let syntax = match syntax with
| None | Some "proto2" -> `Proto2
| Some "proto3" -> `Proto3
| _ -> failwith "Unsupported syntax"
in
let message_type =
DescriptorProto.{name = None; nested_type=message_types; enum_type = enum_types;
field = []; extension; extension_range = []; oneof_decl = [];
options = None; reserved_range = []; reserved_name = []; }
in
let implementation = Code.init () in
Code.emit implementation `None "(************************************************)";
Code.emit implementation `None "(* AUTOGENERATED FILE - DO NOT EDIT! *)";
Code.emit implementation `None "(************************************************)";
Code.emit implementation `None "(* Generated by: ocaml-protoc-plugin *)";
Code.emit implementation `None "(* -protoc-plugin *)";
Code.emit implementation `None "(************************************************)";
Code.emit implementation `None "(*";
Code.emit implementation `None " Source: %s" name;
Code.emit implementation `None " Syntax: %s" (match syntax with `Proto2 -> "proto2" | `Proto3 -> "proto3");
Code.emit implementation `None " Parameters:";
Code.emit implementation `None " debug=%b" params.debug;
Code.emit implementation `None " annot='%s'" params.annot;
Code.emit implementation `None " opens=[%s]" (String.concat ~sep:"; " params.opens);
Code.emit implementation `None " int64_as_int=%b" params.int64_as_int;
Code.emit implementation `None " int32_as_int=%b" params.int32_as_int;
Code.emit implementation `None " fixed_as_int=%b" params.fixed_as_int;
Code.emit implementation `None " singleton_record=%b" params.singleton_record;
Code.emit implementation `None "*)";
Code.emit implementation `None "";
Code.emit implementation `None "open Ocaml_protoc_plugin.Runtime [@@warning \"-33\"]";
List.iter ~f:(Code.emit implementation `None "open %s [@@warning \"-33\"]" ) params.opens;
let _ = match dependencies with
| [] -> ()
| dependencies ->
Code.emit implementation `None "(**/**)";
Code.emit implementation `Begin "module %s = struct" Scope.import_module_name;
List.iter ~f:(fun proto_file ->
let module_name = Scope.module_name_of_proto proto_file in
Code.emit implementation `None "module %s = %s" module_name module_name;
) dependencies;
Code.emit implementation `End "end";
Code.emit implementation `None "(**/**)";
in
wrap_packages ~params ~syntax scope message_type services (Option.value_map ~default:[] ~f:(String.split_on_char ~sep:'.') package)
|> Code.append implementation;
let out_name =
Filename.remove_extension name
|> sprintf "%s.ml"
in
out_name, implementation
|
57896d39b2a84bc0dbea12f9c95f2d65ad3ffdd68b9a36ec44a9e8b397eeec5f | MaximilianAlgehed/VisPar | Tiny.hs | import VisPar
import Control.DeepSeq
example :: Par Int
example = do
ivar <- new
fork (put ivar 5)
get ivar
main :: IO ()
main = do
print $ runPar example
g <- visPar Complete "0" example
saveGraphPdf Vertical "tiny.graph.pdf" g
| null | https://raw.githubusercontent.com/MaximilianAlgehed/VisPar/c63fc5bdaf6325158e85eb1602c7a87c66bb8d9a/examples/Tiny.hs | haskell | import VisPar
import Control.DeepSeq
example :: Par Int
example = do
ivar <- new
fork (put ivar 5)
get ivar
main :: IO ()
main = do
print $ runPar example
g <- visPar Complete "0" example
saveGraphPdf Vertical "tiny.graph.pdf" g
| |
25cc3c2a46fd9b3991082fe7b8fced146ae23b07484ac8d4ac5e3b89b8ea67b3 | dwayne/eopl3 | translator.rkt | #lang eopl
(require "./parser.rkt")
(require "./senv.rkt")
(provide
Translator
translate)
(define (translate prog)
(let ([init-senv (extend-senv
'i
(extend-senv
'v
(extend-senv
'x
(empty-senv))))])
(cases program prog
[a-program (exp) (a-program (translate-exp exp init-senv))])))
(define (translate-exp exp senv)
(cases expression exp
[const-exp (n)
(const-exp n)]
[var-exp (var)
(nameless-var-exp
(apply-senv senv var))]
[diff-exp (exp1 exp2)
(diff-exp (translate-exp exp1 senv)
(translate-exp exp2 senv))]
[zero?-exp (exp1)
(zero?-exp (translate-exp exp1 senv))]
[if-exp (exp1 exp2 exp3)
(if-exp (translate-exp exp1 senv)
(translate-exp exp2 senv)
(translate-exp exp3 senv))]
[cond-exp (conds exps)
(cond-exp (translate-exps conds senv)
(translate-exps exps senv))]
[let-exp (var exp1 body)
(nameless-let-exp
(translate-exp exp1 senv)
(translate-exp body (extend-senv var senv)))]
[proc-exp (var body)
(nameless-proc-exp
(translate-exp body (extend-senv var senv)))]
[call-exp (rator rand)
(call-exp (translate-exp rator senv)
(translate-exp rand senv))]
[else
(eopl:error 'translate-exp "Invalid source expression: ~s" exp)]))
(define (translate-exps exps senv)
(map (lambda (exp1) (translate-exp exp1 senv)) exps))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/03-ch3/interpreters/racket/NAMELESS-PROC-3.38/translator.rkt | racket | #lang eopl
(require "./parser.rkt")
(require "./senv.rkt")
(provide
Translator
translate)
(define (translate prog)
(let ([init-senv (extend-senv
'i
(extend-senv
'v
(extend-senv
'x
(empty-senv))))])
(cases program prog
[a-program (exp) (a-program (translate-exp exp init-senv))])))
(define (translate-exp exp senv)
(cases expression exp
[const-exp (n)
(const-exp n)]
[var-exp (var)
(nameless-var-exp
(apply-senv senv var))]
[diff-exp (exp1 exp2)
(diff-exp (translate-exp exp1 senv)
(translate-exp exp2 senv))]
[zero?-exp (exp1)
(zero?-exp (translate-exp exp1 senv))]
[if-exp (exp1 exp2 exp3)
(if-exp (translate-exp exp1 senv)
(translate-exp exp2 senv)
(translate-exp exp3 senv))]
[cond-exp (conds exps)
(cond-exp (translate-exps conds senv)
(translate-exps exps senv))]
[let-exp (var exp1 body)
(nameless-let-exp
(translate-exp exp1 senv)
(translate-exp body (extend-senv var senv)))]
[proc-exp (var body)
(nameless-proc-exp
(translate-exp body (extend-senv var senv)))]
[call-exp (rator rand)
(call-exp (translate-exp rator senv)
(translate-exp rand senv))]
[else
(eopl:error 'translate-exp "Invalid source expression: ~s" exp)]))
(define (translate-exps exps senv)
(map (lambda (exp1) (translate-exp exp1 senv)) exps))
| |
ab28ce8516a857b357e9fc93a1b8a895fbe209d8d79a0a04d504d435175c4c25 | f-me/carma-public | ContractGenerator.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE QuasiQuotes #
-- Allowed fields
-- VIN | car_vin
|
Марка | car_make
Модель | car_model
ФИО владельца карты | cardnumber_cardowner
Номер карты | cardnumber_cardnumber
ФИО менеджера | cardnumber_manager
-- Дата регистрации в программе | cardnumber_validfrom
Программа действует до ( Дата ) | cardnumber_validuntil
-- Межсервисный интервал | cardnumber_serviceinterval
-- Дата начала гарантии | car_warrantystart
-- Дата покупки | car_buydate
-- Дата первой продажи | car_firstsaledate
, продавший автомобиль | car_seller
Заказчик
Адрес заказчика
module AppHandlers.ContractGenerator where
import BasicPrelude
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.ByteString.Lazy as B (toStrict)
import Data.Aeson as Aeson
import System.FilePath
import System.Process.ByteString
import System.Exit (ExitCode(..))
import Snap
import Snap.Snaplet.PostgresqlSimple
import Database.PostgreSQL.Simple.SqlQQ
import Application
import AppHandlers.Util
import Snaplet.FileUpload
q :: Query
q = [sql|
SELECT
c.vin
, s.name
, carMake.label
, carModel.label
, plateNum
, to_char(c.buyDate, 'DD/MM/YYYY')
, to_char(c.firstSaleDate, 'DD/MM/YYYY')
, cardNumber::text
, to_char(c.validSince, 'DD/MM/YYYY')
, to_char(c.validUntil, 'DD/MM/YYYY')
, (c.startMileage + c.checkPeriod)::text
, c.startMileage::text
, c.checkPeriod::text
, c.name
, c.managerName
, to_char(c.validSince, 'DD/MM/YYYY')
, client, clientCode, clientAddress
, u.realName
, spgm.label
, pgm.label
FROM "Contract" c
INNER JOIN "SubProgram" spgm ON c.subprogram = spgm.id
INNER JOIN "Program" pgm ON spgm.parent = pgm.id
LEFT JOIN "CarMake" carMake ON carMake.id = make
LEFT JOIN "CarModel" carModel ON carModel.id = model
LEFT JOIN usermetatbl u ON u.id = c.committer
LEFT JOIN partnertbl s ON s.id = seller
WHERE c.id = ?
|]
fields :: [Text]
fields = [ "car_vin"
, "car_seller"
, "car_make"
, "car_model"
, "car_platenum"
, "car_buydate"
, "car_firstsaledate"
, "cardnumber_cardnumber"
, "cardnumber_validfrom"
, "cardnumber_validuntil"
, "cardnumber_validuntilmilage"
, "cardnumber_milageto"
, "cardnumber_serviceinterval"
, "cardnumber_cardowner"
, "cardnumber_manager"
, "car_warrantystart"
, "client"
, "clientCode"
, "clientAddress"
, "owner"
, "subprogram"
, "program"
]
renderContractHandler :: AppHandler ()
renderContractHandler = do
Just contractId <- getParamT "contract"
aids <- query
[sql|
SELECT a.id
FROM attachmenttbl a, "SubProgram" s, "Contract" c
WHERE s.template=concat('Attachment:', a.id)
AND c.subprogram = s.id
AND c.id = ?
|]
[contractId]
case aids of
(Only aid:_) -> do
tplPath <- with fileUpload $ getAttachmentPath aid
contracts <- query q [contractId]
case contracts of
(row:_) -> do
let [m] = mkMap fields [row]
tplFName = takeFileName tplPath
f = T.encodeUtf8
$ T.pack
$ concat ["attachment; filename=\"", tplFName, "\""]
(e, out, err) <- liftIO
$ readProcessWithExitCode "fill-pdf.sh" [tplPath, "-"]
$ B.toStrict $ Aeson.encode m
case e of
ExitSuccess -> do
modifyResponse $ setHeader "Content-Disposition" f
writeBS out
ExitFailure _ -> writeBS err
[] -> error "No contract selected (bad id or broken contract data)"
[] -> error "No template attached to subprogram or bad contract id"
| null | https://raw.githubusercontent.com/f-me/carma-public/82a9f44f7d919e54daa4114aa08dfec58b01009b/srv/src/AppHandlers/ContractGenerator.hs | haskell | Allowed fields
VIN | car_vin
Дата регистрации в программе | cardnumber_validfrom
Межсервисный интервал | cardnumber_serviceinterval
Дата начала гарантии | car_warrantystart
Дата покупки | car_buydate
Дата первой продажи | car_firstsaledate | # LANGUAGE NoImplicitPrelude #
# LANGUAGE QuasiQuotes #
|
Марка | car_make
Модель | car_model
ФИО владельца карты | cardnumber_cardowner
Номер карты | cardnumber_cardnumber
ФИО менеджера | cardnumber_manager
Программа действует до ( Дата ) | cardnumber_validuntil
, продавший автомобиль | car_seller
Заказчик
Адрес заказчика
module AppHandlers.ContractGenerator where
import BasicPrelude
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.ByteString.Lazy as B (toStrict)
import Data.Aeson as Aeson
import System.FilePath
import System.Process.ByteString
import System.Exit (ExitCode(..))
import Snap
import Snap.Snaplet.PostgresqlSimple
import Database.PostgreSQL.Simple.SqlQQ
import Application
import AppHandlers.Util
import Snaplet.FileUpload
q :: Query
q = [sql|
SELECT
c.vin
, s.name
, carMake.label
, carModel.label
, plateNum
, to_char(c.buyDate, 'DD/MM/YYYY')
, to_char(c.firstSaleDate, 'DD/MM/YYYY')
, cardNumber::text
, to_char(c.validSince, 'DD/MM/YYYY')
, to_char(c.validUntil, 'DD/MM/YYYY')
, (c.startMileage + c.checkPeriod)::text
, c.startMileage::text
, c.checkPeriod::text
, c.name
, c.managerName
, to_char(c.validSince, 'DD/MM/YYYY')
, client, clientCode, clientAddress
, u.realName
, spgm.label
, pgm.label
FROM "Contract" c
INNER JOIN "SubProgram" spgm ON c.subprogram = spgm.id
INNER JOIN "Program" pgm ON spgm.parent = pgm.id
LEFT JOIN "CarMake" carMake ON carMake.id = make
LEFT JOIN "CarModel" carModel ON carModel.id = model
LEFT JOIN usermetatbl u ON u.id = c.committer
LEFT JOIN partnertbl s ON s.id = seller
WHERE c.id = ?
|]
fields :: [Text]
fields = [ "car_vin"
, "car_seller"
, "car_make"
, "car_model"
, "car_platenum"
, "car_buydate"
, "car_firstsaledate"
, "cardnumber_cardnumber"
, "cardnumber_validfrom"
, "cardnumber_validuntil"
, "cardnumber_validuntilmilage"
, "cardnumber_milageto"
, "cardnumber_serviceinterval"
, "cardnumber_cardowner"
, "cardnumber_manager"
, "car_warrantystart"
, "client"
, "clientCode"
, "clientAddress"
, "owner"
, "subprogram"
, "program"
]
renderContractHandler :: AppHandler ()
renderContractHandler = do
Just contractId <- getParamT "contract"
aids <- query
[sql|
SELECT a.id
FROM attachmenttbl a, "SubProgram" s, "Contract" c
WHERE s.template=concat('Attachment:', a.id)
AND c.subprogram = s.id
AND c.id = ?
|]
[contractId]
case aids of
(Only aid:_) -> do
tplPath <- with fileUpload $ getAttachmentPath aid
contracts <- query q [contractId]
case contracts of
(row:_) -> do
let [m] = mkMap fields [row]
tplFName = takeFileName tplPath
f = T.encodeUtf8
$ T.pack
$ concat ["attachment; filename=\"", tplFName, "\""]
(e, out, err) <- liftIO
$ readProcessWithExitCode "fill-pdf.sh" [tplPath, "-"]
$ B.toStrict $ Aeson.encode m
case e of
ExitSuccess -> do
modifyResponse $ setHeader "Content-Disposition" f
writeBS out
ExitFailure _ -> writeBS err
[] -> error "No contract selected (bad id or broken contract data)"
[] -> error "No template attached to subprogram or bad contract id"
|
3dfcc123ddfe7dddf005a4fedf77b4df38798155f75e220a5a7446261016cdfb | ghilesZ/geoml | circum_incircle.ml | open Geoml
let iof = int_of_float
let foi = float_of_int
(*************** Random utilities *******************)
let gen_point xmin xmax ymin ymax =
let x = xmin +. (foi (Random.int (int_of_float (xmax-.xmin))))
and y = ymin +. (foi (Random.int (int_of_float (ymax-.ymin)))) in
Point.make x y
let gen_triangle xmin xmax ymin ymax =
let p1 = gen_point xmin xmax ymin ymax
and p2 = gen_point xmin xmax ymin ymax
and p3 = gen_point xmin xmax ymin ymax
in Triangle.make p1 p2 p3
(****************** Main example **********************)
let size_x = 800.
let size_y = 700.
let title = "Calculating the circumscribed circle and the incircle of a triangle"
let new_val () = gen_triangle 200. (size_x-.200.) 200. (size_y-.200.)
let work t =
let (pa,pb,pc) = Triangle.points t in
let inc = (Circle.incircle pa pb pc) in
(Circle.circumscribed pa pb pc), inc
let frame v =
Drawing.draw_string 25 675 "Press 'r' to generate a new triangle" Graphics.black;
Drawing.draw_triangle ~lw:1 v Graphics.blue;
Triangle.tri_iter (fun e ->
let c = Circle.make e 5. in
Drawing.fill_circle c Graphics.green
) v;
let (c1,c2) = (work v) in
Drawing.draw_circle c1 Graphics.red;
Drawing.draw_circle c2 Graphics.blue
(****** Window and event handling *****)
let clear () = Drawing.fill_screen Graphics.white
let handler status =
let open Graphics in
if status.key = 'r' then begin
clear ();
new_val () |> frame
end
let loop () =
Graphics.loop_at_exit [Graphics.Key_pressed] handler
let doit () =
Random.self_init ();
Drawing.open_graph size_x size_y title;
new_val () |> frame;
loop ()
let () = doit()
| null | https://raw.githubusercontent.com/ghilesZ/geoml/a239499dabbbfbf74bae73a105ed567546f43312/examples/circle/circum_incircle.ml | ocaml | ************** Random utilities ******************
***************** Main example *********************
***** Window and event handling **** | open Geoml
let iof = int_of_float
let foi = float_of_int
let gen_point xmin xmax ymin ymax =
let x = xmin +. (foi (Random.int (int_of_float (xmax-.xmin))))
and y = ymin +. (foi (Random.int (int_of_float (ymax-.ymin)))) in
Point.make x y
let gen_triangle xmin xmax ymin ymax =
let p1 = gen_point xmin xmax ymin ymax
and p2 = gen_point xmin xmax ymin ymax
and p3 = gen_point xmin xmax ymin ymax
in Triangle.make p1 p2 p3
let size_x = 800.
let size_y = 700.
let title = "Calculating the circumscribed circle and the incircle of a triangle"
let new_val () = gen_triangle 200. (size_x-.200.) 200. (size_y-.200.)
let work t =
let (pa,pb,pc) = Triangle.points t in
let inc = (Circle.incircle pa pb pc) in
(Circle.circumscribed pa pb pc), inc
let frame v =
Drawing.draw_string 25 675 "Press 'r' to generate a new triangle" Graphics.black;
Drawing.draw_triangle ~lw:1 v Graphics.blue;
Triangle.tri_iter (fun e ->
let c = Circle.make e 5. in
Drawing.fill_circle c Graphics.green
) v;
let (c1,c2) = (work v) in
Drawing.draw_circle c1 Graphics.red;
Drawing.draw_circle c2 Graphics.blue
let clear () = Drawing.fill_screen Graphics.white
let handler status =
let open Graphics in
if status.key = 'r' then begin
clear ();
new_val () |> frame
end
let loop () =
Graphics.loop_at_exit [Graphics.Key_pressed] handler
let doit () =
Random.self_init ();
Drawing.open_graph size_x size_y title;
new_val () |> frame;
loop ()
let () = doit()
|
94c01e0f086ae99eb3f6448c9f79693c827b6ecbc2fe0d6812acae75239e1cd9 | issuu/ocaml-zmq | test.mli | module Make: functor(T: Zmq_deferred.Deferred.T) -> sig
val run: ((unit -> unit T.Deferred.t) -> unit) -> unit
end
| null | https://raw.githubusercontent.com/issuu/ocaml-zmq/f1aad60f136529f45543a08a2f42c63d716e4e8f/zmq-deferred/test/test.mli | ocaml | module Make: functor(T: Zmq_deferred.Deferred.T) -> sig
val run: ((unit -> unit T.Deferred.t) -> unit) -> unit
end
| |
82487031087ebf651eb0b524c4bf289aa7034b48c01c7fcdde44d3b269046b36 | runexec/chp | main.cljs | (ns main)
(defn clojurescript []
(js/alert "Hi from ClojureScript!"))
| null | https://raw.githubusercontent.com/runexec/chp/9059399c46fb4106a73631c741f1e557af541a8b/chp-examples/basic/resources/cljs/main.cljs | clojure | (ns main)
(defn clojurescript []
(js/alert "Hi from ClojureScript!"))
| |
d7a8fdc4bb4af1751c0c3f99268e395ac2d5af3b8ad2436dab912df36202db9c | zellerin/http2 | errors.lisp | (in-package #:http2)
(defun test-bad-headers (headers)
(fiasco:signals http-stream-error
(with-http2-connection
(connection
'vanilla-client-connection
:network-stream (connect-to-tls-server *server-domain* :port *server-port*))
(loop
with stream = (open-http2-stream connection headers)
do
;; if it does not signal eventually we lose.
(read-frame connection)))))
(fiasco:deftest empty-headers ()
(test-bad-headers nil))
(fiasco:deftest string-headers-before-authority ()
(test-bad-headers '((:path "/") ("foo" "bar")
(:scheme "https")
(:authority "localhost"))))
(fiasco:deftest uppercase-headers ()
(test-bad-headers '((:method "GET")
(:path "/")
(:scheme "https")
(:authority "localhost")
("FOO" "bar"))))
(defmacro define-protocol-error-test (name &body body)
`(fiasco:deftest ,name ()
(let ((err (fiasco:signals go-away
,@body)))
(fiasco:is (eq '+protocol-error+ (get-error-code err)))
err)))
(define-protocol-error-test send-bad-stream-id
"Send request with bad stream ID. Should raise a protocol error."
(with-http2-connection
(connection
'vanilla-client-connection
:network-stream (connect-to-tls-server *server-domain* :port *server-port*)
:id-to-use 2)
(open-http2-stream connection
'((:method "HEAD")
(:path "/")
(:scheme "https")
(:authority "localhost"))
:end-stream t)
(process-pending-frames connection)))
(define-protocol-error-test send-too-low-stream-id
(with-http2-connection
(connection
'vanilla-client-connection
:network-stream (connect-to-tls-server *server-domain* :port *server-port*)
:id-to-use 7)
(http-stream-to-vector
(open-http2-stream connection
'((:method "HEAD")
(:path "/")
(:scheme "https")
(:authority "localhost"))
:end-stream t))
(setf (get-id-to-use connection) 1)
(http-stream-to-vector
(open-http2-stream connection
'((:method "HEAD")
(:path "/")
(:scheme "https")
(:authority "localhost"))
:end-stream t))))
;; test:
( let ( ( * server - domain * " www.example.com")(*server - port * 443 ) ) ( send - bad - stream - id ) )
( let ( ( * server - domain * " www.example.com")(*server - port * 443 ) ) ( send - too - low - stream - id ) )
( let ( ( * server - domain * " www.akamai.com")(*server - port * 443 ) ) ( send - too - low - stream - id ) )
| null | https://raw.githubusercontent.com/zellerin/http2/6b3216a2743d303686c3c94bacaee66abccd9d1e/tests/errors.lisp | lisp | if it does not signal eventually we lose.
test: | (in-package #:http2)
(defun test-bad-headers (headers)
(fiasco:signals http-stream-error
(with-http2-connection
(connection
'vanilla-client-connection
:network-stream (connect-to-tls-server *server-domain* :port *server-port*))
(loop
with stream = (open-http2-stream connection headers)
do
(read-frame connection)))))
(fiasco:deftest empty-headers ()
(test-bad-headers nil))
(fiasco:deftest string-headers-before-authority ()
(test-bad-headers '((:path "/") ("foo" "bar")
(:scheme "https")
(:authority "localhost"))))
(fiasco:deftest uppercase-headers ()
(test-bad-headers '((:method "GET")
(:path "/")
(:scheme "https")
(:authority "localhost")
("FOO" "bar"))))
(defmacro define-protocol-error-test (name &body body)
`(fiasco:deftest ,name ()
(let ((err (fiasco:signals go-away
,@body)))
(fiasco:is (eq '+protocol-error+ (get-error-code err)))
err)))
(define-protocol-error-test send-bad-stream-id
"Send request with bad stream ID. Should raise a protocol error."
(with-http2-connection
(connection
'vanilla-client-connection
:network-stream (connect-to-tls-server *server-domain* :port *server-port*)
:id-to-use 2)
(open-http2-stream connection
'((:method "HEAD")
(:path "/")
(:scheme "https")
(:authority "localhost"))
:end-stream t)
(process-pending-frames connection)))
(define-protocol-error-test send-too-low-stream-id
(with-http2-connection
(connection
'vanilla-client-connection
:network-stream (connect-to-tls-server *server-domain* :port *server-port*)
:id-to-use 7)
(http-stream-to-vector
(open-http2-stream connection
'((:method "HEAD")
(:path "/")
(:scheme "https")
(:authority "localhost"))
:end-stream t))
(setf (get-id-to-use connection) 1)
(http-stream-to-vector
(open-http2-stream connection
'((:method "HEAD")
(:path "/")
(:scheme "https")
(:authority "localhost"))
:end-stream t))))
( let ( ( * server - domain * " www.example.com")(*server - port * 443 ) ) ( send - bad - stream - id ) )
( let ( ( * server - domain * " www.example.com")(*server - port * 443 ) ) ( send - too - low - stream - id ) )
( let ( ( * server - domain * " www.akamai.com")(*server - port * 443 ) ) ( send - too - low - stream - id ) )
|
20315e1dbb60022b1b23d8f95f169cc832c7d157fc72cb98aeff4be92059ce4b | TyOverby/mono | tailwind_colors.mli | * The color palettes included in the Tailwind CSS library , taken from
[ -colors ] on 2021 - 02 - 13 . The larger
the number on a color , the darker it is .
This library takes the approach of * not * ascribing semantic value to
certain colors ; instead , it selects several " palettes " of colors which work
well together , and offloads the semantics of each color to the library or
application that depends on this one . Thus , this library does not aim to
provide any consistent design pattern or color conventions . However , a set
of conventions could easily be created using this set of colors .
[-colors] on 2021-02-13. The larger
the number on a color, the darker it is.
This library takes the approach of *not* ascribing semantic value to
certain colors; instead, it selects several "palettes" of colors which work
well together, and offloads the semantics of each color to the library or
application that depends on this one. Thus, this library does not aim to
provide any consistent design pattern or color conventions. However, a set
of conventions could easily be created using this set of colors. *)
type t := [ `Hex of string ]
(** The gray palette *)
val gray50 : t
val gray100 : t
val gray200 : t
val gray300 : t
val gray400 : t
val gray500 : t
val gray600 : t
val gray700 : t
val gray800 : t
val gray900 : t
(** The red palette *)
val red50 : t
val red100 : t
val red200 : t
val red300 : t
val red400 : t
val red500 : t
val red600 : t
val red700 : t
val red800 : t
val red900 : t
(** The yellow palette *)
val yellow50 : t
val yellow100 : t
val yellow200 : t
val yellow300 : t
val yellow400 : t
val yellow500 : t
val yellow600 : t
val yellow700 : t
val yellow800 : t
val yellow900 : t
(** The green palette *)
val green50 : t
val green100 : t
val green200 : t
val green300 : t
val green400 : t
val green500 : t
val green600 : t
val green700 : t
val green800 : t
val green900 : t
(** The blue palette *)
val blue50 : t
val blue100 : t
val blue200 : t
val blue300 : t
val blue400 : t
val blue500 : t
val blue600 : t
val blue700 : t
val blue800 : t
val blue900 : t
(** The indigo palette *)
val indigo50 : t
val indigo100 : t
val indigo200 : t
val indigo300 : t
val indigo400 : t
val indigo500 : t
val indigo600 : t
val indigo700 : t
val indigo800 : t
val indigo900 : t
(** The purple palette *)
val purple50 : t
val purple100 : t
val purple200 : t
val purple300 : t
val purple400 : t
val purple500 : t
val purple600 : t
val purple700 : t
val purple800 : t
val purple900 : t
(** The pink palette *)
val pink50 : t
val pink100 : t
val pink200 : t
val pink300 : t
val pink400 : t
val pink500 : t
val pink600 : t
val pink700 : t
val pink800 : t
val pink900 : t
| null | https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-bonsai/web_ui/tailwind_colors/tailwind_colors.mli | ocaml | * The gray palette
* The red palette
* The yellow palette
* The green palette
* The blue palette
* The indigo palette
* The purple palette
* The pink palette | * The color palettes included in the Tailwind CSS library , taken from
[ -colors ] on 2021 - 02 - 13 . The larger
the number on a color , the darker it is .
This library takes the approach of * not * ascribing semantic value to
certain colors ; instead , it selects several " palettes " of colors which work
well together , and offloads the semantics of each color to the library or
application that depends on this one . Thus , this library does not aim to
provide any consistent design pattern or color conventions . However , a set
of conventions could easily be created using this set of colors .
[-colors] on 2021-02-13. The larger
the number on a color, the darker it is.
This library takes the approach of *not* ascribing semantic value to
certain colors; instead, it selects several "palettes" of colors which work
well together, and offloads the semantics of each color to the library or
application that depends on this one. Thus, this library does not aim to
provide any consistent design pattern or color conventions. However, a set
of conventions could easily be created using this set of colors. *)
type t := [ `Hex of string ]
val gray50 : t
val gray100 : t
val gray200 : t
val gray300 : t
val gray400 : t
val gray500 : t
val gray600 : t
val gray700 : t
val gray800 : t
val gray900 : t
val red50 : t
val red100 : t
val red200 : t
val red300 : t
val red400 : t
val red500 : t
val red600 : t
val red700 : t
val red800 : t
val red900 : t
val yellow50 : t
val yellow100 : t
val yellow200 : t
val yellow300 : t
val yellow400 : t
val yellow500 : t
val yellow600 : t
val yellow700 : t
val yellow800 : t
val yellow900 : t
val green50 : t
val green100 : t
val green200 : t
val green300 : t
val green400 : t
val green500 : t
val green600 : t
val green700 : t
val green800 : t
val green900 : t
val blue50 : t
val blue100 : t
val blue200 : t
val blue300 : t
val blue400 : t
val blue500 : t
val blue600 : t
val blue700 : t
val blue800 : t
val blue900 : t
val indigo50 : t
val indigo100 : t
val indigo200 : t
val indigo300 : t
val indigo400 : t
val indigo500 : t
val indigo600 : t
val indigo700 : t
val indigo800 : t
val indigo900 : t
val purple50 : t
val purple100 : t
val purple200 : t
val purple300 : t
val purple400 : t
val purple500 : t
val purple600 : t
val purple700 : t
val purple800 : t
val purple900 : t
val pink50 : t
val pink100 : t
val pink200 : t
val pink300 : t
val pink400 : t
val pink500 : t
val pink600 : t
val pink700 : t
val pink800 : t
val pink900 : t
|
682d4e313476601f0f1050ca6eba39e4a3068e5aa8b72cc6ed493d32a3e09bfb | kupl/FixML | sub24.ml | type exp =
| Num of int
| Plus of exp * exp
| Minus of exp * exp
type formula =
| True
| False
| Not of formula
| AndAlso of formula * formula
| OrElse of formula * formula
| Imply of formula * formula
| Equal of exp * exp
let rec eval_exp a =
match a with
| Num n -> n
| Plus (n1,n2) -> eval_exp n1 + eval_exp n2
| Minus (n1,n2) -> eval_exp n1 + eval_exp n2;;
let rec eval thing =
match thing with
| True -> true
| False -> false
| Not a -> if (eval a) then false else true
| AndAlso (a,b) -> (eval a) && (eval b)
| OrElse (a,b) -> (eval a) || (eval b)
| Imply (a,b) -> if ((eval a = true) &&(eval b) = false) then false
else true
| Equal (a,b) -> if (eval_exp a = eval_exp b) then true else false;; | null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/formula/formula1/submissions/sub24.ml | ocaml | type exp =
| Num of int
| Plus of exp * exp
| Minus of exp * exp
type formula =
| True
| False
| Not of formula
| AndAlso of formula * formula
| OrElse of formula * formula
| Imply of formula * formula
| Equal of exp * exp
let rec eval_exp a =
match a with
| Num n -> n
| Plus (n1,n2) -> eval_exp n1 + eval_exp n2
| Minus (n1,n2) -> eval_exp n1 + eval_exp n2;;
let rec eval thing =
match thing with
| True -> true
| False -> false
| Not a -> if (eval a) then false else true
| AndAlso (a,b) -> (eval a) && (eval b)
| OrElse (a,b) -> (eval a) || (eval b)
| Imply (a,b) -> if ((eval a = true) &&(eval b) = false) then false
else true
| Equal (a,b) -> if (eval_exp a = eval_exp b) then true else false;; | |
7daf5f096234179deb42a90d5586b4c4567bb806d532e2ee2c0126e231ce6367 | BoeingX/haskell-programming-from-first-principles | PhoneNumbers.hs | module ParserCombinators.ChapterExercises.PhoneNumbers where
import Control.Applicative
import Data.List
import Text.Trifecta
instance (Eq a) => Eq (Result a) where
Success a == Success b = a == b
Failure a == Failure b = True
_ == _ = False
type NumberingPlanArea = Int -- aka area code
type Exchange = Int
type LineNumber = Int
data PhoneNumber =
PhoneNumber NumberingPlanArea Exchange LineNumber
deriving (Eq, Show)
number :: String -> Int
number = foldl' (\acc x -> acc * 10 + read [x]) 0
parseNumberingPlanArea :: Parser NumberingPlanArea
parseNumberingPlanArea = do
_ <- optional (string "1-")
numberingPlanArea <- char '(' *> count 3 digit <* char ')' <* char ' '
<|> (count 3 digit <* optional (char '-'))
return $ number numberingPlanArea
parseExchange :: Parser Exchange
parseExchange = number <$> count 3 digit
parseLineNumber :: Parser LineNumber
parseLineNumber = number <$> count 4 digit
parsePhone :: Parser PhoneNumber
parsePhone = do
numberingPlanArea <- parseNumberingPlanArea
exchange <- parseExchange
_ <- optional (char '-')
lineNumber <- parseLineNumber
return $ PhoneNumber numberingPlanArea exchange lineNumber
| null | https://raw.githubusercontent.com/BoeingX/haskell-programming-from-first-principles/ffb637f536597f552a4e4567fee848ed27f3ba74/src/ParserCombinators/ChapterExercises/PhoneNumbers.hs | haskell | aka area code | module ParserCombinators.ChapterExercises.PhoneNumbers where
import Control.Applicative
import Data.List
import Text.Trifecta
instance (Eq a) => Eq (Result a) where
Success a == Success b = a == b
Failure a == Failure b = True
_ == _ = False
type Exchange = Int
type LineNumber = Int
data PhoneNumber =
PhoneNumber NumberingPlanArea Exchange LineNumber
deriving (Eq, Show)
number :: String -> Int
number = foldl' (\acc x -> acc * 10 + read [x]) 0
parseNumberingPlanArea :: Parser NumberingPlanArea
parseNumberingPlanArea = do
_ <- optional (string "1-")
numberingPlanArea <- char '(' *> count 3 digit <* char ')' <* char ' '
<|> (count 3 digit <* optional (char '-'))
return $ number numberingPlanArea
parseExchange :: Parser Exchange
parseExchange = number <$> count 3 digit
parseLineNumber :: Parser LineNumber
parseLineNumber = number <$> count 4 digit
parsePhone :: Parser PhoneNumber
parsePhone = do
numberingPlanArea <- parseNumberingPlanArea
exchange <- parseExchange
_ <- optional (char '-')
lineNumber <- parseLineNumber
return $ PhoneNumber numberingPlanArea exchange lineNumber
|
8ac722e33d2f580fea1b41150d14340944f3f4d7feb0be64e32d0286a49eeb70 | screenshotbot/screenshotbot-oss | harbormaster.lisp | ;;;; Copyright 2018-Present Modern Interpreters Inc.
;;;;
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 /.
(defpackage :util/phabricator/harbormaster
(:use #:cl)
(:import-from #:util/phabricator/conduit
#:call-conduit
#:phab-instance)
(:import-from #:alexandria
#:assoc-value)
(:import-from #:local-time
#:timestamp+
#:timestamp-to-unix)
(:export
#:download-file
#:upload-file
#:create-artifact))
(in-package :util/phabricator/harbormaster)
(defun delete-after-epoch ()
(timestamp-to-unix
(timestamp+
(local-time:now)
1 :day)))
(defun p (x)
#+nil
(log:info "result: ~s" x)
x)
(defmethod file-allocate ((phab phab-instance) file-size &key (name (Error "needs name")))
(log:info "allocating file")
(assoc-value
(assoc-value
(call-conduit
phab
"file.allocate"
`(("name" . ,name)
("contentLength" . ,(p file-size))
("deleteAfterEpoch" . ,(delete-after-epoch))))
:result)
:file-+phid+))
(defmethod upload-file ((phab phab-instance) pathname
&key (name "unnamed"))
"Upload a file and return the PHID"
(with-open-file (stream pathname :direction :input
:element-type 'flex:octet)
(let ((phid (file-allocate phab (file-length stream) :name name)))
(cond
(phid
(upload-file-chunked phab phid stream)
phid)
(t
(let ((arr (make-array (file-length stream)
:element-type 'flex:octet)))
(read-sequence arr stream)
(let ((response
(call-conduit
phab
"file.upload"
`(("name" . ,name)
("data_base64" . ,(base64:usb8-array-to-base64-string arr))))))
(assoc-value response :result))))))))
(defmethod upload-file-chunked ((phab phab-instance)
phid
stream)
(let ((chunks (reverse (file-query-chunks phab phid))))
(let ((buf (make-array 1 :element-type '(unsigned-byte 8)
:adjustable t
:fill-pointer t)))
(dolist (chunk chunks)
(assert (not (assoc-value chunk :complete)))
(let* ((start (parse-integer (assoc-value chunk :byte-start)))
(end (parse-integer (assoc-value chunk :byte-end))))
(adjust-array buf (- end start)
:fill-pointer (- end start))
(file-position stream start)
(read-sequence buf stream)
(file-upload-chunk phab phid start buf))))))
(defmethod file-query-chunks ((phab phab-instance)
phid)
(assoc-value
(call-conduit
phab
"file.querychunks"
`(("filePHID" . ,phid)))
:result))
(defmethod file-upload-chunk ((phab phab-instance)
phid
pos
seq)
(log:info "Uploading chunk at pos ~a" pos)
(call-conduit
phab
"file.uploadchunk"
`(("filePHID" . ,phid)
("byteStart" . ,pos)
("data" . ,(base64:usb8-array-to-base64-string seq))
("dataEncoding" . "base64"))))
(defmethod download-file ((phab phab-instance) phid output)
(let ((response
(call-conduit
phab
"file.download"
`(("phid" . ,phid)))))
(assert (not (assoc-value response :error--code)))
(let ((base64 (assoc-value response :result)))
(with-open-file (stream output :direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(base64:base64-string-to-stream base64
:stream
#-sbcl
stream
#+sbcl
(flex:make-flexi-stream
stream
:external-format :latin-1))))))
(defmethod create-artifact ((phab phab-instance)
phid
file
&key (name (error "must provide artifact name")))
(let ((file-phid (upload-file phab file)))
(let ((data (make-hash-table :test #'equal)))
(setf (gethash "filePHID" data) file-phid)
(call-conduit
phab
"harbormaster.createartifact"
`(("buildTargetPHID" . ,phid)
("artifactKey" . ,name)
("artifactType" . "file")
("artifactData" . ,data))))))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/7dca84b3b0cd08c32b1d7721ac8a4195786f0361/src/util/phabricator/harbormaster.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
| 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 /.
(defpackage :util/phabricator/harbormaster
(:use #:cl)
(:import-from #:util/phabricator/conduit
#:call-conduit
#:phab-instance)
(:import-from #:alexandria
#:assoc-value)
(:import-from #:local-time
#:timestamp+
#:timestamp-to-unix)
(:export
#:download-file
#:upload-file
#:create-artifact))
(in-package :util/phabricator/harbormaster)
(defun delete-after-epoch ()
(timestamp-to-unix
(timestamp+
(local-time:now)
1 :day)))
(defun p (x)
#+nil
(log:info "result: ~s" x)
x)
(defmethod file-allocate ((phab phab-instance) file-size &key (name (Error "needs name")))
(log:info "allocating file")
(assoc-value
(assoc-value
(call-conduit
phab
"file.allocate"
`(("name" . ,name)
("contentLength" . ,(p file-size))
("deleteAfterEpoch" . ,(delete-after-epoch))))
:result)
:file-+phid+))
(defmethod upload-file ((phab phab-instance) pathname
&key (name "unnamed"))
"Upload a file and return the PHID"
(with-open-file (stream pathname :direction :input
:element-type 'flex:octet)
(let ((phid (file-allocate phab (file-length stream) :name name)))
(cond
(phid
(upload-file-chunked phab phid stream)
phid)
(t
(let ((arr (make-array (file-length stream)
:element-type 'flex:octet)))
(read-sequence arr stream)
(let ((response
(call-conduit
phab
"file.upload"
`(("name" . ,name)
("data_base64" . ,(base64:usb8-array-to-base64-string arr))))))
(assoc-value response :result))))))))
(defmethod upload-file-chunked ((phab phab-instance)
phid
stream)
(let ((chunks (reverse (file-query-chunks phab phid))))
(let ((buf (make-array 1 :element-type '(unsigned-byte 8)
:adjustable t
:fill-pointer t)))
(dolist (chunk chunks)
(assert (not (assoc-value chunk :complete)))
(let* ((start (parse-integer (assoc-value chunk :byte-start)))
(end (parse-integer (assoc-value chunk :byte-end))))
(adjust-array buf (- end start)
:fill-pointer (- end start))
(file-position stream start)
(read-sequence buf stream)
(file-upload-chunk phab phid start buf))))))
(defmethod file-query-chunks ((phab phab-instance)
phid)
(assoc-value
(call-conduit
phab
"file.querychunks"
`(("filePHID" . ,phid)))
:result))
(defmethod file-upload-chunk ((phab phab-instance)
phid
pos
seq)
(log:info "Uploading chunk at pos ~a" pos)
(call-conduit
phab
"file.uploadchunk"
`(("filePHID" . ,phid)
("byteStart" . ,pos)
("data" . ,(base64:usb8-array-to-base64-string seq))
("dataEncoding" . "base64"))))
(defmethod download-file ((phab phab-instance) phid output)
(let ((response
(call-conduit
phab
"file.download"
`(("phid" . ,phid)))))
(assert (not (assoc-value response :error--code)))
(let ((base64 (assoc-value response :result)))
(with-open-file (stream output :direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(base64:base64-string-to-stream base64
:stream
#-sbcl
stream
#+sbcl
(flex:make-flexi-stream
stream
:external-format :latin-1))))))
(defmethod create-artifact ((phab phab-instance)
phid
file
&key (name (error "must provide artifact name")))
(let ((file-phid (upload-file phab file)))
(let ((data (make-hash-table :test #'equal)))
(setf (gethash "filePHID" data) file-phid)
(call-conduit
phab
"harbormaster.createartifact"
`(("buildTargetPHID" . ,phid)
("artifactKey" . ,name)
("artifactType" . "file")
("artifactData" . ,data))))))
|
024a514bd6dc085214d349f69c9722582721a709aeff851b75482ee813ad1c5d | wilbowma/cur | equality.rkt | #lang s-exp "../main.rkt"
(provide elim-== PM-sym PM-trans
ML-= ML-refl elim-ML-=
f-equal
(for-syntax ~== ~ML-= (rename-out [~== ~PM-=]))
(rename-out [==/i PM-=]
[==/i ==]
[refl/i PM-refl]
[refl/i refl]
[elim-== elim-PM-=]
[PM-sym sym]
[PM-trans trans]))
(require "sugar.rkt")
Paulin - Mohring ( coq ) equality
(data == : 2 (forall (A : Type) (x : A) (y : A) Type)
(refl : (forall (A : Type) (x : A) (== A x x))))
(define-implicit refl/i = refl 1)
(define-implicit ==/i = == 1)
;; pm symmetry
(define-for-export PM-sym
(λ [A : Type]
(λ [x : A] [y : A]
(λ [e : (== A x y)]
(new-elim
e
(λ [b : A]
(λ [e2 : (== A x b)]
(== A b x)))
(refl A x))))))
;; pm transitivity (using pm-sym)
(define-for-export PM-trans
(λ [A : Type]
(λ [x : A] [y : A] [z : A]
(λ [e1 : (== A x y)] [e2 : (== A y z)]
(new-elim
(PM-sym A x y e1)
(λ [b : A]
(λ [e : (== A y b)]
(== A b z)))
e2)))))
;; coq f_equal
(define-for-export f-equal
(λ [A : Type] [B : Type]
[f : (-> A B)]
[x : A] [y : A]
[H : (== A x y)]
(elim-==
H
(λ b h (== B (f x) (f b)))
(refl B (f x)))))
equality , I think
(data ML-= : 1 (forall (A : Type) (x : A) (y : A) Type)
(ML-refl : (forall (A : Type) (x : A) (ML-= A x x))))
| null | https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur-lib/cur/stdlib/equality.rkt | racket | pm symmetry
pm transitivity (using pm-sym)
coq f_equal | #lang s-exp "../main.rkt"
(provide elim-== PM-sym PM-trans
ML-= ML-refl elim-ML-=
f-equal
(for-syntax ~== ~ML-= (rename-out [~== ~PM-=]))
(rename-out [==/i PM-=]
[==/i ==]
[refl/i PM-refl]
[refl/i refl]
[elim-== elim-PM-=]
[PM-sym sym]
[PM-trans trans]))
(require "sugar.rkt")
Paulin - Mohring ( coq ) equality
(data == : 2 (forall (A : Type) (x : A) (y : A) Type)
(refl : (forall (A : Type) (x : A) (== A x x))))
(define-implicit refl/i = refl 1)
(define-implicit ==/i = == 1)
(define-for-export PM-sym
(λ [A : Type]
(λ [x : A] [y : A]
(λ [e : (== A x y)]
(new-elim
e
(λ [b : A]
(λ [e2 : (== A x b)]
(== A b x)))
(refl A x))))))
(define-for-export PM-trans
(λ [A : Type]
(λ [x : A] [y : A] [z : A]
(λ [e1 : (== A x y)] [e2 : (== A y z)]
(new-elim
(PM-sym A x y e1)
(λ [b : A]
(λ [e : (== A y b)]
(== A b z)))
e2)))))
(define-for-export f-equal
(λ [A : Type] [B : Type]
[f : (-> A B)]
[x : A] [y : A]
[H : (== A x y)]
(elim-==
H
(λ b h (== B (f x) (f b)))
(refl B (f x)))))
equality , I think
(data ML-= : 1 (forall (A : Type) (x : A) (y : A) Type)
(ML-refl : (forall (A : Type) (x : A) (ML-= A x x))))
|
d630d7740cac66141dbf3dcd6dcd2cfd8db8a5db1685579d30284aab8f72103a | azimut/shiny | main.lisp | (in-package :shiny)
(defvar *dimensions-fbo* nil)
(defvar *fbo* nil)
(defvar *sam* nil)
;; Assimp
(defvar *mesh* nil)
(defvar *mesh-light* nil)
(defvar *ass* nil)
(defvar *ass-light* nil)
(defvar *blend* nil)
(defvar *bs* nil)
;; Merge
(defvar *sam-depth* nil)
(defvar *fbo-secondary* nil)
(defvar *sam-secondary* nil)
(defvar *fbo-terciary* nil)
(defvar *sam-terciary* nil)
SSAO
(defvar *sam-pos* nil)
(defvar *sam-nor* nil)
(defvar *sam-alb* nil)
(defvar *fbo-ao* nil)
(defvar *sam-ao* nil)
(defvar *noise-tex* nil)
(defvar *noise-sam* nil)
(defvar *fbo-ao-blur* nil)
(defvar *sam-ao-blur* nil)
(defvar *ubo-kernel* nil)
Blur
(defvar *sam1* nil)
(defvar *half-fbo* nil)
(defvar *fourth-fbo* nil)
(defvar *eighth-fbo* nil)
(defvar *sixteen-fbo* nil)
(defvar *sam-half-fbo* nil)
(defvar *sam-fourth-fbo* nil)
(defvar *sam-eighth-fbo* nil)
(defvar *sam-sixteen-fbo* nil)
(defun generate-rotation-kernel ()
(loop :repeat 4 :collect
(loop :repeat 4 :collect
(v! (1- (* 2 (random 1f0)))
(1- (* 2 (random 1f0)))
0f0))))
(defun generate-sample-kernel ()
(loop :for i :below 64 :collect
(let* ((sample (v! (1- (* 2 (random 1f0)))
(1- (* 2 (random 1f0)))
(random 1f0)))
(sample (v3:normalize sample))
(sample (v3:*s sample (random 1f0)))
(scale (/ i 64f0))
(scale (lerp .1 1f0 (* scale scale))))
(v3:*s sample scale))))
(defun initialize ()
;;(unless *mesh*)
(setf *mesh*
(elt
(slot-value
(ai:import-into-lisp
"/home/sendai/untitled.3ds"
:processing-flags '(:ai-process-triangulate
:ai-process-calc-tangent-space))
'ai:meshes)
0))
(setf *mesh-light*
(elt
(slot-value
(ai:import-into-lisp
"/home/sendai/untitled-light.3ds"
:processing-flags '(:ai-process-triangulate
:ai-process-calc-tangent-space))
'ai:meshes)
0))
(when *ass* (cepl:free (slot-value *ass* 'buf)))
(when *ass-light* (cepl:free (slot-value *ass-light* 'buf)))
(setf *ass*
(make-instance 'assimp-thing-with-maps
:rot (q:from-axis-angle (v! 1 0 0)
(radians -90))
:buf (assimp-mesh-to-stream *mesh*)))
(setf *ass-light*
(make-instance 'assimp-bloom
:rot (q:from-axis-angle (v! 1 0 0)
(radians -90))
:buf (assimp-mesh-to-stream *mesh-light*)))
;;--------------------------------------------------
;; Buffer stream for single stage pipelines
(unless *bs* (setf *bs* (make-buffer-stream nil :primitive :points)))
;;--------------------------------------------------
;; HDR fbo(s)
(when *fbo*
(free *fbo*)
;; (free *fbo-secondary*)
;; (free *fbo-terciary*)
;; (free *fbo-ao*)
)
( setf * fbo * ( make - fbo ( list 0 : element - type : rgba16f )
; ; BLOOM LIGHT
( list 1 : element - type : rgba16f )
; ; SSAO
( list 2 : element - type : rgb16f ) ; ; pos
( list 3 : element - type : rgb16f ) ; ; nor
;; :d))
( list 0 : element - type : rgb16f ) ; ; pos
(list 0 :element-type :rgb16f) ;; nor
:d))
(setf *dimensions-fbo* (dimensions (attachment-tex *fbo* 0)))
( setf * * ( cepl : sample ( attachment - tex * fbo * 0 ) : wrap : clamp - to - edge ) )
( setf * sam1 * ( cepl : sample ( attachment - tex * fbo * 1 ) : wrap : clamp - to - edge ) )
;;--------------------------------------------------
SSAO - Normal and position textures
(setf *sam-depth* (cepl:sample (attachment-tex *fbo* :d)
:minify-filter :nearest
:magnify-filter :nearest
:wrap :clamp-to-edge))
( setf * * ( cepl : sample ( attachment - tex * fbo * 0 )
;; :minify-filter :nearest
;; :magnify-filter :nearest
;; :wrap :clamp-to-edge))
(setf *sam-nor* (cepl:sample (attachment-tex *fbo* 0)
:minify-filter :nearest
:magnify-filter :nearest))
SSAO - Random kernel rotations - generate noise texture
(unless *noise-tex*
(setf *noise-tex* (make-texture (generate-rotation-kernel)
:element-type :rgb32f))
(setf *noise-sam* (cepl:sample *noise-tex*
:minify-filter :nearest
:magnify-filter :nearest)))
SSAO - samples
(unless *ubo-kernel*
(setf *ubo-kernel* (make-ubo (list (generate-sample-kernel))
'random-kernel)))
;; (unless *g-kernel*
( setf * g - kernel * ( make - gpu - array ( generate - sample - kernel )
: dimensions 64
;; :element-type :vec3)))
SSAO - ?
( setf * fbo - ao * ( make - fbo ( list 0 : element - type : r16 ) ) )
( setf * * ( cepl : sample ( attachment - tex * fbo - ao * 0 )
;; :minify-filter :nearest
;; :magnify-filter :nearest
;; :wrap :clamp-to-edge))
( setf * fbo - ao - blur * ( make - fbo ( list 0 : element - type : r8 ) ) )
( setf * * ( cepl : sample ( attachment - tex * fbo - ao - blur * 0 )
;; :minify-filter :nearest
;; :magnify-filter :nearest
;; :wrap :clamp-to-edge))
;;--------------------------------------------------
;; Sec FBO
( setf * fbo - secondary * ( make - fbo ( list 0 : element - type : rgba16f ) ) )
( setf * *
( cepl : sample ( attachment - tex * fbo - secondary * 0 )
;; :wrap :clamp-to-edge))
;; Ter FBO
( setf * fbo - terciary * ( make - fbo ( list 0 : element - type : rgba16f ) ) )
( setf * *
( cepl : sample ( attachment - tex * fbo - terciary * 0 )
;; :wrap :clamp-to-edge))
;;--------------------------------------------------
BLUR
;; Used for the upsampling part of the blur
(unless *blend*
(setf *blend* (make-blending-params :source-rgb :one
:destination-rgb :one)))
(when *half-fbo*
(free *half-fbo*)
(free *fourth-fbo*)
(free *eighth-fbo*)
(free *sixteen-fbo*))
;; (flet ((f (d) (mapcar (lambda (x) (round (/ x d)))
;; *dimensions-fbo*)))
( setf * half - fbo *
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 2))))
( setf * fourth - fbo *
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 4))))
( setf * eighth - fbo *
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 8))))
( setf * sixteen - fbo *
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 16))))
( setf * * ( cepl : sample ( attachment - tex * half - fbo * 0 )
;; :wrap :clamp-to-edge))
( setf * * ( cepl : sample ( attachment - tex * fourth - fbo * 0 )
;; :wrap :clamp-to-edge))
( setf * - fbo * ( cepl : sample ( attachment - tex * eighth - fbo * 0 )
;; :wrap :clamp-to-edge))
( setf * - fbo * ( cepl : sample ( attachment - tex * sixteen - fbo * 0 )
;; :wrap :clamp-to-edge)))
;;--------------------------------------------------
(setf (clear-color) (v! 0 0 0 1))
( setf ( clear - color ) ( v ! 0 0 0 1 ) )
(setf *actors* nil)
;;;(make-box)
(make-cement)
(make-celestial-sphere)
;;(push *ass* *actors*)
;;(push *ass-light* *actors*)
;;(make-sphere)
;;(make-piso)
NIL)
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (resolution (current-viewport)) res)
(update *currentcamera*)
(update-all-the-things *actors*)
(with-fbo-bound (*fbo*)
(clear-fbo *fbo*)
(loop :for actor :in *actors* :do
(draw actor *currentcamera*)))
;; Really poor implementation of the awesome and more effective bloom from:
;; -rendering/bloom/
;; (let ((width (car *dimensions-fbo*))
;; (height (car (last *dimensions-fbo*))))
;; (with-setf* ((depth-mask) nil
;; (cull-face) nil
( clear - color ) ( v ! 0 0 0 1 )
;; (depth-test-function) #'always)
;;;;--------------------------------------------------
( with - fbo - bound ( * half - fbo * )
;; (clear-fbo *half-fbo*)
;; (map-g #'bloom-pipe *bs*
: * sam1 *
:x ( / 1f0 width )
: y ( / 1f0 height )
: delta 1f0 ) )
;; (with-fbo-bound (*fourth-fbo*)
;; (clear-fbo *fourth-fbo*)
;; (map-g #'bloom-pipe *bs*
: - fbo *
:x ( / 1f0 ( round ( * .5 width ) ) )
: y ( / 1f0 ( round ( * .5 height ) ) ) ) )
;; (with-fbo-bound (*eighth-fbo*)
;; (clear-fbo *eighth-fbo*)
;; (map-g #'bloom-pipe *bs*
: *
:x ( / 1f0 ( round ( * .5 ( * .5 width ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 height ) ) ) ) ) )
( with - fbo - bound ( * sixteen - fbo * )
( clear - fbo * sixteen - fbo * )
;; (map-g #'bloom-pipe *bs*
: - fbo *
:x ( / 1f0 ( round ( * .5 ( * .5 ( * .5 width ) ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 ( * .5 height ) ) ) ) ) ) )
;;;;--------------------------------------------------
;; ;; END downscale BEGIN upscale
;; (with-blending *blend*
;; (with-fbo-bound (*eighth-fbo*)
;; (clear-fbo *eighth-fbo*)
;; (map-g #'bloom-pipe *bs*
: - fbo *
:x ( / 1f0 ( round ( * .5 ( * .5 ( * .5 width ) ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 ( * .5 height ) ) ) ) )
: delta .5 ) ) )
;; (with-blending *blend*
;; (with-fbo-bound (*fourth-fbo*)
;; (clear-fbo *fourth-fbo*)
;; (map-g #'bloom-pipe *bs*
: - fbo *
:x ( / 1f0 ( round ( * .5 ( * .5 width ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 height ) ) ) ) ) ) )
;; (with-blending *blend*
( with - fbo - bound ( * half - fbo * )
;; (clear-fbo *half-fbo*)
;; (map-g #'bloom-pipe *bs*
: *
:x ( / 1f0 ( round ( * .5 width ) ) )
: y ( / 1f0 ( round ( * .5 height ) ) ) ) ) )
;; (with-blending *blend*
;; (with-fbo-bound (*fbo-secondary*)
;; (clear-fbo *fbo-secondary*)
;; (map-g #'bloom-pipe *bs*
: - fbo *
:x ( / 1f0 width )
: y ( / 1f0 height ) ) ) )
;;--------------------------------------------------
;; ;; END upscale BEGIN merge
;; (with-fbo-bound (*fbo-terciary*)
;; (clear-fbo *fbo-terciary*)
;; (map-g #'dobloom-pipe *bs*
: *
: * *
: delta .5
:x ( / 1f0 width )
: y ( / 1f0 height ) ) ) ) )
(as-frame
(with-setf* ((depth-mask) nil
(cull-face) nil
(clear-color) (v! 0 0 0 1)
(depth-test-function) #'always)
(map-g #'ssao-pipe *bs*
: g - position * *
:g-normal *sam-nor*
:g-depth *sam-depth*
:kernel *kernel*
:kernel-effect *kernel-effect*
:radius *radius*
;; :world-view (world->view *currentcamera*)
:tex-noise *noise-sam*
:random-kernel *ubo-kernel*
:res (v! *dimensions-fbo*)
:view-clip (projection *currentcamera*))))
;; (as-frame
;; (map-g #'generic-2d-pipe *bs*
; ; : *
; ; : *
: *
;; ))
))
(def-simple-main-loop runplay
(:on-start #'initialize)
(draw!))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/examples/light-etude/main.lisp | lisp | Assimp
Merge
(unless *mesh*)
--------------------------------------------------
Buffer stream for single stage pipelines
--------------------------------------------------
HDR fbo(s)
(free *fbo-secondary*)
(free *fbo-terciary*)
(free *fbo-ao*)
; BLOOM LIGHT
; SSAO
; pos
; nor
:d))
; pos
nor
--------------------------------------------------
:minify-filter :nearest
:magnify-filter :nearest
:wrap :clamp-to-edge))
(unless *g-kernel*
:element-type :vec3)))
:minify-filter :nearest
:magnify-filter :nearest
:wrap :clamp-to-edge))
:minify-filter :nearest
:magnify-filter :nearest
:wrap :clamp-to-edge))
--------------------------------------------------
Sec FBO
:wrap :clamp-to-edge))
Ter FBO
:wrap :clamp-to-edge))
--------------------------------------------------
Used for the upsampling part of the blur
(flet ((f (d) (mapcar (lambda (x) (round (/ x d)))
*dimensions-fbo*)))
(make-fbo (list 0 :element-type :rgba16f :dimensions (f 2))))
(make-fbo (list 0 :element-type :rgba16f :dimensions (f 4))))
(make-fbo (list 0 :element-type :rgba16f :dimensions (f 8))))
(make-fbo (list 0 :element-type :rgba16f :dimensions (f 16))))
:wrap :clamp-to-edge))
:wrap :clamp-to-edge))
:wrap :clamp-to-edge))
:wrap :clamp-to-edge)))
--------------------------------------------------
(make-box)
(push *ass* *actors*)
(push *ass-light* *actors*)
(make-sphere)
(make-piso)
Really poor implementation of the awesome and more effective bloom from:
-rendering/bloom/
(let ((width (car *dimensions-fbo*))
(height (car (last *dimensions-fbo*))))
(with-setf* ((depth-mask) nil
(cull-face) nil
(depth-test-function) #'always)
--------------------------------------------------
(clear-fbo *half-fbo*)
(map-g #'bloom-pipe *bs*
(with-fbo-bound (*fourth-fbo*)
(clear-fbo *fourth-fbo*)
(map-g #'bloom-pipe *bs*
(with-fbo-bound (*eighth-fbo*)
(clear-fbo *eighth-fbo*)
(map-g #'bloom-pipe *bs*
(map-g #'bloom-pipe *bs*
--------------------------------------------------
;; END downscale BEGIN upscale
(with-blending *blend*
(with-fbo-bound (*eighth-fbo*)
(clear-fbo *eighth-fbo*)
(map-g #'bloom-pipe *bs*
(with-blending *blend*
(with-fbo-bound (*fourth-fbo*)
(clear-fbo *fourth-fbo*)
(map-g #'bloom-pipe *bs*
(with-blending *blend*
(clear-fbo *half-fbo*)
(map-g #'bloom-pipe *bs*
(with-blending *blend*
(with-fbo-bound (*fbo-secondary*)
(clear-fbo *fbo-secondary*)
(map-g #'bloom-pipe *bs*
--------------------------------------------------
;; END upscale BEGIN merge
(with-fbo-bound (*fbo-terciary*)
(clear-fbo *fbo-terciary*)
(map-g #'dobloom-pipe *bs*
:world-view (world->view *currentcamera*)
(as-frame
(map-g #'generic-2d-pipe *bs*
; : *
; : *
)) | (in-package :shiny)
(defvar *dimensions-fbo* nil)
(defvar *fbo* nil)
(defvar *sam* nil)
(defvar *mesh* nil)
(defvar *mesh-light* nil)
(defvar *ass* nil)
(defvar *ass-light* nil)
(defvar *blend* nil)
(defvar *bs* nil)
(defvar *sam-depth* nil)
(defvar *fbo-secondary* nil)
(defvar *sam-secondary* nil)
(defvar *fbo-terciary* nil)
(defvar *sam-terciary* nil)
SSAO
(defvar *sam-pos* nil)
(defvar *sam-nor* nil)
(defvar *sam-alb* nil)
(defvar *fbo-ao* nil)
(defvar *sam-ao* nil)
(defvar *noise-tex* nil)
(defvar *noise-sam* nil)
(defvar *fbo-ao-blur* nil)
(defvar *sam-ao-blur* nil)
(defvar *ubo-kernel* nil)
Blur
(defvar *sam1* nil)
(defvar *half-fbo* nil)
(defvar *fourth-fbo* nil)
(defvar *eighth-fbo* nil)
(defvar *sixteen-fbo* nil)
(defvar *sam-half-fbo* nil)
(defvar *sam-fourth-fbo* nil)
(defvar *sam-eighth-fbo* nil)
(defvar *sam-sixteen-fbo* nil)
(defun generate-rotation-kernel ()
(loop :repeat 4 :collect
(loop :repeat 4 :collect
(v! (1- (* 2 (random 1f0)))
(1- (* 2 (random 1f0)))
0f0))))
(defun generate-sample-kernel ()
(loop :for i :below 64 :collect
(let* ((sample (v! (1- (* 2 (random 1f0)))
(1- (* 2 (random 1f0)))
(random 1f0)))
(sample (v3:normalize sample))
(sample (v3:*s sample (random 1f0)))
(scale (/ i 64f0))
(scale (lerp .1 1f0 (* scale scale))))
(v3:*s sample scale))))
(defun initialize ()
(setf *mesh*
(elt
(slot-value
(ai:import-into-lisp
"/home/sendai/untitled.3ds"
:processing-flags '(:ai-process-triangulate
:ai-process-calc-tangent-space))
'ai:meshes)
0))
(setf *mesh-light*
(elt
(slot-value
(ai:import-into-lisp
"/home/sendai/untitled-light.3ds"
:processing-flags '(:ai-process-triangulate
:ai-process-calc-tangent-space))
'ai:meshes)
0))
(when *ass* (cepl:free (slot-value *ass* 'buf)))
(when *ass-light* (cepl:free (slot-value *ass-light* 'buf)))
(setf *ass*
(make-instance 'assimp-thing-with-maps
:rot (q:from-axis-angle (v! 1 0 0)
(radians -90))
:buf (assimp-mesh-to-stream *mesh*)))
(setf *ass-light*
(make-instance 'assimp-bloom
:rot (q:from-axis-angle (v! 1 0 0)
(radians -90))
:buf (assimp-mesh-to-stream *mesh-light*)))
(unless *bs* (setf *bs* (make-buffer-stream nil :primitive :points)))
(when *fbo*
(free *fbo*)
)
( setf * fbo * ( make - fbo ( list 0 : element - type : rgba16f )
( list 1 : element - type : rgba16f )
:d))
(setf *dimensions-fbo* (dimensions (attachment-tex *fbo* 0)))
( setf * * ( cepl : sample ( attachment - tex * fbo * 0 ) : wrap : clamp - to - edge ) )
( setf * sam1 * ( cepl : sample ( attachment - tex * fbo * 1 ) : wrap : clamp - to - edge ) )
SSAO - Normal and position textures
(setf *sam-depth* (cepl:sample (attachment-tex *fbo* :d)
:minify-filter :nearest
:magnify-filter :nearest
:wrap :clamp-to-edge))
( setf * * ( cepl : sample ( attachment - tex * fbo * 0 )
(setf *sam-nor* (cepl:sample (attachment-tex *fbo* 0)
:minify-filter :nearest
:magnify-filter :nearest))
SSAO - Random kernel rotations - generate noise texture
(unless *noise-tex*
(setf *noise-tex* (make-texture (generate-rotation-kernel)
:element-type :rgb32f))
(setf *noise-sam* (cepl:sample *noise-tex*
:minify-filter :nearest
:magnify-filter :nearest)))
SSAO - samples
(unless *ubo-kernel*
(setf *ubo-kernel* (make-ubo (list (generate-sample-kernel))
'random-kernel)))
( setf * g - kernel * ( make - gpu - array ( generate - sample - kernel )
: dimensions 64
SSAO - ?
( setf * fbo - ao * ( make - fbo ( list 0 : element - type : r16 ) ) )
( setf * * ( cepl : sample ( attachment - tex * fbo - ao * 0 )
( setf * fbo - ao - blur * ( make - fbo ( list 0 : element - type : r8 ) ) )
( setf * * ( cepl : sample ( attachment - tex * fbo - ao - blur * 0 )
( setf * fbo - secondary * ( make - fbo ( list 0 : element - type : rgba16f ) ) )
( setf * *
( cepl : sample ( attachment - tex * fbo - secondary * 0 )
( setf * fbo - terciary * ( make - fbo ( list 0 : element - type : rgba16f ) ) )
( setf * *
( cepl : sample ( attachment - tex * fbo - terciary * 0 )
BLUR
(unless *blend*
(setf *blend* (make-blending-params :source-rgb :one
:destination-rgb :one)))
(when *half-fbo*
(free *half-fbo*)
(free *fourth-fbo*)
(free *eighth-fbo*)
(free *sixteen-fbo*))
( setf * half - fbo *
( setf * fourth - fbo *
( setf * eighth - fbo *
( setf * sixteen - fbo *
( setf * * ( cepl : sample ( attachment - tex * half - fbo * 0 )
( setf * * ( cepl : sample ( attachment - tex * fourth - fbo * 0 )
( setf * - fbo * ( cepl : sample ( attachment - tex * eighth - fbo * 0 )
( setf * - fbo * ( cepl : sample ( attachment - tex * sixteen - fbo * 0 )
(setf (clear-color) (v! 0 0 0 1))
( setf ( clear - color ) ( v ! 0 0 0 1 ) )
(setf *actors* nil)
(make-cement)
(make-celestial-sphere)
NIL)
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (resolution (current-viewport)) res)
(update *currentcamera*)
(update-all-the-things *actors*)
(with-fbo-bound (*fbo*)
(clear-fbo *fbo*)
(loop :for actor :in *actors* :do
(draw actor *currentcamera*)))
( clear - color ) ( v ! 0 0 0 1 )
( with - fbo - bound ( * half - fbo * )
: * sam1 *
:x ( / 1f0 width )
: y ( / 1f0 height )
: delta 1f0 ) )
: - fbo *
:x ( / 1f0 ( round ( * .5 width ) ) )
: y ( / 1f0 ( round ( * .5 height ) ) ) ) )
: *
:x ( / 1f0 ( round ( * .5 ( * .5 width ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 height ) ) ) ) ) )
( with - fbo - bound ( * sixteen - fbo * )
( clear - fbo * sixteen - fbo * )
: - fbo *
:x ( / 1f0 ( round ( * .5 ( * .5 ( * .5 width ) ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 ( * .5 height ) ) ) ) ) ) )
: - fbo *
:x ( / 1f0 ( round ( * .5 ( * .5 ( * .5 width ) ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 ( * .5 height ) ) ) ) )
: delta .5 ) ) )
: - fbo *
:x ( / 1f0 ( round ( * .5 ( * .5 width ) ) ) )
: y ( / 1f0 ( round ( * .5 ( * .5 height ) ) ) ) ) ) )
( with - fbo - bound ( * half - fbo * )
: *
:x ( / 1f0 ( round ( * .5 width ) ) )
: y ( / 1f0 ( round ( * .5 height ) ) ) ) ) )
: - fbo *
:x ( / 1f0 width )
: y ( / 1f0 height ) ) ) )
: *
: * *
: delta .5
:x ( / 1f0 width )
: y ( / 1f0 height ) ) ) ) )
(as-frame
(with-setf* ((depth-mask) nil
(cull-face) nil
(clear-color) (v! 0 0 0 1)
(depth-test-function) #'always)
(map-g #'ssao-pipe *bs*
: g - position * *
:g-normal *sam-nor*
:g-depth *sam-depth*
:kernel *kernel*
:kernel-effect *kernel-effect*
:radius *radius*
:tex-noise *noise-sam*
:random-kernel *ubo-kernel*
:res (v! *dimensions-fbo*)
:view-clip (projection *currentcamera*))))
: *
))
(def-simple-main-loop runplay
(:on-start #'initialize)
(draw!))
|
855417e1c9f0c6575281c552d0a0f8a17e7750aa0e03b0e436532fca3dab8193 | korya/efuns | jeton.ml | (***********************************************************************)
(* *)
xlib for
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Concur
type 'a value =
NoValue
| Value of 'a
| Exc of exn
type 'a t =
{
mutex: Mutex.t;
condition: Condition.t;
mutable contenu: 'a value
}
let create () =
{ mutex = Mutex.create ();
condition = Condition.create ();
contenu = NoValue
}
let signal_value event v =
Mutex.lock event.mutex;
event.contenu <- Value v;
Condition.signal event.condition;
Mutex.unlock event.mutex
let signal_exception event e =
Mutex.lock event.mutex;
event.contenu <- Exc e;
Condition.signal event.condition;
Mutex.unlock event.mutex
let wait event =
Mutex.lock event.mutex;
Log.printf " < J>%s " " " ;
while event.contenu = NoValue do
Condition.wait event.condition event.mutex;
done;
let contenu = event.contenu in
(* Log.printf "</J>%s" ""; *)
event.contenu <- NoValue;
Mutex.unlock event.mutex;
match contenu with
NoValue -> assert false
| Value v ->
v
| Exc e -> raise e
let check event = event.contenu = NoValue
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/xlib/jeton.ml | ocaml | *********************************************************************
*********************************************************************
Log.printf "</J>%s" ""; | xlib for
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Concur
type 'a value =
NoValue
| Value of 'a
| Exc of exn
type 'a t =
{
mutex: Mutex.t;
condition: Condition.t;
mutable contenu: 'a value
}
let create () =
{ mutex = Mutex.create ();
condition = Condition.create ();
contenu = NoValue
}
let signal_value event v =
Mutex.lock event.mutex;
event.contenu <- Value v;
Condition.signal event.condition;
Mutex.unlock event.mutex
let signal_exception event e =
Mutex.lock event.mutex;
event.contenu <- Exc e;
Condition.signal event.condition;
Mutex.unlock event.mutex
let wait event =
Mutex.lock event.mutex;
Log.printf " < J>%s " " " ;
while event.contenu = NoValue do
Condition.wait event.condition event.mutex;
done;
let contenu = event.contenu in
event.contenu <- NoValue;
Mutex.unlock event.mutex;
match contenu with
NoValue -> assert false
| Value v ->
v
| Exc e -> raise e
let check event = event.contenu = NoValue
|
26400f2328525e667d0c7a5444d4cf1a0ab53ff4e4f7eeff053c2247991b45d4 | LeventErkok/crackNum | Setup.hs | -----------------------------------------------------------------------------
-- |
-- Module : Main
Copyright : ( c )
-- License : BSD3
-- Maintainer :
-- Stability : experimental
--
-- Setup module for crackNum
-----------------------------------------------------------------------------
# OPTIONS_GHC -Wall #
module Main(main) where
import Distribution.Simple
main :: IO ()
main = defaultMain
| null | https://raw.githubusercontent.com/LeventErkok/crackNum/3c89e5a4f70257dd2cb9cb069b8c49fbb90f30c6/Setup.hs | haskell | ---------------------------------------------------------------------------
|
Module : Main
License : BSD3
Maintainer :
Stability : experimental
Setup module for crackNum
--------------------------------------------------------------------------- | Copyright : ( c )
# OPTIONS_GHC -Wall #
module Main(main) where
import Distribution.Simple
main :: IO ()
main = defaultMain
|
54be7b76e595d0b1eb2db9656afec49e71074a2dedb8f6f6931e95dbf8501284 | SuzanneSoy/anaphoric | if-let-test.rkt | #lang racket
(require anaphoric/if-let
rackunit)
(define lst '(x y z a b c))
(check-equal? (if-let [x (member 'a lst)]
(begin (check-equal? x '(a b c))
'seen)
(fail "aif selected wrong branch"))
'seen)
(check-equal? (let ([x 'outer])
(if-let [x (member 'a lst)]
(begin (check-equal? x '(a b c))
'seen)
(fail "aif selected wrong branch")))
'seen)
(check-equal? (let ([x 'outer])
(if-let [x (member 'absent lst)]
(fail "aif selected wrong branch")
'outer))
'outer)
| null | https://raw.githubusercontent.com/SuzanneSoy/anaphoric/c648ec2aad6d2b2ec72acc729143454d1e855cf6/test/if-let-test.rkt | racket | #lang racket
(require anaphoric/if-let
rackunit)
(define lst '(x y z a b c))
(check-equal? (if-let [x (member 'a lst)]
(begin (check-equal? x '(a b c))
'seen)
(fail "aif selected wrong branch"))
'seen)
(check-equal? (let ([x 'outer])
(if-let [x (member 'a lst)]
(begin (check-equal? x '(a b c))
'seen)
(fail "aif selected wrong branch")))
'seen)
(check-equal? (let ([x 'outer])
(if-let [x (member 'absent lst)]
(fail "aif selected wrong branch")
'outer))
'outer)
| |
6d976633252631c0e372173c4bc373c95e8a830999793b6df3efb68f40c43a31 | ocamllabs/ocaml-modular-implicits | t252-pushoffsetclosure.ml | open Lib;;
let rec f x = x
and g _ = f 4
and h _ = f 6
in
if h 1 <> 6 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 25
11 ACC0
12 RETURN 1
14 CONSTINT 4
16 PUSHOFFSETCLOSUREM2
17 APPTERM1 2
19 CONSTINT 6
21 PUSHOFFSETCLOSURE -4
23 APPTERM1 2
25 CLOSUREREC 0 , 11 , 14 , 19
31 CONSTINT 6
33 PUSHCONST1
34 PUSHACC2
35 APPLY1
36 NEQ
37 BRANCHIFNOT 44
39 Not_found
41 MAKEBLOCK1 0
43 RAISE
44 POP 3
46 ATOM0
47 T252 - pushoffsetclosure
49 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 25
11 ACC0
12 RETURN 1
14 CONSTINT 4
16 PUSHOFFSETCLOSUREM2
17 APPTERM1 2
19 CONSTINT 6
21 PUSHOFFSETCLOSURE -4
23 APPTERM1 2
25 CLOSUREREC 0, 11, 14, 19
31 CONSTINT 6
33 PUSHCONST1
34 PUSHACC2
35 APPLY1
36 NEQ
37 BRANCHIFNOT 44
39 GETGLOBAL Not_found
41 MAKEBLOCK1 0
43 RAISE
44 POP 3
46 ATOM0
47 SETGLOBAL T252-pushoffsetclosure
49 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t252-pushoffsetclosure.ml | ocaml | open Lib;;
let rec f x = x
and g _ = f 4
and h _ = f 6
in
if h 1 <> 6 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 25
11 ACC0
12 RETURN 1
14 CONSTINT 4
16 PUSHOFFSETCLOSUREM2
17 APPTERM1 2
19 CONSTINT 6
21 PUSHOFFSETCLOSURE -4
23 APPTERM1 2
25 CLOSUREREC 0 , 11 , 14 , 19
31 CONSTINT 6
33 PUSHCONST1
34 PUSHACC2
35 APPLY1
36 NEQ
37 BRANCHIFNOT 44
39 Not_found
41 MAKEBLOCK1 0
43 RAISE
44 POP 3
46 ATOM0
47 T252 - pushoffsetclosure
49 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 25
11 ACC0
12 RETURN 1
14 CONSTINT 4
16 PUSHOFFSETCLOSUREM2
17 APPTERM1 2
19 CONSTINT 6
21 PUSHOFFSETCLOSURE -4
23 APPTERM1 2
25 CLOSUREREC 0, 11, 14, 19
31 CONSTINT 6
33 PUSHCONST1
34 PUSHACC2
35 APPLY1
36 NEQ
37 BRANCHIFNOT 44
39 GETGLOBAL Not_found
41 MAKEBLOCK1 0
43 RAISE
44 POP 3
46 ATOM0
47 SETGLOBAL T252-pushoffsetclosure
49 STOP
**)
| |
20433aa6e6ccc5cf9a3512798cd6ce22ec563369ee51668a24ed71d437aea306 | orionsbelt-battlegrounds/obb-rules | test_runner.cljs | (ns obb-rules.test-runner
(:require [cljs.test :refer-macros [run-tests run-all-tests] :refer [empty-env report]]
[obb-rules.test-requires]))
(enable-console-print!)
(defn runner
[]
(time (run-all-tests #"obb-rules.*-test")))
(runner)
(defn -main [& args])
(set! *main-cli-fn* -main)
| null | https://raw.githubusercontent.com/orionsbelt-battlegrounds/obb-rules/97fad6506eb81142f74f4722aca58b80d618bf45/test/obb_rules/test_runner.cljs | clojure | (ns obb-rules.test-runner
(:require [cljs.test :refer-macros [run-tests run-all-tests] :refer [empty-env report]]
[obb-rules.test-requires]))
(enable-console-print!)
(defn runner
[]
(time (run-all-tests #"obb-rules.*-test")))
(runner)
(defn -main [& args])
(set! *main-cli-fn* -main)
| |
4d25add05f7fe1a0d27fa86ddd8cd9b003b94a5ae4d796983162199cf0258cb7 | buildsome/buildsome | Show.hs | module Lib.Show (show) where
import Prelude.Compat hiding (show)
import qualified Prelude.Compat as Prelude
import Data.String (IsString(..))
show :: (Show a, IsString str) => a -> str
show = fromString . Prelude.show
| null | https://raw.githubusercontent.com/buildsome/buildsome/479b92bb74a474a5f0c3292b79202cc850bd8653/src/Lib/Show.hs | haskell | module Lib.Show (show) where
import Prelude.Compat hiding (show)
import qualified Prelude.Compat as Prelude
import Data.String (IsString(..))
show :: (Show a, IsString str) => a -> str
show = fromString . Prelude.show
| |
77773ac280cc6ea88d3b9bd0e4289906ce5476cf563a1c1162982606d54396c6 | TerrorJack/ghc-alter | memo001.hs | module Main(main) where
import Memo1
testMemo = do
let keys = [ [1..n] | n <- [1..1000] ]
keys2 = [ [n,n-1..1] | n <- [1..1000] ]
mlength = memo length
putStr (show (map mlength (keys ++ keys ++ keys2 ++ keys2)))
putStr (show (mlength [1..100000]))
will memoize itself over each element of ' keys ' , returning
the memoized result the second time around . Then we move onto
keys2 , and while we 're doing this the first lot of memo table
-- entries can be purged. Finally, we do a a large computation
( length [ 1 .. 10000 ] ) to allow time for the memo table to be fully
-- purged.
main = testMemo
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/memo001.hs | haskell | entries can be purged. Finally, we do a a large computation
purged. | module Main(main) where
import Memo1
testMemo = do
let keys = [ [1..n] | n <- [1..1000] ]
keys2 = [ [n,n-1..1] | n <- [1..1000] ]
mlength = memo length
putStr (show (map mlength (keys ++ keys ++ keys2 ++ keys2)))
putStr (show (mlength [1..100000]))
will memoize itself over each element of ' keys ' , returning
the memoized result the second time around . Then we move onto
keys2 , and while we 're doing this the first lot of memo table
( length [ 1 .. 10000 ] ) to allow time for the memo table to be fully
main = testMemo
|
3b42dd7f98ca760cae44a8d21c3989a83346ccbe700426c6f7c23e947f8b5c70 | xtdb/xtdb | main.clj | (ns xtdb.console-demo.main
(:require [xtdb.api :as xt]
[integrant.core :as ig]
[integrant.repl :as ir]
[clojure.string :as string]
[clojure.java.io :as io]
[xtdb.rocksdb :as rocks])
(:import java.io.Closeable)
(:gen-class))
(defmethod ig/init-key :console-demo/xtdb-node [_ node-opts]
(let [node (doto (xt/start-node node-opts) (xt/sync))
submit-data? (nil? (xt/entity (xt/db node) :tmdb/cast-65731))]
(when submit-data?
(with-open [dataset-rdr (io/reader "-data.s3.eu-west-2.amazonaws.com/kaggle-tmdb-movies.edn")]
(let [last-tx (->> (line-seq dataset-rdr)
(partition-all 1000)
(reduce (fn [last-tx docs-chunk]
(xt/submit-tx node (mapv read-string docs-chunk)))
nil))]
(prn "Loading Sample Data...")
;; Await data-set data
(xt/await-tx node last-tx)
;; Submit :bar multiple times - entity to showcase entity searching/history.
(xt/submit-tx node [[::xt/put {:xt/id :bar} #inst "2018-06-01"]])
(xt/submit-tx node [[::xt/put {:xt/id :bar :map {:a 1 :b 2}} #inst "2019-04-04"]])
(xt/submit-tx node [[::xt/put {:xt/id :bar :vector [:a :b]} #inst "2020-01-02"]])
(xt/await-tx node (xt/submit-tx node [[::xt/put {:xt/id :bar :hello "world"}]]))
(prn "Sample Data Loaded!"))))
node))
(defmethod ig/halt-key! :console-demo/xtdb-node [_ ^Closeable node]
(.close node))
(defn config []
{:console-demo/xtdb-node {:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir "data/tx-log"}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir "data/doc-store"}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir "data/indices"}}
:xtdb.http-server/server {:read-only? true
:server-label "Console Demo"}
:xtdb.metrics/registry {}}})
(defn -main [& args]
(ir/set-prep! config)
(ir/go))
| null | https://raw.githubusercontent.com/xtdb/xtdb/e2f51ed99fc2716faa8ad254c0b18166c937b134/examples/console-demo/src/xtdb/console_demo/main.clj | clojure | Await data-set data
Submit :bar multiple times - entity to showcase entity searching/history. | (ns xtdb.console-demo.main
(:require [xtdb.api :as xt]
[integrant.core :as ig]
[integrant.repl :as ir]
[clojure.string :as string]
[clojure.java.io :as io]
[xtdb.rocksdb :as rocks])
(:import java.io.Closeable)
(:gen-class))
(defmethod ig/init-key :console-demo/xtdb-node [_ node-opts]
(let [node (doto (xt/start-node node-opts) (xt/sync))
submit-data? (nil? (xt/entity (xt/db node) :tmdb/cast-65731))]
(when submit-data?
(with-open [dataset-rdr (io/reader "-data.s3.eu-west-2.amazonaws.com/kaggle-tmdb-movies.edn")]
(let [last-tx (->> (line-seq dataset-rdr)
(partition-all 1000)
(reduce (fn [last-tx docs-chunk]
(xt/submit-tx node (mapv read-string docs-chunk)))
nil))]
(prn "Loading Sample Data...")
(xt/await-tx node last-tx)
(xt/submit-tx node [[::xt/put {:xt/id :bar} #inst "2018-06-01"]])
(xt/submit-tx node [[::xt/put {:xt/id :bar :map {:a 1 :b 2}} #inst "2019-04-04"]])
(xt/submit-tx node [[::xt/put {:xt/id :bar :vector [:a :b]} #inst "2020-01-02"]])
(xt/await-tx node (xt/submit-tx node [[::xt/put {:xt/id :bar :hello "world"}]]))
(prn "Sample Data Loaded!"))))
node))
(defmethod ig/halt-key! :console-demo/xtdb-node [_ ^Closeable node]
(.close node))
(defn config []
{:console-demo/xtdb-node {:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir "data/tx-log"}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir "data/doc-store"}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir "data/indices"}}
:xtdb.http-server/server {:read-only? true
:server-label "Console Demo"}
:xtdb.metrics/registry {}}})
(defn -main [& args]
(ir/set-prep! config)
(ir/go))
|
31551d2d0cf94010922e5c1e4ea27ca228f712dc0a5ed39bd32abfed24f2b509 | grin-compiler/ghc-wpc-sample-programs | Powerpoint.hs | # LANGUAGE NoImplicitPrelude #
module Tests.Writers.Powerpoint (tests) where
import Prelude
import Tests.Writers.OOXML (ooxmlTest)
import Text.Pandoc
import Test.Tasty
import System.FilePath
import Text.DocTemplates (ToContext(toVal), Context(..))
import qualified Data.Map as M
import Data.Text (pack)
-- templating is important enough, and can break enough things, that
-- we want to run all our tests with both default formatting and a
-- template.
modifyPptxName :: FilePath -> FilePath
modifyPptxName fp =
addExtension (dropExtension fp ++ "_templated") "pptx"
pptxTests :: String -> WriterOptions -> FilePath -> FilePath -> (TestTree, TestTree)
pptxTests name opts native pptx =
let referenceDoc = "pptx/reference_depth.pptx"
in
( ooxmlTest
writePowerpoint
name
opts{writerReferenceDoc=Nothing}
native
pptx
, ooxmlTest
writePowerpoint
name
opts{writerReferenceDoc=Just referenceDoc}
native
(modifyPptxName pptx)
)
groupPptxTests :: [(TestTree, TestTree)] -> [TestTree]
groupPptxTests pairs =
let (noRefs, refs) = unzip pairs
in
[ testGroup "Default slide formatting" noRefs
, testGroup "With `--reference-doc` pptx file" refs
]
tests :: [TestTree]
tests = groupPptxTests [ pptxTests "Inline formatting"
def
"pptx/inline_formatting.native"
"pptx/inline_formatting.pptx"
, pptxTests "Slide breaks (default slide-level)"
def
"pptx/slide_breaks.native"
"pptx/slide_breaks.pptx"
, pptxTests "slide breaks (slide-level set to 1)"
def{ writerSlideLevel = Just 1 }
"pptx/slide_breaks.native"
"pptx/slide_breaks_slide_level_1.pptx"
, pptxTests "lists"
def
"pptx/lists.native"
"pptx/lists.pptx"
, pptxTests "start ordered list at specified num"
def
"pptx/start_numbering_at.native"
"pptx/start_numbering_at.pptx"
, pptxTests "tables"
def
"pptx/tables.native"
"pptx/tables.pptx"
, pptxTests "table of contents"
def{ writerTableOfContents = True }
"pptx/slide_breaks.native"
"pptx/slide_breaks_toc.pptx"
, pptxTests "end notes"
def
"pptx/endnotes.native"
"pptx/endnotes.pptx"
, pptxTests "end notes, with table of contents"
def { writerTableOfContents = True }
"pptx/endnotes.native"
"pptx/endnotes_toc.pptx"
, pptxTests "images"
def
"pptx/images.native"
"pptx/images.pptx"
, pptxTests "two-column layout"
def
"pptx/two_column.native"
"pptx/two_column.pptx"
, pptxTests "speaker notes"
def
"pptx/speaker_notes.native"
"pptx/speaker_notes.pptx"
, pptxTests "speaker notes after a separating block"
def
"pptx/speaker_notes_afterseps.native"
"pptx/speaker_notes_afterseps.pptx"
, pptxTests "speaker notes after a separating header"
def
"pptx/speaker_notes_afterheader.native"
"pptx/speaker_notes_afterheader.pptx"
, pptxTests "speaker notes after metadata"
def
"pptx/speaker_notes_after_metadata.native"
"pptx/speaker_notes_after_metadata.pptx"
, pptxTests "remove empty slides"
def
"pptx/remove_empty_slides.native"
"pptx/remove_empty_slides.pptx"
, pptxTests "raw ooxml"
def
"pptx/raw_ooxml.native"
"pptx/raw_ooxml.pptx"
, pptxTests "metadata, custom properties"
def
"pptx/document-properties.native"
"pptx/document-properties.pptx"
, pptxTests "metadata, short description"
def
"pptx/document-properties-short-desc.native"
"pptx/document-properties-short-desc.pptx"
, pptxTests "inline code and code blocks"
def
"pptx/code.native"
"pptx/code.pptx"
, pptxTests "inline code and code blocks, custom formatting"
def { writerVariables = Context $ M.fromList
[(pack "monofont", toVal $ pack "Consolas")] }
"pptx/code.native"
"pptx/code-custom.pptx"
]
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/pandoc-11df2a3c0f2b1b8e351ad8caaa7cdf583e1b3b2e/test/Tests/Writers/Powerpoint.hs | haskell | templating is important enough, and can break enough things, that
we want to run all our tests with both default formatting and a
template. | # LANGUAGE NoImplicitPrelude #
module Tests.Writers.Powerpoint (tests) where
import Prelude
import Tests.Writers.OOXML (ooxmlTest)
import Text.Pandoc
import Test.Tasty
import System.FilePath
import Text.DocTemplates (ToContext(toVal), Context(..))
import qualified Data.Map as M
import Data.Text (pack)
modifyPptxName :: FilePath -> FilePath
modifyPptxName fp =
addExtension (dropExtension fp ++ "_templated") "pptx"
pptxTests :: String -> WriterOptions -> FilePath -> FilePath -> (TestTree, TestTree)
pptxTests name opts native pptx =
let referenceDoc = "pptx/reference_depth.pptx"
in
( ooxmlTest
writePowerpoint
name
opts{writerReferenceDoc=Nothing}
native
pptx
, ooxmlTest
writePowerpoint
name
opts{writerReferenceDoc=Just referenceDoc}
native
(modifyPptxName pptx)
)
groupPptxTests :: [(TestTree, TestTree)] -> [TestTree]
groupPptxTests pairs =
let (noRefs, refs) = unzip pairs
in
[ testGroup "Default slide formatting" noRefs
, testGroup "With `--reference-doc` pptx file" refs
]
tests :: [TestTree]
tests = groupPptxTests [ pptxTests "Inline formatting"
def
"pptx/inline_formatting.native"
"pptx/inline_formatting.pptx"
, pptxTests "Slide breaks (default slide-level)"
def
"pptx/slide_breaks.native"
"pptx/slide_breaks.pptx"
, pptxTests "slide breaks (slide-level set to 1)"
def{ writerSlideLevel = Just 1 }
"pptx/slide_breaks.native"
"pptx/slide_breaks_slide_level_1.pptx"
, pptxTests "lists"
def
"pptx/lists.native"
"pptx/lists.pptx"
, pptxTests "start ordered list at specified num"
def
"pptx/start_numbering_at.native"
"pptx/start_numbering_at.pptx"
, pptxTests "tables"
def
"pptx/tables.native"
"pptx/tables.pptx"
, pptxTests "table of contents"
def{ writerTableOfContents = True }
"pptx/slide_breaks.native"
"pptx/slide_breaks_toc.pptx"
, pptxTests "end notes"
def
"pptx/endnotes.native"
"pptx/endnotes.pptx"
, pptxTests "end notes, with table of contents"
def { writerTableOfContents = True }
"pptx/endnotes.native"
"pptx/endnotes_toc.pptx"
, pptxTests "images"
def
"pptx/images.native"
"pptx/images.pptx"
, pptxTests "two-column layout"
def
"pptx/two_column.native"
"pptx/two_column.pptx"
, pptxTests "speaker notes"
def
"pptx/speaker_notes.native"
"pptx/speaker_notes.pptx"
, pptxTests "speaker notes after a separating block"
def
"pptx/speaker_notes_afterseps.native"
"pptx/speaker_notes_afterseps.pptx"
, pptxTests "speaker notes after a separating header"
def
"pptx/speaker_notes_afterheader.native"
"pptx/speaker_notes_afterheader.pptx"
, pptxTests "speaker notes after metadata"
def
"pptx/speaker_notes_after_metadata.native"
"pptx/speaker_notes_after_metadata.pptx"
, pptxTests "remove empty slides"
def
"pptx/remove_empty_slides.native"
"pptx/remove_empty_slides.pptx"
, pptxTests "raw ooxml"
def
"pptx/raw_ooxml.native"
"pptx/raw_ooxml.pptx"
, pptxTests "metadata, custom properties"
def
"pptx/document-properties.native"
"pptx/document-properties.pptx"
, pptxTests "metadata, short description"
def
"pptx/document-properties-short-desc.native"
"pptx/document-properties-short-desc.pptx"
, pptxTests "inline code and code blocks"
def
"pptx/code.native"
"pptx/code.pptx"
, pptxTests "inline code and code blocks, custom formatting"
def { writerVariables = Context $ M.fromList
[(pack "monofont", toVal $ pack "Consolas")] }
"pptx/code.native"
"pptx/code-custom.pptx"
]
|
2e1ad8320bce7f60ca161b954f4fb0b7d391d58ea786f3106f9b08778460a661 | thheller/shadow-cljs | util.cljs | (ns shadow.cljs.npm.util
(:require
["child_process" :as cp]
["fs" :as fs]))
(defn slurp [file]
(-> (fs/readFileSync file)
(.toString)))
(defn reduce-> [init reduce-fn coll]
(reduce reduce-fn init coll))
(defn conj-set [x y]
(if (nil? x)
#{y}
(conj x y)))
(defn kill-proc [^js proc]
;; the java process should now always exit cleanly when the node process is killed
so we just kill the node process to let the jvm shutdown cleanly
(.kill proc)
#_(case js/process.platform
"win32"
(cp/spawnSync "taskkill" #js ["/pid" (.-pid proc) "/f" #_"/t"])
(.kill proc)
)) | null | https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/main/shadow/cljs/npm/util.cljs | clojure | the java process should now always exit cleanly when the node process is killed | (ns shadow.cljs.npm.util
(:require
["child_process" :as cp]
["fs" :as fs]))
(defn slurp [file]
(-> (fs/readFileSync file)
(.toString)))
(defn reduce-> [init reduce-fn coll]
(reduce reduce-fn init coll))
(defn conj-set [x y]
(if (nil? x)
#{y}
(conj x y)))
(defn kill-proc [^js proc]
so we just kill the node process to let the jvm shutdown cleanly
(.kill proc)
#_(case js/process.platform
"win32"
(cp/spawnSync "taskkill" #js ["/pid" (.-pid proc) "/f" #_"/t"])
(.kill proc)
)) |
dc0ab6d6364684fcc7f54f49fba40204fece900c44c10e062340de568663be84 | metabase/metabase | field_values.clj | (ns metabase.models.params.field-values
"Code related to fetching FieldValues for Fields to populate parameter widgets. Always used by the field
values (`GET /api/field/:id/values`) endpoint; used by the chain filter endpoints under certain circumstances."
(:require
[metabase.models.field-values :as field-values :refer [FieldValues]]
[metabase.models.interface :as mi]
[metabase.plugins.classloader :as classloader]
[metabase.public-settings.premium-features :refer [defenterprise]]
[metabase.util :as u]
[toucan.db :as db]))
(defn default-get-or-create-field-values-for-current-user!
"OSS implementation; used as a fallback for the EE implementation if the field isn't sandboxed."
[field]
(field-values/get-or-create-full-field-values! field))
(defenterprise get-or-create-field-values-for-current-user!*
"Fetch cached FieldValues for a `field`, creating them if needed if the Field should have FieldValues."
metabase-enterprise.sandbox.models.params.field-values
[field]
(default-get-or-create-field-values-for-current-user! field))
(defn current-user-can-fetch-field-values?
"Whether the current User has permissions to fetch FieldValues for a `field`."
[field]
;; read permissions for a Field = partial permissions for its parent Table (including EE segmented permissions)
(mi/can-read? field))
(defn- postprocess-field-values
"Format a FieldValues to use by params functions.
( postprocess - field - values ( db / select - one FieldValues : i d 1 ) ( Field 1 ) )
= > { : values [ 1 2 3 4 ]
:field_id 1
:has_more_values boolean}"
[field-values field]
(if field-values
(-> field-values
(assoc :values (field-values/field-values->pairs field-values))
(select-keys [:values :field_id :has_more_values]))
{:values [], :field_id (u/the-id field), :has_more_values false}))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Advanced FieldValues |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- fetch-advanced-field-values
[fv-type field constraints]
{:pre [(field-values/advanced-field-values-types fv-type)]}
(case fv-type
:linked-filter
(do
(classloader/require 'metabase.models.params.chain-filter)
(let [{:keys [values has_more_values]} ((resolve 'metabase.models.params.chain-filter/unremapped-chain-filter)
(:id field) constraints {})
we have a hard limit for how many values we want to store in FieldValues ,
;; let's make sure we respect that limit here.
For a more detailed docs on this limt check out [ [ field - values / distinct - values ] ]
limited-values (field-values/take-by-length field-values/*total-max-length* values)]
{:values limited-values
:has_more_values (or (> (count values)
(count limited-values))
has_more_values)}))
:sandbox
(field-values/distinct-values field)))
(defn hash-key-for-advanced-field-values
"Returns hash-key for Advanced FieldValues by types."
[fv-type field-id constraints]
(case fv-type
:linked-filter
(field-values/hash-key-for-linked-filters field-id constraints)
:sandbox
(field-values/hash-key-for-sandbox field-id)))
(defn create-advanced-field-values!
"Fetch and create a FieldValues for `field` with type `fv-type`.
The human_readable_values of Advanced FieldValues will be automatically fixed up based on the
list of values and human_readable_values of the full FieldValues of the same field."
[fv-type field hash-key constraints]
(when-let [{:keys [values has_more_values]} (fetch-advanced-field-values fv-type field constraints)]
If the full FieldValues of this field has a human - readable - values , fix it with the new values
human-readable-values (field-values/fixup-human-readable-values
(db/select-one FieldValues
:field_id (:id field)
:type :full)
values)]
(db/insert! FieldValues
:field_id (:id field)
:type fv-type
:hash_key hash-key
:has_more_values has_more_values
:human_readable_values human-readable-values
:values values))))
(defn get-or-create-advanced-field-values!
"Fetch an Advanced FieldValues with type `fv-type` for a `field`, creating them if needed.
If the fetched FieldValues is expired, we delete them then try to create it."
([fv-type field]
(get-or-create-advanced-field-values! fv-type field nil))
([fv-type field constraints]
(let [hash-key (hash-key-for-advanced-field-values fv-type (:id field) constraints)
fv (or (db/select-one FieldValues :field_id (:id field)
:type fv-type
:hash_key hash-key)
(create-advanced-field-values! fv-type field hash-key constraints))]
(cond
(nil? fv) nil
;; If it's expired, delete then try to re-create it
(field-values/advanced-field-values-expired? fv) (do
(db/delete! FieldValues :id (:id fv))
(recur fv-type field constraints))
:else fv))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Public functions |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn get-or-create-field-values-for-current-user!
"Fetch FieldValues for a `field`, creating them if needed if the Field should have FieldValues. These are
filtered as appropriate for the current User, depending on MB version (e.g. EE sandboxing will filter these values).
If the Field has a human-readable values remapping (see documentation at the top of
[[metabase.models.params.chain-filter]] for an explanation of what this means), values are returned in the format
{:values [[original-value human-readable-value]]
:field_id field-id
:has_field_values boolean}
If the Field does *not* have human-readable values remapping, values are returned in the format
{:values [[value]]
:field_id field-id
:has_field_values boolean}"
[field]
(-> (get-or-create-field-values-for-current-user!* field)
(postprocess-field-values field)))
(defn get-or-create-linked-filter-field-values!
"Fetch linked-filter FieldValues for a `field`, creating them if needed if the Field should have FieldValues. These are
filtered as appropriate for the current User, depending on MB version (e.g. EE sandboxing will filter these values).
If the Field has a human-readable values remapping (see documentation at the top of
[[metabase.models.params.chain-filter]] for an explanation of what this means), values are returned in the format
{:values [[original-value human-readable-value]]
:field_id field-id
:has_field_values boolean}
If the Field does *not* have human-readable values remapping, values are returned in the format
{:values [[value]]
:field_id field-id
:has_field_values boolean}"
[field constraints]
(-> (get-or-create-advanced-field-values! :linked-filter field constraints)
(postprocess-field-values field)))
| null | https://raw.githubusercontent.com/metabase/metabase/2cd0bb399bb9c4d1ed2b8de0c5fd05cb499aa02b/src/metabase/models/params/field_values.clj | clojure | used by the chain filter endpoints under certain circumstances."
read permissions for a Field = partial permissions for its parent Table (including EE segmented permissions)
+----------------------------------------------------------------------------------------------------------------+
| Advanced FieldValues |
+----------------------------------------------------------------------------------------------------------------+
let's make sure we respect that limit here.
If it's expired, delete then try to re-create it
+----------------------------------------------------------------------------------------------------------------+
| Public functions |
+----------------------------------------------------------------------------------------------------------------+ | (ns metabase.models.params.field-values
"Code related to fetching FieldValues for Fields to populate parameter widgets. Always used by the field
(:require
[metabase.models.field-values :as field-values :refer [FieldValues]]
[metabase.models.interface :as mi]
[metabase.plugins.classloader :as classloader]
[metabase.public-settings.premium-features :refer [defenterprise]]
[metabase.util :as u]
[toucan.db :as db]))
(defn default-get-or-create-field-values-for-current-user!
"OSS implementation; used as a fallback for the EE implementation if the field isn't sandboxed."
[field]
(field-values/get-or-create-full-field-values! field))
(defenterprise get-or-create-field-values-for-current-user!*
"Fetch cached FieldValues for a `field`, creating them if needed if the Field should have FieldValues."
metabase-enterprise.sandbox.models.params.field-values
[field]
(default-get-or-create-field-values-for-current-user! field))
(defn current-user-can-fetch-field-values?
"Whether the current User has permissions to fetch FieldValues for a `field`."
[field]
(mi/can-read? field))
(defn- postprocess-field-values
"Format a FieldValues to use by params functions.
( postprocess - field - values ( db / select - one FieldValues : i d 1 ) ( Field 1 ) )
= > { : values [ 1 2 3 4 ]
:field_id 1
:has_more_values boolean}"
[field-values field]
(if field-values
(-> field-values
(assoc :values (field-values/field-values->pairs field-values))
(select-keys [:values :field_id :has_more_values]))
{:values [], :field_id (u/the-id field), :has_more_values false}))
(defn- fetch-advanced-field-values
[fv-type field constraints]
{:pre [(field-values/advanced-field-values-types fv-type)]}
(case fv-type
:linked-filter
(do
(classloader/require 'metabase.models.params.chain-filter)
(let [{:keys [values has_more_values]} ((resolve 'metabase.models.params.chain-filter/unremapped-chain-filter)
(:id field) constraints {})
we have a hard limit for how many values we want to store in FieldValues ,
For a more detailed docs on this limt check out [ [ field - values / distinct - values ] ]
limited-values (field-values/take-by-length field-values/*total-max-length* values)]
{:values limited-values
:has_more_values (or (> (count values)
(count limited-values))
has_more_values)}))
:sandbox
(field-values/distinct-values field)))
(defn hash-key-for-advanced-field-values
"Returns hash-key for Advanced FieldValues by types."
[fv-type field-id constraints]
(case fv-type
:linked-filter
(field-values/hash-key-for-linked-filters field-id constraints)
:sandbox
(field-values/hash-key-for-sandbox field-id)))
(defn create-advanced-field-values!
"Fetch and create a FieldValues for `field` with type `fv-type`.
The human_readable_values of Advanced FieldValues will be automatically fixed up based on the
list of values and human_readable_values of the full FieldValues of the same field."
[fv-type field hash-key constraints]
(when-let [{:keys [values has_more_values]} (fetch-advanced-field-values fv-type field constraints)]
If the full FieldValues of this field has a human - readable - values , fix it with the new values
human-readable-values (field-values/fixup-human-readable-values
(db/select-one FieldValues
:field_id (:id field)
:type :full)
values)]
(db/insert! FieldValues
:field_id (:id field)
:type fv-type
:hash_key hash-key
:has_more_values has_more_values
:human_readable_values human-readable-values
:values values))))
(defn get-or-create-advanced-field-values!
"Fetch an Advanced FieldValues with type `fv-type` for a `field`, creating them if needed.
If the fetched FieldValues is expired, we delete them then try to create it."
([fv-type field]
(get-or-create-advanced-field-values! fv-type field nil))
([fv-type field constraints]
(let [hash-key (hash-key-for-advanced-field-values fv-type (:id field) constraints)
fv (or (db/select-one FieldValues :field_id (:id field)
:type fv-type
:hash_key hash-key)
(create-advanced-field-values! fv-type field hash-key constraints))]
(cond
(nil? fv) nil
(field-values/advanced-field-values-expired? fv) (do
(db/delete! FieldValues :id (:id fv))
(recur fv-type field constraints))
:else fv))))
(defn get-or-create-field-values-for-current-user!
"Fetch FieldValues for a `field`, creating them if needed if the Field should have FieldValues. These are
filtered as appropriate for the current User, depending on MB version (e.g. EE sandboxing will filter these values).
If the Field has a human-readable values remapping (see documentation at the top of
[[metabase.models.params.chain-filter]] for an explanation of what this means), values are returned in the format
{:values [[original-value human-readable-value]]
:field_id field-id
:has_field_values boolean}
If the Field does *not* have human-readable values remapping, values are returned in the format
{:values [[value]]
:field_id field-id
:has_field_values boolean}"
[field]
(-> (get-or-create-field-values-for-current-user!* field)
(postprocess-field-values field)))
(defn get-or-create-linked-filter-field-values!
"Fetch linked-filter FieldValues for a `field`, creating them if needed if the Field should have FieldValues. These are
filtered as appropriate for the current User, depending on MB version (e.g. EE sandboxing will filter these values).
If the Field has a human-readable values remapping (see documentation at the top of
[[metabase.models.params.chain-filter]] for an explanation of what this means), values are returned in the format
{:values [[original-value human-readable-value]]
:field_id field-id
:has_field_values boolean}
If the Field does *not* have human-readable values remapping, values are returned in the format
{:values [[value]]
:field_id field-id
:has_field_values boolean}"
[field constraints]
(-> (get-or-create-advanced-field-values! :linked-filter field constraints)
(postprocess-field-values field)))
|
e51c68bf47d042e2032f2e5e6a4c91803be40fb4e409c6e413a81d00ba9203b1 | Relph1119/sicp-solutions-manual | p1-23-find-divisor.scm | (load "src/examples/ch01/p8-square.scm")
(load "src/examples/ch01/p33-divides.scm")
(load "src/practices/ch01/p1-23-next.scm")
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor))))) | null | https://raw.githubusercontent.com/Relph1119/sicp-solutions-manual/f2ff309a6c898376209c198030c70d6adfac1fc1/src/practices/ch01/p1-23-find-divisor.scm | scheme | (load "src/examples/ch01/p8-square.scm")
(load "src/examples/ch01/p33-divides.scm")
(load "src/practices/ch01/p1-23-next.scm")
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor))))) | |
3f2524552455a084d2c11def2b5a4a3ea6932c8a9a403b271550dc688f07c7c1 | cram2/cram | main.lisp | (in-package :cslg)
(defun main (num-experiments)
(setf cram-bullet-reasoning-belief-state:*spawn-debug-window* nil)
(setf cram-tf:*tf-broadcasting-enabled* t)
(roslisp-utilities:startup-ros :name "cram" :anonymous nil)
(setf ccl::*is-logging-enabled* t)
(setf ccl::*host* "''")
(setf ccl::*cert-path* "'/home/koralewski/Desktop/localhost.pem'")
(setf ccl::*api-key* "'K103jdr40Rp8UX4egmRf42VbdB1b5PW7qYOOVvTDAoiNG6lcQoaDHONf5KaFcefs'")
(ccl::connect-to-cloud-logger)
( * nil )
(loop for x from 1 to num-experiments
do (let ((experiment-id (format nil "~d" (truncate (* 1000000 (cram-utilities:current-timestamp))))))
(let ((experiment-save-path
(concatenate 'string
"~/projection-experiments/" experiment-id "/")))
(ensure-directories-exist experiment-save-path)
(setq ccl::*prolog-query-save-path* experiment-save-path)
(format t "Starting experiment ~a~%" experiment-id)
(asdf-utils:run-program (concatenate 'string "rosrun mongodb_log mongodb_log -c " experiment-id " &"))
(unwind-protect
;; (pr2-proj:with-simulated-robot (demo::demo-random nil '(:bowl :spoon)))
(pr2-proj:with-simulated-robot (demo::demo-random))
;; (demo::generate-training-data)
(ccl::export-log-to-owl (concatenate 'string experiment-id ".owl"))
(format t "Done with experiment ~a~%" experiment-id)
(asdf-utils:run-program (concatenate 'string "docker cp seba:/home/ros/user_data/" experiment-id ".owl " experiment-save-path))
(asdf-utils:run-program "killall -r 'mongodb_log'")
(ccl::reset-logged-owl))))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_learning/cram_sim_log_generator/src/main.lisp | lisp | (pr2-proj:with-simulated-robot (demo::demo-random nil '(:bowl :spoon)))
(demo::generate-training-data) | (in-package :cslg)
(defun main (num-experiments)
(setf cram-bullet-reasoning-belief-state:*spawn-debug-window* nil)
(setf cram-tf:*tf-broadcasting-enabled* t)
(roslisp-utilities:startup-ros :name "cram" :anonymous nil)
(setf ccl::*is-logging-enabled* t)
(setf ccl::*host* "''")
(setf ccl::*cert-path* "'/home/koralewski/Desktop/localhost.pem'")
(setf ccl::*api-key* "'K103jdr40Rp8UX4egmRf42VbdB1b5PW7qYOOVvTDAoiNG6lcQoaDHONf5KaFcefs'")
(ccl::connect-to-cloud-logger)
( * nil )
(loop for x from 1 to num-experiments
do (let ((experiment-id (format nil "~d" (truncate (* 1000000 (cram-utilities:current-timestamp))))))
(let ((experiment-save-path
(concatenate 'string
"~/projection-experiments/" experiment-id "/")))
(ensure-directories-exist experiment-save-path)
(setq ccl::*prolog-query-save-path* experiment-save-path)
(format t "Starting experiment ~a~%" experiment-id)
(asdf-utils:run-program (concatenate 'string "rosrun mongodb_log mongodb_log -c " experiment-id " &"))
(unwind-protect
(pr2-proj:with-simulated-robot (demo::demo-random))
(ccl::export-log-to-owl (concatenate 'string experiment-id ".owl"))
(format t "Done with experiment ~a~%" experiment-id)
(asdf-utils:run-program (concatenate 'string "docker cp seba:/home/ros/user_data/" experiment-id ".owl " experiment-save-path))
(asdf-utils:run-program "killall -r 'mongodb_log'")
(ccl::reset-logged-owl))))))
|
e552ec1f0c4995e81424f0c997646a0b930611b7651d47da519f8f20b2e38a88 | BinaryAnalysisPlatform/bap | thumb_mov.mli | open Bap_core_theory
open Thumb_core
open Thumb_opcodes
module Make(CT : Theory.Core) : sig
open Theory
(** [adds rd, rn, #x] aka add(1) *)
val addi3 : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ adds rd , # x ] aka add(2 )
val addi8 : r32 reg -> int -> cond -> unit eff
* [ adds rd , rn , ] aka add(3 ) and add(4 )
val addrr : r32 reg -> r32 reg -> r32 reg -> cond -> unit eff
* [ add rd , sp , # x ] aka add(6 )
val addrspi : r32 reg -> int -> cond -> unit eff
* [ add sp , # x ] aka )
val addspi : int -> cond -> unit eff
* [ ]
val adcs : r32 reg -> r32 reg -> r32 reg -> cond -> unit eff
* [ subs rd , rn , # x ] aka )
val subi3 : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ subs rd , # x ] aka )
val subi8 : r32 reg -> int -> cond -> unit eff
* [ subs rd , rn , ] aka )
val subrr : r32 reg -> r32 reg -> r32 reg -> cond -> unit eff
(** [subs sp, #i] aka sub(4) *)
val subspi : int -> cond -> unit eff
* [ mov rd , # x ]
val movi8 : r32 reg -> int -> cond -> unit eff
* [ movs rd , rn ]
val movsr : r32 reg -> r32 reg -> unit eff
* [ asrs rd , rn , # i ]
val asri : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ lsrs rd , rn , # i ]
val lsri : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ lsls rd , rn , # i ]
val lsli : r32 reg -> r32 reg -> int -> cond -> unit eff
(** [orrs rd, rn] *)
val lorr : r32 reg -> r32 reg -> cond -> unit eff
(** [cmp rn, #i] *)
val cmpi8 : r32 reg -> int -> unit eff
* [ cmp rn , ]
val cmpr : r32 reg -> r32 reg -> unit eff
end
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/354f8082218482d05b05598c172e0364108fd281/plugins/thumb/thumb_mov.mli | ocaml | * [adds rd, rn, #x] aka add(1)
* [subs sp, #i] aka sub(4)
* [orrs rd, rn]
* [cmp rn, #i] | open Bap_core_theory
open Thumb_core
open Thumb_opcodes
module Make(CT : Theory.Core) : sig
open Theory
val addi3 : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ adds rd , # x ] aka add(2 )
val addi8 : r32 reg -> int -> cond -> unit eff
* [ adds rd , rn , ] aka add(3 ) and add(4 )
val addrr : r32 reg -> r32 reg -> r32 reg -> cond -> unit eff
* [ add rd , sp , # x ] aka add(6 )
val addrspi : r32 reg -> int -> cond -> unit eff
* [ add sp , # x ] aka )
val addspi : int -> cond -> unit eff
* [ ]
val adcs : r32 reg -> r32 reg -> r32 reg -> cond -> unit eff
* [ subs rd , rn , # x ] aka )
val subi3 : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ subs rd , # x ] aka )
val subi8 : r32 reg -> int -> cond -> unit eff
* [ subs rd , rn , ] aka )
val subrr : r32 reg -> r32 reg -> r32 reg -> cond -> unit eff
val subspi : int -> cond -> unit eff
* [ mov rd , # x ]
val movi8 : r32 reg -> int -> cond -> unit eff
* [ movs rd , rn ]
val movsr : r32 reg -> r32 reg -> unit eff
* [ asrs rd , rn , # i ]
val asri : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ lsrs rd , rn , # i ]
val lsri : r32 reg -> r32 reg -> int -> cond -> unit eff
* [ lsls rd , rn , # i ]
val lsli : r32 reg -> r32 reg -> int -> cond -> unit eff
val lorr : r32 reg -> r32 reg -> cond -> unit eff
val cmpi8 : r32 reg -> int -> unit eff
* [ cmp rn , ]
val cmpr : r32 reg -> r32 reg -> unit eff
end
|
4f7ee81126d91fe9ee7c3ad31f78bd4f14b541ddadcdcf4b69a7b46b2c5cd1da | haskell/cabal | init-interactive.test.hs | import Test.Cabal.Prelude
main = cabalTest $
withSourceCopyDir "app" $ do
cwd <- fmap testSourceCopyDir getTestEnv
buildOut <- withDirectory cwd $ do
cabalWithStdin "init" ["-i"]
"2\n\n5\n\n\n\n\n\n\n\n\n\n\n\n\n"
setup "configure" []
setup' "build" ["app"]
assertFileDoesContain (cwd </> "app.cabal") "3.0"
assertFileDoesContain (cwd </> "app.cabal") "BSD-3-Clause"
assertFileDoesContain (cwd </> "app.cabal") "Simple"
assertFileDoesContain (cwd </> "app/Main.hs") "This should remain as is!"
assertOutputContains "Linking" buildOut
| null | https://raw.githubusercontent.com/haskell/cabal/869ecdce5b4f663085835a5127b56e725174e3bb/cabal-testsuite/PackageTests/Init/init-interactive.test.hs | haskell | import Test.Cabal.Prelude
main = cabalTest $
withSourceCopyDir "app" $ do
cwd <- fmap testSourceCopyDir getTestEnv
buildOut <- withDirectory cwd $ do
cabalWithStdin "init" ["-i"]
"2\n\n5\n\n\n\n\n\n\n\n\n\n\n\n\n"
setup "configure" []
setup' "build" ["app"]
assertFileDoesContain (cwd </> "app.cabal") "3.0"
assertFileDoesContain (cwd </> "app.cabal") "BSD-3-Clause"
assertFileDoesContain (cwd </> "app.cabal") "Simple"
assertFileDoesContain (cwd </> "app/Main.hs") "This should remain as is!"
assertOutputContains "Linking" buildOut
| |
46e9ed4b5b3a39b3b851c3c896bbf3f10ce0a137f2c0f10ef6b5be0aba8af00a | plewto/Cadejo | subedit.clj | (ns cadejo.ui.instruments.subedit
(:require [seesaw.core :as ss])
)
(defprotocol InstrumentSubEditor
(widgets
[this])
(widget
[this key])
(parent
[this])
(parent!
[this p])
(status!
[this msg])
(warning!
[this msg])
(set-param!
[this param value])
(init!
[this])
(sync-ui!
[this]))
;; Wrap several subeditors to treat them as a single subeditor
editors - list of InstrumentSubEditor
panel - JPanel used as main - panel of the composite editor ,
;; if nil a vertical panel is created.
;; Returns InstrumentSubEditor
;;
(defn subeditor-wrapper [editors panel]
(let [pan-main (or panel (let [acc* (atom [])]
(doseq [e editors]
(swap! acc* (fn [q](conj q (.widget e :pan-main)))))
(ss/vertical-panel :items @acc*)))]
(reify InstrumentSubEditor
(widgets [this] {:pan-main pan-main})
(widget [this key](get (.widgets this) key))
(parent [this](.parent (first editors)))
(parent! [this _] (.parent this)) ;; ignore
(status! [this text](.status! (.parent this) text))
(warning! [this text](.warning! (.parent this) text))
(set-param! [this p v](.set-param! (.parent this) p v))
(init! [this](doseq [e editors](.init! e)))
(sync-ui! [this](doseq [e editors](.sync-ui! e))))))
| null | https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/ui/instruments/subedit.clj | clojure | Wrap several subeditors to treat them as a single subeditor
if nil a vertical panel is created.
Returns InstrumentSubEditor
ignore | (ns cadejo.ui.instruments.subedit
(:require [seesaw.core :as ss])
)
(defprotocol InstrumentSubEditor
(widgets
[this])
(widget
[this key])
(parent
[this])
(parent!
[this p])
(status!
[this msg])
(warning!
[this msg])
(set-param!
[this param value])
(init!
[this])
(sync-ui!
[this]))
editors - list of InstrumentSubEditor
panel - JPanel used as main - panel of the composite editor ,
(defn subeditor-wrapper [editors panel]
(let [pan-main (or panel (let [acc* (atom [])]
(doseq [e editors]
(swap! acc* (fn [q](conj q (.widget e :pan-main)))))
(ss/vertical-panel :items @acc*)))]
(reify InstrumentSubEditor
(widgets [this] {:pan-main pan-main})
(widget [this key](get (.widgets this) key))
(parent [this](.parent (first editors)))
(status! [this text](.status! (.parent this) text))
(warning! [this text](.warning! (.parent this) text))
(set-param! [this p v](.set-param! (.parent this) p v))
(init! [this](doseq [e editors](.init! e)))
(sync-ui! [this](doseq [e editors](.sync-ui! e))))))
|
ab05e595f44bd53d4d4832ca3d509f929b8678d0fc04ff3242ebffa793e77195 | squaresLab/genprog-code | cdiff.ml |
*
* Copyright ( c ) 2012 - 2018 ,
* < >
* < >
* < >
* < >
* < >
* 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) 2012-2018,
* Wes Weimer <>
* Stephanie Forrest <>
* Claire Le Goues <>
* Eric Schulte <>
* Jeremy Lacomis <>
* 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.
*
*)
* cDiff implements the diffX algorithm to produce the structural diff between
two Cil ASTs ( used primarily for [ cilRep]-based experiments ) ; it can also
produce new Cil ASTs by applying a ( potentially partial ) cdiff edit script
to an existing AST
two Cil ASTs (used primarily for [cilRep]-based experiments); it can also
produce new Cil ASTs by applying a (potentially partial) cdiff edit script
to an existing AST *)
open Pretty
open Printf
open Cil
open Global
type node_id = int
let exp_diff_level = ref false
let verbose = ref false
let _ =
options := !options @
[
"--exp-diff",
Arg.Set exp_diff_level,
"perform diffX/delta-debugging at the expression level. Default: false";
]
(** We convert a CIL AST to a very generic data structure for the purposes of
performing the DiffX structural difference algorithm; we convert back later.
This structure is sufficiently generic that it could easily be adapted to non-C
representations *)
type tree_node = {
mutable nid : node_id ; (* unique per node *)
mutable children : int array ;
mutable typelabel : int ;
* two nodes that represent the same C construct will have the same
typelabel . " children " are not considered for calculating typelabels , so ' if
( x < y ) foo ( ) ; ' and ' if ( x < y ) \ { bar ( ) ; \ } ' have the same typelabels , but
their children ( foo and bar ) will not .
typelabel. "children" are not considered for calculating typelabels, so 'if
(x<y) foo(); ' and 'if (x<y) \{ bar(); \} ' have the same typelabels, but
their children (foo and bar) will not. *)
}
type edit_action =
| Insert of int * (int option) * (int option)
| Move of int * (int option) * (int option)
| Delete of int
let typelabel_ht = Hashtbl.create 255
let inv_typelabel_ht = Hashtbl.create 255
let inv_typelabel_exp_ht = Hashtbl.create 255
let typelabel_counter = ref 0
let node_of_nid node_map x = IntMap.find x node_map
(**/**)
let find_str node_map n =
let node = node_of_nid node_map n in
if hmem inv_typelabel_ht node.typelabel then
let _,_,s = hfind inv_typelabel_ht node.typelabel in
s
else begin
snd (hfind inv_typelabel_exp_ht node.typelabel)
end
(**/**)
let noio no = match no with
| Some(n) -> Some(n.nid)
| None -> None
let edit_action_to_str node_map ea =
let io_to_num io = match io with
| Some(n) -> n
| None -> -1
in
let io_to_str io =
match io with
| Some(n) -> if not !verbose then sprintf "%d" n
else find_str node_map n
| None -> "-1"
in
if not !verbose then
match ea with
| Insert(n,no,io) -> sprintf "Insert (%d,%s,%s)" n (io_to_str no)
(io_to_str io)
| Move(n,no,io) -> sprintf "Move (%d,%s,%s)" n (io_to_str no)
(io_to_str io)
| Delete(n) -> sprintf "Delete (%d,0,0)" n
else
match ea with
| Insert(n,no,io) ->
sprintf "Insert (%s,%s,%d)" (find_str node_map n) (io_to_str no) (io_to_num io)
| Move(n,no,io) ->
sprintf "Move (%s,%s,%d)" (find_str node_map n)
(io_to_str no) (io_to_num io)
| Delete(n) ->
sprintf "Delete (%s,0,0)" (find_str node_map n)
let deleted_node = {
nid = -1;
children = [| |] ;
typelabel = -1 ;
}
module OrderedNode =
struct
type t = tree_node
let compare x y = compare x.nid y.nid
end
module OrderedNodeNode =
struct
type t = tree_node * tree_node
let compare (a,b) (c,d) =
let r1 = compare a.nid c.nid in
if r1 = 0 then
compare b.nid d.nid
else
r1
end
(**/**)
module NodeSet = Set.Make(OrderedNode)
* used to track the mapping between two tree - based representations
module NodeMap = Set.Make(OrderedNodeNode)
(** a node_info variable maps node IDs (integers) to cdiff tree nodes. The
generation of the edit script also produces the node map, which is saved as
part of a minimizableObject's structural signature *)
let init_map () = IntMap.add (-1) deleted_node (IntMap.empty)
(** performs tree cleanup after a diff script has been (perhaps sloppily, given
our use case) applied to a tree.
@param node_info map from [node_id] to [tree_node]
@param t [tree_node] root of the tree
@return modified node_info
*)
let rec cleanup_tree node_info t =
let node_info =
Array.fold_left
(fun node_info ->
fun child ->
let child = node_of_nid node_info child in
cleanup_tree node_info child
) node_info (t.children)
in
let lst = Array.to_list t.children in
let lst = List.filter (fun child ->
let child = node_of_nid node_info child in
child.typelabel <> -1
) lst in
t.children <- Array.of_list lst;
IntMap.add (t.nid) t node_info
let delete node_info node =
let nid = node.nid in
node.nid <- -1 ;
node.children <- [| |] ;
node.typelabel <- -1 ;
IntMap.add nid node node_info
(**/**)
exception Found_It
exception Found_Node of tree_node
exception Necessary_line
let map_size (m : NodeMap.t) = NodeMap.cardinal m
let node_counter = ref 0
let find_node_that_maps_to (m : NodeMap.t) (y : tree_node) =
try
NodeMap.iter (fun (a,b) ->
if b.nid = y.nid then raise (Found_Node(a))
) m ;
None
with Found_Node(a) -> Some(a)
(**/**)
let new_node typelabel =
let nid = !node_counter in
incr node_counter ;
{ nid = nid ;
children = [| |] ;
typelabel = typelabel ;
}
(** @param t1 [tree_node]
@param t2 [tree_node]
@return true if both the types and labels of [t1] and [t2] are equal *)
let nodes_eq t1 t2 = t1.typelabel = t2.typelabel
* @param m mapping between the two ASTs being diffed
@param t [ tree_node ]
@return true if ( t , _ ) is in m
@param t [tree_node]
@return true if (t,_) is in m *)
let in_map_domain (m : NodeMap.t) (t : tree_node) =
try
NodeMap.iter (fun (a,_) ->
if a.nid = t.nid then raise Found_It
) m ;
false
with Found_It -> true
* @param m mapping between the two ASTs being diffed
@param t a [ tree_node ]
@return true if ( _ , t ) is in m
@param t a [tree_node]
@return true if (_,t) is in m *)
let in_map_range (m : NodeMap.t) (t : tree_node) =
try
NodeMap.iter (fun (_,a) ->
if a.nid = t.nid then raise Found_It
) m ;
false
with Found_It -> true
* @param node_info map between [ node_id]s and [ tree_node]s
@param t [ tree_node ] root of the tree
@param t [ tree_node ] node being tested
@return a set containing all nodes in t equal to n
@param t [tree_node] root of the tree
@param t [tree_node] node being tested
@return a set containing all nodes in t equal to n *)
let rec nodes_in_tree_equal_to
(node_info : tree_node IntMap.t) (t : tree_node) (n : tree_node) =
let sofar = ref
(if nodes_eq t n then NodeSet.singleton t else NodeSet.empty)
in
Array.iter (fun child ->
let child = node_of_nid node_info child in
sofar := NodeSet.union !sofar (nodes_in_tree_equal_to node_info child n)
) t.children ;
!sofar
* @param node_info map between [ node_id]s and [ tree_node]s
@param t [ tree_node ] root of the tree
@param callback function to call on each node
@return nothing ( unit )
performs a breadth - first walk of a tree
@param t [tree_node] root of the tree
@param callback function to call on each node
@return nothing (unit)
performs a breadth-first walk of a tree *)
let level_order_traversal
(node_info : tree_node IntMap.t) (t : tree_node) callback =
let q = Queue.create () in
Queue.add t q ;
while not (Queue.is_empty q) do
let x = Queue.take q in
Array.iter (fun child ->
let child = node_of_nid node_info child in
Queue.add child q
) x.children ;
callback x ;
done
(**/**)
let parent_of (node_info : tree_node IntMap.t)
(tree : tree_node) (some_node : tree_node) =
try
level_order_traversal node_info tree (fun p ->
Array.iter (fun child ->
let child = node_of_nid node_info child in
if child.nid = some_node.nid then
raise (Found_Node(p) )
) p.children
) ;
None
with Found_Node(n) -> Some(n)
let parent_of_nid (node_info : tree_node IntMap.t)
(tree : tree_node) (some_nid : node_id) =
try
level_order_traversal node_info tree (fun p ->
Array.iter (fun child ->
let child = node_of_nid node_info child in
if child.nid = some_nid then
raise (Found_Node(p) )
) p.children
) ;
None
with Found_Node(n) -> Some(n)
let position_of (node_info : tree_node IntMap.t)
(parent : tree_node option) (child : tree_node) =
match parent with
| None -> None
| Some(parent) ->
let result = ref None in
Array.iteri (fun i child' ->
let child' = node_of_nid node_info child' in
if child.nid = child'.nid then
result := Some(i)
) parent.children ;
!result
let position_of_nid (node_info : tree_node IntMap.t)
(parent : tree_node option) (child_nid : node_id) =
match parent with
| None -> None
| Some(parent) ->
let result = ref None in
Array.iteri (fun i child' ->
let child' = node_of_nid node_info child' in
if child_nid = child'.nid then
result := Some(i)
) parent.children ;
!result
(**/**)
* matches nodes that ( presumably ) do not change between the two trees , using
the algorithm taken verbatim from the DiffX paper .
@param node_info mapping node ids to tree nodes
@param tree1 [ node_id ] root of tree1
@param tree2 [ node_id ] root of tree2
@return a map of type [ NodeMap ] mapping node IDs between and tree2 .
the algorithm taken verbatim from the DiffX paper.
@param node_info mapping node ids to tree nodes
@param tree1 [node_id] root of tree1
@param tree2 [node_id] root of tree2
@return a map of type [NodeMap] mapping node IDs between tree1 and tree2. *)
let rec mapping (node_info : tree_node IntMap.t)
(t1 : node_id) (t2 : node_id) : NodeMap.t =
let t1 = node_of_nid node_info t1 in
let t2 = node_of_nid node_info t2 in
let m = ref NodeMap.empty in
level_order_traversal node_info t1 (fun x ->
if in_map_domain !m x then ()
else begin
let y = nodes_in_tree_equal_to node_info t2 x in
let m'' = ref NodeMap.empty in
NodeSet.iter (fun yi ->
if not (in_map_range !m yi) then begin
let m' = ref NodeMap.empty in
match_fragment node_info x yi !m m' ;
if map_size !m' > map_size !m'' then
m'' := !m'
end
) y ;
m := NodeMap.union !m !m''
end
) ;
!m
(* still taken verbatim from their paper *)
and match_fragment node_info x y (m : NodeMap.t) (m' : NodeMap.t ref) =
if (not (in_map_domain m x)) &&
(not (in_map_range m y)) &&
(nodes_eq x y) then begin
m' := NodeMap.add (x,y) !m' ;
let xc = Array.length x.children in
let yc = Array.length y.children in
for i = 0 to pred (min xc yc) do
match_fragment node_info
(node_of_nid node_info x.children.(i))
(node_of_nid node_info y.children.(i)) m m'
done
end
* generates the edit script between and tree2 using a [ node_info ] the
[ map ] generated by the function [ mapping ] ( above ) . This is not taken
directly from the DiffX paper , because the version in the DiffX paper 's
pseudocode has ( unspecified by , who wrote the code initially ) bugs
@param node_info mapping [ node_id]s to [ tree_node]s
@param tree1 [ tree_node ]
@param tree2 [ tree_node ]
@param map [ NodeMap.t ]
@return edit_action list
[map] generated by the function [mapping] (above). This is not taken
directly from the DiffX paper, because the version in the DiffX paper's
pseudocode has (unspecified by Wes, who wrote the code initially) bugs
@param node_info mapping [node_id]s to [tree_node]s
@param tree1 [tree_node]
@param tree2 [tree_node]
@param map [NodeMap.t]
@return edit_action list
*)
let generate_script (node_info : tree_node IntMap.t) (t1 : tree_node)
(t2 : tree_node) (m : NodeMap.t) : edit_action list =
let s = ref [] in
level_order_traversal node_info t2 (fun y ->
if not (in_map_range m y) then begin
let yparent = parent_of node_info t2 y in
let ypos = position_of node_info yparent y in
match yparent with
| None ->
s := (Insert(y.nid,noio yparent,ypos)) :: !s
| Some(yparent) -> begin
let xx = find_node_that_maps_to m yparent in
match xx with
| Some(xx) -> s := (Insert(y.nid,Some(xx.nid),ypos)) :: !s
| None -> s := (Insert(y.nid,Some(yparent.nid),ypos)) :: !s
(* in the None case, our yParent was moved over, so this works
inductively *)
end
end else begin
match find_node_that_maps_to m y with
| None -> printf "generate_script: error: no node that maps to!\n"
| Some(x) -> begin
let xparent = parent_of node_info t1 x in
let yparent = parent_of node_info t2 y in
let yposition = position_of node_info yparent y in
let xposition = position_of node_info xparent x in
match xparent, yparent with
| Some(xparent), Some(yparent) ->
if not (NodeMap.mem (xparent,yparent) m) then begin
let xx = find_node_that_maps_to m yparent in
match xx with
| Some(xx) -> s := (Move(x.nid,Some(xx.nid),yposition)) :: !s
| None -> s := (Move(x.nid,Some yparent.nid,yposition)) :: !s
end
else if xposition <> yposition then
s := (Move(x.nid,Some xparent.nid,yposition)) :: !s
| _, _ -> ()
end
end
) ;
level_order_traversal node_info t1 (fun x ->
if not (in_map_domain m x) then begin
s := (Delete(x.nid)) :: !s
end
) ;
List.rev !s
(**/**)
let dummyBlock = { battrs = [] ; bstmts = [] ; }
(**/**)
* generates the ' typelabel ' of a CIL construct -- basically by turning if
( x < y ) foo ( ) ; into : if ( x < y ) ( ) and then hashing it . See the DiffX paper for
more detail on the definition of typelabel .
@param s Cil statement
@return ( string , ) pair of the typelabel .
(x<y) foo(); into: if (x<y) () and then hashing it. See the DiffX paper for
more detail on the definition of typelabel.
@param s Cil statement
@return (string,Cil stmt) pair of the typelabel.
*)
let stmt_to_typelabel (s : Cil.stmt) =
let dummyBlock = { battrs = [] ; bstmts = [] ; } in
let dummyLoc = { line = 0 ; file = "" ; byte = 0; } in
let convert_exp exp =
if !exp_diff_level then Cil.zero
else exp
in
let convert_exp_opt exp =
match exp with
Some(e) when !exp_diff_level -> Some(Cil.zero)
| _ -> exp
in
let convert_exps exps =
if !exp_diff_level then []
else exps
in
CLG potential FIXME : lvals ?
let convert_label l = match l with
| Label(s,loc,b) -> Label(s,dummyLoc,b)
| Case(e,loc) -> Case(convert_exp e,dummyLoc)
| Default(loc) -> Default(dummyLoc)
in
let labels = List.map convert_label s.labels in
let convert_il il =
List.map (fun i -> match i with
| Set(lv,e,loc) -> Set(lv,convert_exp e,dummyLoc)
| Call(lvo,e,el,loc) -> Call(lvo,convert_exp e,convert_exps el,dummyLoc)
| Asm(a,b,c,d,e,loc) -> Asm(a,b,c,d,e,dummyLoc)
) il
in
let skind = match s.skind with
| Instr(il) -> Instr(convert_il il)
| Return(eo,l) -> Return(convert_exp_opt eo,dummyLoc)
| Goto(sr,l) -> Goto(sr,dummyLoc)
| Break(l) -> Break(dummyLoc)
| Continue(l) -> Continue(dummyLoc)
| If(e,b1,b2,l) -> If(convert_exp e,dummyBlock,dummyBlock,l)
| Switch(e,b,sl,l) -> Switch(convert_exp e,dummyBlock,[],l)
| Loop(b,l,so1,so2) -> Loop(dummyBlock,l,None,None)
| Block(block) -> Block(dummyBlock)
| TryFinally(b1,b2,l) -> TryFinally(dummyBlock,dummyBlock,dummyLoc)
| TryExcept(b1,(il,e),b2,l) ->
TryExcept(dummyBlock,(convert_il il,convert_exp e),dummyBlock,dummyLoc)
in
let s' = { s with skind = skind ; labels = labels } in
let doc = dn_stmt () s' in
let str = Pretty.sprint ~width:80 doc in
let it = labels, skind, str in
if Hashtbl.mem typelabel_ht str then begin
Hashtbl.find typelabel_ht str , it
end else begin
let res = !typelabel_counter in
incr typelabel_counter ;
Hashtbl.add typelabel_ht str res ;
Hashtbl.add inv_typelabel_ht res it ;
res , it
end
(** this and related helper functions converts a Cil function definition to the
abstract tree datatype used by this implementation of the DiffX algorithm.
@param f Cil.fundec to convert
@return (tree_node,node_info) where the tree_node is the converted f and the
node_info has been updated
*)
let fundec_to_ast (node_info : tree_node IntMap.t) (f:Cil.fundec) =
let wrap_block b = mkStmt (Block(b)) in
let node_info = ref node_info in
let exp_to_typelabel e =
let e' =
match e with
| Const _ | Lval _ | SizeOf _
| SizeOfStr _ | AlignOf _ | AddrOf _
| StartOf _ -> e
| SizeOfE e1 -> SizeOfE(Cil.zero)
| AlignOfE e1 -> AlignOfE(Cil.zero)
| UnOp(u,e1,t) -> UnOp(u,Cil.zero,t)
| BinOp(b,e1,e2,t) -> BinOp(b,Cil.zero, Cil.zero, t)
| CastE(t,e1) -> CastE(t, Cil.zero)
in
let doc = dn_exp () e' in
let str = Pretty.sprint ~width:80 doc in
let it = e', str in
if hmem typelabel_ht str then
hfind typelabel_ht str, it
else
let res = !typelabel_counter in
incr typelabel_counter ;
hadd typelabel_ht str res ;
hadd inv_typelabel_exp_ht res it;
res, it
in
let rec exp_to_node e =
if !exp_diff_level then begin
let tl,it = exp_to_typelabel e in
let n = new_node tl in
let children = exp_children e in
n.children <- children ;
node_info := IntMap.add n.nid n !node_info ;
[n.nid]
end else []
and exp_children e =
match e with
| Const _ | Lval _ | SizeOf _
| SizeOfStr _ | AlignOf _ | AddrOf _
| StartOf _ -> [| |]
| SizeOfE(e')
| AlignOfE(e')
| UnOp(_,e',_)
| CastE(_,e') -> Array.of_list (exp_to_node e')
| BinOp(_,e1,e2,_) -> Array.of_list ((exp_to_node e1) @ (exp_to_node e2))
in
let instr_children i =
if !exp_diff_level then begin
match i with
Set(l,e,_) -> exp_to_node e
| Call(lopt,e,es,l) ->
(exp_to_node e) @ (lfoldl (fun a e -> a @ (exp_to_node e)) [] es)
| Asm(atrs,sls1,sls2,sls3,sls4,l) -> []
end else []
in
let rec stmt_to_node s =
let tl, (labels,skind,_) = stmt_to_typelabel s in
let n = new_node tl in
(* now just fill in the children *)
let children = stmt_children s in
n.children <- children ;
node_info := IntMap.add n.nid n !node_info ;
n.nid
and stmt_children (s : Cil.stmt) : node_id array =
match s.skind with
| Goto _ | Break _ | Continue _ -> [| |]
| Instr ils ->
let lst : node_id list = lfoldl (fun a i -> (instr_children i) @ a) [] ils in
Array.of_list lst
| Return (Some(e),_) when !exp_diff_level -> Array.of_list (exp_to_node e)
| Return _ -> [| |]
| If(e,b1,b2,l) ->
let stmts =
[| stmt_to_node (wrap_block b1) ;
stmt_to_node (wrap_block b2) |]
in
let exps = Array.of_list (exp_to_node e) in
Array.append exps stmts
| Switch(e,b,sl,l) ->
let stmts =
[| stmt_to_node (wrap_block b) |]
in
let exps = Array.of_list (exp_to_node e) in
Array.append exps stmts
| Loop(b,l,so1,so2) ->
[| stmt_to_node (wrap_block b) |]
| TryFinally(b1,b2,l) ->
[| stmt_to_node (wrap_block b1) ; stmt_to_node (wrap_block b2) |]
| TryExcept(b1,(il,e),b2,l) ->
let instrs = Array.of_list (lfoldl (fun a i -> a @ (instr_children i)) [] il) in
let exps = Array.of_list (exp_to_node e) in
let stmts =
[| stmt_to_node (wrap_block b1) ; stmt_to_node (wrap_block b2) |]
in
Array.concat [instrs;exps;stmts]
| Block(block) ->
let children = List.map stmt_to_node block.bstmts in
Array.of_list children
in
let b = wrap_block f.sbody in
stmt_to_node b , !node_info
(** @param node_info mapping [node_id]s to [tree_node]s
@param n [tree_node] a tree node to be converted
@return Cil.stmt created by converting n back to CIL
*)
let rec node_to_stmt (node_info : tree_node IntMap.t) (n : tree_node) : Cil.stmt =
let children = Array.map (fun child ->
let child = node_of_nid node_info child in
node_to_stmt node_info child
) n.children in
let labels, skind,_ = Hashtbl.find inv_typelabel_ht n.typelabel in
let require x =
if Array.length children = x then ()
else begin
printf "// node_to_stmt: warn: wanted %d children, have %d\n"
x (Array.length children) ;
end
in
let block x =
if x >= Array.length children then dummyBlock
else match children.(x).skind with
| Block(b) -> b
| _ -> begin
printf "// node_to_stmt: warn: wanted child %d to be a block\n" x ;
dummyBlock
end
in
let stmt = mkStmt begin
match skind with
| Instr _ | Return _ | Goto _
| Break _ | Continue _ -> skind
| If(e,b1,b2,l) -> require 2 ; If(e,block 0,block 1,l)
| Switch(e,b,sl,l) -> require 1 ; Switch(e,block 0,sl,l)
| Loop(b,l,so1,so2) -> require 1 ; Loop(block 0,l,so1,so2)
| TryFinally(b1,b2,l) -> require 2 ; TryFinally(block 0,block 1,l)
| TryExcept(b1,(il,e),b2,l) ->
require 2; TryExcept(block 0,(il,e),block 1,l)
| Block _ -> Block(mkBlock (Array.to_list children))
end
in
stmt.labels <- labels ;
stmt
* @param node_info mapping [ node_id]s to [ tree_node]s
@param f base Cil.fundec into which we will put the converted AST
@param n [ tree_node ] to convert back into the function body .
@return Cil.file [ f ] with the body replaced by the representation of [ n ]
@raise Fail("need child to be a block " ) if [ n ] does n't correspond to a block
statement .
@param f base Cil.fundec into which we will put the converted AST
@param n [tree_node] to convert back into the function body.
@return Cil.file [f] with the body replaced by the Cil representation of [n]
@raise Fail("need child to be a block") if [n] doesn't correspond to a block
statement. *)
let ast_to_fundec (node_info : tree_node IntMap.t) (f:Cil.fundec) (n : tree_node) =
let stmt = node_to_stmt node_info n in
match stmt.skind with
| Block(b) -> { f with sbody = b ; }
| _ ->
printf "fundec_to_ast: error: wanted child to be a block\n" ;
failwith "fundec_to_ast"
* @param node_info mapping [ node_id]s to [ tree_node]s
@param m [ NodeMap.t ] mapping between two ASTs that have previously been
diffed
@param ast1 [ node_id ] root of the first tree
@param ast2 [ node_id ] root of the second tree
@param edit_action edit action to apply to ast1
@return node_info new node_info , potentially modified , reflecting the
changes wrought by [ edit_action ] on [ ast1 ]
@param m [NodeMap.t] mapping between two ASTs that have previously been
diffed
@param ast1 [node_id] root of the first tree
@param ast2 [node_id] root of the second tree
@param edit_action edit action to apply to ast1
@return node_info new node_info, potentially modified, reflecting the
changes wrought by [edit_action] on [ast1]
*)
let apply_diff (node_info : tree_node IntMap.t) (m : NodeMap.t) (astt1 : node_id)
(astt2 : node_id) (s : edit_action) : tree_node IntMap.t =
let ast1 = node_of_nid node_info astt1 in
let ast2 = node_of_nid node_info astt2 in
try
match s with
(* delete sub-tree rooted at node x *)
| Delete(nid) ->
let node = node_of_nid node_info nid in
delete node_info node
(* insert node x as pth child of node y *)
| Insert(xid,yopt,ypopt) ->
let xnode = node_of_nid node_info xid in
(match yopt with
| None -> printf "apply: error: insert to root?" ; node_info
| Some(yid) ->
let ynode = node_of_nid node_info yid in
(* let ynode = corresponding m ynode in *)
let ypos = match ypopt with
| Some(x) -> x | None -> 0
in
Step 1 : remove children of X
let node_info =
xnode.children <- [| |] ;
IntMap.add xnode.nid xnode node_info
in
Step 2 : remove X from its parent
let node_info =
let xparent1 = parent_of node_info ast1 xnode in
let xparent2 = parent_of node_info ast2 xnode in
(match xparent1, xparent2 with
| Some(parent), _
| _, Some(parent) ->
let plst = Array.to_list parent.children in
let plst = List.map (fun child ->
let child = node_of_nid node_info child in
if child.nid = xid then
deleted_node.nid
else
child.nid
) plst in
parent.children <- Array.of_list plst ;
IntMap.add parent.nid parent node_info
| _, _ -> node_info
(* this case is fine, and typically comes up when we are
Inserting the children of a node that itself was Inserted over *)
)
in
Step 3 : put X as p - th child of Y
let len = Array.length ynode.children in
let before = Array.sub ynode.children 0 ypos in
let after = Array.sub ynode.children ypos (len - ypos) in
let result = Array.concat [ before ; [| xnode.nid |] ; after ] in
ynode.children <- result ;
IntMap.add ynode.nid ynode node_info
)
(* move subtree rooted at node x to as p-th child of node y *)
| Move(xid,yopt,ypopt) ->
let xnode = node_of_nid node_info xid in
(match yopt with
| None ->
printf "apply: error: %s: move to root?\n" (edit_action_to_str node_info s) ; node_info
| Some(yid) ->
let ynode = node_of_nid node_info yid in
(* let ynode = corresponding m ynode in *)
let ypos = match ypopt with
| Some(x) -> x | None -> 0
in
Step 1 : remove X from its parent
let xparent1 = parent_of node_info ast1 xnode in
let xparent2 = parent_of node_info ast2 xnode in
let node_info =
match xparent1, xparent2 with
| Some(parent), _
| _, Some(parent) ->
let plst = Array.to_list parent.children in
let plst = List.map (fun child ->
let child = node_of_nid node_info child in
if child.nid = xid then
deleted_node.nid
else
child.nid
) plst in
parent.children <- Array.of_list plst ;
IntMap.add parent.nid parent node_info
| None, None ->
printf "apply: error: %s: no x parent\n"
(edit_action_to_str node_info s) ; node_info
in
Step 2 : put X as p - th child of Y
let len = Array.length ynode.children in
let before = Array.sub ynode.children 0 ypos in
let after = Array.sub ynode.children ypos (len - ypos) in
let result = Array.concat [ before ; [| xnode.nid |] ; after ] in
ynode.children <- result ;
IntMap.add ynode.nid ynode node_info
)
with e -> raise Necessary_line
* applies a diffscript stored in [ data_ht ] and [ patch_ht ] to [ cil_file ] .
assumes that [ inv_typelabel_ht ] has been populated , because apparently I did
not eliminate all state in this module .
@param cil_file Cil.file
@param node_info mapping between [ node_id]s and [ tree_node]s
@param patch_ht hashtable containing the edits associated with globals in
[ cil_file ]
@param data_ht hashtable containing the map and two asts associated with
globals in [ cil_file ]
@return Cil.file reflecting the changes in [ patch_ht ] as applied to [ cil_file ] .
assumes that [inv_typelabel_ht] has been populated, because apparently I did
not eliminate all state in this module.
@param cil_file Cil.file
@param node_info mapping between [node_id]s and [tree_node]s
@param patch_ht hashtable containing the edits associated with globals in
[cil_file]
@param data_ht hashtable containing the map and two asts associated with
globals in [cil_file]
@return Cil.file reflecting the changes in [patch_ht] as applied to [cil_file].
*)
let apply_diff_to_file f1 node_info patch_ht data_ht =
foldGlobals f1
(fun (globals,node_info) g1 ->
match g1 with
| GFun(fd1,l) when Hashtbl.mem patch_ht fd1.svar.vname ->
let name = fd1.svar.vname in
let patches = Hashtbl.find patch_ht name in
let m, t1, t2 = Hashtbl.find data_ht name in
let node_info =
try
List.fold_left
(fun node_info ->
fun ea ->
apply_diff node_info m t1 t2 ea;
) node_info patches
with Necessary_line -> node_info
in
let node_info =
cleanup_tree node_info (node_of_nid node_info t1)
in
let output_fundec =
ast_to_fundec node_info fd1 (node_of_nid node_info t1) in
(GFun(output_fundec,l)) :: globals, node_info
| _ -> g1 :: globals, node_info
) ([], node_info)
*
@param file Cil.file
@param node_info map between [ node_id]s and [ tree_node]s
@param script strings representing edit actions
@param data_ht map between globals and mappings / ast pairs
@return file that has had the edits represented by [ script ] applied
@param file Cil.file
@param node_info map between [node_id]s and [tree_node]s
@param script strings representing edit actions
@param data_ht map between globals and mappings/ast pairs
@return file that has had the edits represented by [script] applied *)
let usediff (f1 : Cil.file) (node_info : tree_node IntMap.t)
(script : string list) data_ht =
let patch_ht = Hashtbl.create 255 in
let add_patch fname ea = (* preserves order, fwiw *)
let sofar = try Hashtbl.find patch_ht fname with _ -> [] in
Hashtbl.replace patch_ht fname (sofar @ [ea])
in
let num_to_io x = if x < 0 then None else Some(x) in
let _ =
List.iter
(fun line ->
Scanf.sscanf line "%s %s %s (%d,%d,%d)" (fun the_file fname ea a b c ->
let it = match String.lowercase_ascii ea with
| "insert" -> Insert(a, num_to_io b, num_to_io c)
| "move" -> Move(a, num_to_io b, num_to_io c)
| "delete" -> Delete(a)
| _ -> failwith ("invalid patch: " ^ line)
in add_patch fname it
)
) script
in
let globals,_ =
apply_diff_to_file f1 node_info patch_ht data_ht in
{f1 with globals = lrev globals }
| null | https://raw.githubusercontent.com/squaresLab/genprog-code/7982415b347529efee02190ab9ba6bd7eda6195e/src/cdiff.ml | ocaml | * We convert a CIL AST to a very generic data structure for the purposes of
performing the DiffX structural difference algorithm; we convert back later.
This structure is sufficiently generic that it could easily be adapted to non-C
representations
unique per node
*/*
*/*
*/*
* a node_info variable maps node IDs (integers) to cdiff tree nodes. The
generation of the edit script also produces the node map, which is saved as
part of a minimizableObject's structural signature
* performs tree cleanup after a diff script has been (perhaps sloppily, given
our use case) applied to a tree.
@param node_info map from [node_id] to [tree_node]
@param t [tree_node] root of the tree
@return modified node_info
*/*
*/*
* @param t1 [tree_node]
@param t2 [tree_node]
@return true if both the types and labels of [t1] and [t2] are equal
*/*
*/*
still taken verbatim from their paper
in the None case, our yParent was moved over, so this works
inductively
*/*
*/*
* this and related helper functions converts a Cil function definition to the
abstract tree datatype used by this implementation of the DiffX algorithm.
@param f Cil.fundec to convert
@return (tree_node,node_info) where the tree_node is the converted f and the
node_info has been updated
now just fill in the children
* @param node_info mapping [node_id]s to [tree_node]s
@param n [tree_node] a tree node to be converted
@return Cil.stmt created by converting n back to CIL
delete sub-tree rooted at node x
insert node x as pth child of node y
let ynode = corresponding m ynode in
this case is fine, and typically comes up when we are
Inserting the children of a node that itself was Inserted over
move subtree rooted at node x to as p-th child of node y
let ynode = corresponding m ynode in
preserves order, fwiw |
*
* Copyright ( c ) 2012 - 2018 ,
* < >
* < >
* < >
* < >
* < >
* 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) 2012-2018,
* Wes Weimer <>
* Stephanie Forrest <>
* Claire Le Goues <>
* Eric Schulte <>
* Jeremy Lacomis <>
* 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.
*
*)
* cDiff implements the diffX algorithm to produce the structural diff between
two Cil ASTs ( used primarily for [ cilRep]-based experiments ) ; it can also
produce new Cil ASTs by applying a ( potentially partial ) cdiff edit script
to an existing AST
two Cil ASTs (used primarily for [cilRep]-based experiments); it can also
produce new Cil ASTs by applying a (potentially partial) cdiff edit script
to an existing AST *)
open Pretty
open Printf
open Cil
open Global
type node_id = int
let exp_diff_level = ref false
let verbose = ref false
let _ =
options := !options @
[
"--exp-diff",
Arg.Set exp_diff_level,
"perform diffX/delta-debugging at the expression level. Default: false";
]
type tree_node = {
mutable children : int array ;
mutable typelabel : int ;
* two nodes that represent the same C construct will have the same
typelabel . " children " are not considered for calculating typelabels , so ' if
( x < y ) foo ( ) ; ' and ' if ( x < y ) \ { bar ( ) ; \ } ' have the same typelabels , but
their children ( foo and bar ) will not .
typelabel. "children" are not considered for calculating typelabels, so 'if
(x<y) foo(); ' and 'if (x<y) \{ bar(); \} ' have the same typelabels, but
their children (foo and bar) will not. *)
}
type edit_action =
| Insert of int * (int option) * (int option)
| Move of int * (int option) * (int option)
| Delete of int
let typelabel_ht = Hashtbl.create 255
let inv_typelabel_ht = Hashtbl.create 255
let inv_typelabel_exp_ht = Hashtbl.create 255
let typelabel_counter = ref 0
let node_of_nid node_map x = IntMap.find x node_map
let find_str node_map n =
let node = node_of_nid node_map n in
if hmem inv_typelabel_ht node.typelabel then
let _,_,s = hfind inv_typelabel_ht node.typelabel in
s
else begin
snd (hfind inv_typelabel_exp_ht node.typelabel)
end
let noio no = match no with
| Some(n) -> Some(n.nid)
| None -> None
let edit_action_to_str node_map ea =
let io_to_num io = match io with
| Some(n) -> n
| None -> -1
in
let io_to_str io =
match io with
| Some(n) -> if not !verbose then sprintf "%d" n
else find_str node_map n
| None -> "-1"
in
if not !verbose then
match ea with
| Insert(n,no,io) -> sprintf "Insert (%d,%s,%s)" n (io_to_str no)
(io_to_str io)
| Move(n,no,io) -> sprintf "Move (%d,%s,%s)" n (io_to_str no)
(io_to_str io)
| Delete(n) -> sprintf "Delete (%d,0,0)" n
else
match ea with
| Insert(n,no,io) ->
sprintf "Insert (%s,%s,%d)" (find_str node_map n) (io_to_str no) (io_to_num io)
| Move(n,no,io) ->
sprintf "Move (%s,%s,%d)" (find_str node_map n)
(io_to_str no) (io_to_num io)
| Delete(n) ->
sprintf "Delete (%s,0,0)" (find_str node_map n)
let deleted_node = {
nid = -1;
children = [| |] ;
typelabel = -1 ;
}
module OrderedNode =
struct
type t = tree_node
let compare x y = compare x.nid y.nid
end
module OrderedNodeNode =
struct
type t = tree_node * tree_node
let compare (a,b) (c,d) =
let r1 = compare a.nid c.nid in
if r1 = 0 then
compare b.nid d.nid
else
r1
end
module NodeSet = Set.Make(OrderedNode)
* used to track the mapping between two tree - based representations
module NodeMap = Set.Make(OrderedNodeNode)
let init_map () = IntMap.add (-1) deleted_node (IntMap.empty)
let rec cleanup_tree node_info t =
let node_info =
Array.fold_left
(fun node_info ->
fun child ->
let child = node_of_nid node_info child in
cleanup_tree node_info child
) node_info (t.children)
in
let lst = Array.to_list t.children in
let lst = List.filter (fun child ->
let child = node_of_nid node_info child in
child.typelabel <> -1
) lst in
t.children <- Array.of_list lst;
IntMap.add (t.nid) t node_info
let delete node_info node =
let nid = node.nid in
node.nid <- -1 ;
node.children <- [| |] ;
node.typelabel <- -1 ;
IntMap.add nid node node_info
exception Found_It
exception Found_Node of tree_node
exception Necessary_line
let map_size (m : NodeMap.t) = NodeMap.cardinal m
let node_counter = ref 0
let find_node_that_maps_to (m : NodeMap.t) (y : tree_node) =
try
NodeMap.iter (fun (a,b) ->
if b.nid = y.nid then raise (Found_Node(a))
) m ;
None
with Found_Node(a) -> Some(a)
let new_node typelabel =
let nid = !node_counter in
incr node_counter ;
{ nid = nid ;
children = [| |] ;
typelabel = typelabel ;
}
let nodes_eq t1 t2 = t1.typelabel = t2.typelabel
* @param m mapping between the two ASTs being diffed
@param t [ tree_node ]
@return true if ( t , _ ) is in m
@param t [tree_node]
@return true if (t,_) is in m *)
let in_map_domain (m : NodeMap.t) (t : tree_node) =
try
NodeMap.iter (fun (a,_) ->
if a.nid = t.nid then raise Found_It
) m ;
false
with Found_It -> true
* @param m mapping between the two ASTs being diffed
@param t a [ tree_node ]
@return true if ( _ , t ) is in m
@param t a [tree_node]
@return true if (_,t) is in m *)
let in_map_range (m : NodeMap.t) (t : tree_node) =
try
NodeMap.iter (fun (_,a) ->
if a.nid = t.nid then raise Found_It
) m ;
false
with Found_It -> true
* @param node_info map between [ node_id]s and [ tree_node]s
@param t [ tree_node ] root of the tree
@param t [ tree_node ] node being tested
@return a set containing all nodes in t equal to n
@param t [tree_node] root of the tree
@param t [tree_node] node being tested
@return a set containing all nodes in t equal to n *)
let rec nodes_in_tree_equal_to
(node_info : tree_node IntMap.t) (t : tree_node) (n : tree_node) =
let sofar = ref
(if nodes_eq t n then NodeSet.singleton t else NodeSet.empty)
in
Array.iter (fun child ->
let child = node_of_nid node_info child in
sofar := NodeSet.union !sofar (nodes_in_tree_equal_to node_info child n)
) t.children ;
!sofar
* @param node_info map between [ node_id]s and [ tree_node]s
@param t [ tree_node ] root of the tree
@param callback function to call on each node
@return nothing ( unit )
performs a breadth - first walk of a tree
@param t [tree_node] root of the tree
@param callback function to call on each node
@return nothing (unit)
performs a breadth-first walk of a tree *)
let level_order_traversal
(node_info : tree_node IntMap.t) (t : tree_node) callback =
let q = Queue.create () in
Queue.add t q ;
while not (Queue.is_empty q) do
let x = Queue.take q in
Array.iter (fun child ->
let child = node_of_nid node_info child in
Queue.add child q
) x.children ;
callback x ;
done
let parent_of (node_info : tree_node IntMap.t)
(tree : tree_node) (some_node : tree_node) =
try
level_order_traversal node_info tree (fun p ->
Array.iter (fun child ->
let child = node_of_nid node_info child in
if child.nid = some_node.nid then
raise (Found_Node(p) )
) p.children
) ;
None
with Found_Node(n) -> Some(n)
let parent_of_nid (node_info : tree_node IntMap.t)
(tree : tree_node) (some_nid : node_id) =
try
level_order_traversal node_info tree (fun p ->
Array.iter (fun child ->
let child = node_of_nid node_info child in
if child.nid = some_nid then
raise (Found_Node(p) )
) p.children
) ;
None
with Found_Node(n) -> Some(n)
let position_of (node_info : tree_node IntMap.t)
(parent : tree_node option) (child : tree_node) =
match parent with
| None -> None
| Some(parent) ->
let result = ref None in
Array.iteri (fun i child' ->
let child' = node_of_nid node_info child' in
if child.nid = child'.nid then
result := Some(i)
) parent.children ;
!result
let position_of_nid (node_info : tree_node IntMap.t)
(parent : tree_node option) (child_nid : node_id) =
match parent with
| None -> None
| Some(parent) ->
let result = ref None in
Array.iteri (fun i child' ->
let child' = node_of_nid node_info child' in
if child_nid = child'.nid then
result := Some(i)
) parent.children ;
!result
* matches nodes that ( presumably ) do not change between the two trees , using
the algorithm taken verbatim from the DiffX paper .
@param node_info mapping node ids to tree nodes
@param tree1 [ node_id ] root of tree1
@param tree2 [ node_id ] root of tree2
@return a map of type [ NodeMap ] mapping node IDs between and tree2 .
the algorithm taken verbatim from the DiffX paper.
@param node_info mapping node ids to tree nodes
@param tree1 [node_id] root of tree1
@param tree2 [node_id] root of tree2
@return a map of type [NodeMap] mapping node IDs between tree1 and tree2. *)
let rec mapping (node_info : tree_node IntMap.t)
(t1 : node_id) (t2 : node_id) : NodeMap.t =
let t1 = node_of_nid node_info t1 in
let t2 = node_of_nid node_info t2 in
let m = ref NodeMap.empty in
level_order_traversal node_info t1 (fun x ->
if in_map_domain !m x then ()
else begin
let y = nodes_in_tree_equal_to node_info t2 x in
let m'' = ref NodeMap.empty in
NodeSet.iter (fun yi ->
if not (in_map_range !m yi) then begin
let m' = ref NodeMap.empty in
match_fragment node_info x yi !m m' ;
if map_size !m' > map_size !m'' then
m'' := !m'
end
) y ;
m := NodeMap.union !m !m''
end
) ;
!m
and match_fragment node_info x y (m : NodeMap.t) (m' : NodeMap.t ref) =
if (not (in_map_domain m x)) &&
(not (in_map_range m y)) &&
(nodes_eq x y) then begin
m' := NodeMap.add (x,y) !m' ;
let xc = Array.length x.children in
let yc = Array.length y.children in
for i = 0 to pred (min xc yc) do
match_fragment node_info
(node_of_nid node_info x.children.(i))
(node_of_nid node_info y.children.(i)) m m'
done
end
* generates the edit script between and tree2 using a [ node_info ] the
[ map ] generated by the function [ mapping ] ( above ) . This is not taken
directly from the DiffX paper , because the version in the DiffX paper 's
pseudocode has ( unspecified by , who wrote the code initially ) bugs
@param node_info mapping [ node_id]s to [ tree_node]s
@param tree1 [ tree_node ]
@param tree2 [ tree_node ]
@param map [ NodeMap.t ]
@return edit_action list
[map] generated by the function [mapping] (above). This is not taken
directly from the DiffX paper, because the version in the DiffX paper's
pseudocode has (unspecified by Wes, who wrote the code initially) bugs
@param node_info mapping [node_id]s to [tree_node]s
@param tree1 [tree_node]
@param tree2 [tree_node]
@param map [NodeMap.t]
@return edit_action list
*)
let generate_script (node_info : tree_node IntMap.t) (t1 : tree_node)
(t2 : tree_node) (m : NodeMap.t) : edit_action list =
let s = ref [] in
level_order_traversal node_info t2 (fun y ->
if not (in_map_range m y) then begin
let yparent = parent_of node_info t2 y in
let ypos = position_of node_info yparent y in
match yparent with
| None ->
s := (Insert(y.nid,noio yparent,ypos)) :: !s
| Some(yparent) -> begin
let xx = find_node_that_maps_to m yparent in
match xx with
| Some(xx) -> s := (Insert(y.nid,Some(xx.nid),ypos)) :: !s
| None -> s := (Insert(y.nid,Some(yparent.nid),ypos)) :: !s
end
end else begin
match find_node_that_maps_to m y with
| None -> printf "generate_script: error: no node that maps to!\n"
| Some(x) -> begin
let xparent = parent_of node_info t1 x in
let yparent = parent_of node_info t2 y in
let yposition = position_of node_info yparent y in
let xposition = position_of node_info xparent x in
match xparent, yparent with
| Some(xparent), Some(yparent) ->
if not (NodeMap.mem (xparent,yparent) m) then begin
let xx = find_node_that_maps_to m yparent in
match xx with
| Some(xx) -> s := (Move(x.nid,Some(xx.nid),yposition)) :: !s
| None -> s := (Move(x.nid,Some yparent.nid,yposition)) :: !s
end
else if xposition <> yposition then
s := (Move(x.nid,Some xparent.nid,yposition)) :: !s
| _, _ -> ()
end
end
) ;
level_order_traversal node_info t1 (fun x ->
if not (in_map_domain m x) then begin
s := (Delete(x.nid)) :: !s
end
) ;
List.rev !s
let dummyBlock = { battrs = [] ; bstmts = [] ; }
* generates the ' typelabel ' of a CIL construct -- basically by turning if
( x < y ) foo ( ) ; into : if ( x < y ) ( ) and then hashing it . See the DiffX paper for
more detail on the definition of typelabel .
@param s Cil statement
@return ( string , ) pair of the typelabel .
(x<y) foo(); into: if (x<y) () and then hashing it. See the DiffX paper for
more detail on the definition of typelabel.
@param s Cil statement
@return (string,Cil stmt) pair of the typelabel.
*)
let stmt_to_typelabel (s : Cil.stmt) =
let dummyBlock = { battrs = [] ; bstmts = [] ; } in
let dummyLoc = { line = 0 ; file = "" ; byte = 0; } in
let convert_exp exp =
if !exp_diff_level then Cil.zero
else exp
in
let convert_exp_opt exp =
match exp with
Some(e) when !exp_diff_level -> Some(Cil.zero)
| _ -> exp
in
let convert_exps exps =
if !exp_diff_level then []
else exps
in
CLG potential FIXME : lvals ?
let convert_label l = match l with
| Label(s,loc,b) -> Label(s,dummyLoc,b)
| Case(e,loc) -> Case(convert_exp e,dummyLoc)
| Default(loc) -> Default(dummyLoc)
in
let labels = List.map convert_label s.labels in
let convert_il il =
List.map (fun i -> match i with
| Set(lv,e,loc) -> Set(lv,convert_exp e,dummyLoc)
| Call(lvo,e,el,loc) -> Call(lvo,convert_exp e,convert_exps el,dummyLoc)
| Asm(a,b,c,d,e,loc) -> Asm(a,b,c,d,e,dummyLoc)
) il
in
let skind = match s.skind with
| Instr(il) -> Instr(convert_il il)
| Return(eo,l) -> Return(convert_exp_opt eo,dummyLoc)
| Goto(sr,l) -> Goto(sr,dummyLoc)
| Break(l) -> Break(dummyLoc)
| Continue(l) -> Continue(dummyLoc)
| If(e,b1,b2,l) -> If(convert_exp e,dummyBlock,dummyBlock,l)
| Switch(e,b,sl,l) -> Switch(convert_exp e,dummyBlock,[],l)
| Loop(b,l,so1,so2) -> Loop(dummyBlock,l,None,None)
| Block(block) -> Block(dummyBlock)
| TryFinally(b1,b2,l) -> TryFinally(dummyBlock,dummyBlock,dummyLoc)
| TryExcept(b1,(il,e),b2,l) ->
TryExcept(dummyBlock,(convert_il il,convert_exp e),dummyBlock,dummyLoc)
in
let s' = { s with skind = skind ; labels = labels } in
let doc = dn_stmt () s' in
let str = Pretty.sprint ~width:80 doc in
let it = labels, skind, str in
if Hashtbl.mem typelabel_ht str then begin
Hashtbl.find typelabel_ht str , it
end else begin
let res = !typelabel_counter in
incr typelabel_counter ;
Hashtbl.add typelabel_ht str res ;
Hashtbl.add inv_typelabel_ht res it ;
res , it
end
let fundec_to_ast (node_info : tree_node IntMap.t) (f:Cil.fundec) =
let wrap_block b = mkStmt (Block(b)) in
let node_info = ref node_info in
let exp_to_typelabel e =
let e' =
match e with
| Const _ | Lval _ | SizeOf _
| SizeOfStr _ | AlignOf _ | AddrOf _
| StartOf _ -> e
| SizeOfE e1 -> SizeOfE(Cil.zero)
| AlignOfE e1 -> AlignOfE(Cil.zero)
| UnOp(u,e1,t) -> UnOp(u,Cil.zero,t)
| BinOp(b,e1,e2,t) -> BinOp(b,Cil.zero, Cil.zero, t)
| CastE(t,e1) -> CastE(t, Cil.zero)
in
let doc = dn_exp () e' in
let str = Pretty.sprint ~width:80 doc in
let it = e', str in
if hmem typelabel_ht str then
hfind typelabel_ht str, it
else
let res = !typelabel_counter in
incr typelabel_counter ;
hadd typelabel_ht str res ;
hadd inv_typelabel_exp_ht res it;
res, it
in
let rec exp_to_node e =
if !exp_diff_level then begin
let tl,it = exp_to_typelabel e in
let n = new_node tl in
let children = exp_children e in
n.children <- children ;
node_info := IntMap.add n.nid n !node_info ;
[n.nid]
end else []
and exp_children e =
match e with
| Const _ | Lval _ | SizeOf _
| SizeOfStr _ | AlignOf _ | AddrOf _
| StartOf _ -> [| |]
| SizeOfE(e')
| AlignOfE(e')
| UnOp(_,e',_)
| CastE(_,e') -> Array.of_list (exp_to_node e')
| BinOp(_,e1,e2,_) -> Array.of_list ((exp_to_node e1) @ (exp_to_node e2))
in
let instr_children i =
if !exp_diff_level then begin
match i with
Set(l,e,_) -> exp_to_node e
| Call(lopt,e,es,l) ->
(exp_to_node e) @ (lfoldl (fun a e -> a @ (exp_to_node e)) [] es)
| Asm(atrs,sls1,sls2,sls3,sls4,l) -> []
end else []
in
let rec stmt_to_node s =
let tl, (labels,skind,_) = stmt_to_typelabel s in
let n = new_node tl in
let children = stmt_children s in
n.children <- children ;
node_info := IntMap.add n.nid n !node_info ;
n.nid
and stmt_children (s : Cil.stmt) : node_id array =
match s.skind with
| Goto _ | Break _ | Continue _ -> [| |]
| Instr ils ->
let lst : node_id list = lfoldl (fun a i -> (instr_children i) @ a) [] ils in
Array.of_list lst
| Return (Some(e),_) when !exp_diff_level -> Array.of_list (exp_to_node e)
| Return _ -> [| |]
| If(e,b1,b2,l) ->
let stmts =
[| stmt_to_node (wrap_block b1) ;
stmt_to_node (wrap_block b2) |]
in
let exps = Array.of_list (exp_to_node e) in
Array.append exps stmts
| Switch(e,b,sl,l) ->
let stmts =
[| stmt_to_node (wrap_block b) |]
in
let exps = Array.of_list (exp_to_node e) in
Array.append exps stmts
| Loop(b,l,so1,so2) ->
[| stmt_to_node (wrap_block b) |]
| TryFinally(b1,b2,l) ->
[| stmt_to_node (wrap_block b1) ; stmt_to_node (wrap_block b2) |]
| TryExcept(b1,(il,e),b2,l) ->
let instrs = Array.of_list (lfoldl (fun a i -> a @ (instr_children i)) [] il) in
let exps = Array.of_list (exp_to_node e) in
let stmts =
[| stmt_to_node (wrap_block b1) ; stmt_to_node (wrap_block b2) |]
in
Array.concat [instrs;exps;stmts]
| Block(block) ->
let children = List.map stmt_to_node block.bstmts in
Array.of_list children
in
let b = wrap_block f.sbody in
stmt_to_node b , !node_info
let rec node_to_stmt (node_info : tree_node IntMap.t) (n : tree_node) : Cil.stmt =
let children = Array.map (fun child ->
let child = node_of_nid node_info child in
node_to_stmt node_info child
) n.children in
let labels, skind,_ = Hashtbl.find inv_typelabel_ht n.typelabel in
let require x =
if Array.length children = x then ()
else begin
printf "// node_to_stmt: warn: wanted %d children, have %d\n"
x (Array.length children) ;
end
in
let block x =
if x >= Array.length children then dummyBlock
else match children.(x).skind with
| Block(b) -> b
| _ -> begin
printf "// node_to_stmt: warn: wanted child %d to be a block\n" x ;
dummyBlock
end
in
let stmt = mkStmt begin
match skind with
| Instr _ | Return _ | Goto _
| Break _ | Continue _ -> skind
| If(e,b1,b2,l) -> require 2 ; If(e,block 0,block 1,l)
| Switch(e,b,sl,l) -> require 1 ; Switch(e,block 0,sl,l)
| Loop(b,l,so1,so2) -> require 1 ; Loop(block 0,l,so1,so2)
| TryFinally(b1,b2,l) -> require 2 ; TryFinally(block 0,block 1,l)
| TryExcept(b1,(il,e),b2,l) ->
require 2; TryExcept(block 0,(il,e),block 1,l)
| Block _ -> Block(mkBlock (Array.to_list children))
end
in
stmt.labels <- labels ;
stmt
* @param node_info mapping [ node_id]s to [ tree_node]s
@param f base Cil.fundec into which we will put the converted AST
@param n [ tree_node ] to convert back into the function body .
@return Cil.file [ f ] with the body replaced by the representation of [ n ]
@raise Fail("need child to be a block " ) if [ n ] does n't correspond to a block
statement .
@param f base Cil.fundec into which we will put the converted AST
@param n [tree_node] to convert back into the function body.
@return Cil.file [f] with the body replaced by the Cil representation of [n]
@raise Fail("need child to be a block") if [n] doesn't correspond to a block
statement. *)
let ast_to_fundec (node_info : tree_node IntMap.t) (f:Cil.fundec) (n : tree_node) =
let stmt = node_to_stmt node_info n in
match stmt.skind with
| Block(b) -> { f with sbody = b ; }
| _ ->
printf "fundec_to_ast: error: wanted child to be a block\n" ;
failwith "fundec_to_ast"
* @param node_info mapping [ node_id]s to [ tree_node]s
@param m [ NodeMap.t ] mapping between two ASTs that have previously been
diffed
@param ast1 [ node_id ] root of the first tree
@param ast2 [ node_id ] root of the second tree
@param edit_action edit action to apply to ast1
@return node_info new node_info , potentially modified , reflecting the
changes wrought by [ edit_action ] on [ ast1 ]
@param m [NodeMap.t] mapping between two ASTs that have previously been
diffed
@param ast1 [node_id] root of the first tree
@param ast2 [node_id] root of the second tree
@param edit_action edit action to apply to ast1
@return node_info new node_info, potentially modified, reflecting the
changes wrought by [edit_action] on [ast1]
*)
let apply_diff (node_info : tree_node IntMap.t) (m : NodeMap.t) (astt1 : node_id)
(astt2 : node_id) (s : edit_action) : tree_node IntMap.t =
let ast1 = node_of_nid node_info astt1 in
let ast2 = node_of_nid node_info astt2 in
try
match s with
| Delete(nid) ->
let node = node_of_nid node_info nid in
delete node_info node
| Insert(xid,yopt,ypopt) ->
let xnode = node_of_nid node_info xid in
(match yopt with
| None -> printf "apply: error: insert to root?" ; node_info
| Some(yid) ->
let ynode = node_of_nid node_info yid in
let ypos = match ypopt with
| Some(x) -> x | None -> 0
in
Step 1 : remove children of X
let node_info =
xnode.children <- [| |] ;
IntMap.add xnode.nid xnode node_info
in
Step 2 : remove X from its parent
let node_info =
let xparent1 = parent_of node_info ast1 xnode in
let xparent2 = parent_of node_info ast2 xnode in
(match xparent1, xparent2 with
| Some(parent), _
| _, Some(parent) ->
let plst = Array.to_list parent.children in
let plst = List.map (fun child ->
let child = node_of_nid node_info child in
if child.nid = xid then
deleted_node.nid
else
child.nid
) plst in
parent.children <- Array.of_list plst ;
IntMap.add parent.nid parent node_info
| _, _ -> node_info
)
in
Step 3 : put X as p - th child of Y
let len = Array.length ynode.children in
let before = Array.sub ynode.children 0 ypos in
let after = Array.sub ynode.children ypos (len - ypos) in
let result = Array.concat [ before ; [| xnode.nid |] ; after ] in
ynode.children <- result ;
IntMap.add ynode.nid ynode node_info
)
| Move(xid,yopt,ypopt) ->
let xnode = node_of_nid node_info xid in
(match yopt with
| None ->
printf "apply: error: %s: move to root?\n" (edit_action_to_str node_info s) ; node_info
| Some(yid) ->
let ynode = node_of_nid node_info yid in
let ypos = match ypopt with
| Some(x) -> x | None -> 0
in
Step 1 : remove X from its parent
let xparent1 = parent_of node_info ast1 xnode in
let xparent2 = parent_of node_info ast2 xnode in
let node_info =
match xparent1, xparent2 with
| Some(parent), _
| _, Some(parent) ->
let plst = Array.to_list parent.children in
let plst = List.map (fun child ->
let child = node_of_nid node_info child in
if child.nid = xid then
deleted_node.nid
else
child.nid
) plst in
parent.children <- Array.of_list plst ;
IntMap.add parent.nid parent node_info
| None, None ->
printf "apply: error: %s: no x parent\n"
(edit_action_to_str node_info s) ; node_info
in
Step 2 : put X as p - th child of Y
let len = Array.length ynode.children in
let before = Array.sub ynode.children 0 ypos in
let after = Array.sub ynode.children ypos (len - ypos) in
let result = Array.concat [ before ; [| xnode.nid |] ; after ] in
ynode.children <- result ;
IntMap.add ynode.nid ynode node_info
)
with e -> raise Necessary_line
* applies a diffscript stored in [ data_ht ] and [ patch_ht ] to [ cil_file ] .
assumes that [ inv_typelabel_ht ] has been populated , because apparently I did
not eliminate all state in this module .
@param cil_file Cil.file
@param node_info mapping between [ node_id]s and [ tree_node]s
@param patch_ht hashtable containing the edits associated with globals in
[ cil_file ]
@param data_ht hashtable containing the map and two asts associated with
globals in [ cil_file ]
@return Cil.file reflecting the changes in [ patch_ht ] as applied to [ cil_file ] .
assumes that [inv_typelabel_ht] has been populated, because apparently I did
not eliminate all state in this module.
@param cil_file Cil.file
@param node_info mapping between [node_id]s and [tree_node]s
@param patch_ht hashtable containing the edits associated with globals in
[cil_file]
@param data_ht hashtable containing the map and two asts associated with
globals in [cil_file]
@return Cil.file reflecting the changes in [patch_ht] as applied to [cil_file].
*)
let apply_diff_to_file f1 node_info patch_ht data_ht =
foldGlobals f1
(fun (globals,node_info) g1 ->
match g1 with
| GFun(fd1,l) when Hashtbl.mem patch_ht fd1.svar.vname ->
let name = fd1.svar.vname in
let patches = Hashtbl.find patch_ht name in
let m, t1, t2 = Hashtbl.find data_ht name in
let node_info =
try
List.fold_left
(fun node_info ->
fun ea ->
apply_diff node_info m t1 t2 ea;
) node_info patches
with Necessary_line -> node_info
in
let node_info =
cleanup_tree node_info (node_of_nid node_info t1)
in
let output_fundec =
ast_to_fundec node_info fd1 (node_of_nid node_info t1) in
(GFun(output_fundec,l)) :: globals, node_info
| _ -> g1 :: globals, node_info
) ([], node_info)
*
@param file Cil.file
@param node_info map between [ node_id]s and [ tree_node]s
@param script strings representing edit actions
@param data_ht map between globals and mappings / ast pairs
@return file that has had the edits represented by [ script ] applied
@param file Cil.file
@param node_info map between [node_id]s and [tree_node]s
@param script strings representing edit actions
@param data_ht map between globals and mappings/ast pairs
@return file that has had the edits represented by [script] applied *)
let usediff (f1 : Cil.file) (node_info : tree_node IntMap.t)
(script : string list) data_ht =
let patch_ht = Hashtbl.create 255 in
let sofar = try Hashtbl.find patch_ht fname with _ -> [] in
Hashtbl.replace patch_ht fname (sofar @ [ea])
in
let num_to_io x = if x < 0 then None else Some(x) in
let _ =
List.iter
(fun line ->
Scanf.sscanf line "%s %s %s (%d,%d,%d)" (fun the_file fname ea a b c ->
let it = match String.lowercase_ascii ea with
| "insert" -> Insert(a, num_to_io b, num_to_io c)
| "move" -> Move(a, num_to_io b, num_to_io c)
| "delete" -> Delete(a)
| _ -> failwith ("invalid patch: " ^ line)
in add_patch fname it
)
) script
in
let globals,_ =
apply_diff_to_file f1 node_info patch_ht data_ht in
{f1 with globals = lrev globals }
|
ca5f483affaf7f6c8ef35898f7b953ae2383957fb86d2cedb0ba2af52770cb7d | tomsmalley/semantic-reflex | List.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecursiveDo #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Example.Section.List where
import Control.Lens hiding (List)
import Data.Foldable (for_, traverse_)
import Data.Monoid ((<>))
import Reflex.Dom.SemanticUI
import Reflex.Dom.Core (text)
import Example.QQ
import Example.Common
data Files a = File a | Folder a [Files a]
lists :: (MonadWidget t m, Prerender t m) => Section t m
lists = Section "List" (text "A list is used to group related content. " >> simpleLink "-ui.com/elements/list.html") $ do
hscode $(printDefinition id stripParens ''ListConfig)
hscode $(printDefinition id stripParens ''ListItemConfig)
mkExample "List" (def
& subtitle ?~ text "A list groups related content")
[example|
list def $ for_ ["Apples", "Pears", "Oranges"] $ listItem def . text
|]
mkExample "" def
[example|
list def $ do
listItem (def & listItemConfig_preContent ?~ icon "users" def) $ text "Semantic UI"
listItem (def & listItemConfig_preContent ?~ icon "marker" def) $ text "New York, NY"
listItem (def & listItemConfig_preContent ?~ icon "mail" def) $ simpleLink ""
listItem (def & listItemConfig_preContent ?~ icon "linkify" def) $ simpleLink "semantic-ui.com"
|]
mkExample "" def
[example|
list (def & listConfig_divided |~ True & listConfig_relaxed |?~ Relaxed) $ do
let repos = [ ("Semantic-Org/Semantic-UI", 10 :: Int)
, ("Semantic-Org/Semantic-UI-Docs", 22)
, ("Semantic-Org/Semantic-UI-Meteor", 34) ]
let github = icon "github" $ def
& iconConfig_size |?~ Large & classes |~ "middle aligned"
for_ repos $ \(name, time) -> listItem (def & listItemConfig_preContent ?~ github) $ do
listHeader $ text name
listDescription $ text $ "Updated " <> tshow time <> " mins ago"
|]
mkExample "" def
[example|
let
-- In the absence of local data declarations:
-- data Files a = File a | Folder a [Files a]
files =
[ Folder ("src", "Source files for project")
[ Folder ("site", "Your site's theme") []
, Folder ("themes", "Packaged theme files")
[ Folder ("default", "Default packaged theme") []
, Folder ("my_theme", "Packaged themes are also available in this folder") [] ]
, File ("theme.config", "Config file for setting packaged themes") ]
, Folder ("dist", "Compiled CSS and JS files")
[ Folder ("components", "Individual component CSS and JS") [] ]
, File ("semantic.json", "Contains build settings for gulp") ]
listFiles [] = blank
listFiles fs = list def $ for_ fs $ \f -> case f of
File (name, description) -> listItem (def & listItemConfig_preContent ?~ icon "file" def) $ do
listHeader $ text name
listDescription $ text description
Folder (name, description) fs' -> listItem (def & listItemConfig_preContent ?~ icon "folder" def) $ do
listHeader $ text name
listDescription $ text description
listFiles fs'
listFiles files
|]
mkExample "Bulleted" (def
& subtitle ?~ text "A list can mark items with a bullet")
[example|
list (def & listConfig_type |?~ Bulleted) $ do
listItem def $ text "Gaining Access"
listItem def $ text "Inviting Friends"
listItem def $ do
text "Benefits"
list def $ do
listItem def $ hyperlink "" $ text "Link to somewhere"
listItem def $ text "Rebates"
listItem def $ text "Discounts"
listItem def $ text "Warranty"
|]
mkExample "" def
[example|
list (def & listConfig_type |?~ Bulleted & listConfig_horizontal |~ True) $ do
listItem def $ hyperlink "#" $ text "About Us"
listItem def $ hyperlink "#" $ text "Sitemap"
listItem def $ hyperlink "#" $ text "Contact"
|]
mkExample "Ordered" (def
& subtitle ?~ text "A list can be ordered numerically")
[example|
list (def & listConfig_type |?~ Ordered) $ do
listItem def $ hyperlink "#" $ text "Getting Started"
listItem def $ hyperlink "#" $ text "Introduction"
listItem def $ do
hyperlink "#" $ text "Languages"
list def $ do
listItem def $ hyperlink "#" $ text "HTML"
listItem def $ hyperlink "#" $ text "Javascript"
listItem def $ hyperlink "#" $ text "CSS"
listItem def $ hyperlink "#" $ text "Review"
|]
mkExample "Value" (def
& subtitle ?~ text "A list item can have a custom value"
& inbetween ?~ upstreamIssue 5911 "The data-value attribute is currently ignored for <div> list items.")
[example|
list (def & listConfig_type |?~ Ordered) $ do
listItem (def & attrs |~ "data-value" =: "*") $ text "Signing Up"
listItem (def & attrs |~ "data-value" =: "*") $ text "User Benefits"
listItem (def & attrs |~ "data-value" =: "*") $ do
text "User Types"
list def $ do
listItem (def & attrs |~ "data-value" =: "-") $ text "Admin"
listItem (def & attrs |~ "data-value" =: "-") $ text "Power User"
listItem (def & attrs |~ "data-value" =: "-") $ text "Regular User"
listItem (def & attrs |~ "data-value" =: "*") $ text "Deleting Your Account"
|]
mkExample "Link" (def
& subtitle ?~ text "A list can be specially formatted for navigation links")
[example|
list (def & listConfig_link |~ True) $ do
let conf = def & listItemConfig_element .~ ListItemLink
listItem (conf & classes |~ "active") $ text "Home"
listItem conf $ text "About"
listItem conf $ text "Jobs"
listItem conf $ text "Team"
|]
mkExample "Icon" (def
& subtitle ?~ text "A list item can contain an icon")
[example|
list def $ do
let conf = def & listItemConfig_element .~ ListItemLink
listItem (conf & listItemConfig_preContent ?~ icon "help" def) $ do
listHeader $ text "Floated Icon"
listDescription $ text "This text will always have a left margin to make sure it sits alongside your icon"
listItem (conf & listItemConfig_preContent ?~ icon "right triangle" def) $ do
listHeader $ text "Icon Alignment"
listDescription $ text "Floated icons are by default top aligned"
listItem (def & listItemConfig_preContent ?~ icon "help" def) $ text "Inline Text"
|]
mkExample "Image" (def
& subtitle ?~ text "A list item can contain an image")
[example|
list def $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "fox") $ do
listHeader $ hyperlink "#" $ text "Fiona"
listDescription $ text "Last seen rummaging through the bins just now."
listItem (def & listItemConfig_preContent ?~ animalImage "elephant") $ do
listHeader $ hyperlink "#" $ text "Ethan"
listDescription $ text "Last seen playing in the water 2 hours ago."
listItem (def & listItemConfig_preContent ?~ animalImage "monkey") $ do
listHeader $ hyperlink "#" $ text "Marcus"
listDescription $ text "Last seen swinging on his tyre yesterday."
listItem (def & listItemConfig_preContent ?~ animalImage "giraffe") $ do
listHeader $ hyperlink "#" $ text "Ginny"
listDescription $ text "Last seen nibbling on a tree 3 days ago."
listItem (def & listItemConfig_preContent ?~ animalImage "spider") $ do
listHeader $ hyperlink "#" $ text "Stanley"
listDescription $ text "Last seen spooking people a week ago."
|]
mkExample "Link" (def
& subtitle ?~ text "A list can contain links")
[example|
list def $ do
let conf = def & listItemConfig_element .~ ListItemLink
listItem conf $ text "What is a FAQ?"
listItem conf $ text "Who is our user?"
listItem conf $ text "Where is our office located?"
|]
mkExample "Header" (def
& subtitle ?~ text "A list item can contain a header")
[example|
list def $ do
listItem def $ do
listHeader $ text "Manchester"
text "A lovely city"
listItem def $ do
listHeader $ text "Sheffield"
text "Also quite a lovely city"
listItem def $ do
listHeader $ text "London"
text "Sometimes can be a lovely city"
listItem def $ do
listHeader $ text "Bristol"
text "What a lovely city"
|]
mkExample "Description" (def
& subtitle ?~ text "A list item can contain a description")
[example|
list def $ do
listItem (def & listItemConfig_preContent ?~ icon "map marker" def) $ do
listHeader $ hyperlink "#" $ text "Królewskie Jadło"
listDescription $ text "An excellent polish restaurant, quick delivery and hearty, filling meals."
listItem (def & listItemConfig_preContent ?~ icon "map marker" def) $ do
listHeader $ hyperlink "#" $ text "Sapporo Haru"
listDescription $ text "Greenpoint's best choice for quick and delicious sushi."
|]
mkExample "Horizontal" (def
& subtitle ?~ text "A list can be formatted to have items appear horizontally")
[example|
list (def & listConfig_horizontal |~ True) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "eagle") $ do
listHeader $ text "Eddie"
text "Top Contributor"
listItem (def & listItemConfig_preContent ?~ animalImage "tiger") $ do
listHeader $ text "Tommy"
text "Admin"
listItem (def & listItemConfig_preContent ?~ animalImage "kangaroo") $ do
listHeader $ text "Katie"
text "Top Rated User"
|]
mkExample "Inverted" (def
& subtitle ?~ text "A list can be inverted to appear on a dark background")
[example|
segment (def & segmentConfig_inverted |~ True) $
list (def & listConfig_inverted |~ True
& listConfig_relaxed |?~ Relaxed
& listConfig_divided |~ True) $ do
listItem def $ do
listHeader $ text "Snickerdoodle"
text "An excellent companion"
listItem def $ do
listHeader $ text "Poodle"
text "A poodle, it's pretty basic"
listItem def $ do
listHeader $ text "Paulo"
text "He's also a dog"
|]
mkExample "Selection" (def
& subtitle ?~ text "A selection list formats list items as possible choices")
[example|
list (def & listConfig_selection |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "horse") $
listHeader $ text "Helen"
listItem (def & listItemConfig_preContent ?~ animalImage "chicken") $
listHeader $ text "Christian"
listItem (def & listItemConfig_preContent ?~ animalImage "duck") $
listHeader $ text "Daniel"
|]
mkExample "Animated" (def
& subtitle ?~ text "A list can animate to set the current item apart from the list")
[example|
list (def & listConfig_animated |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "horse") $
listHeader $ text "Helen"
listItem (def & listItemConfig_preContent ?~ animalImage "chicken") $
listHeader $ text "Christian"
listItem (def & listItemConfig_preContent ?~ animalImage "duck") $
listHeader $ text "Daniel"
|]
mkExample "Relaxed" (def
& subtitle ?~ text "A list can relax its padding to provide more negative space")
[example|
list def $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ Relaxed) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ VeryRelaxed) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_horizontal |~ True) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ Relaxed & listConfig_horizontal |~ True) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ VeryRelaxed & listConfig_horizontal |~ True) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
|]
mkExample "Divided" (def
& subtitle ?~ text "A list can show divisions between items")
[example|
list (def & listConfig_divided |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $
listHeader $ text "Betty"
divider $ def & dividerConfig_hidden |~ True
list (def & listConfig_divided |~ True & listConfig_horizontal |~ True) $ do
listItem def $ text "About Us"
listItem def $ text "Contact"
listItem def $ text "Support"
|]
mkExample "Celled" (def
& subtitle ?~ text "A list can divide its items into cells")
[example|
list (def & listConfig_celled |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
text "A cow"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
text "A turtle"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
text "A bear"
divider $ def & dividerConfig_hidden |~ True
list (def & listConfig_celled |~ True & listConfig_horizontal |~ True) $ do
listItem def $ text "About Us"
listItem def $ text "Contact"
listItem def $ text "Support"
|]
mkExample "Size" (def
& subtitle ?~ text "A list can vary in size")
[example|
let conf = def & listConfig_horizontal |~ True & listConfig_aligned |?~ ListMiddle
animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
for_ [minBound .. maxBound] $ \s -> do
list (conf & listConfig_size |?~ s) $ do
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
divider $ def & dividerConfig_hidden |~ True
|]
mkExample "Floated" (def
& subtitle ?~ text "A list can be floated")
[example|
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
list (def & listConfig_floated |?~ LeftFloated) $ do
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
list (def & listConfig_floated |?~ RightFloated) $ do
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
|]
return ()
| null | https://raw.githubusercontent.com/tomsmalley/semantic-reflex/5a973390fae1facbc4351b75ea59210d6756b8e5/semantic-reflex-example/src/Example/Section/List.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes #
# LANGUAGE RecursiveDo #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
In the absence of local data declarations:
data Files a = File a | Folder a [Files a] | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
module Example.Section.List where
import Control.Lens hiding (List)
import Data.Foldable (for_, traverse_)
import Data.Monoid ((<>))
import Reflex.Dom.SemanticUI
import Reflex.Dom.Core (text)
import Example.QQ
import Example.Common
data Files a = File a | Folder a [Files a]
lists :: (MonadWidget t m, Prerender t m) => Section t m
lists = Section "List" (text "A list is used to group related content. " >> simpleLink "-ui.com/elements/list.html") $ do
hscode $(printDefinition id stripParens ''ListConfig)
hscode $(printDefinition id stripParens ''ListItemConfig)
mkExample "List" (def
& subtitle ?~ text "A list groups related content")
[example|
list def $ for_ ["Apples", "Pears", "Oranges"] $ listItem def . text
|]
mkExample "" def
[example|
list def $ do
listItem (def & listItemConfig_preContent ?~ icon "users" def) $ text "Semantic UI"
listItem (def & listItemConfig_preContent ?~ icon "marker" def) $ text "New York, NY"
listItem (def & listItemConfig_preContent ?~ icon "mail" def) $ simpleLink ""
listItem (def & listItemConfig_preContent ?~ icon "linkify" def) $ simpleLink "semantic-ui.com"
|]
mkExample "" def
[example|
list (def & listConfig_divided |~ True & listConfig_relaxed |?~ Relaxed) $ do
let repos = [ ("Semantic-Org/Semantic-UI", 10 :: Int)
, ("Semantic-Org/Semantic-UI-Docs", 22)
, ("Semantic-Org/Semantic-UI-Meteor", 34) ]
let github = icon "github" $ def
& iconConfig_size |?~ Large & classes |~ "middle aligned"
for_ repos $ \(name, time) -> listItem (def & listItemConfig_preContent ?~ github) $ do
listHeader $ text name
listDescription $ text $ "Updated " <> tshow time <> " mins ago"
|]
mkExample "" def
[example|
let
files =
[ Folder ("src", "Source files for project")
[ Folder ("site", "Your site's theme") []
, Folder ("themes", "Packaged theme files")
[ Folder ("default", "Default packaged theme") []
, Folder ("my_theme", "Packaged themes are also available in this folder") [] ]
, File ("theme.config", "Config file for setting packaged themes") ]
, Folder ("dist", "Compiled CSS and JS files")
[ Folder ("components", "Individual component CSS and JS") [] ]
, File ("semantic.json", "Contains build settings for gulp") ]
listFiles [] = blank
listFiles fs = list def $ for_ fs $ \f -> case f of
File (name, description) -> listItem (def & listItemConfig_preContent ?~ icon "file" def) $ do
listHeader $ text name
listDescription $ text description
Folder (name, description) fs' -> listItem (def & listItemConfig_preContent ?~ icon "folder" def) $ do
listHeader $ text name
listDescription $ text description
listFiles fs'
listFiles files
|]
mkExample "Bulleted" (def
& subtitle ?~ text "A list can mark items with a bullet")
[example|
list (def & listConfig_type |?~ Bulleted) $ do
listItem def $ text "Gaining Access"
listItem def $ text "Inviting Friends"
listItem def $ do
text "Benefits"
list def $ do
listItem def $ hyperlink "" $ text "Link to somewhere"
listItem def $ text "Rebates"
listItem def $ text "Discounts"
listItem def $ text "Warranty"
|]
mkExample "" def
[example|
list (def & listConfig_type |?~ Bulleted & listConfig_horizontal |~ True) $ do
listItem def $ hyperlink "#" $ text "About Us"
listItem def $ hyperlink "#" $ text "Sitemap"
listItem def $ hyperlink "#" $ text "Contact"
|]
mkExample "Ordered" (def
& subtitle ?~ text "A list can be ordered numerically")
[example|
list (def & listConfig_type |?~ Ordered) $ do
listItem def $ hyperlink "#" $ text "Getting Started"
listItem def $ hyperlink "#" $ text "Introduction"
listItem def $ do
hyperlink "#" $ text "Languages"
list def $ do
listItem def $ hyperlink "#" $ text "HTML"
listItem def $ hyperlink "#" $ text "Javascript"
listItem def $ hyperlink "#" $ text "CSS"
listItem def $ hyperlink "#" $ text "Review"
|]
mkExample "Value" (def
& subtitle ?~ text "A list item can have a custom value"
& inbetween ?~ upstreamIssue 5911 "The data-value attribute is currently ignored for <div> list items.")
[example|
list (def & listConfig_type |?~ Ordered) $ do
listItem (def & attrs |~ "data-value" =: "*") $ text "Signing Up"
listItem (def & attrs |~ "data-value" =: "*") $ text "User Benefits"
listItem (def & attrs |~ "data-value" =: "*") $ do
text "User Types"
list def $ do
listItem (def & attrs |~ "data-value" =: "-") $ text "Admin"
listItem (def & attrs |~ "data-value" =: "-") $ text "Power User"
listItem (def & attrs |~ "data-value" =: "-") $ text "Regular User"
listItem (def & attrs |~ "data-value" =: "*") $ text "Deleting Your Account"
|]
mkExample "Link" (def
& subtitle ?~ text "A list can be specially formatted for navigation links")
[example|
list (def & listConfig_link |~ True) $ do
let conf = def & listItemConfig_element .~ ListItemLink
listItem (conf & classes |~ "active") $ text "Home"
listItem conf $ text "About"
listItem conf $ text "Jobs"
listItem conf $ text "Team"
|]
mkExample "Icon" (def
& subtitle ?~ text "A list item can contain an icon")
[example|
list def $ do
let conf = def & listItemConfig_element .~ ListItemLink
listItem (conf & listItemConfig_preContent ?~ icon "help" def) $ do
listHeader $ text "Floated Icon"
listDescription $ text "This text will always have a left margin to make sure it sits alongside your icon"
listItem (conf & listItemConfig_preContent ?~ icon "right triangle" def) $ do
listHeader $ text "Icon Alignment"
listDescription $ text "Floated icons are by default top aligned"
listItem (def & listItemConfig_preContent ?~ icon "help" def) $ text "Inline Text"
|]
mkExample "Image" (def
& subtitle ?~ text "A list item can contain an image")
[example|
list def $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "fox") $ do
listHeader $ hyperlink "#" $ text "Fiona"
listDescription $ text "Last seen rummaging through the bins just now."
listItem (def & listItemConfig_preContent ?~ animalImage "elephant") $ do
listHeader $ hyperlink "#" $ text "Ethan"
listDescription $ text "Last seen playing in the water 2 hours ago."
listItem (def & listItemConfig_preContent ?~ animalImage "monkey") $ do
listHeader $ hyperlink "#" $ text "Marcus"
listDescription $ text "Last seen swinging on his tyre yesterday."
listItem (def & listItemConfig_preContent ?~ animalImage "giraffe") $ do
listHeader $ hyperlink "#" $ text "Ginny"
listDescription $ text "Last seen nibbling on a tree 3 days ago."
listItem (def & listItemConfig_preContent ?~ animalImage "spider") $ do
listHeader $ hyperlink "#" $ text "Stanley"
listDescription $ text "Last seen spooking people a week ago."
|]
mkExample "Link" (def
& subtitle ?~ text "A list can contain links")
[example|
list def $ do
let conf = def & listItemConfig_element .~ ListItemLink
listItem conf $ text "What is a FAQ?"
listItem conf $ text "Who is our user?"
listItem conf $ text "Where is our office located?"
|]
mkExample "Header" (def
& subtitle ?~ text "A list item can contain a header")
[example|
list def $ do
listItem def $ do
listHeader $ text "Manchester"
text "A lovely city"
listItem def $ do
listHeader $ text "Sheffield"
text "Also quite a lovely city"
listItem def $ do
listHeader $ text "London"
text "Sometimes can be a lovely city"
listItem def $ do
listHeader $ text "Bristol"
text "What a lovely city"
|]
mkExample "Description" (def
& subtitle ?~ text "A list item can contain a description")
[example|
list def $ do
listItem (def & listItemConfig_preContent ?~ icon "map marker" def) $ do
listHeader $ hyperlink "#" $ text "Królewskie Jadło"
listDescription $ text "An excellent polish restaurant, quick delivery and hearty, filling meals."
listItem (def & listItemConfig_preContent ?~ icon "map marker" def) $ do
listHeader $ hyperlink "#" $ text "Sapporo Haru"
listDescription $ text "Greenpoint's best choice for quick and delicious sushi."
|]
mkExample "Horizontal" (def
& subtitle ?~ text "A list can be formatted to have items appear horizontally")
[example|
list (def & listConfig_horizontal |~ True) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "eagle") $ do
listHeader $ text "Eddie"
text "Top Contributor"
listItem (def & listItemConfig_preContent ?~ animalImage "tiger") $ do
listHeader $ text "Tommy"
text "Admin"
listItem (def & listItemConfig_preContent ?~ animalImage "kangaroo") $ do
listHeader $ text "Katie"
text "Top Rated User"
|]
mkExample "Inverted" (def
& subtitle ?~ text "A list can be inverted to appear on a dark background")
[example|
segment (def & segmentConfig_inverted |~ True) $
list (def & listConfig_inverted |~ True
& listConfig_relaxed |?~ Relaxed
& listConfig_divided |~ True) $ do
listItem def $ do
listHeader $ text "Snickerdoodle"
text "An excellent companion"
listItem def $ do
listHeader $ text "Poodle"
text "A poodle, it's pretty basic"
listItem def $ do
listHeader $ text "Paulo"
text "He's also a dog"
|]
mkExample "Selection" (def
& subtitle ?~ text "A selection list formats list items as possible choices")
[example|
list (def & listConfig_selection |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "horse") $
listHeader $ text "Helen"
listItem (def & listItemConfig_preContent ?~ animalImage "chicken") $
listHeader $ text "Christian"
listItem (def & listItemConfig_preContent ?~ animalImage "duck") $
listHeader $ text "Daniel"
|]
mkExample "Animated" (def
& subtitle ?~ text "A list can animate to set the current item apart from the list")
[example|
list (def & listConfig_animated |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "horse") $
listHeader $ text "Helen"
listItem (def & listItemConfig_preContent ?~ animalImage "chicken") $
listHeader $ text "Christian"
listItem (def & listItemConfig_preContent ?~ animalImage "duck") $
listHeader $ text "Daniel"
|]
mkExample "Relaxed" (def
& subtitle ?~ text "A list can relax its padding to provide more negative space")
[example|
list def $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ Relaxed) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ VeryRelaxed) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_horizontal |~ True) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ Relaxed & listConfig_horizontal |~ True) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
divider def
list (def & listConfig_relaxed |?~ VeryRelaxed & listConfig_horizontal |~ True) $ do
listItem def $ text "One"
listItem def $ text "Two"
listItem def $ text "Three"
|]
mkExample "Divided" (def
& subtitle ?~ text "A list can show divisions between items")
[example|
list (def & listConfig_divided |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $
listHeader $ text "Betty"
divider $ def & dividerConfig_hidden |~ True
list (def & listConfig_divided |~ True & listConfig_horizontal |~ True) $ do
listItem def $ text "About Us"
listItem def $ text "Contact"
listItem def $ text "Support"
|]
mkExample "Celled" (def
& subtitle ?~ text "A list can divide its items into cells")
[example|
list (def & listConfig_celled |~ True & listConfig_aligned |?~ ListMiddle) $ do
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
text "A cow"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
text "A turtle"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
text "A bear"
divider $ def & dividerConfig_hidden |~ True
list (def & listConfig_celled |~ True & listConfig_horizontal |~ True) $ do
listItem def $ text "About Us"
listItem def $ text "Contact"
listItem def $ text "Support"
|]
mkExample "Size" (def
& subtitle ?~ text "A list can vary in size")
[example|
let conf = def & listConfig_horizontal |~ True & listConfig_aligned |?~ ListMiddle
animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
for_ [minBound .. maxBound] $ \s -> do
list (conf & listConfig_size |?~ s) $ do
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
divider $ def & dividerConfig_hidden |~ True
|]
mkExample "Floated" (def
& subtitle ?~ text "A list can be floated")
[example|
let animalImage animal = image (def & imageConfig_shape |?~ Avatar) $
Left $ Img ("images/animals/" <> animal <> ".png") def
list (def & listConfig_floated |?~ LeftFloated) $ do
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
list (def & listConfig_floated |?~ RightFloated) $ do
listItem (def & listItemConfig_preContent ?~ animalImage "cow") $ do
listHeader $ text "Charlie"
listItem (def & listItemConfig_preContent ?~ animalImage "turtle") $ do
listHeader $ text "Tammy"
listItem (def & listItemConfig_preContent ?~ animalImage "bear") $ do
listHeader $ text "Betty"
|]
return ()
|
4a68746efada5d02df82b865ea400ffe8b34fd80f4049cfaa0d42505428553e6 | modular-macros/ocaml-macros | pr7260.ml | type bar = < bar: unit >
type _ ty = Int : int ty
type dyn = Dyn : 'a ty -> dyn;;
class foo =
object (this)
method foo (Dyn ty) =
match ty with
| Int -> (this :> bar)
end;; (* fail, but not for scope *)
[%%expect{|
type bar = < bar : unit >
type _ ty = Int : int ty
type dyn = Dyn : 'a ty -> dyn
Line _, characters 0-108:
Error: This class should be virtual.
The following methods are undefined : bar
|}];;
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/typing-gadts/pr7260.ml | ocaml | fail, but not for scope | type bar = < bar: unit >
type _ ty = Int : int ty
type dyn = Dyn : 'a ty -> dyn;;
class foo =
object (this)
method foo (Dyn ty) =
match ty with
| Int -> (this :> bar)
[%%expect{|
type bar = < bar : unit >
type _ ty = Int : int ty
type dyn = Dyn : 'a ty -> dyn
Line _, characters 0-108:
Error: This class should be virtual.
The following methods are undefined : bar
|}];;
|
f7cf58a1bea4e67dc55be61f05bc51f22c83e88aeb703a2bbff69b91110ce292 | MyPost/cassius | protocols.clj | (ns cassius.protocols)
(def ^:dynamic *default-key-encoding* :utf-8)
(def ^:dynamic *default-value-encoding* :default)
(defprotocol Mappable
(to-map [m] "Converts object into a hashmap"))
(defmulti from-map
"Takes a map and converts it into type t"
(fn [m t] t))
(defprotocol ByteBufferable
(to-bbuff [v] "Converts object into a java.nio.ByteBuffer object"))
(defn to-bytes [v]
(.array (to-bbuff v)))
(defmulti from-bytes
"Takes a ByteArray and converts it into type t"
(fn [bs t] t))
(defn from-bbuff [bb type]
(from-bytes (.array bb) type))
(defprotocol IConnection
(-connect [_])
(-disconnect [_]))
(defmulti create (fn [m] (:type m)))
(defmethod create :default [m]
(create (assoc m :type :pool)))
(defn connect
([conn] (-connect conn))
([host port & [opts]]
(let [conn (-> opts
(assoc :host host :port port)
(create))]
(-connect conn)
conn)))
(defn disconnect [conn]
(-disconnect conn)
conn)
(defprotocol IMap
(-put-in [db arr v])
(-peek-in [db arr])
(-keys-in [db arr])
(-drop-in [db arr])
(-set-in [db arr v])
(-select-in [db arr])
(-mutate-in [db ks add-map del-vec]))
(defn put-in
([db v] (put-in db [] v))
([db arr v]
(-put-in db arr v)
db))
(defn peek-in
([db] (peek-in db []))
([db arr]
(-peek-in db arr)))
(defn keys-in
([db] (keys-in db []))
([db arr]
(-keys-in db arr)))
(defn drop-in
([db] (drop-in db []))
([db arr]
(-drop-in db arr)
db))
(defn set-in
([db v] (set-in db [] v))
([db arr v]
(-set-in db arr v)
db))
(defn select-in
([db] (select-in db []))
([db arr]
(-select-in db arr)))
(defn mutate-in
[db ks add-map del-vec]
(-mutate-in db ks add-map del-vec)
db)
(defprotocol IDatabase
(-init-schema [db schema])
(-schema [db type]))
(defn init-schema
([db] (if-let [sch (:schema db)]
(init-schema db sch)
db))
([db schema]
(-init-schema db schema)
db))
(defn schema [db type]
(-schema db type))
(defprotocol IStream
(-stream-in [conn args opts]))
(defn stream-in
[db [ks cf row :as args] & [opts]]
(-stream-in db args opts))
| null | https://raw.githubusercontent.com/MyPost/cassius/7b5f550fa8e8f825d4ecd7ba6a0d34c5ff606a7c/src/cassius/protocols.clj | clojure | (ns cassius.protocols)
(def ^:dynamic *default-key-encoding* :utf-8)
(def ^:dynamic *default-value-encoding* :default)
(defprotocol Mappable
(to-map [m] "Converts object into a hashmap"))
(defmulti from-map
"Takes a map and converts it into type t"
(fn [m t] t))
(defprotocol ByteBufferable
(to-bbuff [v] "Converts object into a java.nio.ByteBuffer object"))
(defn to-bytes [v]
(.array (to-bbuff v)))
(defmulti from-bytes
"Takes a ByteArray and converts it into type t"
(fn [bs t] t))
(defn from-bbuff [bb type]
(from-bytes (.array bb) type))
(defprotocol IConnection
(-connect [_])
(-disconnect [_]))
(defmulti create (fn [m] (:type m)))
(defmethod create :default [m]
(create (assoc m :type :pool)))
(defn connect
([conn] (-connect conn))
([host port & [opts]]
(let [conn (-> opts
(assoc :host host :port port)
(create))]
(-connect conn)
conn)))
(defn disconnect [conn]
(-disconnect conn)
conn)
(defprotocol IMap
(-put-in [db arr v])
(-peek-in [db arr])
(-keys-in [db arr])
(-drop-in [db arr])
(-set-in [db arr v])
(-select-in [db arr])
(-mutate-in [db ks add-map del-vec]))
(defn put-in
([db v] (put-in db [] v))
([db arr v]
(-put-in db arr v)
db))
(defn peek-in
([db] (peek-in db []))
([db arr]
(-peek-in db arr)))
(defn keys-in
([db] (keys-in db []))
([db arr]
(-keys-in db arr)))
(defn drop-in
([db] (drop-in db []))
([db arr]
(-drop-in db arr)
db))
(defn set-in
([db v] (set-in db [] v))
([db arr v]
(-set-in db arr v)
db))
(defn select-in
([db] (select-in db []))
([db arr]
(-select-in db arr)))
(defn mutate-in
[db ks add-map del-vec]
(-mutate-in db ks add-map del-vec)
db)
(defprotocol IDatabase
(-init-schema [db schema])
(-schema [db type]))
(defn init-schema
([db] (if-let [sch (:schema db)]
(init-schema db sch)
db))
([db schema]
(-init-schema db schema)
db))
(defn schema [db type]
(-schema db type))
(defprotocol IStream
(-stream-in [conn args opts]))
(defn stream-in
[db [ks cf row :as args] & [opts]]
(-stream-in db args opts))
| |
bd66d084bf4a5a6ec34d44c400a4aa82a0e6bf43badf4152cc09c53e9df1772a | yakaz/yamerl | ex_6.11_multiline_comments.erl | -module('ex_6.11_multiline_comments').
-include_lib("eunit/include/eunit.hrl").
-define(FILENAME, "test/parsing/" ?MODULE_STRING ".yaml").
single_test_() ->
?_assertMatch(
{yamerl_parser,
{file,?FILENAME},
[],
<<>>,
43,
true,
[],
0,
44,
5,
1,
false,
3,
8,
utf8,
false,
undefined,
_,
_,
[],
{bcoll,root,0,-1,1,1,-1,1,1},
false,
false,
false,
[{impl_key,false,false,undefined,undefined,1,1}],
false,
false,
_,
[],
0,
11,
10,
undefined,
undefined,
_,
false,
[],
[
{yamerl_stream_end,3,8},
{yamerl_doc_end,3,8},
{yamerl_collection_end,3,8,block,mapping},
{yamerl_scalar,3,3,
{yamerl_tag,3,3,{non_specific,"?"}},
flow,plain,"value"},
{yamerl_mapping_value,1,4},
{yamerl_scalar,1,1,
{yamerl_tag,1,1,{non_specific,"?"}},
flow,plain,"key"},
{yamerl_mapping_key,1,1},
{yamerl_collection_start,1,1,
{yamerl_tag,1,1,{non_specific,"?"}},
block,mapping},
{yamerl_doc_start,1,1,{1,2},_},
{yamerl_stream_start,1,1,utf8}
]
},
yamerl_parser:file(?FILENAME)
).
| null | https://raw.githubusercontent.com/yakaz/yamerl/0032607a7b27fa2b548fc9a02d7ae6b53469c0c5/test/parsing/ex_6.11_multiline_comments.erl | erlang | -module('ex_6.11_multiline_comments').
-include_lib("eunit/include/eunit.hrl").
-define(FILENAME, "test/parsing/" ?MODULE_STRING ".yaml").
single_test_() ->
?_assertMatch(
{yamerl_parser,
{file,?FILENAME},
[],
<<>>,
43,
true,
[],
0,
44,
5,
1,
false,
3,
8,
utf8,
false,
undefined,
_,
_,
[],
{bcoll,root,0,-1,1,1,-1,1,1},
false,
false,
false,
[{impl_key,false,false,undefined,undefined,1,1}],
false,
false,
_,
[],
0,
11,
10,
undefined,
undefined,
_,
false,
[],
[
{yamerl_stream_end,3,8},
{yamerl_doc_end,3,8},
{yamerl_collection_end,3,8,block,mapping},
{yamerl_scalar,3,3,
{yamerl_tag,3,3,{non_specific,"?"}},
flow,plain,"value"},
{yamerl_mapping_value,1,4},
{yamerl_scalar,1,1,
{yamerl_tag,1,1,{non_specific,"?"}},
flow,plain,"key"},
{yamerl_mapping_key,1,1},
{yamerl_collection_start,1,1,
{yamerl_tag,1,1,{non_specific,"?"}},
block,mapping},
{yamerl_doc_start,1,1,{1,2},_},
{yamerl_stream_start,1,1,utf8}
]
},
yamerl_parser:file(?FILENAME)
).
| |
eabc07d583302129b7d039123672cb2bfb4b57a54f518642188194962acd554c | YoshikuniJujo/funpaala | convert.hs | halve :: Double -> Double
halve = (/ 2)
seven :: Integer
seven = 7
convert :: (Double -> Double) -> Integer -> Double
convert f n = f $ fromIntegral n
| null | https://raw.githubusercontent.com/YoshikuniJujo/funpaala/5366130826da0e6b1180992dfff94c4a634cda99/samples/09_tuple/convert.hs | haskell | halve :: Double -> Double
halve = (/ 2)
seven :: Integer
seven = 7
convert :: (Double -> Double) -> Integer -> Double
convert f n = f $ fromIntegral n
| |
03d82759562eecf361603ea648f301cdb75fc39ecb9630d60863f147df278ab8 | ekmett/concurrent | Unsafe.hs | # LANGUAGE PolyKinds #
# LANGUAGE DataKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TupleSections #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RoleAnnotations #
module Concurrent.Par.Unsafe where
import Concurrent.Par.Types
import Control.Concurrent
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader as Reader
import Control.Monad.Trans.State.Lazy as Lazy
import Control.Monad.Trans.State.Strict as Strict
import GHC.Prim (RealWorld)
import System.IO.Unsafe
type role Par nominal nominal nominal representational
newtype Par (d :: Determinism) (i :: Idempotence) (s :: *) a = Par { unPar :: IO a }
deriving (Functor, Applicative, Monad, MonadThrow, MonadCatch, MonadMask)
instance (d ~ 'NonDeterministic, i ~ 'NonIdempotent, s ~ RealWorld) => MonadIO (Par d i s) where
liftIO = Par
-- idempotent computations
class Monad m => MonadPar (d :: Determinism) (i :: Idempotence) (s :: *) m | m -> d i s where
unsafeParIO :: IO a -> m a
fork :: m a -> m ThreadId
instance MonadPar d i s m => MonadPar d i s (ExceptT e m) where
unsafeParIO m = ExceptT $ Right <$> unsafeParIO m
fork (ExceptT m) = ExceptT $ Right <$> fork m
instance MonadPar d i s m => MonadPar d i s (MaybeT m) where
unsafeParIO m = MaybeT $ Just <$> unsafeParIO m
fork (MaybeT m) = MaybeT $ Just <$> fork m
instance MonadPar d i s m => MonadPar d i s (IdentityT m) where
unsafeParIO m = IdentityT $ unsafeParIO m
fork (IdentityT m) = IdentityT $ fork m
instance MonadPar d i s m => MonadPar d i s (ReaderT e m) where
unsafeParIO m = ReaderT $ \_ -> unsafeParIO m
fork (ReaderT f) = ReaderT $ \s -> fork (f s)
instance MonadPar d i s m => MonadPar d i s (Strict.StateT e m) where
unsafeParIO m = Strict.StateT $ \s -> (, s) <$> unsafeParIO m
fork (Strict.StateT f) = Strict.StateT $ \s -> (, s) <$> fork (f s)
instance MonadPar d i s m => MonadPar d i s (Lazy.StateT e m) where
unsafeParIO m = Lazy.StateT $ \s -> (, s) <$> unsafeParIO m
fork (Lazy.StateT f) = Lazy.StateT $ \s -> (, s) <$> fork (f s)
instance MonadPar 'NonDeterministic 'NonIdempotent RealWorld IO where
unsafeParIO = id
fork m = forkIO (() <$ m)
instance MonadPar d i s (Par d i s) where
unsafeParIO = Par
fork (Par m) = Par (forkIO (() <$ m))
unsafeInterleavePar :: Par d i s a -> Par d i s a
unsafeInterleavePar (Par m) = Par (unsafeInterleaveIO m)
retry :: IO a -> IO a
retry act = act `catch` \(SomeException e) -> do
me <- myThreadId
throwTo me e
mask_ $ retry act
restartingUnsafePerformIO :: IO a -> a
restartingUnsafePerformIO m = unsafePerformIO (retry m)
| null | https://raw.githubusercontent.com/ekmett/concurrent/e22acb891890f412a7f16352836fdc4fb8de8936/src/Concurrent/Par/Unsafe.hs | haskell | # LANGUAGE RankNTypes #
idempotent computations | # LANGUAGE PolyKinds #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE TupleSections #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RoleAnnotations #
module Concurrent.Par.Unsafe where
import Concurrent.Par.Types
import Control.Concurrent
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader as Reader
import Control.Monad.Trans.State.Lazy as Lazy
import Control.Monad.Trans.State.Strict as Strict
import GHC.Prim (RealWorld)
import System.IO.Unsafe
type role Par nominal nominal nominal representational
newtype Par (d :: Determinism) (i :: Idempotence) (s :: *) a = Par { unPar :: IO a }
deriving (Functor, Applicative, Monad, MonadThrow, MonadCatch, MonadMask)
instance (d ~ 'NonDeterministic, i ~ 'NonIdempotent, s ~ RealWorld) => MonadIO (Par d i s) where
liftIO = Par
class Monad m => MonadPar (d :: Determinism) (i :: Idempotence) (s :: *) m | m -> d i s where
unsafeParIO :: IO a -> m a
fork :: m a -> m ThreadId
instance MonadPar d i s m => MonadPar d i s (ExceptT e m) where
unsafeParIO m = ExceptT $ Right <$> unsafeParIO m
fork (ExceptT m) = ExceptT $ Right <$> fork m
instance MonadPar d i s m => MonadPar d i s (MaybeT m) where
unsafeParIO m = MaybeT $ Just <$> unsafeParIO m
fork (MaybeT m) = MaybeT $ Just <$> fork m
instance MonadPar d i s m => MonadPar d i s (IdentityT m) where
unsafeParIO m = IdentityT $ unsafeParIO m
fork (IdentityT m) = IdentityT $ fork m
instance MonadPar d i s m => MonadPar d i s (ReaderT e m) where
unsafeParIO m = ReaderT $ \_ -> unsafeParIO m
fork (ReaderT f) = ReaderT $ \s -> fork (f s)
instance MonadPar d i s m => MonadPar d i s (Strict.StateT e m) where
unsafeParIO m = Strict.StateT $ \s -> (, s) <$> unsafeParIO m
fork (Strict.StateT f) = Strict.StateT $ \s -> (, s) <$> fork (f s)
instance MonadPar d i s m => MonadPar d i s (Lazy.StateT e m) where
unsafeParIO m = Lazy.StateT $ \s -> (, s) <$> unsafeParIO m
fork (Lazy.StateT f) = Lazy.StateT $ \s -> (, s) <$> fork (f s)
instance MonadPar 'NonDeterministic 'NonIdempotent RealWorld IO where
unsafeParIO = id
fork m = forkIO (() <$ m)
instance MonadPar d i s (Par d i s) where
unsafeParIO = Par
fork (Par m) = Par (forkIO (() <$ m))
unsafeInterleavePar :: Par d i s a -> Par d i s a
unsafeInterleavePar (Par m) = Par (unsafeInterleaveIO m)
retry :: IO a -> IO a
retry act = act `catch` \(SomeException e) -> do
me <- myThreadId
throwTo me e
mask_ $ retry act
restartingUnsafePerformIO :: IO a -> a
restartingUnsafePerformIO m = unsafePerformIO (retry m)
|
5bacc69c1975cd381020acbfbcc1f3db125b69369d8629ff8ba10031764a3335 | alexkazik/qrcode | Intermediate.hs | # LANGUAGE NoImplicitPrelude #
module Codec.QRCode.Intermediate
(
-- * Generators
-- | The results of the different generators can be appended using `<>`.
mixed
, automatic
, text
, binary
, kanji
, alphanumeric
, numeric
, eci
-- * Intermediate
, intermediate
-- * Encoder
, encode
-- * Re-Exports
, module Codec.QRCode.Data.ErrorLevel
, module Codec.QRCode.Data.Mask
, module Codec.QRCode.Data.QRImage
, module Codec.QRCode.Data.QRCodeOptions
, module Codec.QRCode.Data.QRIntermediate
, module Codec.QRCode.Data.QRSegment
, module Codec.QRCode.Data.Result
, module Codec.QRCode.Data.TextEncoding
, module Codec.QRCode.Data.ToInput
) where
import Codec.QRCode.Code.Intermediate
import Codec.QRCode.Data.ErrorLevel
import Codec.QRCode.Data.Mask
import Codec.QRCode.Data.QRCodeOptions
import Codec.QRCode.Data.QRImage
import Codec.QRCode.Data.QRIntermediate
import Codec.QRCode.Data.QRSegment
import Codec.QRCode.Data.Result
import Codec.QRCode.Data.TextEncoding
import Codec.QRCode.Data.ToInput
import Codec.QRCode.Mode.Alphanumeric
import Codec.QRCode.Mode.Automatic
import Codec.QRCode.Mode.Byte
import Codec.QRCode.Mode.ECI
import Codec.QRCode.Mode.Kanji
import Codec.QRCode.Mode.Mixed
import Codec.QRCode.Mode.Numeric
-- | Convert segments into an intermediate state.
This is the first point where it can be guaranteed that there will
-- be an result. The Version and ErrorLevel is already determined at
-- this point.
intermediate :: QRCodeOptions -> QRSegment -> Result QRIntermediate
# INLINE intermediate #
intermediate = toIntermediate
-- | Convert the intermediate state into an image.
encode :: QRIntermediate -> QRImage
# INLINE encode #
encode = fromIntermediate
| null | https://raw.githubusercontent.com/alexkazik/qrcode/7ee12de893c856a968dc1397602a7f81f8ea2c68/qrcode-core/src/Codec/QRCode/Intermediate.hs | haskell | * Generators
| The results of the different generators can be appended using `<>`.
* Intermediate
* Encoder
* Re-Exports
| Convert segments into an intermediate state.
be an result. The Version and ErrorLevel is already determined at
this point.
| Convert the intermediate state into an image. | # LANGUAGE NoImplicitPrelude #
module Codec.QRCode.Intermediate
(
mixed
, automatic
, text
, binary
, kanji
, alphanumeric
, numeric
, eci
, intermediate
, encode
, module Codec.QRCode.Data.ErrorLevel
, module Codec.QRCode.Data.Mask
, module Codec.QRCode.Data.QRImage
, module Codec.QRCode.Data.QRCodeOptions
, module Codec.QRCode.Data.QRIntermediate
, module Codec.QRCode.Data.QRSegment
, module Codec.QRCode.Data.Result
, module Codec.QRCode.Data.TextEncoding
, module Codec.QRCode.Data.ToInput
) where
import Codec.QRCode.Code.Intermediate
import Codec.QRCode.Data.ErrorLevel
import Codec.QRCode.Data.Mask
import Codec.QRCode.Data.QRCodeOptions
import Codec.QRCode.Data.QRImage
import Codec.QRCode.Data.QRIntermediate
import Codec.QRCode.Data.QRSegment
import Codec.QRCode.Data.Result
import Codec.QRCode.Data.TextEncoding
import Codec.QRCode.Data.ToInput
import Codec.QRCode.Mode.Alphanumeric
import Codec.QRCode.Mode.Automatic
import Codec.QRCode.Mode.Byte
import Codec.QRCode.Mode.ECI
import Codec.QRCode.Mode.Kanji
import Codec.QRCode.Mode.Mixed
import Codec.QRCode.Mode.Numeric
This is the first point where it can be guaranteed that there will
intermediate :: QRCodeOptions -> QRSegment -> Result QRIntermediate
# INLINE intermediate #
intermediate = toIntermediate
encode :: QRIntermediate -> QRImage
# INLINE encode #
encode = fromIntermediate
|
51caf5171ab13ed110ec1d63257273a5a5caf0b816b01acc39187cdf7cb060cb | Bluehouse-Technology/grpc | grpc_app.erl | %%%-------------------------------------------------------------------
Licensed to the Apache Software Foundation ( ASF ) under one
%%% or more contributor license agreements. See the NOTICE file
%%% distributed with this work for additional information
%%% regarding copyright ownership. The ASF licenses this file
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(grpc_app).
-behaviour(application).
-export([start/2]).
-export([stop/1]).
start(_Type, _Args) ->
grpc_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/Bluehouse-Technology/grpc/cdb7ab70c57e248d474369d6b3c5de77151f52f7/src/grpc_app.erl | erlang | -------------------------------------------------------------------
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
"License"); you may not use this file except in compliance
-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.
| Licensed to the Apache Software Foundation ( ASF ) under one
to you under the Apache License , Version 2.0 ( the
with the License . You may obtain a copy of the License at
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(grpc_app).
-behaviour(application).
-export([start/2]).
-export([stop/1]).
start(_Type, _Args) ->
grpc_sup:start_link().
stop(_State) ->
ok.
|
d903b78c54113ab3406e63b6913418207a1b889e77531cea4dd122d8d40bff44 | techascent/tech.ml.dataset | modelling_test.clj | (ns tech.v3.dataset.modelling-test
(:require [tech.v3.dataset.modelling :as modelling]
[tech.v3.dataset :as ds]
[tech.v3.dataset.categorical :as ds-cat]
[tech.v3.dataset.test-utils :as test-utils]
[tech.v3.datatype :as dtype]
[clojure.test :refer [deftest is]]))
(deftest k-fold-sanity
(let [dataset-seq (modelling/k-fold-datasets (test-utils/mapseq-fruit-dataset) 5 {})]
(is (= 5 (count dataset-seq)))
(is (= [[7 47] [7 47] [7 47] [7 47] [7 48]]
(->> dataset-seq
(mapv (comp dtype/shape :train-ds)))))
(is (= [[7 12] [7 12] [7 12] [7 12] [7 11]]
(->> dataset-seq
(mapv (comp dtype/shape :test-ds)))))))
(deftest train-test-split-sanity
(let [dataset (modelling/train-test-split
(test-utils/mapseq-fruit-dataset) {})]
(is (= [7 41]
(dtype/shape (:train-ds dataset))))
(is (= [7 18]
(dtype/shape (:test-ds dataset))))))
(deftest prob-dist->label-col
(let [ds (ds/->dataset (tech.v3.dataset/->dataset
{:y-0 [0.0 0.5 0.3 0.1]
:y-1 [0.3 0.8 0.2 0.3]}))
prob-dist-ds (modelling/probability-distributions->label-column ds :y)
label-ds (ds-cat/reverse-map-categorical-xforms prob-dist-ds)]
(is (= [:y-1 :y-1 :y-0 :y-1]
(label-ds :y)))))
(deftest issue-267-prob-dist-fail-on-nan-missing
(is (thrown? Throwable
(-> (tech.v3.dataset/->dataset {:y-0 [Double/NaN] :y-1 [0.3]})
(modelling/probability-distributions->label-column :y))))
(is (thrown? Throwable
(-> (tech.v3.dataset/->dataset {:y-0 [nil] :y-1 [0.3]} )
(tech.v3.dataset.modelling/probability-distributions->label-column :y)))))
| null | https://raw.githubusercontent.com/techascent/tech.ml.dataset/2e20935e38d3eaf0c3554b274cef8f700b08558e/test/tech/v3/dataset/modelling_test.clj | clojure | (ns tech.v3.dataset.modelling-test
(:require [tech.v3.dataset.modelling :as modelling]
[tech.v3.dataset :as ds]
[tech.v3.dataset.categorical :as ds-cat]
[tech.v3.dataset.test-utils :as test-utils]
[tech.v3.datatype :as dtype]
[clojure.test :refer [deftest is]]))
(deftest k-fold-sanity
(let [dataset-seq (modelling/k-fold-datasets (test-utils/mapseq-fruit-dataset) 5 {})]
(is (= 5 (count dataset-seq)))
(is (= [[7 47] [7 47] [7 47] [7 47] [7 48]]
(->> dataset-seq
(mapv (comp dtype/shape :train-ds)))))
(is (= [[7 12] [7 12] [7 12] [7 12] [7 11]]
(->> dataset-seq
(mapv (comp dtype/shape :test-ds)))))))
(deftest train-test-split-sanity
(let [dataset (modelling/train-test-split
(test-utils/mapseq-fruit-dataset) {})]
(is (= [7 41]
(dtype/shape (:train-ds dataset))))
(is (= [7 18]
(dtype/shape (:test-ds dataset))))))
(deftest prob-dist->label-col
(let [ds (ds/->dataset (tech.v3.dataset/->dataset
{:y-0 [0.0 0.5 0.3 0.1]
:y-1 [0.3 0.8 0.2 0.3]}))
prob-dist-ds (modelling/probability-distributions->label-column ds :y)
label-ds (ds-cat/reverse-map-categorical-xforms prob-dist-ds)]
(is (= [:y-1 :y-1 :y-0 :y-1]
(label-ds :y)))))
(deftest issue-267-prob-dist-fail-on-nan-missing
(is (thrown? Throwable
(-> (tech.v3.dataset/->dataset {:y-0 [Double/NaN] :y-1 [0.3]})
(modelling/probability-distributions->label-column :y))))
(is (thrown? Throwable
(-> (tech.v3.dataset/->dataset {:y-0 [nil] :y-1 [0.3]} )
(tech.v3.dataset.modelling/probability-distributions->label-column :y)))))
| |
ae23d45b22d0703744d8b1af50cfbf5cbc15e3231edc367550d8abb3f168e569 | solita/mnt-teet | comments_view.cljs | (ns teet.comments.comments-view
(:require [herb.core :refer [<class]]
[reagent.core :as r]
[tuck.core :as t]
[teet.app-state :as app-state]
[teet.authorization.authorization-check :as authorization-check :refer [when-authorized]]
[teet.comment.comment-model :as comment-model]
teet.comment.comment-spec
[teet.comments.comments-controller :as comments-controller]
[teet.comments.comments-styles :as comments-styles]
[teet.common.common-controller :as common-controller]
[teet.common.common-styles :as common-styles]
[teet.localization :refer [tr]]
[teet.project.project-navigator-view :as project-navigator-view]
teet.task.task-spec
[teet.ui.animate :as animate]
[teet.ui.buttons :as buttons]
[teet.ui.form :as form]
[teet.ui.format :as format]
[teet.ui.icons :as icons]
[teet.ui.project-context :as project-context]
[teet.ui.query :as query]
[teet.ui.select :as select]
[teet.ui.skeleton :as skeleton]
[teet.ui.mentions :refer [mentions-input]]
[teet.ui.material-ui :refer [IconButton]]
[teet.ui.typography :as typography]
[teet.ui.util :as util :refer [mapc]]
[teet.ui.file-upload :as file-upload]
[teet.user.user-info :as user-info]
[teet.user.user-model :as user-model]
[teet.util.collection :as cu]
[teet.file.file-controller :as file-controller]
[teet.log :as log]
[teet.theme.theme-colors :as theme-colors]
[clojure.string :as str]))
(defn- new-comment-footer [{:keys [validate disabled?]}]
[:div {:class (<class comments-styles/comment-buttons-style)}
[buttons/button-primary {:disabled disabled?
:type :submit
:on-click validate}
(tr [:comment :save])]])
(defn- comment-skeleton
[n]
[:span.lazy-comments-loading
(doall
(for [y (range n)]
^{:key y}
[skeleton/skeleton {:parent-style (skeleton/comment-skeleton-style)}]))])
(defn attachments [{:keys [files on-delete comment-id]}]
(when (seq files)
[:div {:class (<class comments-styles/attachment-list)}
(util/with-keys
(mapc (fn [{file-id :db/id name :file/name :as file}]
[:div {:class (<class comments-styles/attachment-list-item)}
[:a {:class (<class comments-styles/attachment-link)
:target :_blank
:href (common-controller/query-url :file/download-attachment
{:comment-id comment-id
:file-id file-id})}
name]
(when on-delete
[IconButton {:size :small
:on-click #(on-delete file)}
[icons/action-delete]])])
files))]))
(defn- edit-attached-images-field
"File field that only allows uploading images. Files are
directly uploaded and on-change called after success."
[{:keys [e! value on-change comment-id on-success-event project-id]}]
[:div
[attachments {:files value
:comment-id comment-id
:on-delete (fn [{file-id :db/id}]
(on-change
(into []
(cu/remove-by-id file-id)
value)))}]
[file-upload/FileUploadButton
{:id (str "images-field-" comment-id)
:drag-container-id "edit-comment-form"
:color :secondary
:button-attributes {:size :small}
:on-drop #(e! (file-controller/map->UploadFiles
{:files %
:project-id project-id
:attachment? true
:on-success (fn [uploaded-files]
(on-success-event
{:comment/files (into (or value [])
uploaded-files)}))}))}
(str "+ " (tr [:comment :add-images]))]])
(defn form-field-spacer
[]
{:margin-bottom "1rem"})
;; TODO: Both this and the create comment form should be replaced with
;; form2 to make the add image button look decent.
(defn- edit-comment-form* [e! commented-entity close-event comment-form {project-id :db/id}]
(let [comment-data @comment-form
update-event (form/update-atom-event comment-form merge)]
[form/form2 {:e! e!
:id "edit-comment-form"
:value comment-data
:on-change-event update-event
:cancel-event close-event
:save-event #(comments-controller/->SaveEditCommentForm commented-entity @comment-form)
:spec :comment/edit-comment-form}
[:div {:class (<class common-styles/gray-container-style)}
[:div {:class (<class form-field-spacer)}
[form/field :comment/comment
[mentions-input {:e! e!}]]
[form/field :comment/files
[edit-attached-images-field {:e! e!
:comment-id (:db/id comment-data)
:project-id project-id
:on-success-event update-event}]]]
(log/debug "edit-comment-form: can set visibility? ->"
(authorization-check/authorized? @app-state/user
:projects/set-comment-visibility
{:entity comment-data
:project-id project-id})
project-id comment-data)
(when (authorization-check/authorized? @app-state/user
:projects/set-comment-visibility
{:entity comment-data
:project-id project-id})
[:div {:class (<class form-field-spacer)}
[form/field :comment/visibility
[select/select-enum {:e! e! :attribute :comment/visibility}]]])]
[form/footer2]]))
(defn- edit-comment-form [e! commented-entity close-event comment-form]
[project-context/consume
[edit-comment-form* e! commented-entity close-event comment-form]])
(defn- edit-comment-button [e! comment-entity commented-entity]
[form/form-modal-button
{:modal-title (tr [:project :edit-comment])
:button-component
[buttons/button-text {:size :small
:color :primary
:start-icon (r/as-element [icons/image-edit])}
(tr [:buttons :edit])]
:form-component [edit-comment-form e! commented-entity]
:form-value (merge {:comment/files []}
comment-entity
{:comment/mentions (mapv
(fn [mention]
{:user mention})
(:comment/mentions comment-entity))}
{:comment/commented-entity commented-entity})}])
(def ^{:private true :const true} quotation-mark "\u00bb ")
(defn- extract-quote [text]
(let [lines (str/split-lines text)
quote-start-idx (cu/find-idx (fn [[line next-line]]
(and (str/ends-with? line ":")
(str/starts-with? next-line quotation-mark)))
(partition 2 1 lines))]
(if-not quote-start-idx
{:before text}
(let [quote-end-idx (+ quote-start-idx 1
(cu/find-idx #(not (str/starts-with? % quotation-mark))
(drop (inc quote-start-idx) lines)))
quote-lines (take (- quote-end-idx quote-start-idx)
(drop quote-start-idx lines))
before-text (when (pos? quote-start-idx)
(str/join "\n"
(take quote-start-idx lines)))
quote-from (first quote-lines)
quote-from (subs quote-from 0 (dec (count quote-from)))
quote-text (str/join "\n"
(map #(subs % 2)
(drop 1 quote-lines)))
after-text (str/join "\n"
(drop quote-end-idx lines))]
{:before before-text
:quote {:from quote-from :text quote-text}
:after after-text}))))
(defn- text-with-mentions [text]
[:<>
(doall
(map-indexed
(fn [i part]
(if-let [[_ name :as m] (re-matches comment-model/user-mention-name-pattern part)]
^{:key (str i)}
[:b (str "@" name)]
^{:key (str i)}
[:span part]))
(str/split text comment-model/user-mention-pattern)))])
(defn- comment-text*
"Split comment text and highlight user mentions and put quotations in blocks."
([text] (comment-text* text 0))
([text quote-level]
(let [{:keys [before quote after]} (extract-quote text)]
[:<>
(when before
[typography/Text [text-with-mentions before]])
(when quote
[:div.comment-quote {:class (<class comments-styles/quote-block quote-level)}
[:div.comment-quote-from {:class (<class comments-styles/quote-from)}
(:from quote)]
[:div.comment-quote-text
[comment-text* (:text quote) (inc quote-level)]]])
(when (not-empty after)
[comment-text* after quote-level])])))
(defn- comment-text [comment]
[:div.comment {:class (<class comments-styles/comment-text)}
(comment-text* comment)])
(defn- comment-contents-and-status
[e!
{:meta/keys [modified-at]
:comment/keys [comment status mentions]
comment-id :db/id
:as comment-entity}
commented-entity]
[:div {:class (<class comments-styles/comment-contents
(comment-model/tracked? comment-entity)
(:db/ident status))}
(when (comment-model/tracked? comment-entity)
[:div {:class (<class comments-styles/comment-status (:db/ident status))}
(tr [:enum (:db/ident status)])
[when-authorized :comment/set-status
comment-entity
(case (:db/ident status)
:comment.status/unresolved
[buttons/button-text {:color :primary
:end-icon (r/as-element [icons/action-check-circle-outline])
:on-click #(e! (comments-controller/->SetCommentStatus comment-id
:comment.status/resolved
commented-entity))}
(tr [:comment :resolve])]
:comment.status/resolved
[buttons/button-text {:end-icon (r/as-element [icons/content-block])
:on-click #(e! (comments-controller/->SetCommentStatus comment-id
:comment.status/unresolved
commented-entity))}
(tr [:comment :unresolve])])]])
[:div
[comment-text comment]
(when modified-at
[:span {:class (<class comments-styles/data)}
(tr [:comment :edited]
{:date (format/date modified-at)})])]])
(defn- comment-entry [{id :db/id
:comment/keys [author comment timestamp files visibility]
:as comment-entity}
{:keys [e!
commented-entity
quote-comment!
show-comment-form?
focused?
after-comment-deleted-event]}]
[:div (merge {:id (comments-controller/comment-dom-id id)
:class (<class comments-styles/comment-entry focused?)}
(when focused?
{:ref (fn [el]
(when el
(animate/focus! el)))}))
[:div {:class [(<class common-styles/space-between-center) (<class common-styles/margin-bottom 0)]}
[:div
[typography/SectionHeading
{:style {:display :inline-block}}
[user-info/user-name author]]
[:span {:class (<class comments-styles/data)}
(format/date timestamp)]
(when show-comment-form?
[buttons/button-text {:size :small
:color :primary
:start-icon (r/as-element [icons/editor-format-quote])
:on-click #(quote-comment! (user-model/user-name author)
comment)}
(tr [:comment :quote])])]
[:span {:class (<class comments-styles/data)}
(tr [:enum (:db/ident visibility)])]]
[comment-contents-and-status e! comment-entity commented-entity]
[:div
[when-authorized :comment/update
comment-entity
[edit-comment-button e! comment-entity commented-entity]]
[when-authorized :comment/delete-comment
comment-entity
;; (log/debug "showing delete-button-with-confirm, id" (str "delete-button-" id))
[buttons/delete-button-with-confirm {:small? true
:id (str "delete-button-" id)
:icon-position :start
:action (e! comments-controller/->DeleteComment id commented-entity after-comment-deleted-event)}
(tr [:buttons :delete])]]]
[attachments {:files files :comment-id id}]])
(defn unresolved-comments-info [e! commented-entity unresolved-comments]
[:div {:class (<class comments-styles/unresolved-comments)}
(tr [:comment :unresolved-count] {:unresolved-count (count unresolved-comments)})
[buttons/link-button {:on-click #(e! (comments-controller/->FocusOnComment (-> unresolved-comments first :db/id)))}
(tr [:comment :open-latest-unresolved])]
(when (authorization-check/is-tram-personnel? @app-state/user)
[buttons/button-text {:color :primary
:end-icon (r/as-element [icons/action-check-circle-outline])
:on-click #(e! (comments-controller/->ResolveCommentsOfEntity
(:eid commented-entity)
(:for commented-entity)))}
(tr [:comment :resolve-all])])])
(defn comment-list
[{:keys [e! commented-entity after-comment-list-rendered-event]} comments]
(when-let [eid (and (seq comments)
(:eid commented-entity))]
(e! (comments-controller/->CommentsSeen eid (:for commented-entity)))
(when after-comment-list-rendered-event
(e! (after-comment-list-rendered-event))))
(fn [{:keys [e! quote-comment! commented-entity show-comment-form?
focused-comment after-comment-deleted-event]}
comments]
[:div
(if (empty? comments)
[:div {:class (<class common-styles/margin-bottom 1.5)}
[typography/GrayText (tr [:comment :no-comments])]]
(let [unresolved-comments (filterv comment-model/unresolved? comments)]
[:<>
(when (seq unresolved-comments)
[unresolved-comments-info e! commented-entity unresolved-comments])
(doall
(for [{id :db/id :as comment-entity} comments
:let [focused? (= (str id) focused-comment)]]
(if (nil? comment-entity)
;; New comment was just added but hasn't been refetched yet, show skeleton
^{:key "loading-comment"}
[comment-skeleton 1]
^{:key (str id)}
[comment-entry comment-entity {:e! e!
:show-comment-form? show-comment-form?
:commented-entity commented-entity
:quote-comment! quote-comment!
:focused? focused?
:after-comment-deleted-event after-comment-deleted-event}])))]))]))
(defn strip-mentions
"@[Carla Consultant](123456) -> @Carla Consultant"
[string]
(str/replace string
comment-model/user-mention-pattern
(fn [[_ mention]]
(str "@" (second (re-matches comment-model/user-mention-name-pattern mention))))))
(defn- quote-comment-fn
"An ad hoc event that merges the quote at the end of current new
comment text."
[internal-state-atom]
(fn [name quoted-text]
(reify t/Event
(process-event [_ app]
(swap! internal-state-atom update :comment/comment
(fn [old-value]
(let [old-value (if (not-empty old-value)
(str old-value "\n")
"")]
(str
old-value
name ":\n"
(str/join "\n" (map #(str quotation-mark
(strip-mentions %))
(str/split quoted-text "\n")))
"\n"))))
(animate/scroll-into-view-by-id! "new-comment-input" {:behavior :smooth})
(js/setTimeout #(animate/focus-by-id! "new-comment-input")
500)
app))))
(defn- attached-images-field
"File field that only allows uploading images. Files are
directly uploaded and on-change called after success."
[{:keys [e! value on-success-event]}]
[project-context/consume
(fn [{project-id :db/id}]
[:div
[attachments {:files value
:comment-id nil
:on-delete (fn [{id :db/id}]
(e! (file-controller/->DeleteAttachment
(constantly
(on-success-event
{:comment/files
(into []
(cu/remove-by-id id)
value)}))
id)))}]
[file-upload/FileUploadButton
{:id "images-field"
:drag-container-id "new-comment-form"
:drop-message (tr [:drag :drop-to-comment])
:color :secondary
:button-attributes {:size :small}
:on-drop #(e! (file-controller/map->UploadFiles
{:files %
:project-id project-id
:attachment? true
:on-success (fn [files]
(log/info "FILES UPLOADED: " files)
(on-success-event
{:comment/files (into (or value [])
files)}))}))}
(str "+ " (tr [:comment :add-images]))]])])
(defn- comment-form-defaults [entity-type can-set-visibility?]
(merge
(case entity-type
:file {:comment/track? true}
{})
{:comment/comment ""
:comment/visibility (if can-set-visibility?
:comment.visibility/internal
:comment.visibility/all)}))
(defn visibility-selection-style
[]
{:background-color :inherit
:color theme-colors/primary})
(defn lazy-comments*
[{:keys [e! app
entity-type
entity-id
show-comment-form?
after-comment-added-event
after-comment-deleted-event
after-comment-list-rendered-event]
:or {show-comment-form? true}}
proj-map]
(r/with-let [can-set-visibility? (or (authorization-check/authorized? @app-state/user
:projects/set-comment-visibility
{:entity {:meta/creator {:db/id (:db/id @app-state/user)}}
:project-id (:db/id proj-map)
:debug? true})
(authorization-check/is-tram-personnel? @app-state/user))
;; _ (log/debug "keys in page-state map:" (keys (common-controller/page-state @app-state/app)))
initial-comment-form (comment-form-defaults entity-type
can-set-visibility?)
[comment-form ->UpdateCommentForm]
(common-controller/internal-state initial-comment-form
{:merge? true})]
(let [comments (get-in app [:comments-for-entity entity-id])]
[:div
[query/query {:e! e!
:query :comment/fetch-comments
:args {:eid entity-id
:for entity-type}
:skeleton [comment-skeleton 2]
:state-path [:comments-for-entity entity-id]
:state comments
:simple-view [comment-list {:e! e!
:show-comment-form? show-comment-form?
:after-comment-list-rendered-event after-comment-list-rendered-event
:after-comment-deleted-event after-comment-deleted-event
:quote-comment! (fn [name quoted-text]
(e! ((quote-comment-fn comment-form)
name quoted-text)))
:commented-entity {:eid entity-id
:for entity-type}
:focused-comment (get-in app [:query :focus-on])}]
:refresh (count comments)}]
(when (and show-comment-form?
;; TODO: This circumvents the fact that there can be
only one file upload element in the dom at once .
(not (-> app :stepper :dialog)))
[form/form2 {:e! e!
:id "new-comment-form"
:value @comment-form
:on-change-event ->UpdateCommentForm
:save-event #(let [{:comment/keys [comment files visibility track? mentions]} @comment-form]
(reset! comment-form initial-comment-form)
(comments-controller/->CommentOnEntity
entity-type entity-id comment files visibility track? mentions
after-comment-added-event))
:footer new-comment-footer
:spec :task/new-comment-form}
[:div {:class (<class common-styles/gray-container-style)}
[:div {:class (<class common-styles/heading-and-action-style)}
[typography/Heading2 (tr [:document :new-comment])]
(when can-set-visibility?
[form/field :comment/visibility
[select/select-enum {:e! e! :attribute :comment/visibility :tiny-select? true
:show-empty-selection? false
:show-label? false :class (<class visibility-selection-style)}]])]
[:div {:class (<class form-field-spacer)}
[form/field :comment/comment
[mentions-input {:id "new-comment-input"
:e! e!}]
#_[TextField {:id "new-comment-input"
:rows 4
:multiline true
:full-width true
:placeholder (tr [:document :new-comment])}]]
[form/field :comment/files
[attached-images-field {:e! e!
:on-success-event ->UpdateCommentForm}]]]
;; TODO: when-authorized doesn't play well with form
(when (authorization-check/is-tram-personnel? @app-state/user)
[:div {:style {:text-align :right}}
[form/field :comment/track?
[select/checkbox {:label-placement :start}]]])
[new-comment-footer]]])])))
(defn lazy-comments
[opts]
(project-context/consume
[lazy-comments* opts]))
| null | https://raw.githubusercontent.com/solita/mnt-teet/0f1868f8be94e68c5e8daf7e1988541f23ed0631/app/frontend/src/cljs/teet/comments/comments_view.cljs | clojure | TODO: Both this and the create comment form should be replaced with
form2 to make the add image button look decent.
(log/debug "showing delete-button-with-confirm, id" (str "delete-button-" id))
New comment was just added but hasn't been refetched yet, show skeleton
_ (log/debug "keys in page-state map:" (keys (common-controller/page-state @app-state/app)))
TODO: This circumvents the fact that there can be
TODO: when-authorized doesn't play well with form | (ns teet.comments.comments-view
(:require [herb.core :refer [<class]]
[reagent.core :as r]
[tuck.core :as t]
[teet.app-state :as app-state]
[teet.authorization.authorization-check :as authorization-check :refer [when-authorized]]
[teet.comment.comment-model :as comment-model]
teet.comment.comment-spec
[teet.comments.comments-controller :as comments-controller]
[teet.comments.comments-styles :as comments-styles]
[teet.common.common-controller :as common-controller]
[teet.common.common-styles :as common-styles]
[teet.localization :refer [tr]]
[teet.project.project-navigator-view :as project-navigator-view]
teet.task.task-spec
[teet.ui.animate :as animate]
[teet.ui.buttons :as buttons]
[teet.ui.form :as form]
[teet.ui.format :as format]
[teet.ui.icons :as icons]
[teet.ui.project-context :as project-context]
[teet.ui.query :as query]
[teet.ui.select :as select]
[teet.ui.skeleton :as skeleton]
[teet.ui.mentions :refer [mentions-input]]
[teet.ui.material-ui :refer [IconButton]]
[teet.ui.typography :as typography]
[teet.ui.util :as util :refer [mapc]]
[teet.ui.file-upload :as file-upload]
[teet.user.user-info :as user-info]
[teet.user.user-model :as user-model]
[teet.util.collection :as cu]
[teet.file.file-controller :as file-controller]
[teet.log :as log]
[teet.theme.theme-colors :as theme-colors]
[clojure.string :as str]))
(defn- new-comment-footer [{:keys [validate disabled?]}]
[:div {:class (<class comments-styles/comment-buttons-style)}
[buttons/button-primary {:disabled disabled?
:type :submit
:on-click validate}
(tr [:comment :save])]])
(defn- comment-skeleton
[n]
[:span.lazy-comments-loading
(doall
(for [y (range n)]
^{:key y}
[skeleton/skeleton {:parent-style (skeleton/comment-skeleton-style)}]))])
(defn attachments [{:keys [files on-delete comment-id]}]
(when (seq files)
[:div {:class (<class comments-styles/attachment-list)}
(util/with-keys
(mapc (fn [{file-id :db/id name :file/name :as file}]
[:div {:class (<class comments-styles/attachment-list-item)}
[:a {:class (<class comments-styles/attachment-link)
:target :_blank
:href (common-controller/query-url :file/download-attachment
{:comment-id comment-id
:file-id file-id})}
name]
(when on-delete
[IconButton {:size :small
:on-click #(on-delete file)}
[icons/action-delete]])])
files))]))
(defn- edit-attached-images-field
"File field that only allows uploading images. Files are
directly uploaded and on-change called after success."
[{:keys [e! value on-change comment-id on-success-event project-id]}]
[:div
[attachments {:files value
:comment-id comment-id
:on-delete (fn [{file-id :db/id}]
(on-change
(into []
(cu/remove-by-id file-id)
value)))}]
[file-upload/FileUploadButton
{:id (str "images-field-" comment-id)
:drag-container-id "edit-comment-form"
:color :secondary
:button-attributes {:size :small}
:on-drop #(e! (file-controller/map->UploadFiles
{:files %
:project-id project-id
:attachment? true
:on-success (fn [uploaded-files]
(on-success-event
{:comment/files (into (or value [])
uploaded-files)}))}))}
(str "+ " (tr [:comment :add-images]))]])
(defn form-field-spacer
[]
{:margin-bottom "1rem"})
(defn- edit-comment-form* [e! commented-entity close-event comment-form {project-id :db/id}]
(let [comment-data @comment-form
update-event (form/update-atom-event comment-form merge)]
[form/form2 {:e! e!
:id "edit-comment-form"
:value comment-data
:on-change-event update-event
:cancel-event close-event
:save-event #(comments-controller/->SaveEditCommentForm commented-entity @comment-form)
:spec :comment/edit-comment-form}
[:div {:class (<class common-styles/gray-container-style)}
[:div {:class (<class form-field-spacer)}
[form/field :comment/comment
[mentions-input {:e! e!}]]
[form/field :comment/files
[edit-attached-images-field {:e! e!
:comment-id (:db/id comment-data)
:project-id project-id
:on-success-event update-event}]]]
(log/debug "edit-comment-form: can set visibility? ->"
(authorization-check/authorized? @app-state/user
:projects/set-comment-visibility
{:entity comment-data
:project-id project-id})
project-id comment-data)
(when (authorization-check/authorized? @app-state/user
:projects/set-comment-visibility
{:entity comment-data
:project-id project-id})
[:div {:class (<class form-field-spacer)}
[form/field :comment/visibility
[select/select-enum {:e! e! :attribute :comment/visibility}]]])]
[form/footer2]]))
(defn- edit-comment-form [e! commented-entity close-event comment-form]
[project-context/consume
[edit-comment-form* e! commented-entity close-event comment-form]])
(defn- edit-comment-button [e! comment-entity commented-entity]
[form/form-modal-button
{:modal-title (tr [:project :edit-comment])
:button-component
[buttons/button-text {:size :small
:color :primary
:start-icon (r/as-element [icons/image-edit])}
(tr [:buttons :edit])]
:form-component [edit-comment-form e! commented-entity]
:form-value (merge {:comment/files []}
comment-entity
{:comment/mentions (mapv
(fn [mention]
{:user mention})
(:comment/mentions comment-entity))}
{:comment/commented-entity commented-entity})}])
(def ^{:private true :const true} quotation-mark "\u00bb ")
(defn- extract-quote [text]
(let [lines (str/split-lines text)
quote-start-idx (cu/find-idx (fn [[line next-line]]
(and (str/ends-with? line ":")
(str/starts-with? next-line quotation-mark)))
(partition 2 1 lines))]
(if-not quote-start-idx
{:before text}
(let [quote-end-idx (+ quote-start-idx 1
(cu/find-idx #(not (str/starts-with? % quotation-mark))
(drop (inc quote-start-idx) lines)))
quote-lines (take (- quote-end-idx quote-start-idx)
(drop quote-start-idx lines))
before-text (when (pos? quote-start-idx)
(str/join "\n"
(take quote-start-idx lines)))
quote-from (first quote-lines)
quote-from (subs quote-from 0 (dec (count quote-from)))
quote-text (str/join "\n"
(map #(subs % 2)
(drop 1 quote-lines)))
after-text (str/join "\n"
(drop quote-end-idx lines))]
{:before before-text
:quote {:from quote-from :text quote-text}
:after after-text}))))
(defn- text-with-mentions [text]
[:<>
(doall
(map-indexed
(fn [i part]
(if-let [[_ name :as m] (re-matches comment-model/user-mention-name-pattern part)]
^{:key (str i)}
[:b (str "@" name)]
^{:key (str i)}
[:span part]))
(str/split text comment-model/user-mention-pattern)))])
(defn- comment-text*
"Split comment text and highlight user mentions and put quotations in blocks."
([text] (comment-text* text 0))
([text quote-level]
(let [{:keys [before quote after]} (extract-quote text)]
[:<>
(when before
[typography/Text [text-with-mentions before]])
(when quote
[:div.comment-quote {:class (<class comments-styles/quote-block quote-level)}
[:div.comment-quote-from {:class (<class comments-styles/quote-from)}
(:from quote)]
[:div.comment-quote-text
[comment-text* (:text quote) (inc quote-level)]]])
(when (not-empty after)
[comment-text* after quote-level])])))
(defn- comment-text [comment]
[:div.comment {:class (<class comments-styles/comment-text)}
(comment-text* comment)])
(defn- comment-contents-and-status
[e!
{:meta/keys [modified-at]
:comment/keys [comment status mentions]
comment-id :db/id
:as comment-entity}
commented-entity]
[:div {:class (<class comments-styles/comment-contents
(comment-model/tracked? comment-entity)
(:db/ident status))}
(when (comment-model/tracked? comment-entity)
[:div {:class (<class comments-styles/comment-status (:db/ident status))}
(tr [:enum (:db/ident status)])
[when-authorized :comment/set-status
comment-entity
(case (:db/ident status)
:comment.status/unresolved
[buttons/button-text {:color :primary
:end-icon (r/as-element [icons/action-check-circle-outline])
:on-click #(e! (comments-controller/->SetCommentStatus comment-id
:comment.status/resolved
commented-entity))}
(tr [:comment :resolve])]
:comment.status/resolved
[buttons/button-text {:end-icon (r/as-element [icons/content-block])
:on-click #(e! (comments-controller/->SetCommentStatus comment-id
:comment.status/unresolved
commented-entity))}
(tr [:comment :unresolve])])]])
[:div
[comment-text comment]
(when modified-at
[:span {:class (<class comments-styles/data)}
(tr [:comment :edited]
{:date (format/date modified-at)})])]])
(defn- comment-entry [{id :db/id
:comment/keys [author comment timestamp files visibility]
:as comment-entity}
{:keys [e!
commented-entity
quote-comment!
show-comment-form?
focused?
after-comment-deleted-event]}]
[:div (merge {:id (comments-controller/comment-dom-id id)
:class (<class comments-styles/comment-entry focused?)}
(when focused?
{:ref (fn [el]
(when el
(animate/focus! el)))}))
[:div {:class [(<class common-styles/space-between-center) (<class common-styles/margin-bottom 0)]}
[:div
[typography/SectionHeading
{:style {:display :inline-block}}
[user-info/user-name author]]
[:span {:class (<class comments-styles/data)}
(format/date timestamp)]
(when show-comment-form?
[buttons/button-text {:size :small
:color :primary
:start-icon (r/as-element [icons/editor-format-quote])
:on-click #(quote-comment! (user-model/user-name author)
comment)}
(tr [:comment :quote])])]
[:span {:class (<class comments-styles/data)}
(tr [:enum (:db/ident visibility)])]]
[comment-contents-and-status e! comment-entity commented-entity]
[:div
[when-authorized :comment/update
comment-entity
[edit-comment-button e! comment-entity commented-entity]]
[when-authorized :comment/delete-comment
comment-entity
[buttons/delete-button-with-confirm {:small? true
:id (str "delete-button-" id)
:icon-position :start
:action (e! comments-controller/->DeleteComment id commented-entity after-comment-deleted-event)}
(tr [:buttons :delete])]]]
[attachments {:files files :comment-id id}]])
(defn unresolved-comments-info [e! commented-entity unresolved-comments]
[:div {:class (<class comments-styles/unresolved-comments)}
(tr [:comment :unresolved-count] {:unresolved-count (count unresolved-comments)})
[buttons/link-button {:on-click #(e! (comments-controller/->FocusOnComment (-> unresolved-comments first :db/id)))}
(tr [:comment :open-latest-unresolved])]
(when (authorization-check/is-tram-personnel? @app-state/user)
[buttons/button-text {:color :primary
:end-icon (r/as-element [icons/action-check-circle-outline])
:on-click #(e! (comments-controller/->ResolveCommentsOfEntity
(:eid commented-entity)
(:for commented-entity)))}
(tr [:comment :resolve-all])])])
(defn comment-list
[{:keys [e! commented-entity after-comment-list-rendered-event]} comments]
(when-let [eid (and (seq comments)
(:eid commented-entity))]
(e! (comments-controller/->CommentsSeen eid (:for commented-entity)))
(when after-comment-list-rendered-event
(e! (after-comment-list-rendered-event))))
(fn [{:keys [e! quote-comment! commented-entity show-comment-form?
focused-comment after-comment-deleted-event]}
comments]
[:div
(if (empty? comments)
[:div {:class (<class common-styles/margin-bottom 1.5)}
[typography/GrayText (tr [:comment :no-comments])]]
(let [unresolved-comments (filterv comment-model/unresolved? comments)]
[:<>
(when (seq unresolved-comments)
[unresolved-comments-info e! commented-entity unresolved-comments])
(doall
(for [{id :db/id :as comment-entity} comments
:let [focused? (= (str id) focused-comment)]]
(if (nil? comment-entity)
^{:key "loading-comment"}
[comment-skeleton 1]
^{:key (str id)}
[comment-entry comment-entity {:e! e!
:show-comment-form? show-comment-form?
:commented-entity commented-entity
:quote-comment! quote-comment!
:focused? focused?
:after-comment-deleted-event after-comment-deleted-event}])))]))]))
(defn strip-mentions
"@[Carla Consultant](123456) -> @Carla Consultant"
[string]
(str/replace string
comment-model/user-mention-pattern
(fn [[_ mention]]
(str "@" (second (re-matches comment-model/user-mention-name-pattern mention))))))
(defn- quote-comment-fn
"An ad hoc event that merges the quote at the end of current new
comment text."
[internal-state-atom]
(fn [name quoted-text]
(reify t/Event
(process-event [_ app]
(swap! internal-state-atom update :comment/comment
(fn [old-value]
(let [old-value (if (not-empty old-value)
(str old-value "\n")
"")]
(str
old-value
name ":\n"
(str/join "\n" (map #(str quotation-mark
(strip-mentions %))
(str/split quoted-text "\n")))
"\n"))))
(animate/scroll-into-view-by-id! "new-comment-input" {:behavior :smooth})
(js/setTimeout #(animate/focus-by-id! "new-comment-input")
500)
app))))
(defn- attached-images-field
"File field that only allows uploading images. Files are
directly uploaded and on-change called after success."
[{:keys [e! value on-success-event]}]
[project-context/consume
(fn [{project-id :db/id}]
[:div
[attachments {:files value
:comment-id nil
:on-delete (fn [{id :db/id}]
(e! (file-controller/->DeleteAttachment
(constantly
(on-success-event
{:comment/files
(into []
(cu/remove-by-id id)
value)}))
id)))}]
[file-upload/FileUploadButton
{:id "images-field"
:drag-container-id "new-comment-form"
:drop-message (tr [:drag :drop-to-comment])
:color :secondary
:button-attributes {:size :small}
:on-drop #(e! (file-controller/map->UploadFiles
{:files %
:project-id project-id
:attachment? true
:on-success (fn [files]
(log/info "FILES UPLOADED: " files)
(on-success-event
{:comment/files (into (or value [])
files)}))}))}
(str "+ " (tr [:comment :add-images]))]])])
(defn- comment-form-defaults [entity-type can-set-visibility?]
(merge
(case entity-type
:file {:comment/track? true}
{})
{:comment/comment ""
:comment/visibility (if can-set-visibility?
:comment.visibility/internal
:comment.visibility/all)}))
(defn visibility-selection-style
[]
{:background-color :inherit
:color theme-colors/primary})
(defn lazy-comments*
[{:keys [e! app
entity-type
entity-id
show-comment-form?
after-comment-added-event
after-comment-deleted-event
after-comment-list-rendered-event]
:or {show-comment-form? true}}
proj-map]
(r/with-let [can-set-visibility? (or (authorization-check/authorized? @app-state/user
:projects/set-comment-visibility
{:entity {:meta/creator {:db/id (:db/id @app-state/user)}}
:project-id (:db/id proj-map)
:debug? true})
(authorization-check/is-tram-personnel? @app-state/user))
initial-comment-form (comment-form-defaults entity-type
can-set-visibility?)
[comment-form ->UpdateCommentForm]
(common-controller/internal-state initial-comment-form
{:merge? true})]
(let [comments (get-in app [:comments-for-entity entity-id])]
[:div
[query/query {:e! e!
:query :comment/fetch-comments
:args {:eid entity-id
:for entity-type}
:skeleton [comment-skeleton 2]
:state-path [:comments-for-entity entity-id]
:state comments
:simple-view [comment-list {:e! e!
:show-comment-form? show-comment-form?
:after-comment-list-rendered-event after-comment-list-rendered-event
:after-comment-deleted-event after-comment-deleted-event
:quote-comment! (fn [name quoted-text]
(e! ((quote-comment-fn comment-form)
name quoted-text)))
:commented-entity {:eid entity-id
:for entity-type}
:focused-comment (get-in app [:query :focus-on])}]
:refresh (count comments)}]
(when (and show-comment-form?
only one file upload element in the dom at once .
(not (-> app :stepper :dialog)))
[form/form2 {:e! e!
:id "new-comment-form"
:value @comment-form
:on-change-event ->UpdateCommentForm
:save-event #(let [{:comment/keys [comment files visibility track? mentions]} @comment-form]
(reset! comment-form initial-comment-form)
(comments-controller/->CommentOnEntity
entity-type entity-id comment files visibility track? mentions
after-comment-added-event))
:footer new-comment-footer
:spec :task/new-comment-form}
[:div {:class (<class common-styles/gray-container-style)}
[:div {:class (<class common-styles/heading-and-action-style)}
[typography/Heading2 (tr [:document :new-comment])]
(when can-set-visibility?
[form/field :comment/visibility
[select/select-enum {:e! e! :attribute :comment/visibility :tiny-select? true
:show-empty-selection? false
:show-label? false :class (<class visibility-selection-style)}]])]
[:div {:class (<class form-field-spacer)}
[form/field :comment/comment
[mentions-input {:id "new-comment-input"
:e! e!}]
#_[TextField {:id "new-comment-input"
:rows 4
:multiline true
:full-width true
:placeholder (tr [:document :new-comment])}]]
[form/field :comment/files
[attached-images-field {:e! e!
:on-success-event ->UpdateCommentForm}]]]
(when (authorization-check/is-tram-personnel? @app-state/user)
[:div {:style {:text-align :right}}
[form/field :comment/track?
[select/checkbox {:label-placement :start}]]])
[new-comment-footer]]])])))
(defn lazy-comments
[opts]
(project-context/consume
[lazy-comments* opts]))
|
72693edb16c11459b92d7295fa68e5c8031bf852b43fac7a27ce7cd58a8eb83c | Datomic/mbrainz-sample | query.clj | Copyright ( c ) Metadata Partners , LLC . All rights reserved .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns datomic.samples.query
(:require [datomic.api :as d]))
(defn only
"Return the only item from a query result"
[query-result]
(assert (= 1 (count query-result)))
(assert (= 1 (count (first query-result))))
(ffirst query-result))
(defprotocol Eid
(e [_]))
(extend-protocol Eid
java.lang.Long
(e [n] n)
datomic.Entity
(e [ent] (:db/id ent)))
(defn qe
"Returns the single entity returned by a query."
[query db & args]
(let [res (apply d/q query db args)]
(d/entity db (only res))))
(defn find-by
"Returns the unique entity identified by attr and val."
[db attr val]
(qe '[:find ?e
:in $ ?attr ?val
:where [?e ?attr ?val]]
db attr val))
(defn qes
"Returns the entities returned by a query, assuming that
all :find results are entity ids."
[query db & args]
(->> (apply d/q query db args)
(mapv (fn [items]
(mapv (partial d/entity db) items)))))
(defn find-all-by
"Returns all entities possessing attr."
[db attr]
(qes '[:find ?e
:in $ ?attr
:where [?e ?attr]]
db attr))
(defn qfs
"Returns the first of each query result."
[query db & args]
(->> (apply d/q query db args)
(mapv first)))
(defn modes
"Returns the set of modes."
[coll]
(->> (frequencies coll)
(reduce
(fn [[modes ct] [k v]]
(cond
(< v ct) [modes ct]
(= v ct) [(conj modes k) ct]
(> v ct) [#{k} v]))
[#{} 2])
first))
| null | https://raw.githubusercontent.com/Datomic/mbrainz-sample/d5b1221d1df493b9374ec3bf76d445d4f7ae59e1/src/clj/datomic/samples/query.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) Metadata Partners , LLC . All rights reserved .
(ns datomic.samples.query
(:require [datomic.api :as d]))
(defn only
"Return the only item from a query result"
[query-result]
(assert (= 1 (count query-result)))
(assert (= 1 (count (first query-result))))
(ffirst query-result))
(defprotocol Eid
(e [_]))
(extend-protocol Eid
java.lang.Long
(e [n] n)
datomic.Entity
(e [ent] (:db/id ent)))
(defn qe
"Returns the single entity returned by a query."
[query db & args]
(let [res (apply d/q query db args)]
(d/entity db (only res))))
(defn find-by
"Returns the unique entity identified by attr and val."
[db attr val]
(qe '[:find ?e
:in $ ?attr ?val
:where [?e ?attr ?val]]
db attr val))
(defn qes
"Returns the entities returned by a query, assuming that
all :find results are entity ids."
[query db & args]
(->> (apply d/q query db args)
(mapv (fn [items]
(mapv (partial d/entity db) items)))))
(defn find-all-by
"Returns all entities possessing attr."
[db attr]
(qes '[:find ?e
:in $ ?attr
:where [?e ?attr]]
db attr))
(defn qfs
"Returns the first of each query result."
[query db & args]
(->> (apply d/q query db args)
(mapv first)))
(defn modes
"Returns the set of modes."
[coll]
(->> (frequencies coll)
(reduce
(fn [[modes ct] [k v]]
(cond
(< v ct) [modes ct]
(= v ct) [(conj modes k) ct]
(> v ct) [#{k} v]))
[#{} 2])
first))
|
94715e6d0f7fbf8f2175a9e18f2d022bdbb1caa979d63dfc6075fefa883f134f | wavewave/hoodle | StartUp.hs | # LANGUAGE CPP #
# LANGUAGE RecordWildCards #
-- |
-- Module : Hoodle.StartUp
Copyright : ( c ) 2012 , 2014
--
-- License : BSD3
Maintainer : < >
-- Stability : experimental
Portability : GHC
module Hoodle.StartUp where
import qualified Config.Dyre as Dyre
import Hoodle.Command (commandLineProcess)
import Hoodle.ProgType (mode)
import Hoodle.Script (ScriptConfig (..), showError)
import System.Console.CmdArgs (cmdArgs)
import System.Environment (getEnv)
import System.FilePath ((</>))
-- |
hoodleMain :: ScriptConfig -> IO ()
hoodleMain ScriptConfig {..} = do
case errorMsg of
Nothing -> return ()
Just em -> putStrLn $ "Error: " ++ em
maybe (return ()) putStrLn message
param <- cmdArgs mode
commandLineProcess param hook
-- |
hoodleStartMain :: ScriptConfig -> IO ()
hoodleStartMain =
Dyre.wrapMain $
Dyre.newParams "start" hoodleMain showError
-- |
dirHoodled :: IO FilePath
dirHoodled = do
homedir <- getEnv "HOME"
return (homedir </> ".hoodle.d")
| null | https://raw.githubusercontent.com/wavewave/hoodle/518533227caa76d1a3b09423c7d98761c177d429/hoodle/src/Hoodle/StartUp.hs | haskell | |
Module : Hoodle.StartUp
License : BSD3
Stability : experimental
|
|
| | # LANGUAGE CPP #
# LANGUAGE RecordWildCards #
Copyright : ( c ) 2012 , 2014
Maintainer : < >
Portability : GHC
module Hoodle.StartUp where
import qualified Config.Dyre as Dyre
import Hoodle.Command (commandLineProcess)
import Hoodle.ProgType (mode)
import Hoodle.Script (ScriptConfig (..), showError)
import System.Console.CmdArgs (cmdArgs)
import System.Environment (getEnv)
import System.FilePath ((</>))
hoodleMain :: ScriptConfig -> IO ()
hoodleMain ScriptConfig {..} = do
case errorMsg of
Nothing -> return ()
Just em -> putStrLn $ "Error: " ++ em
maybe (return ()) putStrLn message
param <- cmdArgs mode
commandLineProcess param hook
hoodleStartMain :: ScriptConfig -> IO ()
hoodleStartMain =
Dyre.wrapMain $
Dyre.newParams "start" hoodleMain showError
dirHoodled :: IO FilePath
dirHoodled = do
homedir <- getEnv "HOME"
return (homedir </> ".hoodle.d")
|
aa2b1cffe694897f27c8cb685c27fd53bb697488f32a14da5e42c21b9b8986aa | lasp-lang/partisan | demers_anti_entropy.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2018 . All Rights Reserved .
%%
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(demers_anti_entropy).
-author("Christopher S. Meiklejohn <>").
-include("partisan_logger.hrl").
-include("partisan.hrl").
%% API
-export([start_link/0,
stop/0,
broadcast/2,
update/1]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-define(THIS_FANOUT, 2).
-record(state, {next_id, membership}).
%%%===================================================================
%%% API
%%%===================================================================
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop() ->
gen_server:stop(?MODULE).
%% @doc Broadcast.
broadcast(ServerRef, Message) ->
gen_server:cast(?MODULE, {broadcast, ServerRef, Message}).
%% @doc Membership update.
update(LocalState0) ->
LocalState = partisan_peer_service:decode(LocalState0),
gen_server:cast(?MODULE, {update, LocalState}).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
@private
init([]) ->
%% Seed the random number generator.
partisan_config:seed(),
Register membership update callback .
partisan_peer_service:add_sup_callback(fun ?MODULE:update/1),
%% Open ETS table to track received messages.
?MODULE = ets:new(?MODULE, [set, named_table, public]),
%% Start with initial membership.
{ok, Membership} = partisan_peer_service:members(),
?LOG_INFO("Starting with membership: ~p", [Membership]),
%% Schedule anti-entropy.
schedule_anti_entropy(),
{ok, #state{next_id=0, membership=membership(Membership)}}.
@private
handle_call(Msg, _From, State) ->
?LOG_WARNING("Unhandled call messages at module ~p: ~p", [?MODULE, Msg]),
{reply, ok, State}.
@private
handle_cast({broadcast, ServerRef, Message}, #state{next_id=NextId}=State) ->
%% Generate message id.
MyNode = partisan:node(),
Id = {MyNode, NextId},
%% Forward to process.
partisan_peer_service_manager:process_forward(ServerRef, Message),
%% Store outgoing message.
true = ets:insert(?MODULE, {Id, {ServerRef, Message}}),
{noreply, State#state{next_id=NextId}};
handle_cast({update, Membership0}, State) ->
Membership = membership(Membership0),
{noreply, State#state{membership=Membership}};
handle_cast(Msg, State) ->
?LOG_WARNING("Unhandled cast messages at module ~p: ~p", [?MODULE, Msg]),
{noreply, State}.
@private
%% Incoming messages.
handle_info(antientropy, #state{membership=Membership}=State) ->
MyNode = partisan:node(),
%% Get all of our messages.
OurMessages = ets:foldl(fun({Id, {ServerRef, Message}}, Acc) ->
Acc ++ [{Id, {ServerRef, Message}}]
end, [], ?MODULE),
%% Forward to random subset of peers.
AntiEntropyMembers = select_random_sublist(membership(Membership), ?THIS_FANOUT),
lists:foreach(fun(N) ->
partisan:forward_message(
N,
?MODULE,
{push, MyNode, OurMessages},
#{channel => ?DEFAULT_CHANNEL}
)
end, AntiEntropyMembers -- [MyNode]),
%% Reschedule.
schedule_anti_entropy(),
{noreply, State};
handle_info({push, FromNode, TheirMessages}, State) ->
MyNode = partisan:node(),
Encorporate their messages and process them if we did n't see them .
lists:foreach(fun({Id, {ServerRef, Message}}) ->
case ets:lookup(?MODULE, Id) of
[] ->
%% Forward to process.
partisan_peer_service_manager:process_forward(ServerRef, Message),
%% Store.
true = ets:insert(?MODULE, {Id, {ServerRef, Message}}),
ok;
_ ->
ok
end
end, TheirMessages),
%% Get all of our messages.
OurMessages = ets:foldl(fun({Id, {ServerRef, Message}}, Acc) ->
Acc ++ [{Id, {ServerRef, Message}}]
end, [], ?MODULE),
%% Forward message back to sender.
?LOG_INFO("~p: sending messages to node ~p", [node(), FromNode]),
partisan:forward_message(
FromNode,
?MODULE,
{pull, MyNode, OurMessages},
#{channel => ?DEFAULT_CHANNEL}
),
{noreply, State};
handle_info({pull, _FromNode, Messages}, State) ->
%% Process all incoming.
lists:foreach(fun({Id, {ServerRef, Message}}) ->
case ets:lookup(?MODULE, Id) of
[] ->
%% Forward to process.
partisan_peer_service_manager:process_forward(ServerRef, Message),
%% Store.
true = ets:insert(?MODULE, {Id, {ServerRef, Message}}),
ok;
_ ->
ok
end
end, Messages),
{noreply, State};
handle_info(_Msg, State) ->
{noreply, State}.
@private
terminate(_Reason, _State) ->
ok.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
@private -- sort to remove nondeterminism in node selection .
membership(Membership) ->
lists:usort(Membership).
@private
schedule_anti_entropy() ->
Interval = 2000,
erlang:send_after(Interval, ?MODULE, antientropy).
@private
select_random_sublist(Membership, K) ->
lists:sublist(shuffle(Membership), K).
%% @reference -elements-in-a-list-randomly-re-arrange-list-elements/8820501#8820501
shuffle(L) ->
[X || {_, X} <- lists:sort([{rand:uniform(), N} || N <- L])]. | null | https://raw.githubusercontent.com/lasp-lang/partisan/fd048fc1b34309d9fa41450434a7e7b3b2fa1fb8/protocols/demers_anti_entropy.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.
-------------------------------------------------------------------
API
gen_server callbacks
===================================================================
API
===================================================================
@doc Broadcast.
@doc Membership update.
===================================================================
gen_server callbacks
===================================================================
Seed the random number generator.
Open ETS table to track received messages.
Start with initial membership.
Schedule anti-entropy.
Generate message id.
Forward to process.
Store outgoing message.
Incoming messages.
Get all of our messages.
Forward to random subset of peers.
Reschedule.
Forward to process.
Store.
Get all of our messages.
Forward message back to sender.
Process all incoming.
Forward to process.
Store.
===================================================================
===================================================================
@reference -elements-in-a-list-randomly-re-arrange-list-elements/8820501#8820501 | Copyright ( c ) 2018 . All Rights Reserved .
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(demers_anti_entropy).
-author("Christopher S. Meiklejohn <>").
-include("partisan_logger.hrl").
-include("partisan.hrl").
-export([start_link/0,
stop/0,
broadcast/2,
update/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-define(THIS_FANOUT, 2).
-record(state, {next_id, membership}).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop() ->
gen_server:stop(?MODULE).
broadcast(ServerRef, Message) ->
gen_server:cast(?MODULE, {broadcast, ServerRef, Message}).
update(LocalState0) ->
LocalState = partisan_peer_service:decode(LocalState0),
gen_server:cast(?MODULE, {update, LocalState}).
@private
init([]) ->
partisan_config:seed(),
Register membership update callback .
partisan_peer_service:add_sup_callback(fun ?MODULE:update/1),
?MODULE = ets:new(?MODULE, [set, named_table, public]),
{ok, Membership} = partisan_peer_service:members(),
?LOG_INFO("Starting with membership: ~p", [Membership]),
schedule_anti_entropy(),
{ok, #state{next_id=0, membership=membership(Membership)}}.
@private
handle_call(Msg, _From, State) ->
?LOG_WARNING("Unhandled call messages at module ~p: ~p", [?MODULE, Msg]),
{reply, ok, State}.
@private
handle_cast({broadcast, ServerRef, Message}, #state{next_id=NextId}=State) ->
MyNode = partisan:node(),
Id = {MyNode, NextId},
partisan_peer_service_manager:process_forward(ServerRef, Message),
true = ets:insert(?MODULE, {Id, {ServerRef, Message}}),
{noreply, State#state{next_id=NextId}};
handle_cast({update, Membership0}, State) ->
Membership = membership(Membership0),
{noreply, State#state{membership=Membership}};
handle_cast(Msg, State) ->
?LOG_WARNING("Unhandled cast messages at module ~p: ~p", [?MODULE, Msg]),
{noreply, State}.
@private
handle_info(antientropy, #state{membership=Membership}=State) ->
MyNode = partisan:node(),
OurMessages = ets:foldl(fun({Id, {ServerRef, Message}}, Acc) ->
Acc ++ [{Id, {ServerRef, Message}}]
end, [], ?MODULE),
AntiEntropyMembers = select_random_sublist(membership(Membership), ?THIS_FANOUT),
lists:foreach(fun(N) ->
partisan:forward_message(
N,
?MODULE,
{push, MyNode, OurMessages},
#{channel => ?DEFAULT_CHANNEL}
)
end, AntiEntropyMembers -- [MyNode]),
schedule_anti_entropy(),
{noreply, State};
handle_info({push, FromNode, TheirMessages}, State) ->
MyNode = partisan:node(),
Encorporate their messages and process them if we did n't see them .
lists:foreach(fun({Id, {ServerRef, Message}}) ->
case ets:lookup(?MODULE, Id) of
[] ->
partisan_peer_service_manager:process_forward(ServerRef, Message),
true = ets:insert(?MODULE, {Id, {ServerRef, Message}}),
ok;
_ ->
ok
end
end, TheirMessages),
OurMessages = ets:foldl(fun({Id, {ServerRef, Message}}, Acc) ->
Acc ++ [{Id, {ServerRef, Message}}]
end, [], ?MODULE),
?LOG_INFO("~p: sending messages to node ~p", [node(), FromNode]),
partisan:forward_message(
FromNode,
?MODULE,
{pull, MyNode, OurMessages},
#{channel => ?DEFAULT_CHANNEL}
),
{noreply, State};
handle_info({pull, _FromNode, Messages}, State) ->
lists:foreach(fun({Id, {ServerRef, Message}}) ->
case ets:lookup(?MODULE, Id) of
[] ->
partisan_peer_service_manager:process_forward(ServerRef, Message),
true = ets:insert(?MODULE, {Id, {ServerRef, Message}}),
ok;
_ ->
ok
end
end, Messages),
{noreply, State};
handle_info(_Msg, State) ->
{noreply, State}.
@private
terminate(_Reason, _State) ->
ok.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
@private -- sort to remove nondeterminism in node selection .
membership(Membership) ->
lists:usort(Membership).
@private
schedule_anti_entropy() ->
Interval = 2000,
erlang:send_after(Interval, ?MODULE, antientropy).
@private
select_random_sublist(Membership, K) ->
lists:sublist(shuffle(Membership), K).
shuffle(L) ->
[X || {_, X} <- lists:sort([{rand:uniform(), N} || N <- L])]. |
064a64a0b03dfbad52a8cb30ff1c0b884da1bb4e826dfa58fea401ef88fa39e4 | turquoise-hexagon/euler | solution.scm | (import
(euler))
(define (solve n)
(digitsum n))
(let ((_ (solve (expt 2 1000))))
(print _) (assert (= _ 1366)))
| null | https://raw.githubusercontent.com/turquoise-hexagon/euler/592c5f4f45fe8e8b82102be9fe11b3b1134d98fc/src/016/solution.scm | scheme | (import
(euler))
(define (solve n)
(digitsum n))
(let ((_ (solve (expt 2 1000))))
(print _) (assert (= _ 1366)))
| |
c20a0c266e64526f61d8a450ec61b9d2f43eb136b47a04ceaf0af097ef330a2a | zenspider/schemers | exercise.2.21.scm | #lang racket/base
(require "../lib/test.rkt")
Exercise 2.21 :
;; The procedure `square-list' takes a list of numbers as argument and
;; returns a list of the squares of those numbers.
;;
( square - list ( list 1 2 3 4 ) )
;; (1 4 9 16)
;;
Here are two different definitions of ` square - list ' . Complete both
;; of them by filling in the missing expressions:
;;
;; (define (square-list items)
;; (if (null? items)
;; nil
;; (cons <??> <??>)))
;;
;; (define (square-list items)
;; (map <??> <??>))
(define (square n) (* n n))
(define (square-list1 items)
(if (null? items) null
(cons (square (car items)) (square-list1 (cdr items)))))
(define (square-list2 items)
(map square items))
(assert-equal '(1 4 9 16) (square-list1 '(1 2 3 4)))
(assert-equal '(1 4 9 16) (square-list2 '(1 2 3 4)))
(done)
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_2/exercise.2.21.scm | scheme | The procedure `square-list' takes a list of numbers as argument and
returns a list of the squares of those numbers.
(1 4 9 16)
of them by filling in the missing expressions:
(define (square-list items)
(if (null? items)
nil
(cons <??> <??>)))
(define (square-list items)
(map <??> <??>)) | #lang racket/base
(require "../lib/test.rkt")
Exercise 2.21 :
( square - list ( list 1 2 3 4 ) )
Here are two different definitions of ` square - list ' . Complete both
(define (square n) (* n n))
(define (square-list1 items)
(if (null? items) null
(cons (square (car items)) (square-list1 (cdr items)))))
(define (square-list2 items)
(map square items))
(assert-equal '(1 4 9 16) (square-list1 '(1 2 3 4)))
(assert-equal '(1 4 9 16) (square-list2 '(1 2 3 4)))
(done)
|
2fc5f6b3b18043aa3e920ecd2eb3332944627cfa6da5e741b52e07ea0dd07d99 | racket/scribble | info.rkt | #lang info
(define collection 'multi)
(define deps '("scheme-lib"
"base" "at-exp-lib"
"scribble-text-lib"))
(define pkg-desc "Language for HTML with embedded Racket code")
(define pkg-authors '(mflatt eli))
(define license
'(Apache-2.0 OR MIT))
| null | https://raw.githubusercontent.com/racket/scribble/359c0cddf7ba1cf6cf8502f9396f24d362d1eba5/scribble-html-lib/info.rkt | racket | #lang info
(define collection 'multi)
(define deps '("scheme-lib"
"base" "at-exp-lib"
"scribble-text-lib"))
(define pkg-desc "Language for HTML with embedded Racket code")
(define pkg-authors '(mflatt eli))
(define license
'(Apache-2.0 OR MIT))
| |
70d17b3906ac27ce311f66c9faab694f72bf38e83abaf0f426bc89e125378143 | vii/dysfunkycom | joystick.lisp |
(in-package #:sdl-examples)
(defvar *joystick* nil)
(defvar *num-joysticks* 0)
(defvar *current-joystick-index* 0)
(defvar *status* nil)
(defstruct joystick
fp
index
axis-motion
button-down
button-up
hat-motion
ball-motion
status)
(defun incf-line (&optional (lines 1) (font sdl:*default-font*))
(* lines (+ 2 (sdl:char-height font))))
(defun new-axis-motion-event (which axis value)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Axis-Motion: Which: ~A, Axis: ~A, Value: ~A" which axis value)
x y
:color sdl:*white*
:surface surface)))
(defun new-button-down-event (which button state)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Button-Down: Which: ~A, Button: ~A, State: ~A" which button state)
x y
:color sdl:*white*
:surface surface)))
(defun new-button-up-event (which button state)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Button-Up: Which: ~A, Button: ~A, State: ~A" which button state)
x y
:color sdl:*white*
:surface surface)))
(defun new-hat-motion-event (which axis value)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Hat-Motion: Which: ~A, Axis: ~A, Value: ~A" which axis value)
x y
:color sdl:*white*
:surface surface)))
(defun new-ball-motion-event (which ball x-rel y-rel)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Ball-Motion: Which: ~A, Ball: ~A, X-rel: ~A, Y-rel: ~A" which ball x-rel y-rel)
x y
:color sdl:*white*
:surface surface)))
(defun new-joystick (index)
(let ((fp (sdl-cffi::sdl-joystick-open index)))
(if (sdl:is-valid-ptr fp)
(make-joystick :fp fp
:index index
:axis-motion (new-axis-motion-event nil nil nil)
:button-down (new-button-down-event nil nil nil)
:button-up (new-button-up-event nil nil nil)
:hat-motion (new-hat-motion-event nil nil nil)
:ball-motion (new-ball-motion-event nil nil nil nil))
nil)))
(defun close-joystick (joystick)
(when (> (sdl-cffi::sdl-joystick-opened (joystick-index joystick)) 0)
(sdl-cffi::sdl-joystick-close (joystick-fp joystick))))
(defun print-status (&optional (surface sdl:*default-display*))
(let ((x 300) (y 30))
(sdl:draw-string-solid-* "No Joystick Found / Joystick Open Error"
x y
:color sdl:*white*
:surface surface
:justify :center)))
(defun print-joystick (joystick &optional (surface sdl:*default-display*))
(let ((x 20) (y 30))
(sdl:draw-string-solid-* (format nil "Index: ~d \(~d of ~d\)" (joystick-index joystick) (1+ (joystick-index joystick)) *num-joysticks*)
x y
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil "Name: ~A" (sdl-cffi::sdl-joystick-name (joystick-index joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil"Axes: ~d" (sdl-cffi::sdl-joystick-num-axes (joystick-fp joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil"Buttons: ~d" (sdl-cffi::sdl-joystick-num-buttons (joystick-fp joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil"Balls: ~d" (sdl-cffi::sdl-joystick-num-balls (joystick-fp joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(funcall (joystick-axis-motion joystick) x (incf y (incf-line)))
(funcall (joystick-button-up joystick) x (incf y (incf-line)))
(funcall (joystick-button-down joystick) x (incf y (incf-line)))
(funcall (joystick-hat-motion joystick) x (incf y (incf-line)))
(funcall (joystick-ball-motion joystick) x (incf y (incf-line)))))
(defun joystick ()
(sdl:with-init (sdl:SDL-INIT-EVERYTHING)
(sdl:window 600 240 :title-caption "Joystick" :icon-caption "Joystick")
(setf (sdl:frame-rate) 30)
(sdl:initialise-default-font)
(sdl-cffi::sdl-joystick-event-state sdl-cffi::sdl-enable)
(setf *num-joysticks* (sdl:num-joysticks)
*current-joystick-index* 0)
(when (> *num-joysticks* 0)
(setf *joystick* (new-joystick *current-joystick-index*)))
(sdl:with-events ()
(:quit-event ()
(when *joystick*
(close-joystick *joystick*))
t)
(:key-down-event (:key key)
(cond
((sdl:key= key :sdl-key-escape)
(sdl:push-quit-event))
((sdl:key= key :sdl-key-space)
(when *joystick*
(close-joystick *joystick*)
(incf *current-joystick-index*)
(when (>= *current-joystick-index* *num-joysticks*)
(setf *current-joystick-index* 0))
(setf *joystick* (new-joystick *current-joystick-index*))))))
(:joy-axis-motion-event (:WHICH WHICH :AXIS AXIS :VALUE VALUE)
(setf (joystick-axis-motion *joystick*) (new-axis-motion-event which axis value)))
(:joy-button-down-event (:WHICH WHICH :BUTTON BUTTON :STATE STATE)
(setf (joystick-button-down *joystick*) (new-button-down-event which button state)))
(:joy-button-up-event (:WHICH WHICH :BUTTON BUTTON :STATE STATE)
(setf (joystick-button-up *joystick*) (new-button-up-event which button state)))
(:joy-hat-motion-event (:WHICH WHICH :AXIS AXIS :VALUE VALUE)
(setf (joystick-hat-motion *joystick*) (new-hat-motion-event which axis value)))
(:joy-ball-motion-event (:WHICH WHICH :BALL BALL :X-REL X-REL :Y-REL Y-REL)
(setf (joystick-ball-motion *joystick*) (new-ball-motion-event which ball x-rel y-rel)))
(:video-expose-event ()
(sdl:update-display))
(:idle ()
(sdl:clear-display sdl:*black*)
(sdl:draw-string-solid-* (format nil "Joystick Test")
300 5
:color sdl:*white*
:justify :center)
(sdl:draw-string-solid-* (format nil "SPACE to test next joystick. ESC to exit.")
300 15
:color sdl:*white*
:justify :center)
(if *joystick*
(print-joystick *joystick*)
(print-status))
(sdl:update-display)))))
| null | https://raw.githubusercontent.com/vii/dysfunkycom/a493fa72662b79e7c4e70361ad0ea3c7235b6166/addons/lispbuilder-sdl/examples/joystick.lisp | lisp |
(in-package #:sdl-examples)
(defvar *joystick* nil)
(defvar *num-joysticks* 0)
(defvar *current-joystick-index* 0)
(defvar *status* nil)
(defstruct joystick
fp
index
axis-motion
button-down
button-up
hat-motion
ball-motion
status)
(defun incf-line (&optional (lines 1) (font sdl:*default-font*))
(* lines (+ 2 (sdl:char-height font))))
(defun new-axis-motion-event (which axis value)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Axis-Motion: Which: ~A, Axis: ~A, Value: ~A" which axis value)
x y
:color sdl:*white*
:surface surface)))
(defun new-button-down-event (which button state)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Button-Down: Which: ~A, Button: ~A, State: ~A" which button state)
x y
:color sdl:*white*
:surface surface)))
(defun new-button-up-event (which button state)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Button-Up: Which: ~A, Button: ~A, State: ~A" which button state)
x y
:color sdl:*white*
:surface surface)))
(defun new-hat-motion-event (which axis value)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Hat-Motion: Which: ~A, Axis: ~A, Value: ~A" which axis value)
x y
:color sdl:*white*
:surface surface)))
(defun new-ball-motion-event (which ball x-rel y-rel)
(lambda (x y &optional (surface sdl:*default-display*))
(sdl:draw-string-solid-* (format nil "Ball-Motion: Which: ~A, Ball: ~A, X-rel: ~A, Y-rel: ~A" which ball x-rel y-rel)
x y
:color sdl:*white*
:surface surface)))
(defun new-joystick (index)
(let ((fp (sdl-cffi::sdl-joystick-open index)))
(if (sdl:is-valid-ptr fp)
(make-joystick :fp fp
:index index
:axis-motion (new-axis-motion-event nil nil nil)
:button-down (new-button-down-event nil nil nil)
:button-up (new-button-up-event nil nil nil)
:hat-motion (new-hat-motion-event nil nil nil)
:ball-motion (new-ball-motion-event nil nil nil nil))
nil)))
(defun close-joystick (joystick)
(when (> (sdl-cffi::sdl-joystick-opened (joystick-index joystick)) 0)
(sdl-cffi::sdl-joystick-close (joystick-fp joystick))))
(defun print-status (&optional (surface sdl:*default-display*))
(let ((x 300) (y 30))
(sdl:draw-string-solid-* "No Joystick Found / Joystick Open Error"
x y
:color sdl:*white*
:surface surface
:justify :center)))
(defun print-joystick (joystick &optional (surface sdl:*default-display*))
(let ((x 20) (y 30))
(sdl:draw-string-solid-* (format nil "Index: ~d \(~d of ~d\)" (joystick-index joystick) (1+ (joystick-index joystick)) *num-joysticks*)
x y
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil "Name: ~A" (sdl-cffi::sdl-joystick-name (joystick-index joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil"Axes: ~d" (sdl-cffi::sdl-joystick-num-axes (joystick-fp joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil"Buttons: ~d" (sdl-cffi::sdl-joystick-num-buttons (joystick-fp joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(sdl:draw-string-solid-* (format nil"Balls: ~d" (sdl-cffi::sdl-joystick-num-balls (joystick-fp joystick)))
x (incf y (incf-line))
:color sdl:*white*
:surface surface)
(funcall (joystick-axis-motion joystick) x (incf y (incf-line)))
(funcall (joystick-button-up joystick) x (incf y (incf-line)))
(funcall (joystick-button-down joystick) x (incf y (incf-line)))
(funcall (joystick-hat-motion joystick) x (incf y (incf-line)))
(funcall (joystick-ball-motion joystick) x (incf y (incf-line)))))
(defun joystick ()
(sdl:with-init (sdl:SDL-INIT-EVERYTHING)
(sdl:window 600 240 :title-caption "Joystick" :icon-caption "Joystick")
(setf (sdl:frame-rate) 30)
(sdl:initialise-default-font)
(sdl-cffi::sdl-joystick-event-state sdl-cffi::sdl-enable)
(setf *num-joysticks* (sdl:num-joysticks)
*current-joystick-index* 0)
(when (> *num-joysticks* 0)
(setf *joystick* (new-joystick *current-joystick-index*)))
(sdl:with-events ()
(:quit-event ()
(when *joystick*
(close-joystick *joystick*))
t)
(:key-down-event (:key key)
(cond
((sdl:key= key :sdl-key-escape)
(sdl:push-quit-event))
((sdl:key= key :sdl-key-space)
(when *joystick*
(close-joystick *joystick*)
(incf *current-joystick-index*)
(when (>= *current-joystick-index* *num-joysticks*)
(setf *current-joystick-index* 0))
(setf *joystick* (new-joystick *current-joystick-index*))))))
(:joy-axis-motion-event (:WHICH WHICH :AXIS AXIS :VALUE VALUE)
(setf (joystick-axis-motion *joystick*) (new-axis-motion-event which axis value)))
(:joy-button-down-event (:WHICH WHICH :BUTTON BUTTON :STATE STATE)
(setf (joystick-button-down *joystick*) (new-button-down-event which button state)))
(:joy-button-up-event (:WHICH WHICH :BUTTON BUTTON :STATE STATE)
(setf (joystick-button-up *joystick*) (new-button-up-event which button state)))
(:joy-hat-motion-event (:WHICH WHICH :AXIS AXIS :VALUE VALUE)
(setf (joystick-hat-motion *joystick*) (new-hat-motion-event which axis value)))
(:joy-ball-motion-event (:WHICH WHICH :BALL BALL :X-REL X-REL :Y-REL Y-REL)
(setf (joystick-ball-motion *joystick*) (new-ball-motion-event which ball x-rel y-rel)))
(:video-expose-event ()
(sdl:update-display))
(:idle ()
(sdl:clear-display sdl:*black*)
(sdl:draw-string-solid-* (format nil "Joystick Test")
300 5
:color sdl:*white*
:justify :center)
(sdl:draw-string-solid-* (format nil "SPACE to test next joystick. ESC to exit.")
300 15
:color sdl:*white*
:justify :center)
(if *joystick*
(print-joystick *joystick*)
(print-status))
(sdl:update-display)))))
| |
a281d1fcf6d092087025d8dda46b5980b5d7cda4500937a905815c790151a1ee | input-output-hk/cardano-rest | Web.hs | module Explorer.Web
( runServer
, WebserverConfig(..)
-- For testing.
, CAddress (..)
, CTxAddressBrief (..)
, CAddressSummary (..)
, CCoin (..)
, CGenesisAddressInfo (..)
, CHash (..)
, CTxBrief (..)
, CTxHash (..)
, queryAddressSummary
, queryAllGenesisAddresses
, queryBlocksTxs
, queryChainTip
, runQuery
) where
import Explorer.Web.Api.Legacy.AddressSummary (queryAddressSummary)
import Explorer.Web.Api.Legacy.BlocksTxs (queryBlocksTxs)
import Explorer.Web.Api.Legacy.GenesisAddress (queryAllGenesisAddresses)
import Explorer.Web.Api.Legacy.Util (runQuery)
import Explorer.Web.ClientTypes (CAddress (..), CTxAddressBrief (..), CAddressSummary (..),
CCoin (..), CGenesisAddressInfo (..), CHash (..), CTxBrief (..), CTxHash (..))
import Explorer.Web.Query (queryChainTip)
import Explorer.Web.Server (runServer, WebserverConfig(..))
| null | https://raw.githubusercontent.com/input-output-hk/cardano-rest/040b123b45af06060aae04479d92fada68820f12/explorer-api/src/Explorer/Web.hs | haskell | For testing. | module Explorer.Web
( runServer
, WebserverConfig(..)
, CAddress (..)
, CTxAddressBrief (..)
, CAddressSummary (..)
, CCoin (..)
, CGenesisAddressInfo (..)
, CHash (..)
, CTxBrief (..)
, CTxHash (..)
, queryAddressSummary
, queryAllGenesisAddresses
, queryBlocksTxs
, queryChainTip
, runQuery
) where
import Explorer.Web.Api.Legacy.AddressSummary (queryAddressSummary)
import Explorer.Web.Api.Legacy.BlocksTxs (queryBlocksTxs)
import Explorer.Web.Api.Legacy.GenesisAddress (queryAllGenesisAddresses)
import Explorer.Web.Api.Legacy.Util (runQuery)
import Explorer.Web.ClientTypes (CAddress (..), CTxAddressBrief (..), CAddressSummary (..),
CCoin (..), CGenesisAddressInfo (..), CHash (..), CTxBrief (..), CTxHash (..))
import Explorer.Web.Query (queryChainTip)
import Explorer.Web.Server (runServer, WebserverConfig(..))
|
e275faef0c619b159b2763a62c6449f7e3fe221b5875fe9eb803a9f02bb5f750 | serioga/webapp-clojure-2020 | core.clj | (ns app.html.core
(:require [clojure.java.io :as io]
[rum.core :as rum])
(:import (org.apache.commons.codec.digest DigestUtils)))
(set! *warn-on-reflection* true)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn render-page
"Renders hiccup to HTML page string."
[hiccup]
(str "<!DOCTYPE html>\n"
(rum/render-static-markup hiccup)))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn include-css
"Hiccup to include external CSS."
[href]
[:link {:type "text/css", :href href, :rel "stylesheet"}])
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn include-js
"Hiccup to include external JS."
([src]
(include-js src nil))
([src, defer-or-async]
(list [:script {:type "text/javascript"
:src src
:defer (= :defer defer-or-async)
:async (= :async defer-or-async)}])))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn static-uri-with-hash
"Attach hash parameter to URI of static resource."
[uri]
(let [path (str "public" uri)
content (slurp (or (io/resource path)
(throw (ex-info (print-str "Missing static resource" (pr-str path))
{:name name :resource-path path}))))
content-hash (DigestUtils/sha256Hex content)]
(str uri "?" content-hash)))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
| null | https://raw.githubusercontent.com/serioga/webapp-clojure-2020/9b33fe785fddeaa0a0a22b288d34d9be0c72ffc6/src/app/html/core.clj | clojure | (ns app.html.core
(:require [clojure.java.io :as io]
[rum.core :as rum])
(:import (org.apache.commons.codec.digest DigestUtils)))
(set! *warn-on-reflection* true)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn render-page
"Renders hiccup to HTML page string."
[hiccup]
(str "<!DOCTYPE html>\n"
(rum/render-static-markup hiccup)))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn include-css
"Hiccup to include external CSS."
[href]
[:link {:type "text/css", :href href, :rel "stylesheet"}])
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn include-js
"Hiccup to include external JS."
([src]
(include-js src nil))
([src, defer-or-async]
(list [:script {:type "text/javascript"
:src src
:defer (= :defer defer-or-async)
:async (= :async defer-or-async)}])))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn static-uri-with-hash
"Attach hash parameter to URI of static resource."
[uri]
(let [path (str "public" uri)
content (slurp (or (io/resource path)
(throw (ex-info (print-str "Missing static resource" (pr-str path))
{:name name :resource-path path}))))
content-hash (DigestUtils/sha256Hex content)]
(str uri "?" content-hash)))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
| |
aec41091e576983a515c63fcae91f13bed0e6fc5adf50bc8fb53a2fbb203a1c4 | clash-lang/clash-compiler | VRotate.hs | module VRotate where
import Clash.Prelude
import Clash.Explicit.Testbench
topEntity :: Vec 5 Int -> (Vec 5 Int,Vec 5 Int)
topEntity v = (rotateLeftS v d2,rotateRightS v d2)
{-# NOINLINE topEntity #-}
testBench :: Signal System Bool
testBench = done
where
testInput = pure (1:>2:>3:>4:>5:>Nil)
expectedOutput = outputVerifier' clk rst ((3:>4:>5:>1:>2:>Nil,4:>5:>1:>2:>3:>Nil):>Nil)
done = expectedOutput (topEntity <$> testInput)
clk = tbSystemClockGen (not <$> done)
rst = systemResetGen
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/Vector/VRotate.hs | haskell | # NOINLINE topEntity # | module VRotate where
import Clash.Prelude
import Clash.Explicit.Testbench
topEntity :: Vec 5 Int -> (Vec 5 Int,Vec 5 Int)
topEntity v = (rotateLeftS v d2,rotateRightS v d2)
testBench :: Signal System Bool
testBench = done
where
testInput = pure (1:>2:>3:>4:>5:>Nil)
expectedOutput = outputVerifier' clk rst ((3:>4:>5:>1:>2:>Nil,4:>5:>1:>2:>3:>Nil):>Nil)
done = expectedOutput (topEntity <$> testInput)
clk = tbSystemClockGen (not <$> done)
rst = systemResetGen
|
9495f4948890f115bd496992e1b296f143be66c9ebb959feef4bdec4c8c04ceb | garycrawford/lein-life | user.clj | (ns user
"Tools for interactive development with the REPL. This file should
not be included in a production build of the application."
(:require
[clojure.tools.namespace.repl :refer [refresh]]
[midje.repl :refer [autotest]]
[reloaded.repl :refer [system init start stop go reset]]
[cemerick.pomegranate :refer [add-dependencies]]
[{{ns-name}}.components.system :refer [new-{{ns-name}}-system]]))
(reloaded.repl/set-init! new-{{ns-name}}-system)
(autotest)
(defn fix-exception
[]
(require 'user :reload-all))
;; TODO: switch out for alembic as it allows reloading of project file
(defn add-dependency
"Allows dynamic adding of dependencies to the classpath."
[dependency version]
(add-dependencies :coordinates [[dependency version]]
:repositories {"clojars" ""
"central" "/"}))
| null | https://raw.githubusercontent.com/garycrawford/lein-life/d55f3636950b58b02399ab32eb1f6d81ecfce823/src/leiningen/new/life/common/dev/user.clj | clojure | TODO: switch out for alembic as it allows reloading of project file | (ns user
"Tools for interactive development with the REPL. This file should
not be included in a production build of the application."
(:require
[clojure.tools.namespace.repl :refer [refresh]]
[midje.repl :refer [autotest]]
[reloaded.repl :refer [system init start stop go reset]]
[cemerick.pomegranate :refer [add-dependencies]]
[{{ns-name}}.components.system :refer [new-{{ns-name}}-system]]))
(reloaded.repl/set-init! new-{{ns-name}}-system)
(autotest)
(defn fix-exception
[]
(require 'user :reload-all))
(defn add-dependency
"Allows dynamic adding of dependencies to the classpath."
[dependency version]
(add-dependencies :coordinates [[dependency version]]
:repositories {"clojars" ""
"central" "/"}))
|
19136871dcd9c723125de42438d95b7301d0eda5efda05fa79d37ec7a0b15f8e | fission-codes/fission | Types.hs | module Fission.CLI.PubSub.Secure.Session.Handshake.Types (Handshake (..)) where
import Data.ByteArray as ByteArray
import qualified Data.ByteString.Base64 as Base64
import qualified RIO.ByteString.Lazy as Lazy
import qualified RIO.Text as Text
import Crypto.Cipher.AES (AES256)
import Crypto.Cipher.Types
import qualified Crypto.PubKey.RSA as RSA
import Fission.Prelude
import Fission.Key.EncryptedWith as EncryptedWith
import qualified Fission.Key.Symmetric.Types as Symmetric
import qualified Fission.Web.Auth.Token.Bearer.Types as Bearer
data Handshake = Handshake
{ iv :: IV AES256
, sessionKey :: Symmetric.Key AES256 `EncryptedWith` RSA.PrivateKey
, msg :: Bearer.BareToken `EncryptedWith` Symmetric.Key AES256
}
deriving Eq
instance Display Handshake where
textDisplay Handshake {..} =
mconcat
[ "PubSub.Session.Handshake{"
, "sessionKey=" <> textDisplay sessionKey
, ", msg=" <> textDisplay msg
, ", iv=" <> decodeUtf8Lenient (ByteArray.convert iv)
, "}"
]
instance Show Handshake where
show = Text.unpack . textDisplay
instance ToJSON Handshake where
toJSON Handshake {..} =
object [ "iv" .= encodedIV
, "msg" .= encodedMsg
, "sessionKey" .= encodedKey
]
where
encodedIV = decodeUtf8Lenient . Base64.encode $ ByteArray.convert iv
encodedKey = decodeUtf8Lenient . Base64.encode . Lazy.toStrict $ cipherLBS sessionKey
encodedMsg = decodeUtf8Lenient . Base64.encode . Lazy.toStrict $ cipherLBS msg
instance FromJSON Handshake where
parseJSON = withObject "PubSub.Session.Handshake" \obj -> do
token' <- obj .: "msg"
key' <- obj .: "sessionKey"
ivTxt <- obj .: "iv"
case makeIV . Base64.decodeLenient $ encodeUtf8 ivTxt of
Nothing -> fail "Invalid (IV AES256)"
Just iv -> return Handshake { iv
, sessionKey = EncryptedWith.fromBase64 key'
, msg = EncryptedWith.fromBase64 token'
}
| null | https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-cli/library/Fission/CLI/PubSub/Secure/Session/Handshake/Types.hs | haskell | module Fission.CLI.PubSub.Secure.Session.Handshake.Types (Handshake (..)) where
import Data.ByteArray as ByteArray
import qualified Data.ByteString.Base64 as Base64
import qualified RIO.ByteString.Lazy as Lazy
import qualified RIO.Text as Text
import Crypto.Cipher.AES (AES256)
import Crypto.Cipher.Types
import qualified Crypto.PubKey.RSA as RSA
import Fission.Prelude
import Fission.Key.EncryptedWith as EncryptedWith
import qualified Fission.Key.Symmetric.Types as Symmetric
import qualified Fission.Web.Auth.Token.Bearer.Types as Bearer
data Handshake = Handshake
{ iv :: IV AES256
, sessionKey :: Symmetric.Key AES256 `EncryptedWith` RSA.PrivateKey
, msg :: Bearer.BareToken `EncryptedWith` Symmetric.Key AES256
}
deriving Eq
instance Display Handshake where
textDisplay Handshake {..} =
mconcat
[ "PubSub.Session.Handshake{"
, "sessionKey=" <> textDisplay sessionKey
, ", msg=" <> textDisplay msg
, ", iv=" <> decodeUtf8Lenient (ByteArray.convert iv)
, "}"
]
instance Show Handshake where
show = Text.unpack . textDisplay
instance ToJSON Handshake where
toJSON Handshake {..} =
object [ "iv" .= encodedIV
, "msg" .= encodedMsg
, "sessionKey" .= encodedKey
]
where
encodedIV = decodeUtf8Lenient . Base64.encode $ ByteArray.convert iv
encodedKey = decodeUtf8Lenient . Base64.encode . Lazy.toStrict $ cipherLBS sessionKey
encodedMsg = decodeUtf8Lenient . Base64.encode . Lazy.toStrict $ cipherLBS msg
instance FromJSON Handshake where
parseJSON = withObject "PubSub.Session.Handshake" \obj -> do
token' <- obj .: "msg"
key' <- obj .: "sessionKey"
ivTxt <- obj .: "iv"
case makeIV . Base64.decodeLenient $ encodeUtf8 ivTxt of
Nothing -> fail "Invalid (IV AES256)"
Just iv -> return Handshake { iv
, sessionKey = EncryptedWith.fromBase64 key'
, msg = EncryptedWith.fromBase64 token'
}
| |
4d59c8a5b68535827bf6043e1fa194acc314553391f614263b18578806b31635 | ocaml-flambda/ocaml-jst | typedecl.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
and , 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. *)
(* *)
(**************************************************************************)
(**** Typing of type definitions ****)
open Misc
open Asttypes
open Parsetree
open Primitive
open Types
open Typetexp
module String = Misc.Stdlib.String
type native_repr_kind = Unboxed | Untagged
type error =
Repeated_parameter
| Duplicate_constructor of string
| Too_many_constructors
| Duplicate_label of string
| Recursive_abbrev of string
| Cycle_in_def of string * type_expr
| Definition_mismatch of type_expr * Env.t * Includecore.type_mismatch option
| Constraint_failed of Env.t * Errortrace.unification_error
| Inconsistent_constraint of Env.t * Errortrace.unification_error
| Type_clash of Env.t * Errortrace.unification_error
| Non_regular of {
definition: Path.t;
used_as: type_expr;
defined_as: type_expr;
expansions: (type_expr * type_expr) list;
}
| Null_arity_external
| Missing_native_external
| Unbound_type_var of type_expr * type_declaration
| Cannot_extend_private_type of Path.t
| Not_extensible_type of Path.t
| Extension_mismatch of Path.t * Env.t * Includecore.type_mismatch
| Rebind_wrong_type of
Longident.t * Env.t * Errortrace.unification_error
| Rebind_mismatch of Longident.t * Path.t * Path.t
| Rebind_private of Longident.t
| Variance of Typedecl_variance.error
| Unavailable_type_constructor of Path.t
| Unbound_type_var_ext of type_expr * extension_constructor
| Val_in_structure
| Multiple_native_repr_attributes
| Cannot_unbox_or_untag_type of native_repr_kind
| Deep_unbox_or_untag_attribute of native_repr_kind
| Immediacy of Typedecl_immediacy.error
| Separability of Typedecl_separability.error
| Bad_unboxed_attribute of string
| Boxed_and_unboxed
| Nonrec_gadt
| Invalid_private_row_declaration of type_expr
| Local_not_enabled
| Global_and_nonlocal
open Typedtree
exception Error of Location.t * error
let get_unboxed_from_attributes sdecl =
let unboxed = Builtin_attributes.has_unboxed sdecl.ptype_attributes in
let boxed = Builtin_attributes.has_boxed sdecl.ptype_attributes in
match boxed, unboxed with
| true, true -> raise (Error(sdecl.ptype_loc, Boxed_and_unboxed))
| true, false -> Some false
| false, true -> Some true
| false, false -> None
(* Enter all declared types in the environment as abstract types *)
let add_type ~check id decl env =
Builtin_attributes.warning_scope ~ppwarning:false decl.type_attributes
(fun () -> Env.add_type ~check id decl env)
let enter_type rec_flag env sdecl (id, uid) =
let needed =
match rec_flag with
| Asttypes.Nonrecursive ->
begin match sdecl.ptype_kind with
| Ptype_variant scds ->
List.iter (fun cd ->
if cd.pcd_res <> None then raise (Error(cd.pcd_loc, Nonrec_gadt)))
scds
| _ -> ()
end;
Btype.is_row_name (Ident.name id)
| Asttypes.Recursive -> true
in
let arity = List.length sdecl.ptype_params in
if not needed then env else
let decl =
{ type_params =
List.map (fun _ -> Btype.newgenvar ()) sdecl.ptype_params;
type_arity = arity;
type_kind = Type_abstract;
type_private = sdecl.ptype_private;
type_manifest =
begin match sdecl.ptype_manifest with None -> None
| Some _ -> Some(Ctype.newvar ()) end;
type_variance = Variance.unknown_signature ~injective:false ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default = false;
type_uid = uid;
}
in
add_type ~check:true id decl env
let update_type temp_env env id loc =
let path = Path.Pident id in
let decl = Env.find_type path temp_env in
match decl.type_manifest with None -> ()
| Some ty ->
let params = List.map (fun _ -> Ctype.newvar ()) decl.type_params in
try Ctype.unify env (Ctype.newconstr path params) ty
with Ctype.Unify err ->
raise (Error(loc, Type_clash (env, err)))
(* Determine if a type's values are represented by floats at run-time. *)
let is_float env ty =
match Typedecl_unboxed.get_unboxed_type_representation env ty with
Some ty' ->
begin match get_desc ty' with
Tconstr(p, _, _) -> Path.same p Predef.path_float
| _ -> false
end
| _ -> false
Determine if a type definition defines a fixed type . ( PW )
let is_fixed_type sd =
let rec has_row_var sty =
match sty.ptyp_desc with
Ptyp_alias (sty, _) -> has_row_var sty
| Ptyp_class _
| Ptyp_object (_, Open)
| Ptyp_variant (_, Open, _)
| Ptyp_variant (_, Closed, Some _) -> true
| _ -> false
in
match sd.ptype_manifest with
None -> false
| Some sty ->
sd.ptype_kind = Ptype_abstract &&
sd.ptype_private = Private &&
has_row_var sty
Set the row variable to a fixed type in a private row type declaration .
( e.g. [ type t = private [ < ` A | ` B ] ] or [ type u = private < .. > ] )
Require [ ] as a precondition
(e.g. [ type t = private [< `A | `B ] ] or [type u = private < .. > ])
Require [is_fixed_type decl] as a precondition
*)
let set_private_row env loc p decl =
let tm =
match decl.type_manifest with
None -> assert false
| Some t -> Ctype.expand_head env t
in
let rv =
match get_desc tm with
Tvariant row ->
let Row {fields; more; closed; name} = row_repr row in
set_type_desc tm
(Tvariant (create_row ~fields ~more ~closed ~name
~fixed:(Some Fixed_private)));
if Btype.static_row row then
(* the syntax hinted at the existence of a row variable,
but there is in fact no row variable to make private, e.g.
[ type t = private [< `A > `A] ] *)
raise (Error(loc, Invalid_private_row_declaration tm))
else more
| Tobject (ty, _) ->
let r = snd (Ctype.flatten_fields ty) in
if not (Btype.is_Tvar r) then
(* a syntactically open object was closed by a constraint *)
raise (Error(loc, Invalid_private_row_declaration tm));
r
| _ -> assert false
in
set_type_desc rv (Tconstr (p, decl.type_params, ref Mnil))
Translate one type declaration
let make_params env params =
let make_param (sty, v) =
try
(transl_type_param env sty, v)
with Already_bound ->
raise(Error(sty.ptyp_loc, Repeated_parameter))
in
List.map make_param params
let transl_global_flags loc attrs =
let transl_global_flag loc (r : (bool,unit) result) =
match r with
| Ok b -> b
| Error () -> raise(Error(loc, Local_not_enabled))
in
let global = transl_global_flag loc (Builtin_attributes.has_global attrs) in
let nonlocal = transl_global_flag loc (Builtin_attributes.has_nonlocal attrs) in
match global, nonlocal with
| true, true -> raise(Error(loc, Global_and_nonlocal))
| true, false -> Types.Global
| false, true -> Types.Nonlocal
| false, false -> Types.Unrestricted
let transl_labels env univars closed lbls =
assert (lbls <> []);
let all_labels = ref String.Set.empty in
List.iter
(fun {pld_name = {txt=name; loc}} ->
if String.Set.mem name !all_labels then
raise(Error(loc, Duplicate_label name));
all_labels := String.Set.add name !all_labels)
lbls;
let mk {pld_name=name;pld_mutable=mut;pld_type=arg;pld_loc=loc;
pld_attributes=attrs} =
Builtin_attributes.warning_scope attrs
(fun () ->
let arg = Ast_helper.Typ.force_poly arg in
let cty = transl_simple_type env ?univars ~closed Global arg in
let gbl =
match mut with
| Mutable -> Types.Global
| Immutable -> transl_global_flags loc attrs
in
{ld_id = Ident.create_local name.txt;
ld_name = name; ld_mutable = mut; ld_global = gbl;
ld_type = cty; ld_loc = loc; ld_attributes = attrs}
)
in
let lbls = List.map mk lbls in
let lbls' =
List.map
(fun ld ->
let ty = ld.ld_type.ctyp_type in
let ty = match get_desc ty with Tpoly(t,[]) -> t | _ -> ty in
{Types.ld_id = ld.ld_id;
ld_mutable = ld.ld_mutable;
ld_global = ld.ld_global;
ld_type = ty;
ld_loc = ld.ld_loc;
ld_attributes = ld.ld_attributes;
ld_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
)
lbls in
lbls, lbls'
let transl_types_gf env univars closed tyl =
let mk arg =
let cty = transl_simple_type env ?univars ~closed Global arg in
let gf = transl_global_flags arg.ptyp_loc arg.ptyp_attributes in
(cty, gf)
in
let tyl_gfl = List.map mk tyl in
let tyl_gfl' = List.map (fun (cty, gf) -> cty.ctyp_type, gf) tyl_gfl in
tyl_gfl, tyl_gfl'
let transl_constructor_arguments env univars closed = function
| Pcstr_tuple l ->
let flds, flds' = transl_types_gf env univars closed l in
Types.Cstr_tuple flds',
Cstr_tuple flds
| Pcstr_record l ->
let lbls, lbls' = transl_labels env univars closed l in
Types.Cstr_record lbls',
Cstr_record lbls
let make_constructor env loc type_path type_params svars sargs sret_type =
match sret_type with
| None ->
let args, targs =
transl_constructor_arguments env None true sargs
in
targs, None, args, None
| Some sret_type -> TyVarEnv.with_local_scope begin fun () ->
(* if it's a generalized constructor we must work in a narrowed
context so as to not introduce any new constraints *)
TyVarEnv.reset ();
let univars, closed =
match svars with
| [] -> None, false
| vs ->
Ctype.begin_def();
Some (TyVarEnv.make_poly_univars (List.map (fun v -> v.txt) vs)), true
in
let args, targs =
transl_constructor_arguments env univars closed sargs
in
let tret_type = transl_simple_type env ?univars ~closed Global sret_type in
let ret_type = tret_type.ctyp_type in
TODO add back type_path as a parameter ?
begin match get_desc ret_type with
| Tconstr (p', _, _) when Path.same type_path p' -> ()
| _ ->
let trace =
Expansion is not helpful here -- the restriction on GADT return
types is purely syntactic . ( In the worst case , expansion
produces gibberish . )
types is purely syntactic. (In the worst case, expansion
produces gibberish.) *)
[Ctype.unexpanded_diff
~got:ret_type
~expected:(Ctype.newconstr type_path type_params)]
in
raise (Error(sret_type.ptyp_loc,
Constraint_failed(env,
Errortrace.unification_error ~trace)))
end;
begin match univars with
| None -> ()
| Some univars ->
Ctype.end_def();
Btype.iter_type_expr_cstr_args Ctype.generalize args;
Ctype.generalize ret_type;
let _vars = TyVarEnv.instance_poly_univars env loc univars in
let set_level t = Ctype.unify_var env (Ctype.newvar()) t in
Btype.iter_type_expr_cstr_args set_level args;
set_level ret_type;
end;
targs, Some tret_type, args, Some ret_type
end
let transl_declaration env sdecl (id, uid) =
(* Bind type parameters *)
TyVarEnv.reset ();
Ctype.begin_def ();
let tparams = make_params env sdecl.ptype_params in
let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
let cstrs = List.map
(fun (sty, sty', loc) ->
transl_simple_type env ~closed:false Global sty,
transl_simple_type env ~closed:false Global sty', loc)
sdecl.ptype_cstrs
in
let unboxed_attr = get_unboxed_from_attributes sdecl in
begin match unboxed_attr with
| (None | Some false) -> ()
| Some true ->
let bad msg = raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute msg)) in
match sdecl.ptype_kind with
| Ptype_abstract -> bad "it is abstract"
| Ptype_open -> bad "extensible variant types cannot be unboxed"
| Ptype_record fields -> begin match fields with
| [] -> bad "it has no fields"
| _::_::_ -> bad "it has more than one field"
| [{pld_mutable = Mutable}] -> bad "it is mutable"
| [{pld_mutable = Immutable}] -> ()
end
| Ptype_variant constructors -> begin match constructors with
| [] -> bad "it has no constructor"
| (_::_::_) -> bad "it has more than one constructor"
| [c] -> begin match c.pcd_args with
| Pcstr_tuple [] ->
bad "its constructor has no argument"
| Pcstr_tuple (_::_::_) ->
bad "its constructor has more than one argument"
| Pcstr_tuple [_] ->
()
| Pcstr_record [] ->
bad "its constructor has no fields"
| Pcstr_record (_::_::_) ->
bad "its constructor has more than one field"
| Pcstr_record [{pld_mutable = Mutable}] ->
bad "it is mutable"
| Pcstr_record [{pld_mutable = Immutable}] ->
()
end
end
end;
let unbox, unboxed_default =
match sdecl.ptype_kind with
| Ptype_variant [{pcd_args = Pcstr_tuple [_]; _}]
| Ptype_variant [{pcd_args = Pcstr_record [{pld_mutable=Immutable; _}]; _}]
| Ptype_record [{pld_mutable=Immutable; _}] ->
Option.value unboxed_attr ~default:!Clflags.unboxed_types,
Option.is_none unboxed_attr
| _ -> false, false (* Not unboxable, mark as boxed *)
in
let (tkind, kind) =
match sdecl.ptype_kind with
| Ptype_abstract -> Ttype_abstract, Type_abstract
| Ptype_variant scstrs ->
if List.exists (fun cstr -> cstr.pcd_res <> None) scstrs then begin
match cstrs with
[] -> ()
| (_,_,loc)::_ ->
Location.prerr_warning loc Warnings.Constraint_on_gadt
end;
let all_constrs = ref String.Set.empty in
List.iter
(fun {pcd_name = {txt = name}} ->
if String.Set.mem name !all_constrs then
raise(Error(sdecl.ptype_loc, Duplicate_constructor name));
all_constrs := String.Set.add name !all_constrs)
scstrs;
if List.length
(List.filter (fun cd -> cd.pcd_args <> Pcstr_tuple []) scstrs)
> (Config.max_tag + 1) then
raise(Error(sdecl.ptype_loc, Too_many_constructors));
let make_cstr scstr =
let name = Ident.create_local scstr.pcd_name.txt in
let targs, tret_type, args, ret_type =
make_constructor env scstr.pcd_loc (Path.Pident id) params
scstr.pcd_vars scstr.pcd_args scstr.pcd_res
in
let tcstr =
{ cd_id = name;
cd_name = scstr.pcd_name;
cd_vars = scstr.pcd_vars;
cd_args = targs;
cd_res = tret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = scstr.pcd_attributes }
in
let cstr =
{ Types.cd_id = name;
cd_args = args;
cd_res = ret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = scstr.pcd_attributes;
cd_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) }
in
tcstr, cstr
in
let make_cstr scstr =
Builtin_attributes.warning_scope scstr.pcd_attributes
(fun () -> make_cstr scstr)
in
let rep = if unbox then Variant_unboxed else Variant_regular in
let tcstrs, cstrs = List.split (List.map make_cstr scstrs) in
Ttype_variant tcstrs, Type_variant (cstrs, rep)
| Ptype_record lbls ->
let lbls, lbls' = transl_labels env None true lbls in
let rep =
if unbox then Record_unboxed false
else if List.for_all (fun l -> is_float env l.Types.ld_type) lbls'
then Record_float
else Record_regular
in
Ttype_record lbls, Type_record(lbls', rep)
| Ptype_open -> Ttype_open, Type_open
in
let (tman, man) = match sdecl.ptype_manifest with
None -> None, None
| Some sty ->
let no_row = not (is_fixed_type sdecl) in
let cty = transl_simple_type env ~closed:no_row Global sty in
Some cty, Some cty.ctyp_type
in
let arity = List.length params in
let decl =
{ type_params = params;
type_arity = arity;
type_kind = kind;
type_private = sdecl.ptype_private;
type_manifest = man;
type_variance = Variance.unknown_signature ~injective:false ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default = unboxed_default;
type_uid = uid;
} in
(* Check constraints *)
List.iter
(fun (cty, cty', loc) ->
let ty = cty.ctyp_type in
let ty' = cty'.ctyp_type in
try Ctype.unify env ty ty' with Ctype.Unify err ->
raise(Error(loc, Inconsistent_constraint (env, err))))
cstrs;
Ctype.end_def ();
(* Add abstract row *)
if is_fixed_type sdecl then begin
let p, _ =
try Env.find_type_by_name
(Longident.Lident(Ident.name id ^ "#row")) env
with Not_found -> assert false
in
set_private_row env sdecl.ptype_loc p decl
end;
{
typ_id = id;
typ_name = sdecl.ptype_name;
typ_params = tparams;
typ_type = decl;
typ_cstrs = cstrs;
typ_loc = sdecl.ptype_loc;
typ_manifest = tman;
typ_kind = tkind;
typ_private = sdecl.ptype_private;
typ_attributes = sdecl.ptype_attributes;
}
a type declaration
let generalize_decl decl =
List.iter Ctype.generalize decl.type_params;
Btype.iter_type_expr_kind Ctype.generalize decl.type_kind;
begin match decl.type_manifest with
| None -> ()
| Some ty -> Ctype.generalize ty
end
(* Check that all constraints are enforced *)
module TypeSet = Btype.TypeSet
module TypeMap = Btype.TypeMap
let rec check_constraints_rec env loc visited ty =
if TypeSet.mem ty !visited then () else begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tconstr (path, args, _) ->
let decl =
try Env.find_type path env
with Not_found ->
raise (Error(loc, Unavailable_type_constructor path)) in
let ty' = Ctype.newconstr path (Ctype.instance_list decl.type_params) in
begin
(* We don't expand the error trace because that produces types that
*already* violate the constraints -- we need to report a problem with
the unexpanded types, or we get errors that talk about the same type
twice. This is generally true for constraint errors. *)
try Ctype.matches ~expand_error_trace:false env ty ty'
with Ctype.Matches_failure (env, err) ->
raise (Error(loc, Constraint_failed (env, err)))
end;
List.iter (check_constraints_rec env loc visited) args
| Tpoly (ty, tl) ->
let _, ty = Ctype.instance_poly false tl ty in
check_constraints_rec env loc visited ty
| _ ->
Btype.iter_type_expr (check_constraints_rec env loc visited) ty
end
let check_constraints_labels env visited l pl =
let rec get_loc name = function
[] -> assert false
| pld :: tl ->
if name = pld.pld_name.txt then pld.pld_type.ptyp_loc
else get_loc name tl
in
List.iter
(fun {Types.ld_id=name; ld_type=ty} ->
check_constraints_rec env (get_loc (Ident.name name) pl) visited ty)
l
let check_constraints env sdecl (_, decl) =
let visited = ref TypeSet.empty in
List.iter2
(fun (sty, _) ty -> check_constraints_rec env sty.ptyp_loc visited ty)
sdecl.ptype_params decl.type_params;
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant (l, _rep) ->
let find_pl = function
Ptype_variant pl -> pl
| Ptype_record _ | Ptype_abstract | Ptype_open -> assert false
in
let pl = find_pl sdecl.ptype_kind in
let pl_index =
let foldf acc x =
String.Map.add x.pcd_name.txt x acc
in
List.fold_left foldf String.Map.empty pl
in
List.iter
(fun {Types.cd_id=name; cd_args; cd_res} ->
let {pcd_args; pcd_res; _} =
try String.Map.find (Ident.name name) pl_index
with Not_found -> assert false in
begin match cd_args, pcd_args with
| Cstr_tuple tyl, Pcstr_tuple styl ->
List.iter2
(fun sty (ty, _) ->
check_constraints_rec env sty.ptyp_loc visited ty)
styl tyl
| Cstr_record tyl, Pcstr_record styl ->
check_constraints_labels env visited tyl styl
| _ -> assert false
end;
match pcd_res, cd_res with
| Some sr, Some r ->
check_constraints_rec env sr.ptyp_loc visited r
| _ ->
() )
l
| Type_record (l, _) ->
let find_pl = function
Ptype_record pl -> pl
| Ptype_variant _ | Ptype_abstract | Ptype_open -> assert false
in
let pl = find_pl sdecl.ptype_kind in
check_constraints_labels env visited l pl
| Type_open -> ()
end;
begin match decl.type_manifest with
| None -> ()
| Some ty ->
let sty =
match sdecl.ptype_manifest with Some sty -> sty | _ -> assert false
in
check_constraints_rec env sty.ptyp_loc visited ty
end
(*
If both a variant/record definition and a type equation are given,
need to check that the equation refers to a type of the same kind
with the same constructors and labels.
*)
let check_coherence env loc dpath decl =
match decl with
{ type_kind = (Type_variant _ | Type_record _| Type_open);
type_manifest = Some ty } ->
begin match get_desc ty with
Tconstr(path, args, _) ->
begin try
let decl' = Env.find_type path env in
let err =
if List.length args <> List.length decl.type_params
then Some Includecore.Arity
else begin
match Ctype.equal env false args decl.type_params with
| exception Ctype.Equality err ->
Some (Includecore.Constraint err)
| () ->
Includecore.type_declarations ~loc ~equality:true env
~mark:true
(Path.last path)
decl'
dpath
(Subst.type_declaration
(Subst.add_type_path dpath path Subst.identity) decl)
end
in
if err <> None then
raise(Error(loc, Definition_mismatch (ty, env, err)))
with Not_found ->
raise(Error(loc, Unavailable_type_constructor path))
end
| _ -> raise(Error(loc, Definition_mismatch (ty, env, None)))
end
| _ -> ()
let check_abbrev env sdecl (id, decl) =
check_coherence env sdecl.ptype_loc (Path.Pident id) decl
(* Check that recursion is well-founded *)
let check_well_founded env loc path to_check ty =
let visited = ref TypeMap.empty in
let rec check ty0 parents ty =
if TypeSet.mem ty parents then begin
(*Format.eprintf "@[%a@]@." Printtyp.raw_type_expr ty;*)
if match get_desc ty0 with
| Tconstr (p, _, _) -> Path.same p path
| _ -> false
then raise (Error (loc, Recursive_abbrev (Path.name path)))
else raise (Error (loc, Cycle_in_def (Path.name path, ty0)))
end;
let (fini, parents) =
try
let prev = TypeMap.find ty !visited in
if TypeSet.subset parents prev then (true, parents) else
(false, TypeSet.union parents prev)
with Not_found ->
(false, parents)
in
if fini then () else
let rec_ok =
match get_desc ty with
Tconstr(p,_,_) ->
!Clflags.recursive_types && Ctype.is_contractive env p
| Tobject _ | Tvariant _ -> true
| _ -> !Clflags.recursive_types
in
let visited' = TypeMap.add ty parents !visited in
let arg_exn =
try
visited := visited';
let parents =
if rec_ok then TypeSet.empty else TypeSet.add ty parents in
Btype.iter_type_expr (check ty0 parents) ty;
None
with e ->
visited := visited'; Some e
in
match get_desc ty with
| Tconstr(p, _, _) when arg_exn <> None || to_check p ->
if to_check p then Option.iter raise arg_exn
else Btype.iter_type_expr (check ty0 TypeSet.empty) ty;
begin try
let ty' = Ctype.try_expand_once_opt env ty in
let ty0 = if TypeSet.is_empty parents then ty else ty0 in
check ty0 (TypeSet.add ty parents) ty'
with
Ctype.Cannot_expand -> Option.iter raise arg_exn
end
| _ -> Option.iter raise arg_exn
in
let snap = Btype.snapshot () in
try Ctype.wrap_trace_gadt_instances env (check ty TypeSet.empty) ty
with Ctype.Escape _ ->
(* Will be detected by check_recursion *)
Btype.backtrack snap
let check_well_founded_manifest env loc path decl =
if decl.type_manifest = None then () else
let args = List.map (fun _ -> Ctype.newvar()) decl.type_params in
check_well_founded env loc path (Path.same path) (Ctype.newconstr path args)
let check_well_founded_decl env loc path decl to_check =
let open Btype in
let it =
{type_iterators with
it_type_expr = (fun _ -> check_well_founded env loc path to_check)} in
it.it_type_declaration it (Ctype.generic_instance_declaration decl)
Check for ill - defined
let check_recursion ~orig_env env loc path decl to_check =
to_check is true for potentially mutually recursive paths .
( path , ) is the type declaration to be checked .
(path, decl) is the type declaration to be checked. *)
if decl.type_params = [] then () else
let visited = ref TypeSet.empty in
let rec check_regular cpath args prev_exp prev_expansions ty =
if not (TypeSet.mem ty !visited) then begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tconstr(path', args', _) ->
if Path.same path path' then begin
if not (Ctype.is_equal orig_env false args args') then
raise (Error(loc,
Non_regular {
definition=path;
used_as=ty;
defined_as=Ctype.newconstr path args;
expansions=List.rev prev_expansions;
}))
end
(* Attempt to expand a type abbreviation if:
1- [to_check path'] holds
(otherwise the expansion cannot involve [path]);
2- we haven't expanded this type constructor before
(otherwise we could loop if [path'] is itself
a non-regular abbreviation). *)
else if to_check path' && not (List.mem path' prev_exp) then begin
try
(* Attempt expansion *)
let (params0, body0, _) = Env.find_type_expansion path' env in
let (params, body) =
Ctype.instance_parameterized_type params0 body0 in
begin
try List.iter2 (Ctype.unify orig_env) params args'
with Ctype.Unify err ->
raise (Error(loc, Constraint_failed (orig_env, err)));
end;
check_regular path' args
(path' :: prev_exp) ((ty,body) :: prev_expansions)
body
with Not_found -> ()
end;
List.iter (check_regular cpath args prev_exp prev_expansions) args'
| Tpoly (ty, tl) ->
let (_, ty) = Ctype.instance_poly ~keep_names:true false tl ty in
check_regular cpath args prev_exp prev_expansions ty
| _ ->
Btype.iter_type_expr
(check_regular cpath args prev_exp prev_expansions) ty
end in
Option.iter
(fun body ->
let (args, body) =
Ctype.instance_parameterized_type
~keep_names:true decl.type_params body in
List.iter (check_regular path args [] []) args;
check_regular path args [] [] body)
decl.type_manifest
let check_abbrev_recursion ~orig_env env id_loc_list to_check tdecl =
let decl = tdecl.typ_type in
let id = tdecl.typ_id in
check_recursion ~orig_env env (List.assoc id id_loc_list) (Path.Pident id)
decl to_check
let check_duplicates sdecl_list =
let labels = Hashtbl.create 7 and constrs = Hashtbl.create 7 in
List.iter
(fun sdecl -> match sdecl.ptype_kind with
Ptype_variant cl ->
List.iter
(fun pcd ->
try
let name' = Hashtbl.find constrs pcd.pcd_name.txt in
Location.prerr_warning pcd.pcd_loc
(Warnings.Duplicate_definitions
("constructor", pcd.pcd_name.txt, name',
sdecl.ptype_name.txt))
with Not_found ->
Hashtbl.add constrs pcd.pcd_name.txt sdecl.ptype_name.txt)
cl
| Ptype_record fl ->
List.iter
(fun {pld_name=cname;pld_loc=loc} ->
try
let name' = Hashtbl.find labels cname.txt in
Location.prerr_warning loc
(Warnings.Duplicate_definitions
("label", cname.txt, name', sdecl.ptype_name.txt))
with Not_found -> Hashtbl.add labels cname.txt sdecl.ptype_name.txt)
fl
| Ptype_abstract -> ()
| Ptype_open -> ())
sdecl_list
Force recursion to go through i d for private types
let name_recursion sdecl id decl =
match decl with
| { type_kind = Type_abstract;
type_manifest = Some ty;
type_private = Private; } when is_fixed_type sdecl ->
let ty' = newty2 ~level:(get_level ty) (get_desc ty) in
if Ctype.deep_occur ty ty' then
let td = Tconstr(Path.Pident id, decl.type_params, ref Mnil) in
link_type ty (newty2 ~level:(get_level ty) td);
{decl with type_manifest = Some ty'}
else decl
| _ -> decl
let name_recursion_decls sdecls decls =
List.map2 (fun sdecl (id, decl) -> (id, name_recursion sdecl id decl))
sdecls decls
(* Warn on definitions of type "type foo = ()" which redefine a different unit
type and are likely a mistake. *)
let check_redefined_unit (td: Parsetree.type_declaration) =
let open Parsetree in
let is_unit_constructor cd = cd.pcd_name.txt = "()" in
match td with
| { ptype_name = { txt = name };
ptype_manifest = None;
ptype_kind = Ptype_variant [ cd ] }
when is_unit_constructor cd ->
Location.prerr_warning td.ptype_loc (Warnings.Redefining_unit name)
| _ ->
()
let add_types_to_env decls env =
List.fold_right
(fun (id, decl) env -> add_type ~check:true id decl env)
decls env
(* Translate a set of type declarations, mutually recursive or not *)
let transl_type_decl env rec_flag sdecl_list =
List.iter check_redefined_unit sdecl_list;
(* Add dummy types for fixed rows *)
let fixed_types = List.filter is_fixed_type sdecl_list in
let sdecl_list =
List.map
(fun sdecl ->
let ptype_name =
let loc = { sdecl.ptype_name.loc with Location.loc_ghost = true } in
mkloc (sdecl.ptype_name.txt ^"#row") loc
in
let ptype_kind = Ptype_abstract in
let ptype_manifest = None in
let ptype_loc = { sdecl.ptype_loc with Location.loc_ghost = true } in
{sdecl with
ptype_name; ptype_kind; ptype_manifest; ptype_loc })
fixed_types
@ sdecl_list
in
(* Create identifiers. *)
let scope = Ctype.create_scope () in
let ids_list =
List.map (fun sdecl ->
Ident.create_scoped ~scope sdecl.ptype_name.txt,
Uid.mk ~current_unit:(Env.get_unit_name ())
) sdecl_list
in
Ctype.begin_def();
(* Enter types. *)
let temp_env =
List.fold_left2 (enter_type rec_flag) env sdecl_list ids_list in
(* Translate each declaration. *)
let current_slot = ref None in
let warn_unused = Warnings.is_active (Warnings.Unused_type_declaration "") in
let ids_slots (id, _uid as ids) =
match rec_flag with
| Asttypes.Recursive when warn_unused ->
(* See typecore.ml for a description of the algorithm used
to detect unused declarations in a set of recursive definitions. *)
let slot = ref [] in
let td = Env.find_type (Path.Pident id) temp_env in
Env.set_type_used_callback
td
(fun old_callback ->
match !current_slot with
| Some slot -> slot := td.type_uid :: !slot
| None ->
List.iter Env.mark_type_used (get_ref slot);
old_callback ()
);
ids, Some slot
| Asttypes.Recursive | Asttypes.Nonrecursive ->
ids, None
in
let transl_declaration name_sdecl (id, slot) =
current_slot := slot;
Builtin_attributes.warning_scope
name_sdecl.ptype_attributes
(fun () -> transl_declaration temp_env name_sdecl id)
in
let tdecls =
List.map2 transl_declaration sdecl_list (List.map ids_slots ids_list) in
let decls =
List.map (fun tdecl -> (tdecl.typ_id, tdecl.typ_type)) tdecls in
current_slot := None;
(* Check for duplicates *)
check_duplicates sdecl_list;
(* Build the final env. *)
let new_env = add_types_to_env decls env in
(* Update stubs *)
begin match rec_flag with
| Asttypes.Nonrecursive -> ()
| Asttypes.Recursive ->
List.iter2
(fun (id, _) sdecl -> update_type temp_env new_env id sdecl.ptype_loc)
ids_list sdecl_list
end;
Generalize type declarations .
Ctype.end_def();
List.iter (fun (_, decl) -> generalize_decl decl) decls;
Check for ill - formed
let id_loc_list =
List.map2 (fun (id, _) sdecl -> (id, sdecl.ptype_loc))
ids_list sdecl_list
in
List.iter (fun (id, decl) ->
check_well_founded_manifest new_env (List.assoc id id_loc_list)
(Path.Pident id) decl)
decls;
let to_check =
function Path.Pident id -> List.mem_assoc id id_loc_list | _ -> false in
List.iter (fun (id, decl) ->
check_well_founded_decl new_env (List.assoc id id_loc_list) (Path.Pident id)
decl to_check)
decls;
List.iter
(check_abbrev_recursion ~orig_env:env new_env id_loc_list to_check) tdecls;
(* Check that all type variables are closed *)
List.iter2
(fun sdecl tdecl ->
let decl = tdecl.typ_type in
match Ctype.closed_type_decl decl with
Some ty -> raise(Error(sdecl.ptype_loc, Unbound_type_var(ty,decl)))
| None -> ())
sdecl_list tdecls;
(* Check that constraints are enforced *)
List.iter2 (check_constraints new_env) sdecl_list decls;
(* Add type properties to declarations *)
let decls =
try
decls
|> name_recursion_decls sdecl_list
|> Typedecl_variance.update_decls env sdecl_list
|> Typedecl_immediacy.update_decls env
|> Typedecl_separability.update_decls env
with
| Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err))
| Typedecl_immediacy.Error (loc, err) ->
raise (Error (loc, Immediacy err))
| Typedecl_separability.Error (loc, err) ->
raise (Error (loc, Separability err))
in
(* Compute the final environment with variance and immediacy *)
let final_env = add_types_to_env decls env in
(* Check re-exportation *)
List.iter2 (check_abbrev final_env) sdecl_list decls;
(* Keep original declaration *)
let final_decls =
List.map2
(fun tdecl (_id2, decl) ->
{ tdecl with typ_type = decl }
) tdecls decls
in
(* Done *)
(final_decls, final_env)
(* Translating type extensions *)
let transl_extension_constructor ~scope env type_path type_params
typext_params priv sext =
let id = Ident.create_scoped ~scope sext.pext_name.txt in
let args, ret_type, kind =
match sext.pext_kind with
Pext_decl(svars, sargs, sret_type) ->
let targs, tret_type, args, ret_type =
make_constructor env sext.pext_loc type_path typext_params
svars sargs sret_type
in
args, ret_type, Text_decl(svars, targs, tret_type)
| Pext_rebind lid ->
let usage : Env.constructor_usage =
if priv = Public then Env.Exported else Env.Exported_private
in
let cdescr = Env.lookup_constructor ~loc:lid.loc usage lid.txt env in
let (args, cstr_res, _ex) = Ctype.instance_constructor cdescr in
let res, ret_type =
if cdescr.cstr_generalized then
let params = Ctype.instance_list type_params in
let res = Ctype.newconstr type_path params in
let ret_type = Some (Ctype.newconstr type_path params) in
res, ret_type
else (Ctype.newconstr type_path typext_params), None
in
begin
try
Ctype.unify env cstr_res res
with Ctype.Unify err ->
raise (Error(lid.loc,
Rebind_wrong_type(lid.txt, env, err)))
end;
(* Remove "_" names from parameters used in the constructor *)
if not cdescr.cstr_generalized then begin
let vars =
Ctype.free_variables (Btype.newgenty (Ttuple (List.map fst args)))
in
List.iter
(fun ty ->
if get_desc ty = Tvar (Some "_")
&& List.exists (eq_type ty) vars
then set_type_desc ty (Tvar None))
typext_params
end;
(* Ensure that constructor's type matches the type being extended *)
let cstr_type_path = Btype.cstr_type_path cdescr in
let cstr_type_params = (Env.find_type cstr_type_path env).type_params in
let cstr_types =
(Btype.newgenty
(Tconstr(cstr_type_path, cstr_type_params, ref Mnil)))
:: cstr_type_params
in
let ext_types =
(Btype.newgenty
(Tconstr(type_path, type_params, ref Mnil)))
:: type_params
in
if not (Ctype.is_equal env true cstr_types ext_types) then
raise (Error(lid.loc,
Rebind_mismatch(lid.txt, cstr_type_path, type_path)));
(* Disallow rebinding private constructors to non-private *)
begin
match cdescr.cstr_private, priv with
Private, Public ->
raise (Error(lid.loc, Rebind_private lid.txt))
| _ -> ()
end;
let path =
match cdescr.cstr_tag with
Cstr_extension(path, _) -> path
| _ -> assert false
in
let args =
match cdescr.cstr_inlined with
| None ->
Types.Cstr_tuple args
| Some decl ->
let tl =
match List.map (fun (ty, _) -> get_desc ty) args with
| [ Tconstr(_, tl, _) ] -> tl
| _ -> assert false
in
let decl = Ctype.instance_declaration decl in
assert (List.length decl.type_params = List.length tl);
List.iter2 (Ctype.unify env) decl.type_params tl;
let lbls =
match decl.type_kind with
| Type_record (lbls, Record_extension _) -> lbls
| _ -> assert false
in
Types.Cstr_record lbls
in
args, ret_type, Text_rebind(path, lid)
in
let ext =
{ ext_type_path = type_path;
ext_type_params = typext_params;
ext_args = args;
ext_ret_type = ret_type;
ext_private = priv;
Types.ext_loc = sext.pext_loc;
Types.ext_attributes = sext.pext_attributes;
ext_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
in
{ ext_id = id;
ext_name = sext.pext_name;
ext_type = ext;
ext_kind = kind;
Typedtree.ext_loc = sext.pext_loc;
Typedtree.ext_attributes = sext.pext_attributes; }
let transl_extension_constructor ~scope env type_path type_params
typext_params priv sext =
Builtin_attributes.warning_scope sext.pext_attributes
(fun () -> transl_extension_constructor ~scope env type_path type_params
typext_params priv sext)
let is_rebind ext =
match ext.ext_kind with
| Text_rebind _ -> true
| Text_decl _ -> false
let transl_type_extension extend env loc styext =
Note : it would be incorrect to call [ create_scope ] * after *
[ TyVarEnv.reset ] or after [ begin_def ] ( see # 10010 ) .
[TyVarEnv.reset] or after [begin_def] (see #10010). *)
let scope = Ctype.create_scope () in
TyVarEnv.reset ();
Ctype.begin_def();
let type_path, type_decl =
let lid = styext.ptyext_path in
Env.lookup_type ~loc:lid.loc lid.txt env
in
begin
match type_decl.type_kind with
| Type_open -> begin
match type_decl.type_private with
| Private when extend -> begin
match
List.find
(function {pext_kind = Pext_decl _} -> true
| {pext_kind = Pext_rebind _} -> false)
styext.ptyext_constructors
with
| {pext_loc} ->
raise (Error(pext_loc, Cannot_extend_private_type type_path))
| exception Not_found -> ()
end
| _ -> ()
end
| _ ->
raise (Error(loc, Not_extensible_type type_path))
end;
let type_variance =
List.map (fun v ->
let (co, cn) = Variance.get_upper v in
(not cn, not co, false))
type_decl.type_variance
in
let err =
if type_decl.type_arity <> List.length styext.ptyext_params then
Some Includecore.Arity
else
if List.for_all2
(fun (c1, n1, _) (c2, n2, _) -> (not c2 || c1) && (not n2 || n1))
type_variance
(Typedecl_variance.variance_of_params styext.ptyext_params)
then None else Some Includecore.Variance
in
begin match err with
| None -> ()
| Some err -> raise (Error(loc, Extension_mismatch (type_path, env, err)))
end;
let ttype_params = make_params env styext.ptyext_params in
let type_params = List.map (fun (cty, _) -> cty.ctyp_type) ttype_params in
List.iter2 (Ctype.unify_var env)
(Ctype.instance_list type_decl.type_params)
type_params;
let constructors =
List.map (transl_extension_constructor ~scope env type_path
type_decl.type_params type_params styext.ptyext_private)
styext.ptyext_constructors
in
Ctype.end_def();
types
List.iter Ctype.generalize type_params;
List.iter
(fun ext ->
Btype.iter_type_expr_cstr_args Ctype.generalize ext.ext_type.ext_args;
Option.iter Ctype.generalize ext.ext_type.ext_ret_type)
constructors;
(* Check that all type variables are closed *)
List.iter
(fun ext ->
match Ctype.closed_extension_constructor ext.ext_type with
Some ty ->
raise(Error(ext.ext_loc, Unbound_type_var_ext(ty, ext.ext_type)))
| None -> ())
constructors;
(* Check variances are correct *)
List.iter
(fun ext->
(* Note that [loc] here is distinct from [type_decl.type_loc], which
makes the [loc] parameter to this function useful. [loc] is the
location of the extension, while [type_decl] points to the original
type declaration being extended. *)
try Typedecl_variance.check_variance_extension
env type_decl ext (type_variance, loc)
with Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err)))
constructors;
(* Add extension constructors to the environment *)
let newenv =
List.fold_left
(fun env ext ->
let rebind = is_rebind ext in
Env.add_extension ~check:true ~rebind ext.ext_id ext.ext_type env)
env constructors
in
let tyext =
{ tyext_path = type_path;
tyext_txt = styext.ptyext_path;
tyext_params = ttype_params;
tyext_constructors = constructors;
tyext_private = styext.ptyext_private;
tyext_loc = styext.ptyext_loc;
tyext_attributes = styext.ptyext_attributes; }
in
(tyext, newenv)
let transl_type_extension extend env loc styext =
Builtin_attributes.warning_scope styext.ptyext_attributes
(fun () -> transl_type_extension extend env loc styext)
let transl_exception env sext =
let scope = Ctype.create_scope () in
TyVarEnv.reset ();
Ctype.begin_def();
let ext =
transl_extension_constructor ~scope env
Predef.path_exn [] [] Asttypes.Public sext
in
Ctype.end_def();
types
Btype.iter_type_expr_cstr_args Ctype.generalize ext.ext_type.ext_args;
Option.iter Ctype.generalize ext.ext_type.ext_ret_type;
(* Check that all type variables are closed *)
begin match Ctype.closed_extension_constructor ext.ext_type with
Some ty ->
raise (Error(ext.ext_loc, Unbound_type_var_ext(ty, ext.ext_type)))
| None -> ()
end;
let rebind = is_rebind ext in
let newenv =
Env.add_extension ~check:true ~rebind ext.ext_id ext.ext_type env
in
ext, newenv
let transl_type_exception env t =
let contructor, newenv =
Builtin_attributes.warning_scope t.ptyexn_attributes
(fun () ->
transl_exception env t.ptyexn_constructor
)
in
{tyexn_constructor = contructor;
tyexn_loc = t.ptyexn_loc;
tyexn_attributes = t.ptyexn_attributes}, newenv
type native_repr_attribute =
| Native_repr_attr_absent
| Native_repr_attr_present of native_repr_kind
let get_native_repr_attribute attrs ~global_repr =
match
Attr_helper.get_no_payload_attribute ["unboxed"; "ocaml.unboxed"] attrs,
Attr_helper.get_no_payload_attribute ["untagged"; "ocaml.untagged"] attrs,
global_repr
with
| None, None, None -> Native_repr_attr_absent
| None, None, Some repr -> Native_repr_attr_present repr
| Some _, None, None -> Native_repr_attr_present Unboxed
| None, Some _, None -> Native_repr_attr_present Untagged
| Some { Location.loc }, _, _
| _, Some { Location.loc }, _ ->
raise (Error (loc, Multiple_native_repr_attributes))
let native_repr_of_type env kind ty =
match kind, get_desc (Ctype.expand_head_opt env ty) with
| Untagged, Tconstr (path, _, _) when Path.same path Predef.path_int ->
Some Untagged_int
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_float ->
Some Unboxed_float
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_int32 ->
Some (Unboxed_integer Pint32)
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_int64 ->
Some (Unboxed_integer Pint64)
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_nativeint ->
Some (Unboxed_integer Pnativeint)
| _ ->
None
Raises an error when [ core_type ] contains an [ @unboxed ] or [ @untagged ]
attribute in a strict sub - term .
attribute in a strict sub-term. *)
let error_if_has_deep_native_repr_attributes core_type =
let open Ast_iterator in
let this_iterator =
{ default_iterator with typ = fun iterator core_type ->
begin
match
get_native_repr_attribute core_type.ptyp_attributes ~global_repr:None
with
| Native_repr_attr_present kind ->
raise (Error (core_type.ptyp_loc,
Deep_unbox_or_untag_attribute kind))
| Native_repr_attr_absent -> ()
end;
default_iterator.typ iterator core_type }
in
default_iterator.typ this_iterator core_type
let make_native_repr env core_type ty ~global_repr =
error_if_has_deep_native_repr_attributes core_type;
match get_native_repr_attribute core_type.ptyp_attributes ~global_repr with
| Native_repr_attr_absent ->
Same_as_ocaml_repr
| Native_repr_attr_present kind ->
begin match native_repr_of_type env kind ty with
| None ->
raise (Error (core_type.ptyp_loc, Cannot_unbox_or_untag_type kind))
| Some repr -> repr
end
let prim_const_mode m =
match Types.Alloc_mode.check_const m with
| Some Global -> Prim_global
| Some Local -> Prim_local
| None -> assert false
let rec parse_native_repr_attributes env core_type ty rmode ~global_repr =
match core_type.ptyp_desc, get_desc ty,
get_native_repr_attribute core_type.ptyp_attributes ~global_repr:None
with
| Ptyp_arrow _, Tarrow _, Native_repr_attr_present kind ->
raise (Error (core_type.ptyp_loc, Cannot_unbox_or_untag_type kind))
| Ptyp_arrow (_, ct1, ct2), Tarrow ((_,marg,mret), t1, t2, _), _
when not (Builtin_attributes.has_curry core_type.ptyp_attributes) ->
let t1, _ = Btype.tpoly_get_poly t1 in
let repr_arg = make_native_repr env ct1 t1 ~global_repr in
let mode =
if Builtin_attributes.has_local_opt ct1.ptyp_attributes
then Prim_poly
else prim_const_mode marg
in
let repr_args, repr_res =
parse_native_repr_attributes env ct2 t2 (prim_const_mode mret) ~global_repr
in
((mode,repr_arg) :: repr_args, repr_res)
| (Ptyp_poly (_, t) | Ptyp_alias (t, _)), _, _ ->
parse_native_repr_attributes env t ty rmode ~global_repr
| _ ->
let rmode =
if Builtin_attributes.has_local_opt core_type.ptyp_attributes
then Prim_poly
else rmode
in
([], (rmode, make_native_repr env core_type ty ~global_repr))
let check_unboxable env loc ty =
let rec check_type acc ty : Path.Set.t =
let ty = Ctype.expand_head_opt env ty in
try match get_desc ty with
| Tconstr (p, _, _) ->
let tydecl = Env.find_type p env in
if tydecl.type_unboxed_default then
Path.Set.add p acc
else acc
| Tpoly (ty, []) -> check_type acc ty
| _ -> acc
with Not_found -> acc
in
let all_unboxable_types = Btype.fold_type_expr check_type Path.Set.empty ty in
Path.Set.fold
(fun p () ->
Location.prerr_warning loc
(Warnings.Unboxable_type_in_prim_decl (Path.name p))
)
all_unboxable_types
()
(* Translate a value declaration *)
let transl_value_decl env loc valdecl =
let cty = Typetexp.transl_type_scheme env valdecl.pval_type in
let ty = cty.ctyp_type in
let v =
match valdecl.pval_prim with
[] when Env.is_in_signature env ->
{ val_type = ty; val_kind = Val_reg; Types.val_loc = loc;
val_attributes = valdecl.pval_attributes;
val_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
| [] ->
raise (Error(valdecl.pval_loc, Val_in_structure))
| _ ->
let global_repr =
match
get_native_repr_attribute valdecl.pval_attributes ~global_repr:None
with
| Native_repr_attr_present repr -> Some repr
| Native_repr_attr_absent -> None
in
let native_repr_args, native_repr_res =
parse_native_repr_attributes env valdecl.pval_type ty Prim_global ~global_repr
in
let prim =
Primitive.parse_declaration valdecl
~native_repr_args
~native_repr_res
in
if prim.prim_arity = 0 &&
(prim.prim_name = "" || prim.prim_name.[0] <> '%') then
raise(Error(valdecl.pval_type.ptyp_loc, Null_arity_external));
if !Clflags.native_code
&& prim.prim_arity > 5
&& prim.prim_native_name = ""
then raise(Error(valdecl.pval_type.ptyp_loc, Missing_native_external));
check_unboxable env loc ty;
{ val_type = ty; val_kind = Val_prim prim; Types.val_loc = loc;
val_attributes = valdecl.pval_attributes;
val_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
in
let (id, newenv) =
Env.enter_value valdecl.pval_name.txt v env
~check:(fun s -> Warnings.Unused_value_declaration s)
in
let desc =
{
val_id = id;
val_name = valdecl.pval_name;
val_desc = cty; val_val = v;
val_prim = valdecl.pval_prim;
val_loc = valdecl.pval_loc;
val_attributes = valdecl.pval_attributes;
}
in
desc, newenv
let transl_value_decl env loc valdecl =
Builtin_attributes.warning_scope valdecl.pval_attributes
(fun () -> transl_value_decl env loc valdecl)
Translate a " with " constraint -- much simplified version of
transl_type_decl . For a constraint [ Sig with t = sdecl ] ,
there are two declarations of interest in two environments :
- [ sig_decl ] is the declaration of [ t ] in [ Sig ] ,
in the environment [ sig_env ] ( containing the declarations
of [ Sig ] before [ t ] )
- [ sdecl ] is the new syntactic declaration , to be type - checked
in the current , outer environment [ with_env ] .
In particular , note that [ sig_env ] is an extension of
[ outer_env ] .
transl_type_decl. For a constraint [Sig with t = sdecl],
there are two declarations of interest in two environments:
- [sig_decl] is the declaration of [t] in [Sig],
in the environment [sig_env] (containing the declarations
of [Sig] before [t])
- [sdecl] is the new syntactic declaration, to be type-checked
in the current, outer environment [with_env].
In particular, note that [sig_env] is an extension of
[outer_env].
*)
let transl_with_constraint id ?fixed_row_path ~sig_env ~sig_decl ~outer_env
sdecl =
Env.mark_type_used sig_decl.type_uid;
TyVarEnv.reset ();
Ctype.begin_def();
In the first part of this function , we typecheck the syntactic
declaration [ sdecl ] in the outer environment [ outer_env ] .
declaration [sdecl] in the outer environment [outer_env]. *)
let env = outer_env in
let loc = sdecl.ptype_loc in
let tparams = make_params env sdecl.ptype_params in
let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
let arity = List.length params in
let constraints =
List.map (fun (ty, ty', loc) ->
let cty = transl_simple_type env ~closed:false Global ty in
let cty' = transl_simple_type env ~closed:false Global ty' in
(* Note: We delay the unification of those constraints
after the unification of parameters, so that clashing
constraints report an error on the constraint location
rather than the parameter location. *)
(cty, cty', loc)
) sdecl.ptype_cstrs
in
let no_row = not (is_fixed_type sdecl) in
let (tman, man) = match sdecl.ptype_manifest with
None -> None, None
| Some sty ->
let cty = transl_simple_type env ~closed:no_row Global sty in
Some cty, Some cty.ctyp_type
in
In the second part , we check the consistency between the two
declarations and compute a " merged " declaration ; we now need to
work in the larger signature environment [ sig_env ] , because
[ sig_decl.type_params ] and [ sig_decl.type_kind ] are only valid
there .
declarations and compute a "merged" declaration; we now need to
work in the larger signature environment [sig_env], because
[sig_decl.type_params] and [sig_decl.type_kind] are only valid
there. *)
let env = sig_env in
let sig_decl = Ctype.instance_declaration sig_decl in
let arity_ok = arity = sig_decl.type_arity in
if arity_ok then
List.iter2 (fun (cty, _) tparam ->
try Ctype.unify_var env cty.ctyp_type tparam
with Ctype.Unify err ->
raise(Error(cty.ctyp_loc, Inconsistent_constraint (env, err)))
) tparams sig_decl.type_params;
List.iter (fun (cty, cty', loc) ->
(* Note: constraints must also be enforced in [sig_env] because
they may contain parameter variables from [tparams]
that have now be unified in [sig_env]. *)
try Ctype.unify env cty.ctyp_type cty'.ctyp_type
with Ctype.Unify err ->
raise(Error(loc, Inconsistent_constraint (env, err)))
) constraints;
let priv =
if sdecl.ptype_private = Private then Private else
if arity_ok && sig_decl.type_kind <> Type_abstract
then sig_decl.type_private else sdecl.ptype_private
in
if arity_ok && sig_decl.type_kind <> Type_abstract
&& sdecl.ptype_private = Private then
Location.deprecated loc "spurious use of private";
let type_kind, type_unboxed_default =
if arity_ok && man <> None then
sig_decl.type_kind, sig_decl.type_unboxed_default
else
Type_abstract, false
in
let new_sig_decl =
{ type_params = params;
type_arity = arity;
type_kind;
type_private = priv;
type_manifest = man;
type_variance = [];
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default;
type_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
in
Option.iter (fun p -> set_private_row env sdecl.ptype_loc p new_sig_decl)
fixed_row_path;
begin match Ctype.closed_type_decl new_sig_decl with None -> ()
| Some ty -> raise(Error(loc, Unbound_type_var(ty, new_sig_decl)))
end;
let new_sig_decl = name_recursion sdecl id new_sig_decl in
let new_type_variance =
let required = Typedecl_variance.variance_of_sdecl sdecl in
try
Typedecl_variance.compute_decl env ~check:true new_sig_decl required
with Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err)) in
let new_type_immediate =
(* Typedecl_immediacy.compute_decl never raises *)
Typedecl_immediacy.compute_decl env new_sig_decl in
let new_type_separability =
try Typedecl_separability.compute_decl env new_sig_decl
with Typedecl_separability.Error (loc, err) ->
raise (Error (loc, Separability err)) in
let new_sig_decl =
we intentionally write this without a fragile { decl with ... }
to ensure that people adding new fields to type declarations
consider whether they need to recompute it here ; for an example
of bug caused by the previous approach , see # 9607
to ensure that people adding new fields to type declarations
consider whether they need to recompute it here; for an example
of bug caused by the previous approach, see #9607 *)
{
type_params = new_sig_decl.type_params;
type_arity = new_sig_decl.type_arity;
type_kind = new_sig_decl.type_kind;
type_private = new_sig_decl.type_private;
type_manifest = new_sig_decl.type_manifest;
type_unboxed_default = new_sig_decl.type_unboxed_default;
type_is_newtype = new_sig_decl.type_is_newtype;
type_expansion_scope = new_sig_decl.type_expansion_scope;
type_loc = new_sig_decl.type_loc;
type_attributes = new_sig_decl.type_attributes;
type_uid = new_sig_decl.type_uid;
type_variance = new_type_variance;
type_immediate = new_type_immediate;
type_separability = new_type_separability;
} in
Ctype.end_def();
generalize_decl new_sig_decl;
{
typ_id = id;
typ_name = sdecl.ptype_name;
typ_params = tparams;
typ_type = new_sig_decl;
typ_cstrs = constraints;
typ_loc = loc;
typ_manifest = tman;
typ_kind = Ttype_abstract;
typ_private = sdecl.ptype_private;
typ_attributes = sdecl.ptype_attributes;
}
(* Approximate a type declaration: just make all types abstract *)
let abstract_type_decl ~injective arity =
let rec make_params n =
if n <= 0 then [] else Ctype.newvar() :: make_params (n-1) in
Ctype.begin_def();
let decl =
{ type_params = make_params arity;
type_arity = arity;
type_kind = Type_abstract;
type_private = Public;
type_manifest = None;
type_variance = Variance.unknown_signature ~injective ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = Location.none;
type_attributes = [];
type_immediate = Unknown;
type_unboxed_default = false;
type_uid = Uid.internal_not_actually_unique;
} in
Ctype.end_def();
generalize_decl decl;
decl
let approx_type_decl sdecl_list =
let scope = Ctype.create_scope () in
List.map
(fun sdecl ->
let injective = sdecl.ptype_kind <> Ptype_abstract in
(Ident.create_scoped ~scope sdecl.ptype_name.txt,
abstract_type_decl ~injective (List.length sdecl.ptype_params)))
sdecl_list
(* Variant of check_abbrev_recursion to check the well-formedness
conditions on type abbreviations defined within recursive modules. *)
let check_recmod_typedecl env loc recmod_ids path decl =
recmod_ids is the list of recursively - defined module idents .
( path , ) is the type declaration to be checked .
(path, decl) is the type declaration to be checked. *)
let to_check path = Path.exists_free recmod_ids path in
check_well_founded_decl env loc path decl to_check;
check_recursion ~orig_env:env env loc path decl to_check;
(* additionally check coherece, as one might build an incoherent signature,
and use it to build an incoherent module, cf. #7851 *)
check_coherence env loc path decl
(**** Error report ****)
open Format
let explain_unbound_gen ppf tv tl typ kwd pr =
try
let ti = List.find (fun ti -> Ctype.deep_occur tv (typ ti)) tl in
let ty0 = (* Hack to force aliasing when needed *)
Btype.newgenty (Tobject(tv, ref None)) in
Printtyp.prepare_for_printing [typ ti; ty0];
fprintf ppf
".@ @[<hov2>In %s@ %a@;<1 -2>the variable %a is unbound@]"
kwd pr ti Printtyp.prepared_type_expr tv
with Not_found -> ()
let explain_unbound ppf tv tl typ kwd lab =
explain_unbound_gen ppf tv tl typ kwd
(fun ppf ti ->
fprintf ppf "%s%a" (lab ti) Printtyp.prepared_type_expr (typ ti)
)
let explain_unbound_single ppf tv ty =
let trivial ty =
explain_unbound ppf tv [ty] (fun t -> t) "type" (fun _ -> "") in
match get_desc ty with
Tobject(fi,_) ->
let (tl, rv) = Ctype.flatten_fields fi in
if eq_type rv tv then trivial ty else
explain_unbound ppf tv tl (fun (_,_,t) -> t)
"method" (fun (lab,_,_) -> lab ^ ": ")
| Tvariant row ->
if eq_type (row_more row) tv then trivial ty else
explain_unbound ppf tv (row_fields row)
(fun (_l,f) -> match row_field_repr f with
Rpresent (Some t) -> t
| Reither (_,[t],_) -> t
| Reither (_,tl,_) -> Btype.newgenty (Ttuple tl)
| _ -> Btype.newgenty (Ttuple[]))
"case" (fun (lab,_) -> "`" ^ lab ^ " of ")
| _ -> trivial ty
let tys_of_constr_args = function
| Types.Cstr_tuple tl -> List.map fst tl
| Types.Cstr_record lbls -> List.map (fun l -> l.Types.ld_type) lbls
let report_error ppf = function
| Repeated_parameter ->
fprintf ppf "A type parameter occurs several times"
| Duplicate_constructor s ->
fprintf ppf "Two constructors are named %s" s
| Too_many_constructors ->
fprintf ppf
"@[Too many non-constant constructors@ -- maximum is %i %s@]"
(Config.max_tag + 1) "non-constant constructors"
| Duplicate_label s ->
fprintf ppf "Two labels are named %s" s
| Recursive_abbrev s ->
fprintf ppf "The type abbreviation %s is cyclic" s
| Cycle_in_def (s, ty) ->
fprintf ppf "@[<v>The definition of %s contains a cycle:@ %a@]"
s Printtyp.type_expr ty
| Definition_mismatch (ty, _env, None) ->
fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%a@]@]"
"This variant or record definition" "does not match that of type"
Printtyp.type_expr ty
| Definition_mismatch (ty, env, Some err) ->
fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%a@]%a@]"
"This variant or record definition" "does not match that of type"
Printtyp.type_expr ty
(Includecore.report_type_mismatch
"the original" "this" "definition" env)
err
| Constraint_failed (env, err) ->
fprintf ppf "@[<v>Constraints are not satisfied in this type.@ ";
Printtyp.report_unification_error ppf env err
(fun ppf -> fprintf ppf "Type")
(fun ppf -> fprintf ppf "should be an instance of");
fprintf ppf "@]"
| Non_regular { definition; used_as; defined_as; expansions } ->
let pp_expansion ppf (ty,body) =
Format.fprintf ppf "%a = %a"
Printtyp.type_expr ty
Printtyp.type_expr body in
let comma ppf () = Format.fprintf ppf ",@;<1 2>" in
let pp_expansions ppf expansions =
Format.(pp_print_list ~pp_sep:comma pp_expansion) ppf expansions in
Printtyp.prepare_for_printing [used_as; defined_as];
Printtyp.Naming_context.reset ();
begin match expansions with
| [] ->
fprintf ppf
"@[<hv>This recursive type is not regular.@ \
The type constructor %s is defined as@;<1 2>type %a@ \
but it is used as@;<1 2>%a.@ \
All uses need to match the definition for the recursive type \
to be regular.@]"
(Path.name definition)
!Oprint.out_type (Printtyp.tree_of_typexp Type defined_as)
!Oprint.out_type (Printtyp.tree_of_typexp Type used_as)
| _ :: _ ->
fprintf ppf
"@[<hv>This recursive type is not regular.@ \
The type constructor %s is defined as@;<1 2>type %a@ \
but it is used as@;<1 2>%a@ \
after the following expansion(s):@;<1 2>%a@ \
All uses need to match the definition for the recursive type \
to be regular.@]"
(Path.name definition)
!Oprint.out_type (Printtyp.tree_of_typexp Type defined_as)
!Oprint.out_type (Printtyp.tree_of_typexp Type used_as)
pp_expansions expansions
end
| Inconsistent_constraint (env, err) ->
fprintf ppf "@[<v>The type constraints are not consistent.@ ";
Printtyp.report_unification_error ppf env err
(fun ppf -> fprintf ppf "Type")
(fun ppf -> fprintf ppf "is not compatible with type");
fprintf ppf "@]"
| Type_clash (env, err) ->
Printtyp.report_unification_error ppf env err
(function ppf ->
fprintf ppf "This type constructor expands to type")
(function ppf ->
fprintf ppf "but is used here with type")
| Null_arity_external ->
fprintf ppf "External identifiers must be functions"
| Missing_native_external ->
fprintf ppf "@[<hv>An external function with more than 5 arguments \
requires a second stub function@ \
for native-code compilation@]"
| Unbound_type_var (ty, decl) ->
fprintf ppf "@[A type variable is unbound in this type declaration";
begin match decl.type_kind, decl.type_manifest with
| Type_variant (tl, _rep), _ ->
explain_unbound_gen ppf ty tl (fun c ->
let tl = tys_of_constr_args c.Types.cd_args in
Btype.newgenty (Ttuple tl)
)
"case" (fun ppf c ->
fprintf ppf
"%a of %a" Printtyp.ident c.Types.cd_id
Printtyp.constructor_arguments c.Types.cd_args)
| Type_record (tl, _), _ ->
explain_unbound ppf ty tl (fun l -> l.Types.ld_type)
"field" (fun l -> Ident.name l.Types.ld_id ^ ": ")
| Type_abstract, Some ty' ->
explain_unbound_single ppf ty ty'
| _ -> ()
end;
fprintf ppf "@]"
| Unbound_type_var_ext (ty, ext) ->
fprintf ppf "@[A type variable is unbound in this extension constructor";
let args = tys_of_constr_args ext.ext_args in
explain_unbound ppf ty args (fun c -> c) "type" (fun _ -> "");
fprintf ppf "@]"
| Cannot_extend_private_type path ->
fprintf ppf "@[%s@ %a@]"
"Cannot extend private type definition"
Printtyp.path path
| Not_extensible_type path ->
fprintf ppf "@[%s@ %a@ %s@]"
"Type definition"
Printtyp.path path
"is not extensible"
| Extension_mismatch (path, env, err) ->
fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%s@]%a@]"
"This extension" "does not match the definition of type"
(Path.name path)
(Includecore.report_type_mismatch
"the type" "this extension" "definition" env)
err
| Rebind_wrong_type (lid, env, err) ->
Printtyp.report_unification_error ppf env err
(function ppf ->
fprintf ppf "The constructor %a@ has type"
Printtyp.longident lid)
(function ppf ->
fprintf ppf "but was expected to be of type")
| Rebind_mismatch (lid, p, p') ->
fprintf ppf
"@[%s@ %a@ %s@ %s@ %s@ %s@ %s@]"
"The constructor" Printtyp.longident lid
"extends type" (Path.name p)
"whose declaration does not match"
"the declaration of type" (Path.name p')
| Rebind_private lid ->
fprintf ppf "@[%s@ %a@ %s@]"
"The constructor"
Printtyp.longident lid
"is private"
| Variance (Typedecl_variance.Bad_variance (n, v1, v2)) ->
let variance (p,n,i) =
let inj = if i then "injective " else "" in
match p, n with
true, true -> inj ^ "invariant"
| true, false -> inj ^ "covariant"
| false, true -> inj ^ "contravariant"
| false, false -> if inj = "" then "unrestricted" else inj
in
(match n with
| Variance_not_reflected ->
fprintf ppf "@[%s@ %s@ It"
"In this definition, a type variable has a variance that"
"is not reflected by its occurrence in type parameters."
| No_variable ->
fprintf ppf "@[%s@ %s@]"
"In this definition, a type variable cannot be deduced"
"from the type parameters."
| Variance_not_deducible ->
fprintf ppf "@[%s@ %s@ It"
"In this definition, a type variable has a variance that"
"cannot be deduced from the type parameters."
| Variance_not_satisfied n ->
fprintf ppf "@[%s@ %s@ The %d%s type parameter"
"In this definition, expected parameter"
"variances are not satisfied."
n (Misc.ordinal_suffix n));
(match n with
| No_variable -> ()
| _ ->
fprintf ppf " was expected to be %s,@ but it is %s.@]"
(variance v2) (variance v1))
| Unavailable_type_constructor p ->
fprintf ppf "The definition of type %a@ is unavailable" Printtyp.path p
| Variance Typedecl_variance.Varying_anonymous ->
fprintf ppf "@[%s@ %s@ %s@]"
"In this GADT definition," "the variance of some parameter"
"cannot be checked"
| Val_in_structure ->
fprintf ppf "Value declarations are only allowed in signatures"
| Multiple_native_repr_attributes ->
fprintf ppf "Too many [@@unboxed]/[@@untagged] attributes"
| Cannot_unbox_or_untag_type Unboxed ->
fprintf ppf "@[Don't know how to unbox this type.@ \
Only float, int32, int64 and nativeint can be unboxed.@]"
| Cannot_unbox_or_untag_type Untagged ->
fprintf ppf "@[Don't know how to untag this type.@ \
Only int can be untagged.@]"
| Deep_unbox_or_untag_attribute kind ->
fprintf ppf
"@[The attribute '%s' should be attached to@ \
a direct argument or result of the primitive,@ \
it should not occur deeply into its type.@]"
(match kind with Unboxed -> "@unboxed" | Untagged -> "@untagged")
| Immediacy (Typedecl_immediacy.Bad_immediacy_attribute violation) ->
fprintf ppf "@[%a@]" Format.pp_print_text
(match violation with
| Type_immediacy.Violation.Not_always_immediate ->
"Types marked with the immediate attribute must be \
non-pointer types like int or bool."
| Type_immediacy.Violation.Not_always_immediate_on_64bits ->
"Types marked with the immediate64 attribute must be \
produced using the Stdlib.Sys.Immediate64.Make functor.")
| Bad_unboxed_attribute msg ->
fprintf ppf "@[This type cannot be unboxed because@ %s.@]" msg
| Separability (Typedecl_separability.Non_separable_evar evar) ->
let pp_evar ppf = function
| None ->
fprintf ppf "an unnamed existential variable"
| Some str ->
fprintf ppf "the existential variable %a"
Pprintast.tyvar str in
fprintf ppf "@[This type cannot be unboxed because@ \
it might contain both float and non-float values,@ \
depending on the instantiation of %a.@ \
You should annotate it with [%@%@ocaml.boxed].@]"
pp_evar evar
| Boxed_and_unboxed ->
fprintf ppf "@[A type cannot be boxed and unboxed at the same time.@]"
| Nonrec_gadt ->
fprintf ppf
"@[GADT case syntax cannot be used in a 'nonrec' block.@]"
| Invalid_private_row_declaration ty ->
Format.fprintf ppf
"@[<hv>This private row type declaration is invalid.@ \
The type expression on the right-hand side reduces to@;<1 2>%a@ \
which does not have a free row type variable.@]@,\
@[<hv>@[Hint: If you intended to define a private type abbreviation,@ \
write explicitly@]@;<1 2>private %a@]"
Printtyp.type_expr ty Printtyp.type_expr ty
| Local_not_enabled ->
fprintf ppf "@[The local extension is disabled@ \
To enable it, pass the '-extension local' flag@]"
| Global_and_nonlocal ->
fprintf ppf "@[A type cannot be both global and nonlocal@]"
let () =
Location.register_error_of_exn
(function
| Error (loc, err) ->
Some (Location.error_of_printer ~loc report_error err)
| _ ->
None
)
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/c703f5f7772dd4252405b086be11c15a3c67f2ac/typing/typedecl.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
*** Typing of type definitions ***
Enter all declared types in the environment as abstract types
Determine if a type's values are represented by floats at run-time.
the syntax hinted at the existence of a row variable,
but there is in fact no row variable to make private, e.g.
[ type t = private [< `A > `A] ]
a syntactically open object was closed by a constraint
if it's a generalized constructor we must work in a narrowed
context so as to not introduce any new constraints
Bind type parameters
Not unboxable, mark as boxed
Check constraints
Add abstract row
Check that all constraints are enforced
We don't expand the error trace because that produces types that
*already* violate the constraints -- we need to report a problem with
the unexpanded types, or we get errors that talk about the same type
twice. This is generally true for constraint errors.
If both a variant/record definition and a type equation are given,
need to check that the equation refers to a type of the same kind
with the same constructors and labels.
Check that recursion is well-founded
Format.eprintf "@[%a@]@." Printtyp.raw_type_expr ty;
Will be detected by check_recursion
Attempt to expand a type abbreviation if:
1- [to_check path'] holds
(otherwise the expansion cannot involve [path]);
2- we haven't expanded this type constructor before
(otherwise we could loop if [path'] is itself
a non-regular abbreviation).
Attempt expansion
Warn on definitions of type "type foo = ()" which redefine a different unit
type and are likely a mistake.
Translate a set of type declarations, mutually recursive or not
Add dummy types for fixed rows
Create identifiers.
Enter types.
Translate each declaration.
See typecore.ml for a description of the algorithm used
to detect unused declarations in a set of recursive definitions.
Check for duplicates
Build the final env.
Update stubs
Check that all type variables are closed
Check that constraints are enforced
Add type properties to declarations
Compute the final environment with variance and immediacy
Check re-exportation
Keep original declaration
Done
Translating type extensions
Remove "_" names from parameters used in the constructor
Ensure that constructor's type matches the type being extended
Disallow rebinding private constructors to non-private
Check that all type variables are closed
Check variances are correct
Note that [loc] here is distinct from [type_decl.type_loc], which
makes the [loc] parameter to this function useful. [loc] is the
location of the extension, while [type_decl] points to the original
type declaration being extended.
Add extension constructors to the environment
Check that all type variables are closed
Translate a value declaration
Note: We delay the unification of those constraints
after the unification of parameters, so that clashing
constraints report an error on the constraint location
rather than the parameter location.
Note: constraints must also be enforced in [sig_env] because
they may contain parameter variables from [tparams]
that have now be unified in [sig_env].
Typedecl_immediacy.compute_decl never raises
Approximate a type declaration: just make all types abstract
Variant of check_abbrev_recursion to check the well-formedness
conditions on type abbreviations defined within recursive modules.
additionally check coherece, as one might build an incoherent signature,
and use it to build an incoherent module, cf. #7851
*** Error report ***
Hack to force aliasing when needed | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Misc
open Asttypes
open Parsetree
open Primitive
open Types
open Typetexp
module String = Misc.Stdlib.String
type native_repr_kind = Unboxed | Untagged
type error =
Repeated_parameter
| Duplicate_constructor of string
| Too_many_constructors
| Duplicate_label of string
| Recursive_abbrev of string
| Cycle_in_def of string * type_expr
| Definition_mismatch of type_expr * Env.t * Includecore.type_mismatch option
| Constraint_failed of Env.t * Errortrace.unification_error
| Inconsistent_constraint of Env.t * Errortrace.unification_error
| Type_clash of Env.t * Errortrace.unification_error
| Non_regular of {
definition: Path.t;
used_as: type_expr;
defined_as: type_expr;
expansions: (type_expr * type_expr) list;
}
| Null_arity_external
| Missing_native_external
| Unbound_type_var of type_expr * type_declaration
| Cannot_extend_private_type of Path.t
| Not_extensible_type of Path.t
| Extension_mismatch of Path.t * Env.t * Includecore.type_mismatch
| Rebind_wrong_type of
Longident.t * Env.t * Errortrace.unification_error
| Rebind_mismatch of Longident.t * Path.t * Path.t
| Rebind_private of Longident.t
| Variance of Typedecl_variance.error
| Unavailable_type_constructor of Path.t
| Unbound_type_var_ext of type_expr * extension_constructor
| Val_in_structure
| Multiple_native_repr_attributes
| Cannot_unbox_or_untag_type of native_repr_kind
| Deep_unbox_or_untag_attribute of native_repr_kind
| Immediacy of Typedecl_immediacy.error
| Separability of Typedecl_separability.error
| Bad_unboxed_attribute of string
| Boxed_and_unboxed
| Nonrec_gadt
| Invalid_private_row_declaration of type_expr
| Local_not_enabled
| Global_and_nonlocal
open Typedtree
exception Error of Location.t * error
let get_unboxed_from_attributes sdecl =
let unboxed = Builtin_attributes.has_unboxed sdecl.ptype_attributes in
let boxed = Builtin_attributes.has_boxed sdecl.ptype_attributes in
match boxed, unboxed with
| true, true -> raise (Error(sdecl.ptype_loc, Boxed_and_unboxed))
| true, false -> Some false
| false, true -> Some true
| false, false -> None
let add_type ~check id decl env =
Builtin_attributes.warning_scope ~ppwarning:false decl.type_attributes
(fun () -> Env.add_type ~check id decl env)
let enter_type rec_flag env sdecl (id, uid) =
let needed =
match rec_flag with
| Asttypes.Nonrecursive ->
begin match sdecl.ptype_kind with
| Ptype_variant scds ->
List.iter (fun cd ->
if cd.pcd_res <> None then raise (Error(cd.pcd_loc, Nonrec_gadt)))
scds
| _ -> ()
end;
Btype.is_row_name (Ident.name id)
| Asttypes.Recursive -> true
in
let arity = List.length sdecl.ptype_params in
if not needed then env else
let decl =
{ type_params =
List.map (fun _ -> Btype.newgenvar ()) sdecl.ptype_params;
type_arity = arity;
type_kind = Type_abstract;
type_private = sdecl.ptype_private;
type_manifest =
begin match sdecl.ptype_manifest with None -> None
| Some _ -> Some(Ctype.newvar ()) end;
type_variance = Variance.unknown_signature ~injective:false ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default = false;
type_uid = uid;
}
in
add_type ~check:true id decl env
let update_type temp_env env id loc =
let path = Path.Pident id in
let decl = Env.find_type path temp_env in
match decl.type_manifest with None -> ()
| Some ty ->
let params = List.map (fun _ -> Ctype.newvar ()) decl.type_params in
try Ctype.unify env (Ctype.newconstr path params) ty
with Ctype.Unify err ->
raise (Error(loc, Type_clash (env, err)))
let is_float env ty =
match Typedecl_unboxed.get_unboxed_type_representation env ty with
Some ty' ->
begin match get_desc ty' with
Tconstr(p, _, _) -> Path.same p Predef.path_float
| _ -> false
end
| _ -> false
Determine if a type definition defines a fixed type . ( PW )
let is_fixed_type sd =
let rec has_row_var sty =
match sty.ptyp_desc with
Ptyp_alias (sty, _) -> has_row_var sty
| Ptyp_class _
| Ptyp_object (_, Open)
| Ptyp_variant (_, Open, _)
| Ptyp_variant (_, Closed, Some _) -> true
| _ -> false
in
match sd.ptype_manifest with
None -> false
| Some sty ->
sd.ptype_kind = Ptype_abstract &&
sd.ptype_private = Private &&
has_row_var sty
Set the row variable to a fixed type in a private row type declaration .
( e.g. [ type t = private [ < ` A | ` B ] ] or [ type u = private < .. > ] )
Require [ ] as a precondition
(e.g. [ type t = private [< `A | `B ] ] or [type u = private < .. > ])
Require [is_fixed_type decl] as a precondition
*)
let set_private_row env loc p decl =
let tm =
match decl.type_manifest with
None -> assert false
| Some t -> Ctype.expand_head env t
in
let rv =
match get_desc tm with
Tvariant row ->
let Row {fields; more; closed; name} = row_repr row in
set_type_desc tm
(Tvariant (create_row ~fields ~more ~closed ~name
~fixed:(Some Fixed_private)));
if Btype.static_row row then
raise (Error(loc, Invalid_private_row_declaration tm))
else more
| Tobject (ty, _) ->
let r = snd (Ctype.flatten_fields ty) in
if not (Btype.is_Tvar r) then
raise (Error(loc, Invalid_private_row_declaration tm));
r
| _ -> assert false
in
set_type_desc rv (Tconstr (p, decl.type_params, ref Mnil))
Translate one type declaration
let make_params env params =
let make_param (sty, v) =
try
(transl_type_param env sty, v)
with Already_bound ->
raise(Error(sty.ptyp_loc, Repeated_parameter))
in
List.map make_param params
let transl_global_flags loc attrs =
let transl_global_flag loc (r : (bool,unit) result) =
match r with
| Ok b -> b
| Error () -> raise(Error(loc, Local_not_enabled))
in
let global = transl_global_flag loc (Builtin_attributes.has_global attrs) in
let nonlocal = transl_global_flag loc (Builtin_attributes.has_nonlocal attrs) in
match global, nonlocal with
| true, true -> raise(Error(loc, Global_and_nonlocal))
| true, false -> Types.Global
| false, true -> Types.Nonlocal
| false, false -> Types.Unrestricted
let transl_labels env univars closed lbls =
assert (lbls <> []);
let all_labels = ref String.Set.empty in
List.iter
(fun {pld_name = {txt=name; loc}} ->
if String.Set.mem name !all_labels then
raise(Error(loc, Duplicate_label name));
all_labels := String.Set.add name !all_labels)
lbls;
let mk {pld_name=name;pld_mutable=mut;pld_type=arg;pld_loc=loc;
pld_attributes=attrs} =
Builtin_attributes.warning_scope attrs
(fun () ->
let arg = Ast_helper.Typ.force_poly arg in
let cty = transl_simple_type env ?univars ~closed Global arg in
let gbl =
match mut with
| Mutable -> Types.Global
| Immutable -> transl_global_flags loc attrs
in
{ld_id = Ident.create_local name.txt;
ld_name = name; ld_mutable = mut; ld_global = gbl;
ld_type = cty; ld_loc = loc; ld_attributes = attrs}
)
in
let lbls = List.map mk lbls in
let lbls' =
List.map
(fun ld ->
let ty = ld.ld_type.ctyp_type in
let ty = match get_desc ty with Tpoly(t,[]) -> t | _ -> ty in
{Types.ld_id = ld.ld_id;
ld_mutable = ld.ld_mutable;
ld_global = ld.ld_global;
ld_type = ty;
ld_loc = ld.ld_loc;
ld_attributes = ld.ld_attributes;
ld_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
)
lbls in
lbls, lbls'
let transl_types_gf env univars closed tyl =
let mk arg =
let cty = transl_simple_type env ?univars ~closed Global arg in
let gf = transl_global_flags arg.ptyp_loc arg.ptyp_attributes in
(cty, gf)
in
let tyl_gfl = List.map mk tyl in
let tyl_gfl' = List.map (fun (cty, gf) -> cty.ctyp_type, gf) tyl_gfl in
tyl_gfl, tyl_gfl'
let transl_constructor_arguments env univars closed = function
| Pcstr_tuple l ->
let flds, flds' = transl_types_gf env univars closed l in
Types.Cstr_tuple flds',
Cstr_tuple flds
| Pcstr_record l ->
let lbls, lbls' = transl_labels env univars closed l in
Types.Cstr_record lbls',
Cstr_record lbls
let make_constructor env loc type_path type_params svars sargs sret_type =
match sret_type with
| None ->
let args, targs =
transl_constructor_arguments env None true sargs
in
targs, None, args, None
| Some sret_type -> TyVarEnv.with_local_scope begin fun () ->
TyVarEnv.reset ();
let univars, closed =
match svars with
| [] -> None, false
| vs ->
Ctype.begin_def();
Some (TyVarEnv.make_poly_univars (List.map (fun v -> v.txt) vs)), true
in
let args, targs =
transl_constructor_arguments env univars closed sargs
in
let tret_type = transl_simple_type env ?univars ~closed Global sret_type in
let ret_type = tret_type.ctyp_type in
TODO add back type_path as a parameter ?
begin match get_desc ret_type with
| Tconstr (p', _, _) when Path.same type_path p' -> ()
| _ ->
let trace =
Expansion is not helpful here -- the restriction on GADT return
types is purely syntactic . ( In the worst case , expansion
produces gibberish . )
types is purely syntactic. (In the worst case, expansion
produces gibberish.) *)
[Ctype.unexpanded_diff
~got:ret_type
~expected:(Ctype.newconstr type_path type_params)]
in
raise (Error(sret_type.ptyp_loc,
Constraint_failed(env,
Errortrace.unification_error ~trace)))
end;
begin match univars with
| None -> ()
| Some univars ->
Ctype.end_def();
Btype.iter_type_expr_cstr_args Ctype.generalize args;
Ctype.generalize ret_type;
let _vars = TyVarEnv.instance_poly_univars env loc univars in
let set_level t = Ctype.unify_var env (Ctype.newvar()) t in
Btype.iter_type_expr_cstr_args set_level args;
set_level ret_type;
end;
targs, Some tret_type, args, Some ret_type
end
let transl_declaration env sdecl (id, uid) =
TyVarEnv.reset ();
Ctype.begin_def ();
let tparams = make_params env sdecl.ptype_params in
let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
let cstrs = List.map
(fun (sty, sty', loc) ->
transl_simple_type env ~closed:false Global sty,
transl_simple_type env ~closed:false Global sty', loc)
sdecl.ptype_cstrs
in
let unboxed_attr = get_unboxed_from_attributes sdecl in
begin match unboxed_attr with
| (None | Some false) -> ()
| Some true ->
let bad msg = raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute msg)) in
match sdecl.ptype_kind with
| Ptype_abstract -> bad "it is abstract"
| Ptype_open -> bad "extensible variant types cannot be unboxed"
| Ptype_record fields -> begin match fields with
| [] -> bad "it has no fields"
| _::_::_ -> bad "it has more than one field"
| [{pld_mutable = Mutable}] -> bad "it is mutable"
| [{pld_mutable = Immutable}] -> ()
end
| Ptype_variant constructors -> begin match constructors with
| [] -> bad "it has no constructor"
| (_::_::_) -> bad "it has more than one constructor"
| [c] -> begin match c.pcd_args with
| Pcstr_tuple [] ->
bad "its constructor has no argument"
| Pcstr_tuple (_::_::_) ->
bad "its constructor has more than one argument"
| Pcstr_tuple [_] ->
()
| Pcstr_record [] ->
bad "its constructor has no fields"
| Pcstr_record (_::_::_) ->
bad "its constructor has more than one field"
| Pcstr_record [{pld_mutable = Mutable}] ->
bad "it is mutable"
| Pcstr_record [{pld_mutable = Immutable}] ->
()
end
end
end;
let unbox, unboxed_default =
match sdecl.ptype_kind with
| Ptype_variant [{pcd_args = Pcstr_tuple [_]; _}]
| Ptype_variant [{pcd_args = Pcstr_record [{pld_mutable=Immutable; _}]; _}]
| Ptype_record [{pld_mutable=Immutable; _}] ->
Option.value unboxed_attr ~default:!Clflags.unboxed_types,
Option.is_none unboxed_attr
in
let (tkind, kind) =
match sdecl.ptype_kind with
| Ptype_abstract -> Ttype_abstract, Type_abstract
| Ptype_variant scstrs ->
if List.exists (fun cstr -> cstr.pcd_res <> None) scstrs then begin
match cstrs with
[] -> ()
| (_,_,loc)::_ ->
Location.prerr_warning loc Warnings.Constraint_on_gadt
end;
let all_constrs = ref String.Set.empty in
List.iter
(fun {pcd_name = {txt = name}} ->
if String.Set.mem name !all_constrs then
raise(Error(sdecl.ptype_loc, Duplicate_constructor name));
all_constrs := String.Set.add name !all_constrs)
scstrs;
if List.length
(List.filter (fun cd -> cd.pcd_args <> Pcstr_tuple []) scstrs)
> (Config.max_tag + 1) then
raise(Error(sdecl.ptype_loc, Too_many_constructors));
let make_cstr scstr =
let name = Ident.create_local scstr.pcd_name.txt in
let targs, tret_type, args, ret_type =
make_constructor env scstr.pcd_loc (Path.Pident id) params
scstr.pcd_vars scstr.pcd_args scstr.pcd_res
in
let tcstr =
{ cd_id = name;
cd_name = scstr.pcd_name;
cd_vars = scstr.pcd_vars;
cd_args = targs;
cd_res = tret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = scstr.pcd_attributes }
in
let cstr =
{ Types.cd_id = name;
cd_args = args;
cd_res = ret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = scstr.pcd_attributes;
cd_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) }
in
tcstr, cstr
in
let make_cstr scstr =
Builtin_attributes.warning_scope scstr.pcd_attributes
(fun () -> make_cstr scstr)
in
let rep = if unbox then Variant_unboxed else Variant_regular in
let tcstrs, cstrs = List.split (List.map make_cstr scstrs) in
Ttype_variant tcstrs, Type_variant (cstrs, rep)
| Ptype_record lbls ->
let lbls, lbls' = transl_labels env None true lbls in
let rep =
if unbox then Record_unboxed false
else if List.for_all (fun l -> is_float env l.Types.ld_type) lbls'
then Record_float
else Record_regular
in
Ttype_record lbls, Type_record(lbls', rep)
| Ptype_open -> Ttype_open, Type_open
in
let (tman, man) = match sdecl.ptype_manifest with
None -> None, None
| Some sty ->
let no_row = not (is_fixed_type sdecl) in
let cty = transl_simple_type env ~closed:no_row Global sty in
Some cty, Some cty.ctyp_type
in
let arity = List.length params in
let decl =
{ type_params = params;
type_arity = arity;
type_kind = kind;
type_private = sdecl.ptype_private;
type_manifest = man;
type_variance = Variance.unknown_signature ~injective:false ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default = unboxed_default;
type_uid = uid;
} in
List.iter
(fun (cty, cty', loc) ->
let ty = cty.ctyp_type in
let ty' = cty'.ctyp_type in
try Ctype.unify env ty ty' with Ctype.Unify err ->
raise(Error(loc, Inconsistent_constraint (env, err))))
cstrs;
Ctype.end_def ();
if is_fixed_type sdecl then begin
let p, _ =
try Env.find_type_by_name
(Longident.Lident(Ident.name id ^ "#row")) env
with Not_found -> assert false
in
set_private_row env sdecl.ptype_loc p decl
end;
{
typ_id = id;
typ_name = sdecl.ptype_name;
typ_params = tparams;
typ_type = decl;
typ_cstrs = cstrs;
typ_loc = sdecl.ptype_loc;
typ_manifest = tman;
typ_kind = tkind;
typ_private = sdecl.ptype_private;
typ_attributes = sdecl.ptype_attributes;
}
a type declaration
let generalize_decl decl =
List.iter Ctype.generalize decl.type_params;
Btype.iter_type_expr_kind Ctype.generalize decl.type_kind;
begin match decl.type_manifest with
| None -> ()
| Some ty -> Ctype.generalize ty
end
module TypeSet = Btype.TypeSet
module TypeMap = Btype.TypeMap
let rec check_constraints_rec env loc visited ty =
if TypeSet.mem ty !visited then () else begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tconstr (path, args, _) ->
let decl =
try Env.find_type path env
with Not_found ->
raise (Error(loc, Unavailable_type_constructor path)) in
let ty' = Ctype.newconstr path (Ctype.instance_list decl.type_params) in
begin
try Ctype.matches ~expand_error_trace:false env ty ty'
with Ctype.Matches_failure (env, err) ->
raise (Error(loc, Constraint_failed (env, err)))
end;
List.iter (check_constraints_rec env loc visited) args
| Tpoly (ty, tl) ->
let _, ty = Ctype.instance_poly false tl ty in
check_constraints_rec env loc visited ty
| _ ->
Btype.iter_type_expr (check_constraints_rec env loc visited) ty
end
let check_constraints_labels env visited l pl =
let rec get_loc name = function
[] -> assert false
| pld :: tl ->
if name = pld.pld_name.txt then pld.pld_type.ptyp_loc
else get_loc name tl
in
List.iter
(fun {Types.ld_id=name; ld_type=ty} ->
check_constraints_rec env (get_loc (Ident.name name) pl) visited ty)
l
let check_constraints env sdecl (_, decl) =
let visited = ref TypeSet.empty in
List.iter2
(fun (sty, _) ty -> check_constraints_rec env sty.ptyp_loc visited ty)
sdecl.ptype_params decl.type_params;
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant (l, _rep) ->
let find_pl = function
Ptype_variant pl -> pl
| Ptype_record _ | Ptype_abstract | Ptype_open -> assert false
in
let pl = find_pl sdecl.ptype_kind in
let pl_index =
let foldf acc x =
String.Map.add x.pcd_name.txt x acc
in
List.fold_left foldf String.Map.empty pl
in
List.iter
(fun {Types.cd_id=name; cd_args; cd_res} ->
let {pcd_args; pcd_res; _} =
try String.Map.find (Ident.name name) pl_index
with Not_found -> assert false in
begin match cd_args, pcd_args with
| Cstr_tuple tyl, Pcstr_tuple styl ->
List.iter2
(fun sty (ty, _) ->
check_constraints_rec env sty.ptyp_loc visited ty)
styl tyl
| Cstr_record tyl, Pcstr_record styl ->
check_constraints_labels env visited tyl styl
| _ -> assert false
end;
match pcd_res, cd_res with
| Some sr, Some r ->
check_constraints_rec env sr.ptyp_loc visited r
| _ ->
() )
l
| Type_record (l, _) ->
let find_pl = function
Ptype_record pl -> pl
| Ptype_variant _ | Ptype_abstract | Ptype_open -> assert false
in
let pl = find_pl sdecl.ptype_kind in
check_constraints_labels env visited l pl
| Type_open -> ()
end;
begin match decl.type_manifest with
| None -> ()
| Some ty ->
let sty =
match sdecl.ptype_manifest with Some sty -> sty | _ -> assert false
in
check_constraints_rec env sty.ptyp_loc visited ty
end
let check_coherence env loc dpath decl =
match decl with
{ type_kind = (Type_variant _ | Type_record _| Type_open);
type_manifest = Some ty } ->
begin match get_desc ty with
Tconstr(path, args, _) ->
begin try
let decl' = Env.find_type path env in
let err =
if List.length args <> List.length decl.type_params
then Some Includecore.Arity
else begin
match Ctype.equal env false args decl.type_params with
| exception Ctype.Equality err ->
Some (Includecore.Constraint err)
| () ->
Includecore.type_declarations ~loc ~equality:true env
~mark:true
(Path.last path)
decl'
dpath
(Subst.type_declaration
(Subst.add_type_path dpath path Subst.identity) decl)
end
in
if err <> None then
raise(Error(loc, Definition_mismatch (ty, env, err)))
with Not_found ->
raise(Error(loc, Unavailable_type_constructor path))
end
| _ -> raise(Error(loc, Definition_mismatch (ty, env, None)))
end
| _ -> ()
let check_abbrev env sdecl (id, decl) =
check_coherence env sdecl.ptype_loc (Path.Pident id) decl
let check_well_founded env loc path to_check ty =
let visited = ref TypeMap.empty in
let rec check ty0 parents ty =
if TypeSet.mem ty parents then begin
if match get_desc ty0 with
| Tconstr (p, _, _) -> Path.same p path
| _ -> false
then raise (Error (loc, Recursive_abbrev (Path.name path)))
else raise (Error (loc, Cycle_in_def (Path.name path, ty0)))
end;
let (fini, parents) =
try
let prev = TypeMap.find ty !visited in
if TypeSet.subset parents prev then (true, parents) else
(false, TypeSet.union parents prev)
with Not_found ->
(false, parents)
in
if fini then () else
let rec_ok =
match get_desc ty with
Tconstr(p,_,_) ->
!Clflags.recursive_types && Ctype.is_contractive env p
| Tobject _ | Tvariant _ -> true
| _ -> !Clflags.recursive_types
in
let visited' = TypeMap.add ty parents !visited in
let arg_exn =
try
visited := visited';
let parents =
if rec_ok then TypeSet.empty else TypeSet.add ty parents in
Btype.iter_type_expr (check ty0 parents) ty;
None
with e ->
visited := visited'; Some e
in
match get_desc ty with
| Tconstr(p, _, _) when arg_exn <> None || to_check p ->
if to_check p then Option.iter raise arg_exn
else Btype.iter_type_expr (check ty0 TypeSet.empty) ty;
begin try
let ty' = Ctype.try_expand_once_opt env ty in
let ty0 = if TypeSet.is_empty parents then ty else ty0 in
check ty0 (TypeSet.add ty parents) ty'
with
Ctype.Cannot_expand -> Option.iter raise arg_exn
end
| _ -> Option.iter raise arg_exn
in
let snap = Btype.snapshot () in
try Ctype.wrap_trace_gadt_instances env (check ty TypeSet.empty) ty
with Ctype.Escape _ ->
Btype.backtrack snap
let check_well_founded_manifest env loc path decl =
if decl.type_manifest = None then () else
let args = List.map (fun _ -> Ctype.newvar()) decl.type_params in
check_well_founded env loc path (Path.same path) (Ctype.newconstr path args)
let check_well_founded_decl env loc path decl to_check =
let open Btype in
let it =
{type_iterators with
it_type_expr = (fun _ -> check_well_founded env loc path to_check)} in
it.it_type_declaration it (Ctype.generic_instance_declaration decl)
Check for ill - defined
let check_recursion ~orig_env env loc path decl to_check =
to_check is true for potentially mutually recursive paths .
( path , ) is the type declaration to be checked .
(path, decl) is the type declaration to be checked. *)
if decl.type_params = [] then () else
let visited = ref TypeSet.empty in
let rec check_regular cpath args prev_exp prev_expansions ty =
if not (TypeSet.mem ty !visited) then begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tconstr(path', args', _) ->
if Path.same path path' then begin
if not (Ctype.is_equal orig_env false args args') then
raise (Error(loc,
Non_regular {
definition=path;
used_as=ty;
defined_as=Ctype.newconstr path args;
expansions=List.rev prev_expansions;
}))
end
else if to_check path' && not (List.mem path' prev_exp) then begin
try
let (params0, body0, _) = Env.find_type_expansion path' env in
let (params, body) =
Ctype.instance_parameterized_type params0 body0 in
begin
try List.iter2 (Ctype.unify orig_env) params args'
with Ctype.Unify err ->
raise (Error(loc, Constraint_failed (orig_env, err)));
end;
check_regular path' args
(path' :: prev_exp) ((ty,body) :: prev_expansions)
body
with Not_found -> ()
end;
List.iter (check_regular cpath args prev_exp prev_expansions) args'
| Tpoly (ty, tl) ->
let (_, ty) = Ctype.instance_poly ~keep_names:true false tl ty in
check_regular cpath args prev_exp prev_expansions ty
| _ ->
Btype.iter_type_expr
(check_regular cpath args prev_exp prev_expansions) ty
end in
Option.iter
(fun body ->
let (args, body) =
Ctype.instance_parameterized_type
~keep_names:true decl.type_params body in
List.iter (check_regular path args [] []) args;
check_regular path args [] [] body)
decl.type_manifest
let check_abbrev_recursion ~orig_env env id_loc_list to_check tdecl =
let decl = tdecl.typ_type in
let id = tdecl.typ_id in
check_recursion ~orig_env env (List.assoc id id_loc_list) (Path.Pident id)
decl to_check
let check_duplicates sdecl_list =
let labels = Hashtbl.create 7 and constrs = Hashtbl.create 7 in
List.iter
(fun sdecl -> match sdecl.ptype_kind with
Ptype_variant cl ->
List.iter
(fun pcd ->
try
let name' = Hashtbl.find constrs pcd.pcd_name.txt in
Location.prerr_warning pcd.pcd_loc
(Warnings.Duplicate_definitions
("constructor", pcd.pcd_name.txt, name',
sdecl.ptype_name.txt))
with Not_found ->
Hashtbl.add constrs pcd.pcd_name.txt sdecl.ptype_name.txt)
cl
| Ptype_record fl ->
List.iter
(fun {pld_name=cname;pld_loc=loc} ->
try
let name' = Hashtbl.find labels cname.txt in
Location.prerr_warning loc
(Warnings.Duplicate_definitions
("label", cname.txt, name', sdecl.ptype_name.txt))
with Not_found -> Hashtbl.add labels cname.txt sdecl.ptype_name.txt)
fl
| Ptype_abstract -> ()
| Ptype_open -> ())
sdecl_list
Force recursion to go through i d for private types
let name_recursion sdecl id decl =
match decl with
| { type_kind = Type_abstract;
type_manifest = Some ty;
type_private = Private; } when is_fixed_type sdecl ->
let ty' = newty2 ~level:(get_level ty) (get_desc ty) in
if Ctype.deep_occur ty ty' then
let td = Tconstr(Path.Pident id, decl.type_params, ref Mnil) in
link_type ty (newty2 ~level:(get_level ty) td);
{decl with type_manifest = Some ty'}
else decl
| _ -> decl
let name_recursion_decls sdecls decls =
List.map2 (fun sdecl (id, decl) -> (id, name_recursion sdecl id decl))
sdecls decls
let check_redefined_unit (td: Parsetree.type_declaration) =
let open Parsetree in
let is_unit_constructor cd = cd.pcd_name.txt = "()" in
match td with
| { ptype_name = { txt = name };
ptype_manifest = None;
ptype_kind = Ptype_variant [ cd ] }
when is_unit_constructor cd ->
Location.prerr_warning td.ptype_loc (Warnings.Redefining_unit name)
| _ ->
()
let add_types_to_env decls env =
List.fold_right
(fun (id, decl) env -> add_type ~check:true id decl env)
decls env
let transl_type_decl env rec_flag sdecl_list =
List.iter check_redefined_unit sdecl_list;
let fixed_types = List.filter is_fixed_type sdecl_list in
let sdecl_list =
List.map
(fun sdecl ->
let ptype_name =
let loc = { sdecl.ptype_name.loc with Location.loc_ghost = true } in
mkloc (sdecl.ptype_name.txt ^"#row") loc
in
let ptype_kind = Ptype_abstract in
let ptype_manifest = None in
let ptype_loc = { sdecl.ptype_loc with Location.loc_ghost = true } in
{sdecl with
ptype_name; ptype_kind; ptype_manifest; ptype_loc })
fixed_types
@ sdecl_list
in
let scope = Ctype.create_scope () in
let ids_list =
List.map (fun sdecl ->
Ident.create_scoped ~scope sdecl.ptype_name.txt,
Uid.mk ~current_unit:(Env.get_unit_name ())
) sdecl_list
in
Ctype.begin_def();
let temp_env =
List.fold_left2 (enter_type rec_flag) env sdecl_list ids_list in
let current_slot = ref None in
let warn_unused = Warnings.is_active (Warnings.Unused_type_declaration "") in
let ids_slots (id, _uid as ids) =
match rec_flag with
| Asttypes.Recursive when warn_unused ->
let slot = ref [] in
let td = Env.find_type (Path.Pident id) temp_env in
Env.set_type_used_callback
td
(fun old_callback ->
match !current_slot with
| Some slot -> slot := td.type_uid :: !slot
| None ->
List.iter Env.mark_type_used (get_ref slot);
old_callback ()
);
ids, Some slot
| Asttypes.Recursive | Asttypes.Nonrecursive ->
ids, None
in
let transl_declaration name_sdecl (id, slot) =
current_slot := slot;
Builtin_attributes.warning_scope
name_sdecl.ptype_attributes
(fun () -> transl_declaration temp_env name_sdecl id)
in
let tdecls =
List.map2 transl_declaration sdecl_list (List.map ids_slots ids_list) in
let decls =
List.map (fun tdecl -> (tdecl.typ_id, tdecl.typ_type)) tdecls in
current_slot := None;
check_duplicates sdecl_list;
let new_env = add_types_to_env decls env in
begin match rec_flag with
| Asttypes.Nonrecursive -> ()
| Asttypes.Recursive ->
List.iter2
(fun (id, _) sdecl -> update_type temp_env new_env id sdecl.ptype_loc)
ids_list sdecl_list
end;
Generalize type declarations .
Ctype.end_def();
List.iter (fun (_, decl) -> generalize_decl decl) decls;
Check for ill - formed
let id_loc_list =
List.map2 (fun (id, _) sdecl -> (id, sdecl.ptype_loc))
ids_list sdecl_list
in
List.iter (fun (id, decl) ->
check_well_founded_manifest new_env (List.assoc id id_loc_list)
(Path.Pident id) decl)
decls;
let to_check =
function Path.Pident id -> List.mem_assoc id id_loc_list | _ -> false in
List.iter (fun (id, decl) ->
check_well_founded_decl new_env (List.assoc id id_loc_list) (Path.Pident id)
decl to_check)
decls;
List.iter
(check_abbrev_recursion ~orig_env:env new_env id_loc_list to_check) tdecls;
List.iter2
(fun sdecl tdecl ->
let decl = tdecl.typ_type in
match Ctype.closed_type_decl decl with
Some ty -> raise(Error(sdecl.ptype_loc, Unbound_type_var(ty,decl)))
| None -> ())
sdecl_list tdecls;
List.iter2 (check_constraints new_env) sdecl_list decls;
let decls =
try
decls
|> name_recursion_decls sdecl_list
|> Typedecl_variance.update_decls env sdecl_list
|> Typedecl_immediacy.update_decls env
|> Typedecl_separability.update_decls env
with
| Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err))
| Typedecl_immediacy.Error (loc, err) ->
raise (Error (loc, Immediacy err))
| Typedecl_separability.Error (loc, err) ->
raise (Error (loc, Separability err))
in
let final_env = add_types_to_env decls env in
List.iter2 (check_abbrev final_env) sdecl_list decls;
let final_decls =
List.map2
(fun tdecl (_id2, decl) ->
{ tdecl with typ_type = decl }
) tdecls decls
in
(final_decls, final_env)
let transl_extension_constructor ~scope env type_path type_params
typext_params priv sext =
let id = Ident.create_scoped ~scope sext.pext_name.txt in
let args, ret_type, kind =
match sext.pext_kind with
Pext_decl(svars, sargs, sret_type) ->
let targs, tret_type, args, ret_type =
make_constructor env sext.pext_loc type_path typext_params
svars sargs sret_type
in
args, ret_type, Text_decl(svars, targs, tret_type)
| Pext_rebind lid ->
let usage : Env.constructor_usage =
if priv = Public then Env.Exported else Env.Exported_private
in
let cdescr = Env.lookup_constructor ~loc:lid.loc usage lid.txt env in
let (args, cstr_res, _ex) = Ctype.instance_constructor cdescr in
let res, ret_type =
if cdescr.cstr_generalized then
let params = Ctype.instance_list type_params in
let res = Ctype.newconstr type_path params in
let ret_type = Some (Ctype.newconstr type_path params) in
res, ret_type
else (Ctype.newconstr type_path typext_params), None
in
begin
try
Ctype.unify env cstr_res res
with Ctype.Unify err ->
raise (Error(lid.loc,
Rebind_wrong_type(lid.txt, env, err)))
end;
if not cdescr.cstr_generalized then begin
let vars =
Ctype.free_variables (Btype.newgenty (Ttuple (List.map fst args)))
in
List.iter
(fun ty ->
if get_desc ty = Tvar (Some "_")
&& List.exists (eq_type ty) vars
then set_type_desc ty (Tvar None))
typext_params
end;
let cstr_type_path = Btype.cstr_type_path cdescr in
let cstr_type_params = (Env.find_type cstr_type_path env).type_params in
let cstr_types =
(Btype.newgenty
(Tconstr(cstr_type_path, cstr_type_params, ref Mnil)))
:: cstr_type_params
in
let ext_types =
(Btype.newgenty
(Tconstr(type_path, type_params, ref Mnil)))
:: type_params
in
if not (Ctype.is_equal env true cstr_types ext_types) then
raise (Error(lid.loc,
Rebind_mismatch(lid.txt, cstr_type_path, type_path)));
begin
match cdescr.cstr_private, priv with
Private, Public ->
raise (Error(lid.loc, Rebind_private lid.txt))
| _ -> ()
end;
let path =
match cdescr.cstr_tag with
Cstr_extension(path, _) -> path
| _ -> assert false
in
let args =
match cdescr.cstr_inlined with
| None ->
Types.Cstr_tuple args
| Some decl ->
let tl =
match List.map (fun (ty, _) -> get_desc ty) args with
| [ Tconstr(_, tl, _) ] -> tl
| _ -> assert false
in
let decl = Ctype.instance_declaration decl in
assert (List.length decl.type_params = List.length tl);
List.iter2 (Ctype.unify env) decl.type_params tl;
let lbls =
match decl.type_kind with
| Type_record (lbls, Record_extension _) -> lbls
| _ -> assert false
in
Types.Cstr_record lbls
in
args, ret_type, Text_rebind(path, lid)
in
let ext =
{ ext_type_path = type_path;
ext_type_params = typext_params;
ext_args = args;
ext_ret_type = ret_type;
ext_private = priv;
Types.ext_loc = sext.pext_loc;
Types.ext_attributes = sext.pext_attributes;
ext_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
in
{ ext_id = id;
ext_name = sext.pext_name;
ext_type = ext;
ext_kind = kind;
Typedtree.ext_loc = sext.pext_loc;
Typedtree.ext_attributes = sext.pext_attributes; }
let transl_extension_constructor ~scope env type_path type_params
typext_params priv sext =
Builtin_attributes.warning_scope sext.pext_attributes
(fun () -> transl_extension_constructor ~scope env type_path type_params
typext_params priv sext)
let is_rebind ext =
match ext.ext_kind with
| Text_rebind _ -> true
| Text_decl _ -> false
let transl_type_extension extend env loc styext =
Note : it would be incorrect to call [ create_scope ] * after *
[ TyVarEnv.reset ] or after [ begin_def ] ( see # 10010 ) .
[TyVarEnv.reset] or after [begin_def] (see #10010). *)
let scope = Ctype.create_scope () in
TyVarEnv.reset ();
Ctype.begin_def();
let type_path, type_decl =
let lid = styext.ptyext_path in
Env.lookup_type ~loc:lid.loc lid.txt env
in
begin
match type_decl.type_kind with
| Type_open -> begin
match type_decl.type_private with
| Private when extend -> begin
match
List.find
(function {pext_kind = Pext_decl _} -> true
| {pext_kind = Pext_rebind _} -> false)
styext.ptyext_constructors
with
| {pext_loc} ->
raise (Error(pext_loc, Cannot_extend_private_type type_path))
| exception Not_found -> ()
end
| _ -> ()
end
| _ ->
raise (Error(loc, Not_extensible_type type_path))
end;
let type_variance =
List.map (fun v ->
let (co, cn) = Variance.get_upper v in
(not cn, not co, false))
type_decl.type_variance
in
let err =
if type_decl.type_arity <> List.length styext.ptyext_params then
Some Includecore.Arity
else
if List.for_all2
(fun (c1, n1, _) (c2, n2, _) -> (not c2 || c1) && (not n2 || n1))
type_variance
(Typedecl_variance.variance_of_params styext.ptyext_params)
then None else Some Includecore.Variance
in
begin match err with
| None -> ()
| Some err -> raise (Error(loc, Extension_mismatch (type_path, env, err)))
end;
let ttype_params = make_params env styext.ptyext_params in
let type_params = List.map (fun (cty, _) -> cty.ctyp_type) ttype_params in
List.iter2 (Ctype.unify_var env)
(Ctype.instance_list type_decl.type_params)
type_params;
let constructors =
List.map (transl_extension_constructor ~scope env type_path
type_decl.type_params type_params styext.ptyext_private)
styext.ptyext_constructors
in
Ctype.end_def();
types
List.iter Ctype.generalize type_params;
List.iter
(fun ext ->
Btype.iter_type_expr_cstr_args Ctype.generalize ext.ext_type.ext_args;
Option.iter Ctype.generalize ext.ext_type.ext_ret_type)
constructors;
List.iter
(fun ext ->
match Ctype.closed_extension_constructor ext.ext_type with
Some ty ->
raise(Error(ext.ext_loc, Unbound_type_var_ext(ty, ext.ext_type)))
| None -> ())
constructors;
List.iter
(fun ext->
try Typedecl_variance.check_variance_extension
env type_decl ext (type_variance, loc)
with Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err)))
constructors;
let newenv =
List.fold_left
(fun env ext ->
let rebind = is_rebind ext in
Env.add_extension ~check:true ~rebind ext.ext_id ext.ext_type env)
env constructors
in
let tyext =
{ tyext_path = type_path;
tyext_txt = styext.ptyext_path;
tyext_params = ttype_params;
tyext_constructors = constructors;
tyext_private = styext.ptyext_private;
tyext_loc = styext.ptyext_loc;
tyext_attributes = styext.ptyext_attributes; }
in
(tyext, newenv)
let transl_type_extension extend env loc styext =
Builtin_attributes.warning_scope styext.ptyext_attributes
(fun () -> transl_type_extension extend env loc styext)
let transl_exception env sext =
let scope = Ctype.create_scope () in
TyVarEnv.reset ();
Ctype.begin_def();
let ext =
transl_extension_constructor ~scope env
Predef.path_exn [] [] Asttypes.Public sext
in
Ctype.end_def();
types
Btype.iter_type_expr_cstr_args Ctype.generalize ext.ext_type.ext_args;
Option.iter Ctype.generalize ext.ext_type.ext_ret_type;
begin match Ctype.closed_extension_constructor ext.ext_type with
Some ty ->
raise (Error(ext.ext_loc, Unbound_type_var_ext(ty, ext.ext_type)))
| None -> ()
end;
let rebind = is_rebind ext in
let newenv =
Env.add_extension ~check:true ~rebind ext.ext_id ext.ext_type env
in
ext, newenv
let transl_type_exception env t =
let contructor, newenv =
Builtin_attributes.warning_scope t.ptyexn_attributes
(fun () ->
transl_exception env t.ptyexn_constructor
)
in
{tyexn_constructor = contructor;
tyexn_loc = t.ptyexn_loc;
tyexn_attributes = t.ptyexn_attributes}, newenv
type native_repr_attribute =
| Native_repr_attr_absent
| Native_repr_attr_present of native_repr_kind
let get_native_repr_attribute attrs ~global_repr =
match
Attr_helper.get_no_payload_attribute ["unboxed"; "ocaml.unboxed"] attrs,
Attr_helper.get_no_payload_attribute ["untagged"; "ocaml.untagged"] attrs,
global_repr
with
| None, None, None -> Native_repr_attr_absent
| None, None, Some repr -> Native_repr_attr_present repr
| Some _, None, None -> Native_repr_attr_present Unboxed
| None, Some _, None -> Native_repr_attr_present Untagged
| Some { Location.loc }, _, _
| _, Some { Location.loc }, _ ->
raise (Error (loc, Multiple_native_repr_attributes))
let native_repr_of_type env kind ty =
match kind, get_desc (Ctype.expand_head_opt env ty) with
| Untagged, Tconstr (path, _, _) when Path.same path Predef.path_int ->
Some Untagged_int
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_float ->
Some Unboxed_float
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_int32 ->
Some (Unboxed_integer Pint32)
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_int64 ->
Some (Unboxed_integer Pint64)
| Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_nativeint ->
Some (Unboxed_integer Pnativeint)
| _ ->
None
Raises an error when [ core_type ] contains an [ @unboxed ] or [ @untagged ]
attribute in a strict sub - term .
attribute in a strict sub-term. *)
let error_if_has_deep_native_repr_attributes core_type =
let open Ast_iterator in
let this_iterator =
{ default_iterator with typ = fun iterator core_type ->
begin
match
get_native_repr_attribute core_type.ptyp_attributes ~global_repr:None
with
| Native_repr_attr_present kind ->
raise (Error (core_type.ptyp_loc,
Deep_unbox_or_untag_attribute kind))
| Native_repr_attr_absent -> ()
end;
default_iterator.typ iterator core_type }
in
default_iterator.typ this_iterator core_type
let make_native_repr env core_type ty ~global_repr =
error_if_has_deep_native_repr_attributes core_type;
match get_native_repr_attribute core_type.ptyp_attributes ~global_repr with
| Native_repr_attr_absent ->
Same_as_ocaml_repr
| Native_repr_attr_present kind ->
begin match native_repr_of_type env kind ty with
| None ->
raise (Error (core_type.ptyp_loc, Cannot_unbox_or_untag_type kind))
| Some repr -> repr
end
let prim_const_mode m =
match Types.Alloc_mode.check_const m with
| Some Global -> Prim_global
| Some Local -> Prim_local
| None -> assert false
let rec parse_native_repr_attributes env core_type ty rmode ~global_repr =
match core_type.ptyp_desc, get_desc ty,
get_native_repr_attribute core_type.ptyp_attributes ~global_repr:None
with
| Ptyp_arrow _, Tarrow _, Native_repr_attr_present kind ->
raise (Error (core_type.ptyp_loc, Cannot_unbox_or_untag_type kind))
| Ptyp_arrow (_, ct1, ct2), Tarrow ((_,marg,mret), t1, t2, _), _
when not (Builtin_attributes.has_curry core_type.ptyp_attributes) ->
let t1, _ = Btype.tpoly_get_poly t1 in
let repr_arg = make_native_repr env ct1 t1 ~global_repr in
let mode =
if Builtin_attributes.has_local_opt ct1.ptyp_attributes
then Prim_poly
else prim_const_mode marg
in
let repr_args, repr_res =
parse_native_repr_attributes env ct2 t2 (prim_const_mode mret) ~global_repr
in
((mode,repr_arg) :: repr_args, repr_res)
| (Ptyp_poly (_, t) | Ptyp_alias (t, _)), _, _ ->
parse_native_repr_attributes env t ty rmode ~global_repr
| _ ->
let rmode =
if Builtin_attributes.has_local_opt core_type.ptyp_attributes
then Prim_poly
else rmode
in
([], (rmode, make_native_repr env core_type ty ~global_repr))
let check_unboxable env loc ty =
let rec check_type acc ty : Path.Set.t =
let ty = Ctype.expand_head_opt env ty in
try match get_desc ty with
| Tconstr (p, _, _) ->
let tydecl = Env.find_type p env in
if tydecl.type_unboxed_default then
Path.Set.add p acc
else acc
| Tpoly (ty, []) -> check_type acc ty
| _ -> acc
with Not_found -> acc
in
let all_unboxable_types = Btype.fold_type_expr check_type Path.Set.empty ty in
Path.Set.fold
(fun p () ->
Location.prerr_warning loc
(Warnings.Unboxable_type_in_prim_decl (Path.name p))
)
all_unboxable_types
()
let transl_value_decl env loc valdecl =
let cty = Typetexp.transl_type_scheme env valdecl.pval_type in
let ty = cty.ctyp_type in
let v =
match valdecl.pval_prim with
[] when Env.is_in_signature env ->
{ val_type = ty; val_kind = Val_reg; Types.val_loc = loc;
val_attributes = valdecl.pval_attributes;
val_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
| [] ->
raise (Error(valdecl.pval_loc, Val_in_structure))
| _ ->
let global_repr =
match
get_native_repr_attribute valdecl.pval_attributes ~global_repr:None
with
| Native_repr_attr_present repr -> Some repr
| Native_repr_attr_absent -> None
in
let native_repr_args, native_repr_res =
parse_native_repr_attributes env valdecl.pval_type ty Prim_global ~global_repr
in
let prim =
Primitive.parse_declaration valdecl
~native_repr_args
~native_repr_res
in
if prim.prim_arity = 0 &&
(prim.prim_name = "" || prim.prim_name.[0] <> '%') then
raise(Error(valdecl.pval_type.ptyp_loc, Null_arity_external));
if !Clflags.native_code
&& prim.prim_arity > 5
&& prim.prim_native_name = ""
then raise(Error(valdecl.pval_type.ptyp_loc, Missing_native_external));
check_unboxable env loc ty;
{ val_type = ty; val_kind = Val_prim prim; Types.val_loc = loc;
val_attributes = valdecl.pval_attributes;
val_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
in
let (id, newenv) =
Env.enter_value valdecl.pval_name.txt v env
~check:(fun s -> Warnings.Unused_value_declaration s)
in
let desc =
{
val_id = id;
val_name = valdecl.pval_name;
val_desc = cty; val_val = v;
val_prim = valdecl.pval_prim;
val_loc = valdecl.pval_loc;
val_attributes = valdecl.pval_attributes;
}
in
desc, newenv
let transl_value_decl env loc valdecl =
Builtin_attributes.warning_scope valdecl.pval_attributes
(fun () -> transl_value_decl env loc valdecl)
Translate a " with " constraint -- much simplified version of
transl_type_decl . For a constraint [ Sig with t = sdecl ] ,
there are two declarations of interest in two environments :
- [ sig_decl ] is the declaration of [ t ] in [ Sig ] ,
in the environment [ sig_env ] ( containing the declarations
of [ Sig ] before [ t ] )
- [ sdecl ] is the new syntactic declaration , to be type - checked
in the current , outer environment [ with_env ] .
In particular , note that [ sig_env ] is an extension of
[ outer_env ] .
transl_type_decl. For a constraint [Sig with t = sdecl],
there are two declarations of interest in two environments:
- [sig_decl] is the declaration of [t] in [Sig],
in the environment [sig_env] (containing the declarations
of [Sig] before [t])
- [sdecl] is the new syntactic declaration, to be type-checked
in the current, outer environment [with_env].
In particular, note that [sig_env] is an extension of
[outer_env].
*)
let transl_with_constraint id ?fixed_row_path ~sig_env ~sig_decl ~outer_env
sdecl =
Env.mark_type_used sig_decl.type_uid;
TyVarEnv.reset ();
Ctype.begin_def();
In the first part of this function , we typecheck the syntactic
declaration [ sdecl ] in the outer environment [ outer_env ] .
declaration [sdecl] in the outer environment [outer_env]. *)
let env = outer_env in
let loc = sdecl.ptype_loc in
let tparams = make_params env sdecl.ptype_params in
let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
let arity = List.length params in
let constraints =
List.map (fun (ty, ty', loc) ->
let cty = transl_simple_type env ~closed:false Global ty in
let cty' = transl_simple_type env ~closed:false Global ty' in
(cty, cty', loc)
) sdecl.ptype_cstrs
in
let no_row = not (is_fixed_type sdecl) in
let (tman, man) = match sdecl.ptype_manifest with
None -> None, None
| Some sty ->
let cty = transl_simple_type env ~closed:no_row Global sty in
Some cty, Some cty.ctyp_type
in
In the second part , we check the consistency between the two
declarations and compute a " merged " declaration ; we now need to
work in the larger signature environment [ sig_env ] , because
[ sig_decl.type_params ] and [ sig_decl.type_kind ] are only valid
there .
declarations and compute a "merged" declaration; we now need to
work in the larger signature environment [sig_env], because
[sig_decl.type_params] and [sig_decl.type_kind] are only valid
there. *)
let env = sig_env in
let sig_decl = Ctype.instance_declaration sig_decl in
let arity_ok = arity = sig_decl.type_arity in
if arity_ok then
List.iter2 (fun (cty, _) tparam ->
try Ctype.unify_var env cty.ctyp_type tparam
with Ctype.Unify err ->
raise(Error(cty.ctyp_loc, Inconsistent_constraint (env, err)))
) tparams sig_decl.type_params;
List.iter (fun (cty, cty', loc) ->
try Ctype.unify env cty.ctyp_type cty'.ctyp_type
with Ctype.Unify err ->
raise(Error(loc, Inconsistent_constraint (env, err)))
) constraints;
let priv =
if sdecl.ptype_private = Private then Private else
if arity_ok && sig_decl.type_kind <> Type_abstract
then sig_decl.type_private else sdecl.ptype_private
in
if arity_ok && sig_decl.type_kind <> Type_abstract
&& sdecl.ptype_private = Private then
Location.deprecated loc "spurious use of private";
let type_kind, type_unboxed_default =
if arity_ok && man <> None then
sig_decl.type_kind, sig_decl.type_unboxed_default
else
Type_abstract, false
in
let new_sig_decl =
{ type_params = params;
type_arity = arity;
type_kind;
type_private = priv;
type_manifest = man;
type_variance = [];
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default;
type_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
in
Option.iter (fun p -> set_private_row env sdecl.ptype_loc p new_sig_decl)
fixed_row_path;
begin match Ctype.closed_type_decl new_sig_decl with None -> ()
| Some ty -> raise(Error(loc, Unbound_type_var(ty, new_sig_decl)))
end;
let new_sig_decl = name_recursion sdecl id new_sig_decl in
let new_type_variance =
let required = Typedecl_variance.variance_of_sdecl sdecl in
try
Typedecl_variance.compute_decl env ~check:true new_sig_decl required
with Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err)) in
let new_type_immediate =
Typedecl_immediacy.compute_decl env new_sig_decl in
let new_type_separability =
try Typedecl_separability.compute_decl env new_sig_decl
with Typedecl_separability.Error (loc, err) ->
raise (Error (loc, Separability err)) in
let new_sig_decl =
we intentionally write this without a fragile { decl with ... }
to ensure that people adding new fields to type declarations
consider whether they need to recompute it here ; for an example
of bug caused by the previous approach , see # 9607
to ensure that people adding new fields to type declarations
consider whether they need to recompute it here; for an example
of bug caused by the previous approach, see #9607 *)
{
type_params = new_sig_decl.type_params;
type_arity = new_sig_decl.type_arity;
type_kind = new_sig_decl.type_kind;
type_private = new_sig_decl.type_private;
type_manifest = new_sig_decl.type_manifest;
type_unboxed_default = new_sig_decl.type_unboxed_default;
type_is_newtype = new_sig_decl.type_is_newtype;
type_expansion_scope = new_sig_decl.type_expansion_scope;
type_loc = new_sig_decl.type_loc;
type_attributes = new_sig_decl.type_attributes;
type_uid = new_sig_decl.type_uid;
type_variance = new_type_variance;
type_immediate = new_type_immediate;
type_separability = new_type_separability;
} in
Ctype.end_def();
generalize_decl new_sig_decl;
{
typ_id = id;
typ_name = sdecl.ptype_name;
typ_params = tparams;
typ_type = new_sig_decl;
typ_cstrs = constraints;
typ_loc = loc;
typ_manifest = tman;
typ_kind = Ttype_abstract;
typ_private = sdecl.ptype_private;
typ_attributes = sdecl.ptype_attributes;
}
let abstract_type_decl ~injective arity =
let rec make_params n =
if n <= 0 then [] else Ctype.newvar() :: make_params (n-1) in
Ctype.begin_def();
let decl =
{ type_params = make_params arity;
type_arity = arity;
type_kind = Type_abstract;
type_private = Public;
type_manifest = None;
type_variance = Variance.unknown_signature ~injective ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = Location.none;
type_attributes = [];
type_immediate = Unknown;
type_unboxed_default = false;
type_uid = Uid.internal_not_actually_unique;
} in
Ctype.end_def();
generalize_decl decl;
decl
let approx_type_decl sdecl_list =
let scope = Ctype.create_scope () in
List.map
(fun sdecl ->
let injective = sdecl.ptype_kind <> Ptype_abstract in
(Ident.create_scoped ~scope sdecl.ptype_name.txt,
abstract_type_decl ~injective (List.length sdecl.ptype_params)))
sdecl_list
let check_recmod_typedecl env loc recmod_ids path decl =
recmod_ids is the list of recursively - defined module idents .
( path , ) is the type declaration to be checked .
(path, decl) is the type declaration to be checked. *)
let to_check path = Path.exists_free recmod_ids path in
check_well_founded_decl env loc path decl to_check;
check_recursion ~orig_env:env env loc path decl to_check;
check_coherence env loc path decl
open Format
let explain_unbound_gen ppf tv tl typ kwd pr =
try
let ti = List.find (fun ti -> Ctype.deep_occur tv (typ ti)) tl in
Btype.newgenty (Tobject(tv, ref None)) in
Printtyp.prepare_for_printing [typ ti; ty0];
fprintf ppf
".@ @[<hov2>In %s@ %a@;<1 -2>the variable %a is unbound@]"
kwd pr ti Printtyp.prepared_type_expr tv
with Not_found -> ()
let explain_unbound ppf tv tl typ kwd lab =
explain_unbound_gen ppf tv tl typ kwd
(fun ppf ti ->
fprintf ppf "%s%a" (lab ti) Printtyp.prepared_type_expr (typ ti)
)
let explain_unbound_single ppf tv ty =
let trivial ty =
explain_unbound ppf tv [ty] (fun t -> t) "type" (fun _ -> "") in
match get_desc ty with
Tobject(fi,_) ->
let (tl, rv) = Ctype.flatten_fields fi in
if eq_type rv tv then trivial ty else
explain_unbound ppf tv tl (fun (_,_,t) -> t)
"method" (fun (lab,_,_) -> lab ^ ": ")
| Tvariant row ->
if eq_type (row_more row) tv then trivial ty else
explain_unbound ppf tv (row_fields row)
(fun (_l,f) -> match row_field_repr f with
Rpresent (Some t) -> t
| Reither (_,[t],_) -> t
| Reither (_,tl,_) -> Btype.newgenty (Ttuple tl)
| _ -> Btype.newgenty (Ttuple[]))
"case" (fun (lab,_) -> "`" ^ lab ^ " of ")
| _ -> trivial ty
let tys_of_constr_args = function
| Types.Cstr_tuple tl -> List.map fst tl
| Types.Cstr_record lbls -> List.map (fun l -> l.Types.ld_type) lbls
let report_error ppf = function
| Repeated_parameter ->
fprintf ppf "A type parameter occurs several times"
| Duplicate_constructor s ->
fprintf ppf "Two constructors are named %s" s
| Too_many_constructors ->
fprintf ppf
"@[Too many non-constant constructors@ -- maximum is %i %s@]"
(Config.max_tag + 1) "non-constant constructors"
| Duplicate_label s ->
fprintf ppf "Two labels are named %s" s
| Recursive_abbrev s ->
fprintf ppf "The type abbreviation %s is cyclic" s
| Cycle_in_def (s, ty) ->
fprintf ppf "@[<v>The definition of %s contains a cycle:@ %a@]"
s Printtyp.type_expr ty
| Definition_mismatch (ty, _env, None) ->
fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%a@]@]"
"This variant or record definition" "does not match that of type"
Printtyp.type_expr ty
| Definition_mismatch (ty, env, Some err) ->
fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%a@]%a@]"
"This variant or record definition" "does not match that of type"
Printtyp.type_expr ty
(Includecore.report_type_mismatch
"the original" "this" "definition" env)
err
| Constraint_failed (env, err) ->
fprintf ppf "@[<v>Constraints are not satisfied in this type.@ ";
Printtyp.report_unification_error ppf env err
(fun ppf -> fprintf ppf "Type")
(fun ppf -> fprintf ppf "should be an instance of");
fprintf ppf "@]"
| Non_regular { definition; used_as; defined_as; expansions } ->
let pp_expansion ppf (ty,body) =
Format.fprintf ppf "%a = %a"
Printtyp.type_expr ty
Printtyp.type_expr body in
let comma ppf () = Format.fprintf ppf ",@;<1 2>" in
let pp_expansions ppf expansions =
Format.(pp_print_list ~pp_sep:comma pp_expansion) ppf expansions in
Printtyp.prepare_for_printing [used_as; defined_as];
Printtyp.Naming_context.reset ();
begin match expansions with
| [] ->
fprintf ppf
"@[<hv>This recursive type is not regular.@ \
The type constructor %s is defined as@;<1 2>type %a@ \
but it is used as@;<1 2>%a.@ \
All uses need to match the definition for the recursive type \
to be regular.@]"
(Path.name definition)
!Oprint.out_type (Printtyp.tree_of_typexp Type defined_as)
!Oprint.out_type (Printtyp.tree_of_typexp Type used_as)
| _ :: _ ->
fprintf ppf
"@[<hv>This recursive type is not regular.@ \
The type constructor %s is defined as@;<1 2>type %a@ \
but it is used as@;<1 2>%a@ \
after the following expansion(s):@;<1 2>%a@ \
All uses need to match the definition for the recursive type \
to be regular.@]"
(Path.name definition)
!Oprint.out_type (Printtyp.tree_of_typexp Type defined_as)
!Oprint.out_type (Printtyp.tree_of_typexp Type used_as)
pp_expansions expansions
end
| Inconsistent_constraint (env, err) ->
fprintf ppf "@[<v>The type constraints are not consistent.@ ";
Printtyp.report_unification_error ppf env err
(fun ppf -> fprintf ppf "Type")
(fun ppf -> fprintf ppf "is not compatible with type");
fprintf ppf "@]"
| Type_clash (env, err) ->
Printtyp.report_unification_error ppf env err
(function ppf ->
fprintf ppf "This type constructor expands to type")
(function ppf ->
fprintf ppf "but is used here with type")
| Null_arity_external ->
fprintf ppf "External identifiers must be functions"
| Missing_native_external ->
fprintf ppf "@[<hv>An external function with more than 5 arguments \
requires a second stub function@ \
for native-code compilation@]"
| Unbound_type_var (ty, decl) ->
fprintf ppf "@[A type variable is unbound in this type declaration";
begin match decl.type_kind, decl.type_manifest with
| Type_variant (tl, _rep), _ ->
explain_unbound_gen ppf ty tl (fun c ->
let tl = tys_of_constr_args c.Types.cd_args in
Btype.newgenty (Ttuple tl)
)
"case" (fun ppf c ->
fprintf ppf
"%a of %a" Printtyp.ident c.Types.cd_id
Printtyp.constructor_arguments c.Types.cd_args)
| Type_record (tl, _), _ ->
explain_unbound ppf ty tl (fun l -> l.Types.ld_type)
"field" (fun l -> Ident.name l.Types.ld_id ^ ": ")
| Type_abstract, Some ty' ->
explain_unbound_single ppf ty ty'
| _ -> ()
end;
fprintf ppf "@]"
| Unbound_type_var_ext (ty, ext) ->
fprintf ppf "@[A type variable is unbound in this extension constructor";
let args = tys_of_constr_args ext.ext_args in
explain_unbound ppf ty args (fun c -> c) "type" (fun _ -> "");
fprintf ppf "@]"
| Cannot_extend_private_type path ->
fprintf ppf "@[%s@ %a@]"
"Cannot extend private type definition"
Printtyp.path path
| Not_extensible_type path ->
fprintf ppf "@[%s@ %a@ %s@]"
"Type definition"
Printtyp.path path
"is not extensible"
| Extension_mismatch (path, env, err) ->
fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%s@]%a@]"
"This extension" "does not match the definition of type"
(Path.name path)
(Includecore.report_type_mismatch
"the type" "this extension" "definition" env)
err
| Rebind_wrong_type (lid, env, err) ->
Printtyp.report_unification_error ppf env err
(function ppf ->
fprintf ppf "The constructor %a@ has type"
Printtyp.longident lid)
(function ppf ->
fprintf ppf "but was expected to be of type")
| Rebind_mismatch (lid, p, p') ->
fprintf ppf
"@[%s@ %a@ %s@ %s@ %s@ %s@ %s@]"
"The constructor" Printtyp.longident lid
"extends type" (Path.name p)
"whose declaration does not match"
"the declaration of type" (Path.name p')
| Rebind_private lid ->
fprintf ppf "@[%s@ %a@ %s@]"
"The constructor"
Printtyp.longident lid
"is private"
| Variance (Typedecl_variance.Bad_variance (n, v1, v2)) ->
let variance (p,n,i) =
let inj = if i then "injective " else "" in
match p, n with
true, true -> inj ^ "invariant"
| true, false -> inj ^ "covariant"
| false, true -> inj ^ "contravariant"
| false, false -> if inj = "" then "unrestricted" else inj
in
(match n with
| Variance_not_reflected ->
fprintf ppf "@[%s@ %s@ It"
"In this definition, a type variable has a variance that"
"is not reflected by its occurrence in type parameters."
| No_variable ->
fprintf ppf "@[%s@ %s@]"
"In this definition, a type variable cannot be deduced"
"from the type parameters."
| Variance_not_deducible ->
fprintf ppf "@[%s@ %s@ It"
"In this definition, a type variable has a variance that"
"cannot be deduced from the type parameters."
| Variance_not_satisfied n ->
fprintf ppf "@[%s@ %s@ The %d%s type parameter"
"In this definition, expected parameter"
"variances are not satisfied."
n (Misc.ordinal_suffix n));
(match n with
| No_variable -> ()
| _ ->
fprintf ppf " was expected to be %s,@ but it is %s.@]"
(variance v2) (variance v1))
| Unavailable_type_constructor p ->
fprintf ppf "The definition of type %a@ is unavailable" Printtyp.path p
| Variance Typedecl_variance.Varying_anonymous ->
fprintf ppf "@[%s@ %s@ %s@]"
"In this GADT definition," "the variance of some parameter"
"cannot be checked"
| Val_in_structure ->
fprintf ppf "Value declarations are only allowed in signatures"
| Multiple_native_repr_attributes ->
fprintf ppf "Too many [@@unboxed]/[@@untagged] attributes"
| Cannot_unbox_or_untag_type Unboxed ->
fprintf ppf "@[Don't know how to unbox this type.@ \
Only float, int32, int64 and nativeint can be unboxed.@]"
| Cannot_unbox_or_untag_type Untagged ->
fprintf ppf "@[Don't know how to untag this type.@ \
Only int can be untagged.@]"
| Deep_unbox_or_untag_attribute kind ->
fprintf ppf
"@[The attribute '%s' should be attached to@ \
a direct argument or result of the primitive,@ \
it should not occur deeply into its type.@]"
(match kind with Unboxed -> "@unboxed" | Untagged -> "@untagged")
| Immediacy (Typedecl_immediacy.Bad_immediacy_attribute violation) ->
fprintf ppf "@[%a@]" Format.pp_print_text
(match violation with
| Type_immediacy.Violation.Not_always_immediate ->
"Types marked with the immediate attribute must be \
non-pointer types like int or bool."
| Type_immediacy.Violation.Not_always_immediate_on_64bits ->
"Types marked with the immediate64 attribute must be \
produced using the Stdlib.Sys.Immediate64.Make functor.")
| Bad_unboxed_attribute msg ->
fprintf ppf "@[This type cannot be unboxed because@ %s.@]" msg
| Separability (Typedecl_separability.Non_separable_evar evar) ->
let pp_evar ppf = function
| None ->
fprintf ppf "an unnamed existential variable"
| Some str ->
fprintf ppf "the existential variable %a"
Pprintast.tyvar str in
fprintf ppf "@[This type cannot be unboxed because@ \
it might contain both float and non-float values,@ \
depending on the instantiation of %a.@ \
You should annotate it with [%@%@ocaml.boxed].@]"
pp_evar evar
| Boxed_and_unboxed ->
fprintf ppf "@[A type cannot be boxed and unboxed at the same time.@]"
| Nonrec_gadt ->
fprintf ppf
"@[GADT case syntax cannot be used in a 'nonrec' block.@]"
| Invalid_private_row_declaration ty ->
Format.fprintf ppf
"@[<hv>This private row type declaration is invalid.@ \
The type expression on the right-hand side reduces to@;<1 2>%a@ \
which does not have a free row type variable.@]@,\
@[<hv>@[Hint: If you intended to define a private type abbreviation,@ \
write explicitly@]@;<1 2>private %a@]"
Printtyp.type_expr ty Printtyp.type_expr ty
| Local_not_enabled ->
fprintf ppf "@[The local extension is disabled@ \
To enable it, pass the '-extension local' flag@]"
| Global_and_nonlocal ->
fprintf ppf "@[A type cannot be both global and nonlocal@]"
let () =
Location.register_error_of_exn
(function
| Error (loc, err) ->
Some (Location.error_of_printer ~loc report_error err)
| _ ->
None
)
|
85cb769bd486cc7d8c5e4d5049621fe87771e08a4f3fbc649a005e71ac9a85f1 | aterreno/etcd-clojure | core_test.clj | (ns etcd-clojure.core-test
(:require [clojure.test :refer :all]
[etcd-clojure.core :as etcd]))
(defn setup-test []
(let [connect (etcd/connect! "127.0.0.1")]
(is (= ":2379") (first connect))))
(defn teardown-test []
(println "teardown"))
(defn once-fixtures [f]
(setup-test)
(try
(f)
(finally (teardown-test))))
(defn setup [])
(defn teardown []
(try
(etcd/delete-dir-recur "test-dir")
(etcd/delete-dir-recur "queue")
(catch Exception e)))
(defn each-fixture [f]
(setup)
(f)
(teardown))
(use-fixtures :once once-fixtures)
(use-fixtures :each each-fixture)
(deftest test-version
(testing "should get some value from the server: note hardcoded version"
(is (=
["etcdserver","etcdcluster"]
(keys (etcd/version))))))
(deftest test-set
(testing "should set a value"
(is (= "bar" (etcd/set "foo-test" "bar")))))
(deftest test-get
(testing "should get a value"
(etcd/set "foo-test" "bar")
(is (= "bar" (etcd/get "foo-test")))))
(deftest test-delete
(testing "should delete a value"
(etcd/set "foo-test" "bar")
(is (= "/foo-test" (etcd/delete "foo-test")))))
(deftest test-create-dir
(testing "should create a directory"
(is (= "/test-dir" (etcd/create-dir "test-dir")))))
(deftest test-delete-dir
(testing "should delete a directory"
(etcd/create-dir "test-dir")
(is (= "/test-dir" (etcd/delete-dir "test-dir")))))
(deftest test-delete-dir-recur
(testing "should delete a directory recursively"
(etcd/create-dir "test-dir")
(etcd/set "test-dir/test-val-on-dir" "bar")
(is (= "/test-dir" (etcd/delete-dir-recur "test-dir")))))
(deftest test-create-and-list-in-order
(testing "should be able to create and retrieve values in order"
(etcd/create-in-order "queue" "1")
(etcd/create-in-order "queue" "2")
(etcd/create-in-order "queue" "3")
(is (= ["1" "2" "3"] (etcd/list-in-order "queue")))))
(deftest test-list-directory
(testing "should list the content of a directory"
(etcd/create-dir "test-dir")
(etcd/set "test-dir/test-val1-on-dir" "1")
(etcd/set "test-dir/test-val2-on-dir" "2")
(etcd/set "test-dir/test-val3-on-dir" "3")
(is (= 3
(count (etcd/list "test-dir"))))))
(deftest test-stats
(testing "should retrive stats"
(is (and
(contains? (etcd/stats) "leader")
(contains? (etcd/stats) "followers")))))
(deftest test-self-stats
(testing "should retrive self stats"
(is (= '("name" "id" "state" "startTime" "leaderInfo" "recvAppendRequestCnt" "sendAppendRequestCnt")
(keys (etcd/self-stats))))))
(deftest test-store-stats
(testing "should retrive store stats"
(is (not (nil?
(etcd/store-stats))))))
(deftest test-machines
(testing "should retrive machines"
(is (= 1
(count (etcd/members)))))) | null | https://raw.githubusercontent.com/aterreno/etcd-clojure/3112e8b1bddbb71bb0cfa12bc9a60550b4f02305/test/etcd_clojure/core_test.clj | clojure | (ns etcd-clojure.core-test
(:require [clojure.test :refer :all]
[etcd-clojure.core :as etcd]))
(defn setup-test []
(let [connect (etcd/connect! "127.0.0.1")]
(is (= ":2379") (first connect))))
(defn teardown-test []
(println "teardown"))
(defn once-fixtures [f]
(setup-test)
(try
(f)
(finally (teardown-test))))
(defn setup [])
(defn teardown []
(try
(etcd/delete-dir-recur "test-dir")
(etcd/delete-dir-recur "queue")
(catch Exception e)))
(defn each-fixture [f]
(setup)
(f)
(teardown))
(use-fixtures :once once-fixtures)
(use-fixtures :each each-fixture)
(deftest test-version
(testing "should get some value from the server: note hardcoded version"
(is (=
["etcdserver","etcdcluster"]
(keys (etcd/version))))))
(deftest test-set
(testing "should set a value"
(is (= "bar" (etcd/set "foo-test" "bar")))))
(deftest test-get
(testing "should get a value"
(etcd/set "foo-test" "bar")
(is (= "bar" (etcd/get "foo-test")))))
(deftest test-delete
(testing "should delete a value"
(etcd/set "foo-test" "bar")
(is (= "/foo-test" (etcd/delete "foo-test")))))
(deftest test-create-dir
(testing "should create a directory"
(is (= "/test-dir" (etcd/create-dir "test-dir")))))
(deftest test-delete-dir
(testing "should delete a directory"
(etcd/create-dir "test-dir")
(is (= "/test-dir" (etcd/delete-dir "test-dir")))))
(deftest test-delete-dir-recur
(testing "should delete a directory recursively"
(etcd/create-dir "test-dir")
(etcd/set "test-dir/test-val-on-dir" "bar")
(is (= "/test-dir" (etcd/delete-dir-recur "test-dir")))))
(deftest test-create-and-list-in-order
(testing "should be able to create and retrieve values in order"
(etcd/create-in-order "queue" "1")
(etcd/create-in-order "queue" "2")
(etcd/create-in-order "queue" "3")
(is (= ["1" "2" "3"] (etcd/list-in-order "queue")))))
(deftest test-list-directory
(testing "should list the content of a directory"
(etcd/create-dir "test-dir")
(etcd/set "test-dir/test-val1-on-dir" "1")
(etcd/set "test-dir/test-val2-on-dir" "2")
(etcd/set "test-dir/test-val3-on-dir" "3")
(is (= 3
(count (etcd/list "test-dir"))))))
(deftest test-stats
(testing "should retrive stats"
(is (and
(contains? (etcd/stats) "leader")
(contains? (etcd/stats) "followers")))))
(deftest test-self-stats
(testing "should retrive self stats"
(is (= '("name" "id" "state" "startTime" "leaderInfo" "recvAppendRequestCnt" "sendAppendRequestCnt")
(keys (etcd/self-stats))))))
(deftest test-store-stats
(testing "should retrive store stats"
(is (not (nil?
(etcd/store-stats))))))
(deftest test-machines
(testing "should retrive machines"
(is (= 1
(count (etcd/members)))))) | |
89ebdbd3ca1148dd88e2e80e1df59d9e630c9c49408caa7ff061c91c45e0a8b4 | rudolph-miller/dyna | error.lisp | (in-package :cl-user)
(defpackage dyna.error
(:use :cl))
(in-package :dyna.error)
(syntax:use-syntax :annot)
@export
(define-condition <dyna-error> (simple-error) ())
@export
(define-condition <dyna-request-error> (<dyna-error>)
((status :initarg :status)
(meta :initarg :meta)
(message :initarg :message))
(:report
(lambda (condition stream)
(format stream
"Error occured in request.~%Status: ~a~%Messssage: ~a~%Meta: ~a."
(slot-value condition 'status)
(slot-value condition 'message)
(let ((meta (slot-value condition 'meta)))
(etypecase meta
(cons meta)
(hash-table (alexandria:hash-table-plist meta))))))))
@export
(define-condition <dyna-incomplete-argumet-error> (<dyna-error>)
((args :initarg :args))
(:report
(lambda (condition stream)
(format stream
"You must complete ~{:~a~^,~}."
(slot-value condition 'args)))))
@export
(define-condition <dyna-incompatible-table-schema> (<dyna-error>)
((table :initarg :table))
(:report
(lambda (condition stream)
(format stream
"Table: ~a is incompatible with the table schema in DynamoDB."
(slot-value condition 'table)))))
@export
(define-condition <dyna-inexist-table> (<dyna-error>)
((table :initarg :table))
(:report
(lambda (condition stream)
(format stream
"Table: ~a doesn't exists in DynamoDB"
(slot-value condition 'table)))))
@export
(define-condition <dyna-unsupported-op-error> (<dyna-error>)
((op :initarg :op))
(:report
(lambda (condition stream)
(format stream "Unsupported operation: ~a"
(slot-value condition 'op)))))
@export
(define-condition <dyna-changing-lsi-error> (<dyna-error>)
()
(:report
(lambda (condition stream)
(declare (ignore condition))
(format stream "Changing Local Secondary Index is not allowed in DynamoDB itself."))))
| null | https://raw.githubusercontent.com/rudolph-miller/dyna/d8cf27bc7428e3ac578ed704ff72de98582d89e0/src/error.lisp | lisp | (in-package :cl-user)
(defpackage dyna.error
(:use :cl))
(in-package :dyna.error)
(syntax:use-syntax :annot)
@export
(define-condition <dyna-error> (simple-error) ())
@export
(define-condition <dyna-request-error> (<dyna-error>)
((status :initarg :status)
(meta :initarg :meta)
(message :initarg :message))
(:report
(lambda (condition stream)
(format stream
"Error occured in request.~%Status: ~a~%Messssage: ~a~%Meta: ~a."
(slot-value condition 'status)
(slot-value condition 'message)
(let ((meta (slot-value condition 'meta)))
(etypecase meta
(cons meta)
(hash-table (alexandria:hash-table-plist meta))))))))
@export
(define-condition <dyna-incomplete-argumet-error> (<dyna-error>)
((args :initarg :args))
(:report
(lambda (condition stream)
(format stream
"You must complete ~{:~a~^,~}."
(slot-value condition 'args)))))
@export
(define-condition <dyna-incompatible-table-schema> (<dyna-error>)
((table :initarg :table))
(:report
(lambda (condition stream)
(format stream
"Table: ~a is incompatible with the table schema in DynamoDB."
(slot-value condition 'table)))))
@export
(define-condition <dyna-inexist-table> (<dyna-error>)
((table :initarg :table))
(:report
(lambda (condition stream)
(format stream
"Table: ~a doesn't exists in DynamoDB"
(slot-value condition 'table)))))
@export
(define-condition <dyna-unsupported-op-error> (<dyna-error>)
((op :initarg :op))
(:report
(lambda (condition stream)
(format stream "Unsupported operation: ~a"
(slot-value condition 'op)))))
@export
(define-condition <dyna-changing-lsi-error> (<dyna-error>)
()
(:report
(lambda (condition stream)
(declare (ignore condition))
(format stream "Changing Local Secondary Index is not allowed in DynamoDB itself."))))
| |
1d8ce7f2692b1751ac53064f96f9f6ac6e948fe3cf45a6315576d52957c854e9 | amnh/PCG | Custom.hs | -----------------------------------------------------------------------------
-- |
Module : Text . . Custom
Copyright : ( c ) 2015 - 2021 Ward Wheeler
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
Custom utility combinators for ' Text . ' parser construction .
--
-----------------------------------------------------------------------------
# LANGUAGE ApplicativeDo #
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Text.Megaparsec.Custom
( anythingTill
, double
, endOfLine
, fails
, noneOfThese
, someOfThese
, somethingTill
, string''
) where
import Data.CaseInsensitive (FoldCase)
import Data.Foldable
import Data.Functor (($>))
import Data.List (sort)
import Data.List.NonEmpty (nonEmpty)
import Data.Maybe (mapMaybe)
import Data.Proxy
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Vector.Unboxed (Unbox, Vector, (!))
import qualified Data.Vector.Unboxed as V
import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as LEX
-- |
-- Parse a string-like chunk.
# INLINEABLE string '' #
# SPECIALISE string '' : : String - > Parsec Void T.Text T.Text #
# SPECIALISE string '' : : String - > Parsec Void LT.Text LT.Text #
# SPECIALISE string '' : : String - > Parsec Void String String #
string'' :: forall e s m. (FoldCase (Tokens s), MonadParsec e s m, Token s ~ Char) => String -> m (Tokens s)
string'' = string' . tokensToChunk (Proxy :: Proxy s)
-- |
@anythingTill end@ consumes zero or more characters until @end@ is matched ,
leaving @end@ in the stream .
{-# INLINEABLE anythingTill #-}
# SPECIALISE anythingTill : : Parsec Void T.Text a - > Parsec Void T.Text String #
# SPECIALISE anythingTill : : Parsec Void LT.Text a - > Parsec Void LT.Text String #
# SPECIALISE anythingTill : : Parsec Void String a - > Parsec Void String String #
anythingTill :: MonadParsec e s m => m a -> m [Token s]
anythingTill c = do
ahead <- optional . try $ lookAhead c
case ahead of
Just _ -> pure []
Nothing -> somethingTill c
-- |
@somethingTill end@ consumes one or more characters until @end@ is matched ,
leaving @end@ in the stream .
# INLINEABLE somethingTill #
# SPECIALISE somethingTill : : Parsec Void T.Text a - > Parsec Void T.Text String #
# SPECIALISE somethingTill : : Parsec Void LT.Text a - > Parsec Void LT.Text String #
# SPECIALISE somethingTill : : Parsec Void String a - > Parsec Void String String #
somethingTill :: MonadParsec e s m => m a -> m [Token s]
somethingTill c = do
_ <- notFollowedBy c
(:) <$> anySingle <*> anythingTill c
-- |
Matches one or more elements from the supplied collection .
--
-- Coerces the collection to a sorted, unboxed vector and performs a binary
-- search on the elements to determine if a 'Token s' is part of the collection.
--
Preferable to ' Text . ' .
# INLINE someOfThese #
# SPECIALISE someOfThese : : Foldable f = > f Char - > Parsec Void T.Text T.Text #
# SPECIALISE someOfThese : : Foldable f = > f Char - > Parsec Void LT.Text LT.Text #
# SPECIALISE someOfThese : : Foldable f = > f Char - > Parsec Void String String #
# SPECIALISE someOfThese : : String - > Parsec Void T.Text T.Text #
# SPECIALISE someOfThese : : String - > Parsec Void LT.Text LT.Text #
# SPECIALISE someOfThese : : String - > Parsec Void String String #
someOfThese :: (Foldable f, MonadParsec e s m, Token s ~ a, Unbox a) => f a -> m (Tokens s)
someOfThese xs =
let !uvec = V.fromList . sort $ toList xs
!cond = withinVec uvec
in takeWhile1P Nothing cond
-- |
Matches one or more elements /not/ from the supplied collection .
--
-- Coerces the collection to a sorted, unboxed vector and performs a binary
-- search on the elements to determine if a 'Token s' is part of the collection.
--
-- Preferable to 'noneOf'.
# INLINE noneOfThese #
# SPECIALISE noneOfThese : : Foldable f = > f Char - > Parsec Void T.Text T.Text #
# SPECIALISE noneOfThese : : Foldable f = > f Char - > Parsec Void LT.Text LT.Text #
# SPECIALISE noneOfThese : : Foldable f = > f Char - > Parsec Void String String #
# SPECIALISE noneOfThese : : String - > Parsec Void T.Text T.Text #
# SPECIALISE noneOfThese : : String - > Parsec Void LT.Text LT.Text #
# SPECIALISE noneOfThese : : String - > Parsec Void String String #
noneOfThese :: (Foldable f, MonadParsec e s m, Token s ~ a, Unbox a) => f a -> m (Tokens s)
noneOfThese xs =
let !uvec = V.fromList . sort $ toList xs
!cond = not . withinVec uvec
in takeWhile1P Nothing cond
-- |
-- Flexibly parses a 'Double' value represented in a variety of forms.
# INLINEABLE double #
# SPECIALISE double : : Parsec Void T.Text Double #
# SPECIALISE double : : Parsec Void LT.Text Double #
# SPECIALISE double : : Parsec Void String Double #
double :: (MonadParsec e s m, Token s ~ Char) => m Double
double = try real <|> fromIntegral <$> int
where
int :: (MonadParsec e s m, Token s ~ Char) => m Integer
int = LEX.signed space LEX.decimal
real = LEX.signed space LEX.float
-- |
Custom ' eol ' combinator to account for /very/ old Mac file formats ending
lines in a single @\'\\r\'@.
# INLINE endOfLine #
# SPECIALISE endOfLine : : Parsec Void T.Text ( ) #
# SPECIALISE endOfLine : : Parsec Void LT.Text ( ) #
# SPECIALISE endOfLine : : Parsec Void String ( ) #
endOfLine :: (Enum (Token s), MonadParsec e s m) => m ()
endOfLine = choice [ nl, try (cr *> nl), cr ] $> ()
where
newLineChar = enumCoerce '\n'
carriageChar = enumCoerce '\r'
nl = single newLineChar $> ()
cr = single carriageChar $> ()
-- |
-- Accepts zero or more Failure messages.
# INLINEABLE fails #
# SPECIALISE fails : : [ String ] - > Parsec Void T.Text a #
# SPECIALISE fails : : [ String ] - > Parsec Void LT.Text a #
# SPECIALISE fails : : [ String ] - > Parsec Void String a #
fails :: MonadParsec e s m => [String] -> m a
fails = failure Nothing . S.fromList . fmap Label . mapMaybe nonEmpty
-- |
Convert one to another through the Int value .
enumCoerce :: (Enum a, Enum b) => a -> b
enumCoerce = toEnum . fromEnum
# INLINE withinVec #
{-# SPECIALISE withinVec :: Vector Char -> Char -> Bool #-}
withinVec :: (Ord a, Unbox a) => Vector a -> a -> Bool
withinVec v e = go 0 (V.length v - 1)
where
-- Perform a binary search on the unboxed vector
-- to determine if a character is valid.
--
-- Equally fast, and uses less memory than a Set.
# INLINE go #
go !lo !hi
| lo > hi = False
| otherwise = let !md = (hi + lo) `div` 2
!z = v ! md
in case z `compare` e of
EQ -> True
LT -> go (md + 1) hi
GT -> go lo (md - 1)
| null | https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/file-parsers/src/Text/Megaparsec/Custom.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
---------------------------------------------------------------------------
# LANGUAGE BangPatterns #
# LANGUAGE FlexibleContexts #
|
Parse a string-like chunk.
|
# INLINEABLE anythingTill #
|
|
Coerces the collection to a sorted, unboxed vector and performs a binary
search on the elements to determine if a 'Token s' is part of the collection.
|
Coerces the collection to a sorted, unboxed vector and performs a binary
search on the elements to determine if a 'Token s' is part of the collection.
Preferable to 'noneOf'.
|
Flexibly parses a 'Double' value represented in a variety of forms.
|
|
Accepts zero or more Failure messages.
|
# SPECIALISE withinVec :: Vector Char -> Char -> Bool #
Perform a binary search on the unboxed vector
to determine if a character is valid.
Equally fast, and uses less memory than a Set. | Module : Text . . Custom
Copyright : ( c ) 2015 - 2021 Ward Wheeler
Custom utility combinators for ' Text . ' parser construction .
# LANGUAGE ApplicativeDo #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Text.Megaparsec.Custom
( anythingTill
, double
, endOfLine
, fails
, noneOfThese
, someOfThese
, somethingTill
, string''
) where
import Data.CaseInsensitive (FoldCase)
import Data.Foldable
import Data.Functor (($>))
import Data.List (sort)
import Data.List.NonEmpty (nonEmpty)
import Data.Maybe (mapMaybe)
import Data.Proxy
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Vector.Unboxed (Unbox, Vector, (!))
import qualified Data.Vector.Unboxed as V
import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as LEX
# INLINEABLE string '' #
# SPECIALISE string '' : : String - > Parsec Void T.Text T.Text #
# SPECIALISE string '' : : String - > Parsec Void LT.Text LT.Text #
# SPECIALISE string '' : : String - > Parsec Void String String #
string'' :: forall e s m. (FoldCase (Tokens s), MonadParsec e s m, Token s ~ Char) => String -> m (Tokens s)
string'' = string' . tokensToChunk (Proxy :: Proxy s)
@anythingTill end@ consumes zero or more characters until @end@ is matched ,
leaving @end@ in the stream .
# SPECIALISE anythingTill : : Parsec Void T.Text a - > Parsec Void T.Text String #
# SPECIALISE anythingTill : : Parsec Void LT.Text a - > Parsec Void LT.Text String #
# SPECIALISE anythingTill : : Parsec Void String a - > Parsec Void String String #
anythingTill :: MonadParsec e s m => m a -> m [Token s]
anythingTill c = do
ahead <- optional . try $ lookAhead c
case ahead of
Just _ -> pure []
Nothing -> somethingTill c
@somethingTill end@ consumes one or more characters until @end@ is matched ,
leaving @end@ in the stream .
# INLINEABLE somethingTill #
# SPECIALISE somethingTill : : Parsec Void T.Text a - > Parsec Void T.Text String #
# SPECIALISE somethingTill : : Parsec Void LT.Text a - > Parsec Void LT.Text String #
# SPECIALISE somethingTill : : Parsec Void String a - > Parsec Void String String #
somethingTill :: MonadParsec e s m => m a -> m [Token s]
somethingTill c = do
_ <- notFollowedBy c
(:) <$> anySingle <*> anythingTill c
Matches one or more elements from the supplied collection .
Preferable to ' Text . ' .
# INLINE someOfThese #
# SPECIALISE someOfThese : : Foldable f = > f Char - > Parsec Void T.Text T.Text #
# SPECIALISE someOfThese : : Foldable f = > f Char - > Parsec Void LT.Text LT.Text #
# SPECIALISE someOfThese : : Foldable f = > f Char - > Parsec Void String String #
# SPECIALISE someOfThese : : String - > Parsec Void T.Text T.Text #
# SPECIALISE someOfThese : : String - > Parsec Void LT.Text LT.Text #
# SPECIALISE someOfThese : : String - > Parsec Void String String #
someOfThese :: (Foldable f, MonadParsec e s m, Token s ~ a, Unbox a) => f a -> m (Tokens s)
someOfThese xs =
let !uvec = V.fromList . sort $ toList xs
!cond = withinVec uvec
in takeWhile1P Nothing cond
Matches one or more elements /not/ from the supplied collection .
# INLINE noneOfThese #
# SPECIALISE noneOfThese : : Foldable f = > f Char - > Parsec Void T.Text T.Text #
# SPECIALISE noneOfThese : : Foldable f = > f Char - > Parsec Void LT.Text LT.Text #
# SPECIALISE noneOfThese : : Foldable f = > f Char - > Parsec Void String String #
# SPECIALISE noneOfThese : : String - > Parsec Void T.Text T.Text #
# SPECIALISE noneOfThese : : String - > Parsec Void LT.Text LT.Text #
# SPECIALISE noneOfThese : : String - > Parsec Void String String #
noneOfThese :: (Foldable f, MonadParsec e s m, Token s ~ a, Unbox a) => f a -> m (Tokens s)
noneOfThese xs =
let !uvec = V.fromList . sort $ toList xs
!cond = not . withinVec uvec
in takeWhile1P Nothing cond
# INLINEABLE double #
# SPECIALISE double : : Parsec Void T.Text Double #
# SPECIALISE double : : Parsec Void LT.Text Double #
# SPECIALISE double : : Parsec Void String Double #
double :: (MonadParsec e s m, Token s ~ Char) => m Double
double = try real <|> fromIntegral <$> int
where
int :: (MonadParsec e s m, Token s ~ Char) => m Integer
int = LEX.signed space LEX.decimal
real = LEX.signed space LEX.float
Custom ' eol ' combinator to account for /very/ old Mac file formats ending
lines in a single @\'\\r\'@.
# INLINE endOfLine #
# SPECIALISE endOfLine : : Parsec Void T.Text ( ) #
# SPECIALISE endOfLine : : Parsec Void LT.Text ( ) #
# SPECIALISE endOfLine : : Parsec Void String ( ) #
endOfLine :: (Enum (Token s), MonadParsec e s m) => m ()
endOfLine = choice [ nl, try (cr *> nl), cr ] $> ()
where
newLineChar = enumCoerce '\n'
carriageChar = enumCoerce '\r'
nl = single newLineChar $> ()
cr = single carriageChar $> ()
# INLINEABLE fails #
# SPECIALISE fails : : [ String ] - > Parsec Void T.Text a #
# SPECIALISE fails : : [ String ] - > Parsec Void LT.Text a #
# SPECIALISE fails : : [ String ] - > Parsec Void String a #
fails :: MonadParsec e s m => [String] -> m a
fails = failure Nothing . S.fromList . fmap Label . mapMaybe nonEmpty
Convert one to another through the Int value .
enumCoerce :: (Enum a, Enum b) => a -> b
enumCoerce = toEnum . fromEnum
# INLINE withinVec #
withinVec :: (Ord a, Unbox a) => Vector a -> a -> Bool
withinVec v e = go 0 (V.length v - 1)
where
# INLINE go #
go !lo !hi
| lo > hi = False
| otherwise = let !md = (hi + lo) `div` 2
!z = v ! md
in case z `compare` e of
EQ -> True
LT -> go (md + 1) hi
GT -> go lo (md - 1)
|
37ca52397ee87401948a1ddf276f43e8247d06e2109d93402d382c33af08cd77 | shirok/Gauche | cross-compile-ios.scm | #!/usr/bin/env gosh
(use gauche.generator)
(use gauche.process)
(use srfi.13)
(use file.util)
;; Global parameters
;; we build stuff under *builddir*/$ARCH
(define *builddir* "build-ios")
;; the final output destination
(define *outdir* (build-path *builddir* "Gauche-iOS-core.framework"))
;; gauche abi version
(define *abi-version* "0.9")
;; SDK versions
(define *ios-deploy-target-version* "7.1")
( define * ios - build - sdk - version * " 8.3 " ) ; unused for now
;;
;; Architecture-dependent stuff
;;
(define (devroot target)
(ecase target
[(armv7 armv7s arm64)
"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer"]
[(i386 x86_64)
"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer"]))
(define (sdkroot target)
(ecase target
[(armv7 armv7s arm64)
(build-path (devroot target)
"SDKs/iPhoneOS.sdk")]
[(i386 x86_64)
(build-path (devroot target)
"SDKs/iPhoneSimulator.sdk")]))
(define (environment-alist target)
(let ([dev (devroot target)]
[sdkdir (sdkroot target)]
[cflags-xtra (case target
[(i386 x86_64) " -DNO_DYLD_BIND_FULLY_IMAGE"]
[else ""])]
[sdk (case target
[(i386 x86_64) "iphonesimulator"]
[else "iphoneos"])])
`(("CC" . ,(process-output->string `("xcrun" "-find" "-sdk" ,sdk "clang")))
("LD" . ,(build-path dev "usr/bin/ld"))
("AR" . ,(process-output->string `("xcrun" "-find" "-sdk" ,sdk "ar")))
("NM" . ,(build-path dev "usr/bin/nm"))
("RANLIB" . ,(process-output->string `("xcrun" "-find" "-sdk" ,sdk "ranlib")))
("CFLAGS" . ,#"-arch ~target -pipe -no-cpp-precomp -isysroot ~sdkdir -miphoneos-version-min=~*ios-deploy-target-version* -I~|sdkdir|/usr/include/ ~cflags-xtra")
("LDFLAGS" . ,#"-framework CoreFoundation -L~|sdkdir|/usr/lib/"))))
(define (build-1 target)
(let* ([envs (map (^p #"~(car p)=~(cdr p)") (environment-alist target))]
[build (process-output->string "./config.guess")]
[builddir (build-path *builddir* (x->string target))]
[host (ecase target
[(armv7) "arm-apple-darwin7"]
[(armv7s) "arm-apple-darwin7s"]
[(arm64) "arm-apple-darwin8"]
[(i386) "i386-apple-darwin12.4"]
[(x86_64) "x86_64-apple-darwin12.4"])]
[configure-cmd `("/usr/bin/env" ,@envs
"../../configure"
,#"--build=~build"
,#"--host=~host"
"--with-dbm=no")]
[make-cmd `("/usr/bin/env" ,@envs "make" "-j")]
[static-cmd `("/usr/bin/env" ,@envs "make" "static")])
(define (run1 cmd dir)
(print cmd)
(let1 p (run-process cmd :wait #t :directory dir)
(unless (= (process-exit-status p) 0)
(error "Process failed:" cmd))))
(make-directory* builddir)
(run1 configure-cmd builddir)
(run1 make-cmd builddir)
(run1 static-cmd (build-path builddir "src"))))
(define (run-lipo)
(define (archive target)
(build-path *builddir* (x->string target) "src"
#"libgauche-static-~|*abi-version*|.a"))
(make-directory* *outdir*)
(let* ([cmd `("xcrun" "-sdk" "iphoneos" "lipo"
"-arch" "armv7s" ,(archive 'armv7s)
"-arch" "armv7" ,(archive 'armv7)
"-arch" "arm64" ,(archive 'arm64)
"-arch" "i386" ,(archive 'i386)
"-arch" "x86_64" ,(archive 'x86_64)
"-create"
"-output" ,(build-path *outdir*
#"libgauche-~|*abi-version*|.a"))]
[p (run-process cmd :wait #t)])
(unless (= (process-exit-status p) 0)
(error "Process failed:" cmd))))
(define (run-all)
(when (file-exists? *builddir*)
(remove-directory* *builddir*))
(build-1 'armv7)
(build-1 'armv7s)
(build-1 'arm64)
(build-1 'i386)
(build-1 'x86_64)
(run-lipo))
(define (copy-includes)
(define (copy file dst)
(let1 src (or (any (^p (and (file-exists? p) p))
(list (build-path "src" file)
(build-path *builddir* "i386/src" file)
(build-path *builddir* "x86_64/src" file)))
(error "Missing file:" file))
(print "Copying " (sys-normalize-pathname src :absolute #t) " -> " dst)
(with-output-to-file dst
(^[]
(do-generator [line (file->line-generator src)]
(print (regexp-replace-all*
line
#/#include <gc\.h>/ "#include <Gauche-iOS-core/gc.h>"
#/#\s*include <(gauche.*)\.h>/ "#include <Gauche-iOS-core/\\1.h>"
#/#\s*include \"(gc.*)\.h\"/ "#include \"Gauche-iOS-core/\\1.h\"")))))))
(make-directory* (build-path *outdir* "Headers/gauche"))
(dolist [hdr (mfvar-ref "src/Makefile.in" "INSTALL_HEADERS")]
(copy hdr (build-path *outdir* "Headers" (sys-basename hdr))))
(dolist [hdr (mfvar-ref "src/Makefile.in" "INSTALL_SUBHEADERS")]
(copy hdr (build-path *outdir* "Headers" hdr))))
(define (copy-resources)
(make-directory* (build-path *outdir* "Resources"))
(copy-file "src/Info.plist" (build-path *outdir* "Resources/Info.plist")))
(define (wire-stuff)
(sys-symlink #"libgauche-~|*abi-version*|.a"
(build-path *outdir* "Gauche-iOS-core")))
(define (preparation)
(sys-system "./DIST gen")
(sys-system "./configure")
(sys-system "(cd src; make pre-package)")
(sys-system "make distclean"))
(define (main args)
(preparation)
(run-all)
(copy-includes)
(copy-resources)
(wire-stuff)
0)
;;
Utilities
;;
(define read-line/continuation
(gbuffer-filter (^[v s]
(if-let1 m (#/\\$/ v)
(values '() (cons (m 'before) s))
(values `(,(string-concatenate-reverse (cons v s))) '())))
'()
read-line
(^[s] `(,(string-concatenate-reverse s)))))
(define (mfvar-ref makefile var :optional default)
(if-let1 line (with-input-from-file makefile
(cute generator-find (string->regexp #"^~|var|\\b")
read-line/continuation))
(remove string-null?
(string-split
(rxmatch->string (string->regexp #"^~|var|\\s*=\\s*")
line 'after)
#[\s+]))
(if (undefined? default)
(errorf "Cannot find ~a definition in ~a" var makefile)
default)))
| null | https://raw.githubusercontent.com/shirok/Gauche/e606bfe5a94b100d5807bca9c2bb95df94f60aa6/src/cross-compile-ios.scm | scheme | Global parameters
we build stuff under *builddir*/$ARCH
the final output destination
gauche abi version
SDK versions
unused for now
Architecture-dependent stuff
| #!/usr/bin/env gosh
(use gauche.generator)
(use gauche.process)
(use srfi.13)
(use file.util)
(define *builddir* "build-ios")
(define *outdir* (build-path *builddir* "Gauche-iOS-core.framework"))
(define *abi-version* "0.9")
(define *ios-deploy-target-version* "7.1")
(define (devroot target)
(ecase target
[(armv7 armv7s arm64)
"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer"]
[(i386 x86_64)
"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer"]))
(define (sdkroot target)
(ecase target
[(armv7 armv7s arm64)
(build-path (devroot target)
"SDKs/iPhoneOS.sdk")]
[(i386 x86_64)
(build-path (devroot target)
"SDKs/iPhoneSimulator.sdk")]))
(define (environment-alist target)
(let ([dev (devroot target)]
[sdkdir (sdkroot target)]
[cflags-xtra (case target
[(i386 x86_64) " -DNO_DYLD_BIND_FULLY_IMAGE"]
[else ""])]
[sdk (case target
[(i386 x86_64) "iphonesimulator"]
[else "iphoneos"])])
`(("CC" . ,(process-output->string `("xcrun" "-find" "-sdk" ,sdk "clang")))
("LD" . ,(build-path dev "usr/bin/ld"))
("AR" . ,(process-output->string `("xcrun" "-find" "-sdk" ,sdk "ar")))
("NM" . ,(build-path dev "usr/bin/nm"))
("RANLIB" . ,(process-output->string `("xcrun" "-find" "-sdk" ,sdk "ranlib")))
("CFLAGS" . ,#"-arch ~target -pipe -no-cpp-precomp -isysroot ~sdkdir -miphoneos-version-min=~*ios-deploy-target-version* -I~|sdkdir|/usr/include/ ~cflags-xtra")
("LDFLAGS" . ,#"-framework CoreFoundation -L~|sdkdir|/usr/lib/"))))
(define (build-1 target)
(let* ([envs (map (^p #"~(car p)=~(cdr p)") (environment-alist target))]
[build (process-output->string "./config.guess")]
[builddir (build-path *builddir* (x->string target))]
[host (ecase target
[(armv7) "arm-apple-darwin7"]
[(armv7s) "arm-apple-darwin7s"]
[(arm64) "arm-apple-darwin8"]
[(i386) "i386-apple-darwin12.4"]
[(x86_64) "x86_64-apple-darwin12.4"])]
[configure-cmd `("/usr/bin/env" ,@envs
"../../configure"
,#"--build=~build"
,#"--host=~host"
"--with-dbm=no")]
[make-cmd `("/usr/bin/env" ,@envs "make" "-j")]
[static-cmd `("/usr/bin/env" ,@envs "make" "static")])
(define (run1 cmd dir)
(print cmd)
(let1 p (run-process cmd :wait #t :directory dir)
(unless (= (process-exit-status p) 0)
(error "Process failed:" cmd))))
(make-directory* builddir)
(run1 configure-cmd builddir)
(run1 make-cmd builddir)
(run1 static-cmd (build-path builddir "src"))))
(define (run-lipo)
(define (archive target)
(build-path *builddir* (x->string target) "src"
#"libgauche-static-~|*abi-version*|.a"))
(make-directory* *outdir*)
(let* ([cmd `("xcrun" "-sdk" "iphoneos" "lipo"
"-arch" "armv7s" ,(archive 'armv7s)
"-arch" "armv7" ,(archive 'armv7)
"-arch" "arm64" ,(archive 'arm64)
"-arch" "i386" ,(archive 'i386)
"-arch" "x86_64" ,(archive 'x86_64)
"-create"
"-output" ,(build-path *outdir*
#"libgauche-~|*abi-version*|.a"))]
[p (run-process cmd :wait #t)])
(unless (= (process-exit-status p) 0)
(error "Process failed:" cmd))))
(define (run-all)
(when (file-exists? *builddir*)
(remove-directory* *builddir*))
(build-1 'armv7)
(build-1 'armv7s)
(build-1 'arm64)
(build-1 'i386)
(build-1 'x86_64)
(run-lipo))
(define (copy-includes)
(define (copy file dst)
(let1 src (or (any (^p (and (file-exists? p) p))
(list (build-path "src" file)
(build-path *builddir* "i386/src" file)
(build-path *builddir* "x86_64/src" file)))
(error "Missing file:" file))
(print "Copying " (sys-normalize-pathname src :absolute #t) " -> " dst)
(with-output-to-file dst
(^[]
(do-generator [line (file->line-generator src)]
(print (regexp-replace-all*
line
#/#include <gc\.h>/ "#include <Gauche-iOS-core/gc.h>"
#/#\s*include <(gauche.*)\.h>/ "#include <Gauche-iOS-core/\\1.h>"
#/#\s*include \"(gc.*)\.h\"/ "#include \"Gauche-iOS-core/\\1.h\"")))))))
(make-directory* (build-path *outdir* "Headers/gauche"))
(dolist [hdr (mfvar-ref "src/Makefile.in" "INSTALL_HEADERS")]
(copy hdr (build-path *outdir* "Headers" (sys-basename hdr))))
(dolist [hdr (mfvar-ref "src/Makefile.in" "INSTALL_SUBHEADERS")]
(copy hdr (build-path *outdir* "Headers" hdr))))
(define (copy-resources)
(make-directory* (build-path *outdir* "Resources"))
(copy-file "src/Info.plist" (build-path *outdir* "Resources/Info.plist")))
(define (wire-stuff)
(sys-symlink #"libgauche-~|*abi-version*|.a"
(build-path *outdir* "Gauche-iOS-core")))
(define (preparation)
(sys-system "./DIST gen")
(sys-system "./configure")
(sys-system "(cd src; make pre-package)")
(sys-system "make distclean"))
(define (main args)
(preparation)
(run-all)
(copy-includes)
(copy-resources)
(wire-stuff)
0)
Utilities
(define read-line/continuation
(gbuffer-filter (^[v s]
(if-let1 m (#/\\$/ v)
(values '() (cons (m 'before) s))
(values `(,(string-concatenate-reverse (cons v s))) '())))
'()
read-line
(^[s] `(,(string-concatenate-reverse s)))))
(define (mfvar-ref makefile var :optional default)
(if-let1 line (with-input-from-file makefile
(cute generator-find (string->regexp #"^~|var|\\b")
read-line/continuation))
(remove string-null?
(string-split
(rxmatch->string (string->regexp #"^~|var|\\s*=\\s*")
line 'after)
#[\s+]))
(if (undefined? default)
(errorf "Cannot find ~a definition in ~a" var makefile)
default)))
|
f7c81fc48612ed59ae709cde0f052e77324866296753e2760caf32f2ac9cab0e | FranklinChen/hugs98-plus-Sep2006 | Utils.hs | # OPTIONS_GHC -fno - implicit - prelude #
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Marshal.Utils
Copyright : ( c ) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer :
-- Stability : provisional
-- Portability : portable
--
Utilities for primitive marshaling
--
-----------------------------------------------------------------------------
module Foreign.Marshal.Utils (
-- * General marshalling utilities
-- ** Combined allocation and marshalling
--
with, -- :: Storable a => a -> (Ptr a -> IO b) -> IO b
new, -- :: Storable a => a -> IO (Ptr a)
* * Marshalling of Boolean values ( non - zero corresponds to ' True ' )
--
: : a = > Bool - > a
: : a = > a - > Bool
-- ** Marshalling of Maybe values
--
maybeNew, -- :: ( a -> IO (Ptr a))
-- -> (Maybe a -> IO (Ptr a))
maybeWith, -- :: ( a -> (Ptr b -> IO c) -> IO c)
-- -> (Maybe a -> (Ptr b -> IO c) -> IO c)
maybePeek, -- :: (Ptr a -> IO b )
-- -> (Ptr a -> IO (Maybe b))
-- ** Marshalling lists of storable objects
--
withMany, -- :: (a -> (b -> res) -> res) -> [a] -> ([b] -> res) -> res
* * Haskellish interface to memcpy and memmove
-- | (argument order: destination, source)
--
copyBytes, -- :: Ptr a -> Ptr a -> Int -> IO ()
moveBytes, -- :: Ptr a -> Ptr a -> Int -> IO ()
) where
import Data.Maybe
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.Storable ( Storable(poke) )
import Foreign.C.Types ( CSize )
import Foreign.Marshal.Alloc ( malloc, alloca )
#ifdef __GLASGOW_HASKELL__
import GHC.IOBase
import GHC.Real ( fromIntegral )
import GHC.Num
import GHC.Base
#endif
#ifdef __NHC__
import Foreign.C.Types ( CInt(..) )
#endif
-- combined allocation and marshalling
-- -----------------------------------
-- |Allocate a block of memory and marshal a value into it
-- (the combination of 'malloc' and 'poke').
-- The size of the area allocated is determined by the 'Foreign.Storable.sizeOf'
method from the instance of ' ' for the appropriate type .
--
-- The memory may be deallocated using 'Foreign.Marshal.Alloc.free' or
' Foreign . Marshal . when no longer required .
--
new :: Storable a => a -> IO (Ptr a)
new val =
do
ptr <- malloc
poke ptr val
return ptr
|@'with ' val f@ executes the computation @f@ , passing as argument
-- a pointer to a temporarily allocated block of memory into which
-- @val@ has been marshalled (the combination of 'alloca' and 'poke').
--
The memory is freed when terminates ( either normally or via an
exception ) , so the pointer passed to must /not/ be used after this .
--
with :: Storable a => a -> (Ptr a -> IO b) -> IO b
with val f =
alloca $ \ptr -> do
poke ptr val
res <- f ptr
return res
marshalling of Boolean values ( non - zero corresponds to ' True ' )
-- -----------------------------
|Convert a ' ' to its numeric representation
--
fromBool :: Num a => Bool -> a
fromBool False = 0
fromBool True = 1
|Convert a Boolean in numeric representation to a value
--
toBool :: Num a => a -> Bool
toBool = (/= 0)
-- marshalling of Maybe values
-- ---------------------------
|Allocate storage and marshall a storable value wrapped into a ' Maybe '
--
-- * the 'nullPtr' is used to represent 'Nothing'
--
maybeNew :: ( a -> IO (Ptr a))
-> (Maybe a -> IO (Ptr a))
maybeNew = maybe (return nullPtr)
|Converts a @withXXX@ combinator into one marshalling a value wrapped
-- into a 'Maybe', using 'nullPtr' to represent 'Nothing'.
--
maybeWith :: ( a -> (Ptr b -> IO c) -> IO c)
-> (Maybe a -> (Ptr b -> IO c) -> IO c)
maybeWith = maybe ($ nullPtr)
-- |Convert a peek combinator into a one returning 'Nothing' if applied to a
-- 'nullPtr'
--
maybePeek :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)
maybePeek peek ptr | ptr == nullPtr = return Nothing
| otherwise = do a <- peek ptr; return (Just a)
-- marshalling lists of storable objects
-- -------------------------------------
|Replicates a @withXXX@ combinator over a list of objects , yielding a list of
-- marshalled objects
--
withXXX combinator for one object
-> [a] -- storable objects
-> ([b] -> res) -- action on list of marshalled obj.s
-> res
withMany _ [] f = f []
withMany withFoo (x:xs) f = withFoo x $ \x' ->
withMany withFoo xs (\xs' -> f (x':xs'))
Haskellish interface to memcpy and memmove
-- ------------------------------------------
|Copies the given number of bytes from the second area ( source ) into the
first ( destination ) ; the copied areas may /not/ overlap
--
copyBytes :: Ptr a -> Ptr a -> Int -> IO ()
copyBytes dest src size = memcpy dest src (fromIntegral size)
|Copies the given number of elements from the second area ( source ) into the
-- first (destination); the copied areas /may/ overlap
--
moveBytes :: Ptr a -> Ptr a -> Int -> IO ()
moveBytes dest src size = memmove dest src (fromIntegral size)
-- auxilliary routines
-- -------------------
|Basic C routines needed for memory copying
--
foreign import ccall unsafe "string.h" memcpy :: Ptr a -> Ptr a -> CSize -> IO ()
foreign import ccall unsafe "string.h" memmove :: Ptr a -> Ptr a -> CSize -> IO ()
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/base/Foreign/Marshal/Utils.hs | haskell | ---------------------------------------------------------------------------
|
Module : Foreign.Marshal.Utils
License : BSD-style (see the file libraries/base/LICENSE)
Stability : provisional
Portability : portable
---------------------------------------------------------------------------
* General marshalling utilities
** Combined allocation and marshalling
:: Storable a => a -> (Ptr a -> IO b) -> IO b
:: Storable a => a -> IO (Ptr a)
** Marshalling of Maybe values
:: ( a -> IO (Ptr a))
-> (Maybe a -> IO (Ptr a))
:: ( a -> (Ptr b -> IO c) -> IO c)
-> (Maybe a -> (Ptr b -> IO c) -> IO c)
:: (Ptr a -> IO b )
-> (Ptr a -> IO (Maybe b))
** Marshalling lists of storable objects
:: (a -> (b -> res) -> res) -> [a] -> ([b] -> res) -> res
| (argument order: destination, source)
:: Ptr a -> Ptr a -> Int -> IO ()
:: Ptr a -> Ptr a -> Int -> IO ()
combined allocation and marshalling
-----------------------------------
|Allocate a block of memory and marshal a value into it
(the combination of 'malloc' and 'poke').
The size of the area allocated is determined by the 'Foreign.Storable.sizeOf'
The memory may be deallocated using 'Foreign.Marshal.Alloc.free' or
a pointer to a temporarily allocated block of memory into which
@val@ has been marshalled (the combination of 'alloca' and 'poke').
-----------------------------
marshalling of Maybe values
---------------------------
* the 'nullPtr' is used to represent 'Nothing'
into a 'Maybe', using 'nullPtr' to represent 'Nothing'.
|Convert a peek combinator into a one returning 'Nothing' if applied to a
'nullPtr'
marshalling lists of storable objects
-------------------------------------
marshalled objects
storable objects
action on list of marshalled obj.s
------------------------------------------
first (destination); the copied areas /may/ overlap
auxilliary routines
-------------------
| # OPTIONS_GHC -fno - implicit - prelude #
Copyright : ( c ) The FFI task force 2001
Maintainer :
Utilities for primitive marshaling
module Foreign.Marshal.Utils (
* * Marshalling of Boolean values ( non - zero corresponds to ' True ' )
: : a = > Bool - > a
: : a = > a - > Bool
* * Haskellish interface to memcpy and memmove
) where
import Data.Maybe
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.Storable ( Storable(poke) )
import Foreign.C.Types ( CSize )
import Foreign.Marshal.Alloc ( malloc, alloca )
#ifdef __GLASGOW_HASKELL__
import GHC.IOBase
import GHC.Real ( fromIntegral )
import GHC.Num
import GHC.Base
#endif
#ifdef __NHC__
import Foreign.C.Types ( CInt(..) )
#endif
method from the instance of ' ' for the appropriate type .
' Foreign . Marshal . when no longer required .
new :: Storable a => a -> IO (Ptr a)
new val =
do
ptr <- malloc
poke ptr val
return ptr
|@'with ' val f@ executes the computation @f@ , passing as argument
The memory is freed when terminates ( either normally or via an
exception ) , so the pointer passed to must /not/ be used after this .
with :: Storable a => a -> (Ptr a -> IO b) -> IO b
with val f =
alloca $ \ptr -> do
poke ptr val
res <- f ptr
return res
marshalling of Boolean values ( non - zero corresponds to ' True ' )
|Convert a ' ' to its numeric representation
fromBool :: Num a => Bool -> a
fromBool False = 0
fromBool True = 1
|Convert a Boolean in numeric representation to a value
toBool :: Num a => a -> Bool
toBool = (/= 0)
|Allocate storage and marshall a storable value wrapped into a ' Maybe '
maybeNew :: ( a -> IO (Ptr a))
-> (Maybe a -> IO (Ptr a))
maybeNew = maybe (return nullPtr)
|Converts a @withXXX@ combinator into one marshalling a value wrapped
maybeWith :: ( a -> (Ptr b -> IO c) -> IO c)
-> (Maybe a -> (Ptr b -> IO c) -> IO c)
maybeWith = maybe ($ nullPtr)
maybePeek :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)
maybePeek peek ptr | ptr == nullPtr = return Nothing
| otherwise = do a <- peek ptr; return (Just a)
|Replicates a @withXXX@ combinator over a list of objects , yielding a list of
withXXX combinator for one object
-> res
withMany _ [] f = f []
withMany withFoo (x:xs) f = withFoo x $ \x' ->
withMany withFoo xs (\xs' -> f (x':xs'))
Haskellish interface to memcpy and memmove
|Copies the given number of bytes from the second area ( source ) into the
first ( destination ) ; the copied areas may /not/ overlap
copyBytes :: Ptr a -> Ptr a -> Int -> IO ()
copyBytes dest src size = memcpy dest src (fromIntegral size)
|Copies the given number of elements from the second area ( source ) into the
moveBytes :: Ptr a -> Ptr a -> Int -> IO ()
moveBytes dest src size = memmove dest src (fromIntegral size)
|Basic C routines needed for memory copying
foreign import ccall unsafe "string.h" memcpy :: Ptr a -> Ptr a -> CSize -> IO ()
foreign import ccall unsafe "string.h" memmove :: Ptr a -> Ptr a -> CSize -> IO ()
|
33f99720353edb1323f88cb130aca808aa4194a97bbced61b407827f4d3a0365 | s3team/uroboros | bb_counting.ml |
This instrumentation plugin is for 32 - bit binary .
It inserts counting instructions
at the beginning of each basic block .
This instrumentation plugin is for 32-bit binary.
It inserts counting instructions
at the beginning of each basic block.
*)
module Instrumentation_Plugin = struct
open Ail_utils
(* il update list *)
let il_update = ref []
let set_update i =
let open Instr_utils in
let l = get_loc i in
il_update := (i, l, INSERT, "") :: !il_update
let set_update_fold i l acc =
let open Instr_utils in
[(i, l, INSERT, "")] :: acc
let sub_update_fold i l i' acc =
let open Pp_print in
let open Instr_utils in
let i_s = pp_print_instr i' in
[(i, l, SUB, i_s)] :: acc
let template_BB_counting acc b il bmap =
let open Type in
let open Batteries in
let module BU = BB_utils in
let bil = Hashtbl.find bmap (b.bblock_name) in
let bn = b.bblock_name in
let i = List.nth bil 0 in
let iloc = get_loc i in
let iloc' = {iloc with loc_label = ""} in
let addr' = iloc.loc_addr in
let i0 = SingleInstr (StackOP (PUSHF), iloc, None) in
let i3 = DoubleInstr (CommonOP (Arithm INCL), Label ("(counter)"), iloc', None) in
let i5 = SingleInstr (StackOP (POPF), iloc', None) in
let i' = set_loc i iloc' in
set_update_fold i5 iloc acc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i0 iloc
|> sub_update_fold i' iloc i
let template_BB_counting_opt acc b il bmap =
let build_stub b =
let open Type in
let n = b.bblock_name in
n ^ "_stub" in
let open Type in
let open Batteries in
let module BU = BB_utils in
let bil = Hashtbl.find bmap (b.bblock_name) in
let bn = b.bblock_name in
let i = List.nth bil 0 in
let iloc = get_loc i in
let iloc' = {iloc with loc_label = ""} in
let addr' = iloc.loc_addr in
let sn = build_stub b in
let i1 = DoubleInstr (StackOP PUSH, Reg (CommonReg ECX), iloc, None) in
let i2 = TripleInstr (CommonOP (Assign MOVL), Reg (CommonReg ECX), Label "index", iloc', None) in
let i3 = DoubleInstr (ControlOP (Loop LOOP), Label sn, iloc', None) in
let i4 = TripleInstr ( CommonOP ( Assign MOVL ) , ( CommonReg ECX ) ,
Const ( Normal 0xffffffff ) , iloc ' , None ) in
Const (Normal 0xffffffff), iloc', None) in *)
let i5 = TripleInstr (CommonOP (Assign MOVL), Label "index", Reg (CommonReg ECX),
{iloc' with loc_label = sn ^ ":"}, None) in
let i6 = DoubleInstr (StackOP POP, Reg (CommonReg ECX), iloc', None) in
let i' = set_loc i iloc' in
let open Instr_utils in
set_update_fold i6 iloc acc
|> set_update_fold i5 iloc
| > set_update_fold i4 iloc
|> set_update_fold i3 iloc
|> set_update_fold i2 iloc
|> set_update_fold i1 iloc
|> sub_update_fold i' iloc i
let gen_BB_counting acc b il bmap =
template_BB_counting_opt acc b il bmap
let insert_instrument_instrs il =
let module IU = Instr_utils in
!il_update
|> IU.sort_il_update
|> IU.update_instrs_infront il
let instrument_bb bmap bl il acc =
List.fold_left (fun acc b ->
gen_BB_counting acc b il bmap) acc bl
let instrument il fb_bbl bbl =
let open Batteries in
let module EU = ELF_utils in
let module DU = Dataset_utils in
let module BU = BB_utils in
let aux f bl acc =
bl :: acc
in
let l = Hashtbl.fold aux fb_bbl [] in
let bbl_sort = BU.bbl_sort bbl in
let bmap = BU.bb_map bbl_sort il in
let help acc bl =
instrument_bb bmap bl il acc
in
try
if EU.elf_32 () then
begin
DU.insert_data "index" "0xff" "0x4" true "before";
il_update := List.flatten @@ List.fold_left help [] l;
insert_instrument_instrs il
end
else
assert false
with _ ->
begin
print_string "Plugin Failed: This plugin is for 32-bit binary, not for 64-bit.\n";
il
end
end
| null | https://raw.githubusercontent.com/s3team/uroboros/cdb379a4678ba912bde5d53f7302ad9409abee71/src/plugins/bb_counting.ml | ocaml | il update list |
This instrumentation plugin is for 32 - bit binary .
It inserts counting instructions
at the beginning of each basic block .
This instrumentation plugin is for 32-bit binary.
It inserts counting instructions
at the beginning of each basic block.
*)
module Instrumentation_Plugin = struct
open Ail_utils
let il_update = ref []
let set_update i =
let open Instr_utils in
let l = get_loc i in
il_update := (i, l, INSERT, "") :: !il_update
let set_update_fold i l acc =
let open Instr_utils in
[(i, l, INSERT, "")] :: acc
let sub_update_fold i l i' acc =
let open Pp_print in
let open Instr_utils in
let i_s = pp_print_instr i' in
[(i, l, SUB, i_s)] :: acc
let template_BB_counting acc b il bmap =
let open Type in
let open Batteries in
let module BU = BB_utils in
let bil = Hashtbl.find bmap (b.bblock_name) in
let bn = b.bblock_name in
let i = List.nth bil 0 in
let iloc = get_loc i in
let iloc' = {iloc with loc_label = ""} in
let addr' = iloc.loc_addr in
let i0 = SingleInstr (StackOP (PUSHF), iloc, None) in
let i3 = DoubleInstr (CommonOP (Arithm INCL), Label ("(counter)"), iloc', None) in
let i5 = SingleInstr (StackOP (POPF), iloc', None) in
let i' = set_loc i iloc' in
set_update_fold i5 iloc acc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i3 iloc
|> set_update_fold i0 iloc
|> sub_update_fold i' iloc i
let template_BB_counting_opt acc b il bmap =
let build_stub b =
let open Type in
let n = b.bblock_name in
n ^ "_stub" in
let open Type in
let open Batteries in
let module BU = BB_utils in
let bil = Hashtbl.find bmap (b.bblock_name) in
let bn = b.bblock_name in
let i = List.nth bil 0 in
let iloc = get_loc i in
let iloc' = {iloc with loc_label = ""} in
let addr' = iloc.loc_addr in
let sn = build_stub b in
let i1 = DoubleInstr (StackOP PUSH, Reg (CommonReg ECX), iloc, None) in
let i2 = TripleInstr (CommonOP (Assign MOVL), Reg (CommonReg ECX), Label "index", iloc', None) in
let i3 = DoubleInstr (ControlOP (Loop LOOP), Label sn, iloc', None) in
let i4 = TripleInstr ( CommonOP ( Assign MOVL ) , ( CommonReg ECX ) ,
Const ( Normal 0xffffffff ) , iloc ' , None ) in
Const (Normal 0xffffffff), iloc', None) in *)
let i5 = TripleInstr (CommonOP (Assign MOVL), Label "index", Reg (CommonReg ECX),
{iloc' with loc_label = sn ^ ":"}, None) in
let i6 = DoubleInstr (StackOP POP, Reg (CommonReg ECX), iloc', None) in
let i' = set_loc i iloc' in
let open Instr_utils in
set_update_fold i6 iloc acc
|> set_update_fold i5 iloc
| > set_update_fold i4 iloc
|> set_update_fold i3 iloc
|> set_update_fold i2 iloc
|> set_update_fold i1 iloc
|> sub_update_fold i' iloc i
let gen_BB_counting acc b il bmap =
template_BB_counting_opt acc b il bmap
let insert_instrument_instrs il =
let module IU = Instr_utils in
!il_update
|> IU.sort_il_update
|> IU.update_instrs_infront il
let instrument_bb bmap bl il acc =
List.fold_left (fun acc b ->
gen_BB_counting acc b il bmap) acc bl
let instrument il fb_bbl bbl =
let open Batteries in
let module EU = ELF_utils in
let module DU = Dataset_utils in
let module BU = BB_utils in
let aux f bl acc =
bl :: acc
in
let l = Hashtbl.fold aux fb_bbl [] in
let bbl_sort = BU.bbl_sort bbl in
let bmap = BU.bb_map bbl_sort il in
let help acc bl =
instrument_bb bmap bl il acc
in
try
if EU.elf_32 () then
begin
DU.insert_data "index" "0xff" "0x4" true "before";
il_update := List.flatten @@ List.fold_left help [] l;
insert_instrument_instrs il
end
else
assert false
with _ ->
begin
print_string "Plugin Failed: This plugin is for 32-bit binary, not for 64-bit.\n";
il
end
end
|
5f85cdb50cd746492c6de50b65a4230f724fe0a4799827c2ea23892ff525db1d | charlieg/Sparser | SGML1.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright ( c ) 1991,1992,1993,1994,1995 -- all rights reserved
;;;
File : " SGML "
;;; Module: "objects;forms:"
Version : 1.0 September 1995
initiated 10/21/91 , tweeked 10/30 .
1.0 ( 5/21/92 ) Moved body to objects;doc
( 5/19/94 ) added define - markup - tag - pair . 6/1 added define - invisible - markup
6/6 added the keyword : annotation . 9/19/95 added html forms . 9/20 pulled
;; them as redundant since the only arg is a string and most will be autodef'd
(in-package :sparser)
;;;------------
;;; sgml cases
;;;------------
(defun define-sgml-tag (string
name
&key ((:initiation-action initiate))
((:termination-action terminate))
((:implicitly-closes close)))
(define-sgml-tag/expr
string name initiate terminate close))
(defun define-markup-tag-pair (name
start-string end-string
&key ((:initiation-action initiate))
((:termination-action terminate))
((:interior-markup interior)))
(define-markup-tag-pair/expr
name start-string end-string initiate terminate interior))
(defun define-invisible-markup (protocol-keyword &rest args)
(ecase protocol-keyword
(:tag-pair (apply #'define-invisible-markup-pair args))
(:annotation (apply #'define-invisible-annotation-tag args))))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/objects/forms/SGML1.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
Module: "objects;forms:"
doc
them as redundant since the only arg is a string and most will be autodef'd
------------
sgml cases
------------ | copyright ( c ) 1991,1992,1993,1994,1995 -- all rights reserved
File : " SGML "
Version : 1.0 September 1995
initiated 10/21/91 , tweeked 10/30 .
( 5/19/94 ) added define - markup - tag - pair . 6/1 added define - invisible - markup
6/6 added the keyword : annotation . 9/19/95 added html forms . 9/20 pulled
(in-package :sparser)
(defun define-sgml-tag (string
name
&key ((:initiation-action initiate))
((:termination-action terminate))
((:implicitly-closes close)))
(define-sgml-tag/expr
string name initiate terminate close))
(defun define-markup-tag-pair (name
start-string end-string
&key ((:initiation-action initiate))
((:termination-action terminate))
((:interior-markup interior)))
(define-markup-tag-pair/expr
name start-string end-string initiate terminate interior))
(defun define-invisible-markup (protocol-keyword &rest args)
(ecase protocol-keyword
(:tag-pair (apply #'define-invisible-markup-pair args))
(:annotation (apply #'define-invisible-annotation-tag args))))
|
001e153b63b8c3963026054683a1e6b458f145404add28d2e2af263fffe229a4 | 3b/cl-opengl | funcs-gl-glcore-gles1-gles2-glsc2.lisp | ;;; this file is automatically generated, do not edit
;;; generated from files with the following copyright:
;;;
Copyright ( c ) 2013 - 2017 The Khronos Group Inc.
;;;
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.
;;;
;;; ------------------------------------------------------------------------
(in-package #:cl-opengl-bindings)
generated 2017 - 10 - 04T20:14:06Z
from gl.xml @ git sha 2c8fa02871abd4102bd03d09d42645cce20c468f , 2017 - 10 - 03T15:09:09Z
(defparameter *glext-version* 20171003)
(defparameter *glext-last-updated* "2017-10-03T15:09:09Z")
(defglextfun ("glDepthRangef" depth-range-f) :void
(n float)
(f float))
(defglextfun ("glClearDepthf" clear-depth-f) :void
(d float))
| null | https://raw.githubusercontent.com/3b/cl-opengl/e2d83e0977b7e7ac3f3d348d8ccc7ccd04e74d59/gl/funcs-gl-glcore-gles1-gles2-glsc2.lisp | lisp | this file is automatically generated, do not edit
generated from files with the following copyright:
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.
------------------------------------------------------------------------ | Copyright ( c ) 2013 - 2017 The Khronos Group Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
(in-package #:cl-opengl-bindings)
generated 2017 - 10 - 04T20:14:06Z
from gl.xml @ git sha 2c8fa02871abd4102bd03d09d42645cce20c468f , 2017 - 10 - 03T15:09:09Z
(defparameter *glext-version* 20171003)
(defparameter *glext-last-updated* "2017-10-03T15:09:09Z")
(defglextfun ("glDepthRangef" depth-range-f) :void
(n float)
(f float))
(defglextfun ("glClearDepthf" clear-depth-f) :void
(d float))
|
cb616833fa59cba82204ef269e3688f2c265241cb7f38c9e4d9d1ab5b97c03f3 | jaspervdj/digestive-functors | Heist.hs | --------------------------------------------------------------------------------
| This module provides a Heist frontend for the digestive - functors library .
--
-- Disclaimer: this documentation requires very basic familiarity with
-- digestive-functors. You might want to take a quick look at this tutorial
-- first:
--
< >
--
-- This module exports the functions 'digestiveSplices' and
-- 'bindDigestiveSplices', and most users will not require anything else.
--
-- These splices are used to create HTML for different form elements. This way,
-- the developer doesn't have to care about setting e.g. the previous values in
-- a text field when something goes wrong.
--
-- For documentation on the different splices, see the different functions
-- exported by this module. All splices have the same name as given in
-- 'digestiveSplices'.
--
-- You can give arbitrary attributes to most of the elements (i.e. where it
-- makes sense). This means you can do e.g.:
--
> < dfInputTextArea ref="description " cols="20 " rows="3 " / >
{-# LANGUAGE OverloadedStrings #-}
module Text.Digestive.Heist
( -- * Core methods
digestiveSplices
, bindDigestiveSplices
-- * Main splices
, dfInput
, dfInputList
, dfInputText
, dfInputTextArea
, dfInputPassword
, dfInputHidden
, dfInputSelect
, dfInputSelectGroup
, dfInputRadio
, dfInputCheckbox
, dfInputFile
, dfInputSubmit
, dfLabel
, dfForm
, dfErrorList
, dfChildErrorList
, dfSubView
-- * Utility splices
, dfIfChildErrors
, dfIfNoChildErrors
) where
--------------------------------------------------------------------------------
import Control.Monad (liftM, mplus)
import Control.Monad.Trans
import Data.Function (on)
import Data.List (unionBy)
import Data.Map.Syntax ((##))
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Heist
import Heist.Interpreted
import qualified Text.XmlHtml as X
--------------------------------------------------------------------------------
import Text.Digestive.Form.List
import Text.Digestive.View
--------------------------------------------------------------------------------
bindDigestiveSplices :: MonadIO m => View Text -> HeistState m -> HeistState m
bindDigestiveSplices = bindSplices . digestiveSplices
--------------------------------------------------------------------------------
digestiveSplices :: MonadIO m => View Text -> Splices (Splice m)
digestiveSplices view = do
"dfInput" ## dfInput view
"dfInputList" ## dfInputList view
"dfInputText" ## dfInputText view
"dfInputTextArea" ## dfInputTextArea view
"dfInputPassword" ## dfInputPassword view
"dfInputHidden" ## dfInputHidden view
"dfInputSelect" ## dfInputSelect view
"dfInputSelectGroup" ## dfInputSelectGroup view
"dfInputRadio" ## dfInputRadio view
"dfInputCheckbox" ## dfInputCheckbox view
"dfInputFile" ## dfInputFile view
"dfInputSubmit" ## dfInputSubmit view
"dfLabel" ## dfLabel view
"dfForm" ## dfForm view
"dfErrorList" ## dfErrorList view
"dfChildErrorList" ## dfChildErrorList view
"dfSubView" ## dfSubView view
"dfIfChildErrors" ## dfIfChildErrors view
"dfIfNoChildErrors" ## dfIfNoChildErrors view
--------------------------------------------------------------------------------
attr :: Bool -> (Text, Text) -> [(Text, Text)] -> [(Text, Text)]
attr False _ = id
attr True a = (a :)
--------------------------------------------------------------------------------
makeElement :: Text -> [X.Node] -> [(Text, Text)] -> [X.Node]
makeElement name nodes = return . flip (X.Element name) nodes
--------------------------------------------------------------------------------
getRefAttributes :: Monad m
=> Maybe Text -- ^ Optional default ref
^ ( Ref , other attrs )
getRefAttributes defaultRef = do
node <- getParamNode
return $ case node of
X.Element _ as _ ->
let ref = fromMaybe (error $ show node ++ ": missing ref") $
lookup "ref" as `mplus` defaultRef
in (ref, filter ((/= "ref") . fst) as)
_ -> (error "Wrong type of node!", [])
--------------------------------------------------------------------------------
getContent :: Monad m => HeistT m m [X.Node]
getContent = liftM X.childNodes getParamNode
--------------------------------------------------------------------------------
-- | Does not override existing attributes
addAttrs :: [(Text, Text)] -- ^ Original attributes
-> [(Text, Text)] -- ^ Attributes to add
-> [(Text, Text)] -- ^ Resulting attributes
addAttrs = unionBy (on (==) fst)
--------------------------------------------------------------------------------
-- |
setDisabled :: Text -> View v -> [(Text, Text)] -> [(Text, Text)]
setDisabled ref view = if viewDisabled ref view then (("disabled",""):) else id
--------------------------------------------------------------------------------
-- | Generate an input field with a supplied type. Example:
--
-- > <dfInput type="date" ref="date" />
dfInput :: Monad m => View v -> Splice m
dfInput view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a text input field. Example:
--
-- > <dfInputText ref="user.name" />
dfInputText :: Monad m => View v -> Splice m
dfInputText view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "text"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a text area. Example:
--
-- > <dfInputTextArea ref="user.about" />
dfInputTextArea :: Monad m => View v -> Splice m
dfInputTextArea view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "textarea" [X.TextNode value] $ addAttrs attrs $
setDisabled ref view [("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a password field. Example:
--
-- > <dfInputPassword ref="user.password" />
dfInputPassword :: Monad m => View v -> Splice m
dfInputPassword view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "password"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a hidden input field. Example:
--
-- > <dfInputHidden ref="user.forgery" />
dfInputHidden :: Monad m => View v -> Splice m
dfInputHidden view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "hidden"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a select button (also known as a combo box). Example:
--
-- > <dfInputSelect ref="user.sex" />
dfInputSelect :: Monad m => View Text -> Splice m
dfInputSelect view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoice ref view
kids = map makeOption choices
makeOption (i, c, sel) = X.Element "option"
(attr sel ("selected", "selected") [("value", i)])
[X.TextNode c]
return $ makeElement "select" kids $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a select button (also known as a combo box). Example:
--
-- > <dfInputSelectGroup ref="user.sex" />
dfInputSelectGroup :: Monad m => View Text -> Splice m
dfInputSelectGroup view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoiceGroup ref view
kids = map makeGroup choices
makeGroup (name, options) = X.Element "optgroup"
[("label", name)] $ map makeOption options
makeOption (i, c, sel) = X.Element "option"
(attr sel ("selected", "selected") [("value", i)])
[X.TextNode c]
return $ makeElement "select" kids $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a number of radio buttons. Example:
--
> < / >
dfInputRadio :: Monad m => View Text -> Splice m
dfInputRadio view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoice ref view
kids = concatMap makeOption choices
makeOption (i, c, sel) =
[ X.Element "label" [("for", i)]
[ X.Element "input"
(attr sel ("checked", "checked") $ addAttrs attrs
[ ("type", "radio"), ("value", i)
, ("id", i), ("name", ref')
]) []
, X.TextNode c]
]
return kids
--------------------------------------------------------------------------------
-- | Generate a checkbox. Example:
--
-- > <dfInputCheckbox ref="user.married" />
dfInputCheckbox :: Monad m => View Text -> Splice m
dfInputCheckbox view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputBool ref view
return $ makeElement "input" [] $ addAttrs attrs $
attr value ("checked", "checked") $ setDisabled ref view
[("type", "checkbox"), ("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a file upload element. Example:
--
-- > <dfInputFile ref="user.avatar" />
dfInputFile :: Monad m => View Text -> Splice m
dfInputFile view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "file"), ("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a submit button. Example:
--
-- > <dfInputSubmit />
dfInputSubmit :: Monad m => View v -> Splice m
dfInputSubmit _ = do
(_, attrs) <- getRefAttributes Nothing
return $ makeElement "input" [] $ addAttrs attrs [("type", "submit")]
--------------------------------------------------------------------------------
-- | Generate a label for a field. Example:
--
-- > <dfLabel ref="user.married">Married: </dfLabel>
-- > <dfInputCheckbox ref="user.married" />
dfLabel :: Monad m => View v -> Splice m
dfLabel view = do
(ref, attrs) <- getRefAttributes Nothing
content <- getContent
let ref' = absoluteRef ref view
return $ makeElement "label" content $ addAttrs attrs [("for", ref')]
--------------------------------------------------------------------------------
| Generate a form tag with the @method@ attribute set to @POST@ and
-- the @enctype@ set to the right value (depending on the form).
-- Custom @method@ or @enctype@ attributes would override this
-- behavior. Example:
--
-- > <dfForm action="/users/new">
-- > <dfInputText ... />
-- > ...
-- > <dfInputSubmit />
-- > </dfForm>
dfForm :: Monad m => View v -> Splice m
dfForm view = do
(_, attrs) <- getRefAttributes Nothing
content <- getContent
return $ makeElement "form" content $ addAttrs attrs
[ ("method", "POST")
, ("enctype", T.pack (show $ viewEncType view))
]
--------------------------------------------------------------------------------
errorList :: [Text] -> [(Text, Text)] -> [X.Node]
errorList [] _ = []
errorList errs attrs = [X.Element "ul" attrs $ map makeError errs]
where
makeError e = X.Element "li" [] [X.TextNode e]
--------------------------------------------------------------------------------
-- | Display the list of errors for a certain field. Example:
--
> < dfErrorList ref="user.name " / >
-- > <dfInputText ref="user.name" />
dfErrorList :: Monad m => View Text -> Splice m
dfErrorList view = do
(ref, attrs) <- getRefAttributes Nothing
return $ errorList (errors ref view) attrs
--------------------------------------------------------------------------------
-- | Display the list of errors for a certain form and all forms below it. E.g.,
-- if there is a subform called @\"user\"@:
--
-- > <dfChildErrorList ref="user" />
--
-- Or display /all/ errors for the form:
--
-- > <dfChildErrorList ref="" />
--
-- Which is more conveniently written as:
--
-- > <dfChildErrorList />
dfChildErrorList :: Monad m => View Text -> Splice m
dfChildErrorList view = do
(ref, attrs) <- getRefAttributes $ Just ""
return $ errorList (childErrors ref view) attrs
--------------------------------------------------------------------------------
-- | This splice allows reuse of templates by selecting some child of a form
-- tree. While this may sound complicated, it's pretty straightforward and
-- practical. Suppose we have:
--
-- > <dfInputText ref="user.name" />
-- > <dfInputText ref="user.password" />
-- >
-- > <dfInputTextArea ref="comment.body" />
--
-- You may want to abstract the @\"user\"@ parts in some other template so you
-- Don't Repeat Yourself (TM). If you create a template called @\"user-form\"@
-- with the following contents:
--
-- > <dfInputText ref="name" />
-- > <dfInputText ref="password" />
--
-- You will be able to use:
--
-- > <dfSubView ref="user">
-- > <apply template="user-form" />
-- > </dfSubView>
-- >
-- > <dfInputTextArea ref="comment.body" />
dfSubView :: MonadIO m => View Text -> Splice m
dfSubView view = do
(ref, _) <- getRefAttributes Nothing
let view' = subView ref view
nodes <- localHS (bindDigestiveSplices view') runChildren
return nodes
disableOnclick :: Text -> View v -> [(Text, Text)] -> [(Text, Text)]
disableOnclick ref view =
if viewDisabled ref view then const [("disabled","")] else id
--------------------------------------------------------------------------------
-- | This splice allows variable length lists. It binds several attribute
-- splices providing functionality for dynamically manipulating the list. The
-- following descriptions will use the example of a form named \"foo\" with a
-- list subform named \"items\".
--
-- Splices:
-- dfListItem - This tag must surround the markup for a single list item.
-- It surrounds all of its children with a div with id \"foo.items\" and
-- class \"inputList\".
--
-- Attribute Splices:
itemAttrs - Attribute you should use on div , span , etc that surrounds all
-- the markup for a single list item. This splice expands to an id of
-- \"foo.items.ix\" (where ix is the index of the current item) and a
-- class of \"inputListItem\".
-- addControl - Use this attribute on the tag you use to define a control
-- for adding elements to the list (usually a button or anchor). It adds
-- an onclick attribute that calls a javascript function addInputListItem.
-- removeControl - Use this attribute on the control for removing individual
-- items. It adds an onclick attribute that calls removeInputListItem.
dfInputList :: MonadIO m => View Text -> Splice m
dfInputList view = do
(ref, _) <- getRefAttributes Nothing
let listRef = absoluteRef ref view
listAttrs =
[ ("id", listRef)
, ("class", "inputList")
]
addControl _ = return $ disableOnclick ref view
[ ("onclick", T.concat [ "addInputListItem(this, '"
, listRef
, "'); return false;"] ) ]
removeControl _ = return $ disableOnclick ref view
[ ("onclick", T.concat [ "removeInputListItem(this, '"
, listRef
, "'); return false;"] ) ]
itemAttrs v _ = return
[ ("id", T.concat [listRef, ".", last $ "0" : viewContext v])
, ("class", T.append listRef ".inputListItem")
]
templateAttrs v _ = return
[ ("id", T.concat [listRef, ".", last $ "-1" : viewContext v])
, ("class", T.append listRef ".inputListTemplate")
, ("style", "display: none;")
]
items = listSubViews ref view
f attrs v = localHS (bindAttributeSplices ("itemAttrs" ## attrs v) .
bindDigestiveSplices v) runChildren
dfListItem = do
template <- f templateAttrs (makeListSubView ref (-1) view)
res <- mapSplices (f itemAttrs) items
return $ template ++ res
attrSplices = do
"addControl" ## addControl
"removeControl" ## removeControl
nodes <- localHS (bindSplices ("dfListItem" ## dfListItem) .
bindAttributeSplices attrSplices) runChildren
let indices = [X.Element "input"
[ ("type", "hidden")
, ("name", T.intercalate "." [listRef, indicesRef])
, ("value", T.intercalate "," $ map
(last . ("0":) . viewContext) items)
] []
]
return [X.Element "div" listAttrs (indices ++ nodes)]
--------------------------------------------------------------------------------
-- | Render some content only if there are any errors. This is useful for markup
-- purposes.
--
-- > <dfIfChildErrors ref="user">
> Content to be rendered if there are any errors ...
-- > </dfIfChildErrors>
--
The @ref@ attribute can be omitted if you want to check the entire form .
dfIfChildErrors :: Monad m => View v -> Splice m
dfIfChildErrors view = do
(ref, _) <- getRefAttributes $ Just ""
if null (childErrors ref view)
then return []
else runChildren
--------------------------------------------------------------------------------
-- | Render some content only if there are no errors. This is useful for markup
-- purposes.
--
-- > <dfIfNoChildErrors ref="user">
> Content to be rendered if there are no errors ...
-- > </dfIfNoChildErrors>
--
The @ref@ attribute can be omitted if you want to check the entire form .
dfIfNoChildErrors :: Monad m => View v -> Splice m
dfIfNoChildErrors view = do
(ref, _) <- getRefAttributes $ Just ""
if null (childErrors ref view)
then runChildren
else return []
| null | https://raw.githubusercontent.com/jaspervdj/digestive-functors/5827b47404a93b103cc57ad0f54f4dc0bdf94e24/digestive-functors-heist/src/Text/Digestive/Heist.hs | haskell | ------------------------------------------------------------------------------
Disclaimer: this documentation requires very basic familiarity with
digestive-functors. You might want to take a quick look at this tutorial
first:
This module exports the functions 'digestiveSplices' and
'bindDigestiveSplices', and most users will not require anything else.
These splices are used to create HTML for different form elements. This way,
the developer doesn't have to care about setting e.g. the previous values in
a text field when something goes wrong.
For documentation on the different splices, see the different functions
exported by this module. All splices have the same name as given in
'digestiveSplices'.
You can give arbitrary attributes to most of the elements (i.e. where it
makes sense). This means you can do e.g.:
# LANGUAGE OverloadedStrings #
* Core methods
* Main splices
* Utility splices
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
^ Optional default ref
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Does not override existing attributes
^ Original attributes
^ Attributes to add
^ Resulting attributes
------------------------------------------------------------------------------
|
------------------------------------------------------------------------------
| Generate an input field with a supplied type. Example:
> <dfInput type="date" ref="date" />
------------------------------------------------------------------------------
| Generate a text input field. Example:
> <dfInputText ref="user.name" />
------------------------------------------------------------------------------
| Generate a text area. Example:
> <dfInputTextArea ref="user.about" />
------------------------------------------------------------------------------
| Generate a password field. Example:
> <dfInputPassword ref="user.password" />
------------------------------------------------------------------------------
| Generate a hidden input field. Example:
> <dfInputHidden ref="user.forgery" />
------------------------------------------------------------------------------
| Generate a select button (also known as a combo box). Example:
> <dfInputSelect ref="user.sex" />
------------------------------------------------------------------------------
| Generate a select button (also known as a combo box). Example:
> <dfInputSelectGroup ref="user.sex" />
------------------------------------------------------------------------------
| Generate a number of radio buttons. Example:
------------------------------------------------------------------------------
| Generate a checkbox. Example:
> <dfInputCheckbox ref="user.married" />
------------------------------------------------------------------------------
| Generate a file upload element. Example:
> <dfInputFile ref="user.avatar" />
------------------------------------------------------------------------------
| Generate a submit button. Example:
> <dfInputSubmit />
------------------------------------------------------------------------------
| Generate a label for a field. Example:
> <dfLabel ref="user.married">Married: </dfLabel>
> <dfInputCheckbox ref="user.married" />
------------------------------------------------------------------------------
the @enctype@ set to the right value (depending on the form).
Custom @method@ or @enctype@ attributes would override this
behavior. Example:
> <dfForm action="/users/new">
> <dfInputText ... />
> ...
> <dfInputSubmit />
> </dfForm>
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Display the list of errors for a certain field. Example:
> <dfInputText ref="user.name" />
------------------------------------------------------------------------------
| Display the list of errors for a certain form and all forms below it. E.g.,
if there is a subform called @\"user\"@:
> <dfChildErrorList ref="user" />
Or display /all/ errors for the form:
> <dfChildErrorList ref="" />
Which is more conveniently written as:
> <dfChildErrorList />
------------------------------------------------------------------------------
| This splice allows reuse of templates by selecting some child of a form
tree. While this may sound complicated, it's pretty straightforward and
practical. Suppose we have:
> <dfInputText ref="user.name" />
> <dfInputText ref="user.password" />
>
> <dfInputTextArea ref="comment.body" />
You may want to abstract the @\"user\"@ parts in some other template so you
Don't Repeat Yourself (TM). If you create a template called @\"user-form\"@
with the following contents:
> <dfInputText ref="name" />
> <dfInputText ref="password" />
You will be able to use:
> <dfSubView ref="user">
> <apply template="user-form" />
> </dfSubView>
>
> <dfInputTextArea ref="comment.body" />
------------------------------------------------------------------------------
| This splice allows variable length lists. It binds several attribute
splices providing functionality for dynamically manipulating the list. The
following descriptions will use the example of a form named \"foo\" with a
list subform named \"items\".
Splices:
dfListItem - This tag must surround the markup for a single list item.
It surrounds all of its children with a div with id \"foo.items\" and
class \"inputList\".
Attribute Splices:
the markup for a single list item. This splice expands to an id of
\"foo.items.ix\" (where ix is the index of the current item) and a
class of \"inputListItem\".
addControl - Use this attribute on the tag you use to define a control
for adding elements to the list (usually a button or anchor). It adds
an onclick attribute that calls a javascript function addInputListItem.
removeControl - Use this attribute on the control for removing individual
items. It adds an onclick attribute that calls removeInputListItem.
------------------------------------------------------------------------------
| Render some content only if there are any errors. This is useful for markup
purposes.
> <dfIfChildErrors ref="user">
> </dfIfChildErrors>
------------------------------------------------------------------------------
| Render some content only if there are no errors. This is useful for markup
purposes.
> <dfIfNoChildErrors ref="user">
> </dfIfNoChildErrors>
| | This module provides a Heist frontend for the digestive - functors library .
< >
> < dfInputTextArea ref="description " cols="20 " rows="3 " / >
module Text.Digestive.Heist
digestiveSplices
, bindDigestiveSplices
, dfInput
, dfInputList
, dfInputText
, dfInputTextArea
, dfInputPassword
, dfInputHidden
, dfInputSelect
, dfInputSelectGroup
, dfInputRadio
, dfInputCheckbox
, dfInputFile
, dfInputSubmit
, dfLabel
, dfForm
, dfErrorList
, dfChildErrorList
, dfSubView
, dfIfChildErrors
, dfIfNoChildErrors
) where
import Control.Monad (liftM, mplus)
import Control.Monad.Trans
import Data.Function (on)
import Data.List (unionBy)
import Data.Map.Syntax ((##))
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Heist
import Heist.Interpreted
import qualified Text.XmlHtml as X
import Text.Digestive.Form.List
import Text.Digestive.View
bindDigestiveSplices :: MonadIO m => View Text -> HeistState m -> HeistState m
bindDigestiveSplices = bindSplices . digestiveSplices
digestiveSplices :: MonadIO m => View Text -> Splices (Splice m)
digestiveSplices view = do
"dfInput" ## dfInput view
"dfInputList" ## dfInputList view
"dfInputText" ## dfInputText view
"dfInputTextArea" ## dfInputTextArea view
"dfInputPassword" ## dfInputPassword view
"dfInputHidden" ## dfInputHidden view
"dfInputSelect" ## dfInputSelect view
"dfInputSelectGroup" ## dfInputSelectGroup view
"dfInputRadio" ## dfInputRadio view
"dfInputCheckbox" ## dfInputCheckbox view
"dfInputFile" ## dfInputFile view
"dfInputSubmit" ## dfInputSubmit view
"dfLabel" ## dfLabel view
"dfForm" ## dfForm view
"dfErrorList" ## dfErrorList view
"dfChildErrorList" ## dfChildErrorList view
"dfSubView" ## dfSubView view
"dfIfChildErrors" ## dfIfChildErrors view
"dfIfNoChildErrors" ## dfIfNoChildErrors view
attr :: Bool -> (Text, Text) -> [(Text, Text)] -> [(Text, Text)]
attr False _ = id
attr True a = (a :)
makeElement :: Text -> [X.Node] -> [(Text, Text)] -> [X.Node]
makeElement name nodes = return . flip (X.Element name) nodes
getRefAttributes :: Monad m
^ ( Ref , other attrs )
getRefAttributes defaultRef = do
node <- getParamNode
return $ case node of
X.Element _ as _ ->
let ref = fromMaybe (error $ show node ++ ": missing ref") $
lookup "ref" as `mplus` defaultRef
in (ref, filter ((/= "ref") . fst) as)
_ -> (error "Wrong type of node!", [])
getContent :: Monad m => HeistT m m [X.Node]
getContent = liftM X.childNodes getParamNode
addAttrs = unionBy (on (==) fst)
setDisabled :: Text -> View v -> [(Text, Text)] -> [(Text, Text)]
setDisabled ref view = if viewDisabled ref view then (("disabled",""):) else id
dfInput :: Monad m => View v -> Splice m
dfInput view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref'), ("value", value)]
dfInputText :: Monad m => View v -> Splice m
dfInputText view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "text"), ("id", ref'), ("name", ref'), ("value", value)]
dfInputTextArea :: Monad m => View v -> Splice m
dfInputTextArea view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "textarea" [X.TextNode value] $ addAttrs attrs $
setDisabled ref view [("id", ref'), ("name", ref')]
dfInputPassword :: Monad m => View v -> Splice m
dfInputPassword view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "password"), ("id", ref'), ("name", ref'), ("value", value)]
dfInputHidden :: Monad m => View v -> Splice m
dfInputHidden view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "hidden"), ("id", ref'), ("name", ref'), ("value", value)]
dfInputSelect :: Monad m => View Text -> Splice m
dfInputSelect view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoice ref view
kids = map makeOption choices
makeOption (i, c, sel) = X.Element "option"
(attr sel ("selected", "selected") [("value", i)])
[X.TextNode c]
return $ makeElement "select" kids $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref')]
dfInputSelectGroup :: Monad m => View Text -> Splice m
dfInputSelectGroup view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoiceGroup ref view
kids = map makeGroup choices
makeGroup (name, options) = X.Element "optgroup"
[("label", name)] $ map makeOption options
makeOption (i, c, sel) = X.Element "option"
(attr sel ("selected", "selected") [("value", i)])
[X.TextNode c]
return $ makeElement "select" kids $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref')]
> < / >
dfInputRadio :: Monad m => View Text -> Splice m
dfInputRadio view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoice ref view
kids = concatMap makeOption choices
makeOption (i, c, sel) =
[ X.Element "label" [("for", i)]
[ X.Element "input"
(attr sel ("checked", "checked") $ addAttrs attrs
[ ("type", "radio"), ("value", i)
, ("id", i), ("name", ref')
]) []
, X.TextNode c]
]
return kids
dfInputCheckbox :: Monad m => View Text -> Splice m
dfInputCheckbox view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputBool ref view
return $ makeElement "input" [] $ addAttrs attrs $
attr value ("checked", "checked") $ setDisabled ref view
[("type", "checkbox"), ("id", ref'), ("name", ref')]
dfInputFile :: Monad m => View Text -> Splice m
dfInputFile view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "file"), ("id", ref'), ("name", ref')]
dfInputSubmit :: Monad m => View v -> Splice m
dfInputSubmit _ = do
(_, attrs) <- getRefAttributes Nothing
return $ makeElement "input" [] $ addAttrs attrs [("type", "submit")]
dfLabel :: Monad m => View v -> Splice m
dfLabel view = do
(ref, attrs) <- getRefAttributes Nothing
content <- getContent
let ref' = absoluteRef ref view
return $ makeElement "label" content $ addAttrs attrs [("for", ref')]
| Generate a form tag with the @method@ attribute set to @POST@ and
dfForm :: Monad m => View v -> Splice m
dfForm view = do
(_, attrs) <- getRefAttributes Nothing
content <- getContent
return $ makeElement "form" content $ addAttrs attrs
[ ("method", "POST")
, ("enctype", T.pack (show $ viewEncType view))
]
errorList :: [Text] -> [(Text, Text)] -> [X.Node]
errorList [] _ = []
errorList errs attrs = [X.Element "ul" attrs $ map makeError errs]
where
makeError e = X.Element "li" [] [X.TextNode e]
> < dfErrorList ref="user.name " / >
dfErrorList :: Monad m => View Text -> Splice m
dfErrorList view = do
(ref, attrs) <- getRefAttributes Nothing
return $ errorList (errors ref view) attrs
dfChildErrorList :: Monad m => View Text -> Splice m
dfChildErrorList view = do
(ref, attrs) <- getRefAttributes $ Just ""
return $ errorList (childErrors ref view) attrs
dfSubView :: MonadIO m => View Text -> Splice m
dfSubView view = do
(ref, _) <- getRefAttributes Nothing
let view' = subView ref view
nodes <- localHS (bindDigestiveSplices view') runChildren
return nodes
disableOnclick :: Text -> View v -> [(Text, Text)] -> [(Text, Text)]
disableOnclick ref view =
if viewDisabled ref view then const [("disabled","")] else id
itemAttrs - Attribute you should use on div , span , etc that surrounds all
dfInputList :: MonadIO m => View Text -> Splice m
dfInputList view = do
(ref, _) <- getRefAttributes Nothing
let listRef = absoluteRef ref view
listAttrs =
[ ("id", listRef)
, ("class", "inputList")
]
addControl _ = return $ disableOnclick ref view
[ ("onclick", T.concat [ "addInputListItem(this, '"
, listRef
, "'); return false;"] ) ]
removeControl _ = return $ disableOnclick ref view
[ ("onclick", T.concat [ "removeInputListItem(this, '"
, listRef
, "'); return false;"] ) ]
itemAttrs v _ = return
[ ("id", T.concat [listRef, ".", last $ "0" : viewContext v])
, ("class", T.append listRef ".inputListItem")
]
templateAttrs v _ = return
[ ("id", T.concat [listRef, ".", last $ "-1" : viewContext v])
, ("class", T.append listRef ".inputListTemplate")
, ("style", "display: none;")
]
items = listSubViews ref view
f attrs v = localHS (bindAttributeSplices ("itemAttrs" ## attrs v) .
bindDigestiveSplices v) runChildren
dfListItem = do
template <- f templateAttrs (makeListSubView ref (-1) view)
res <- mapSplices (f itemAttrs) items
return $ template ++ res
attrSplices = do
"addControl" ## addControl
"removeControl" ## removeControl
nodes <- localHS (bindSplices ("dfListItem" ## dfListItem) .
bindAttributeSplices attrSplices) runChildren
let indices = [X.Element "input"
[ ("type", "hidden")
, ("name", T.intercalate "." [listRef, indicesRef])
, ("value", T.intercalate "," $ map
(last . ("0":) . viewContext) items)
] []
]
return [X.Element "div" listAttrs (indices ++ nodes)]
> Content to be rendered if there are any errors ...
The @ref@ attribute can be omitted if you want to check the entire form .
dfIfChildErrors :: Monad m => View v -> Splice m
dfIfChildErrors view = do
(ref, _) <- getRefAttributes $ Just ""
if null (childErrors ref view)
then return []
else runChildren
> Content to be rendered if there are no errors ...
The @ref@ attribute can be omitted if you want to check the entire form .
dfIfNoChildErrors :: Monad m => View v -> Splice m
dfIfNoChildErrors view = do
(ref, _) <- getRefAttributes $ Just ""
if null (childErrors ref view)
then runChildren
else return []
|
347012dbadfecc6796108e110eecd991d32bb227947790934526ca423465c028 | digital-asset/ghc | T13311.hs | {-# LANGUAGE RankNTypes #-}
module T13311 where
f :: forall a. (Monoid a) => forall b. (Monoid b) => Maybe a -> Maybe b
f _ = mempty
g :: IO ()
g = do
f
putChar 'a'
| null | https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/typecheck/should_fail/T13311.hs | haskell | # LANGUAGE RankNTypes # | module T13311 where
f :: forall a. (Monoid a) => forall b. (Monoid b) => Maybe a -> Maybe b
f _ = mempty
g :: IO ()
g = do
f
putChar 'a'
|
e9cdb6c1db16d1cbcac6276055772fcce37a30d7597616331ef7907077cf212e | CodyReichert/qi | util.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CHUNGA ; Base : 10 -*-
$ Header : /usr / local / cvsrep / chunga / util.lisp , v 1.12 2008/05/25 10:53:48 edi Exp $
Copyright ( c ) 2006 - 2010 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :chunga)
#-:lispworks
(defmacro when-let ((var expr) &body body)
"Evaluates EXPR, binds it to VAR, and executes BODY if VAR has
a true value."
`(let ((,var ,expr))
(when ,var ,@body)))
(defun ends-with-p (seq suffix &key (test #'char-equal))
"Returns true if the sequence SEQ ends with the sequence
SUFFIX. Individual elements are compared with TEST."
(let ((mismatch (mismatch seq suffix :from-end t :test test)))
(or (null mismatch)
(= mismatch (- (length seq) (length suffix))))))
(defun make-keyword (string destructivep)
"Converts the string STRING to a keyword where all characters are
uppercase or lowercase, taking into account the current readtable
case. Destructively modifies STRING if DESTRUCTIVEP is true."
(intern (funcall
(if destructivep
(if (eq (readtable-case *readtable*) :upcase)
#'nstring-upcase
#'nstring-downcase)
(if (eq (readtable-case *readtable*) :upcase)
#'string-upcase
#'string-downcase))
string)
:keyword))
(defun read-char* (stream &optional (eof-error-p t) eof-value)
"The streams we're dealing with are all binary with element type
\(UNSIGNED-BYTE 8) and we're only interested in ISO-8859-1, so we use
this to `simulate' READ-CHAR."
(cond (*char-buffer*
(prog1 *char-buffer*
(setq *char-buffer* nil)))
(t
this assumes that character codes are identical to Unicode code
points , at least for Latin1
(let ((char-code (read-byte stream eof-error-p eof-value)))
(and char-code
(code-char char-code))))))
(defun unread-char* (char)
"Were simulating UNREAD-CHAR by putting the character into
*CHAR-BUFFER*."
;; no error checking, only used internally
(setq *char-buffer* char)
nil)
(defun peek-char* (stream &optional eof-error-p eof-value)
"We're simulating PEEK-CHAR by reading a character and putting it
into *CHAR-BUFFER*."
;; no error checking, only used internally
(setq *char-buffer* (read-char* stream eof-error-p eof-value)))
(defmacro with-character-stream-semantics (&body body)
"Binds *CHAR-BUFFER* around BODY so that within BODY we can use
READ-CHAR* and friends \(see above) to simulate a character stream
although we're reading from a binary stream."
`(let ((*char-buffer* nil))
,@body))
| null | https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/chunga-master/util.lisp | lisp | Syntax : COMMON - LISP ; Package : CHUNGA ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
no error checking, only used internally
no error checking, only used internally | $ Header : /usr / local / cvsrep / chunga / util.lisp , v 1.12 2008/05/25 10:53:48 edi Exp $
Copyright ( c ) 2006 - 2010 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :chunga)
#-:lispworks
(defmacro when-let ((var expr) &body body)
"Evaluates EXPR, binds it to VAR, and executes BODY if VAR has
a true value."
`(let ((,var ,expr))
(when ,var ,@body)))
(defun ends-with-p (seq suffix &key (test #'char-equal))
"Returns true if the sequence SEQ ends with the sequence
SUFFIX. Individual elements are compared with TEST."
(let ((mismatch (mismatch seq suffix :from-end t :test test)))
(or (null mismatch)
(= mismatch (- (length seq) (length suffix))))))
(defun make-keyword (string destructivep)
"Converts the string STRING to a keyword where all characters are
uppercase or lowercase, taking into account the current readtable
case. Destructively modifies STRING if DESTRUCTIVEP is true."
(intern (funcall
(if destructivep
(if (eq (readtable-case *readtable*) :upcase)
#'nstring-upcase
#'nstring-downcase)
(if (eq (readtable-case *readtable*) :upcase)
#'string-upcase
#'string-downcase))
string)
:keyword))
(defun read-char* (stream &optional (eof-error-p t) eof-value)
"The streams we're dealing with are all binary with element type
\(UNSIGNED-BYTE 8) and we're only interested in ISO-8859-1, so we use
this to `simulate' READ-CHAR."
(cond (*char-buffer*
(prog1 *char-buffer*
(setq *char-buffer* nil)))
(t
this assumes that character codes are identical to Unicode code
points , at least for Latin1
(let ((char-code (read-byte stream eof-error-p eof-value)))
(and char-code
(code-char char-code))))))
(defun unread-char* (char)
"Were simulating UNREAD-CHAR by putting the character into
*CHAR-BUFFER*."
(setq *char-buffer* char)
nil)
(defun peek-char* (stream &optional eof-error-p eof-value)
"We're simulating PEEK-CHAR by reading a character and putting it
into *CHAR-BUFFER*."
(setq *char-buffer* (read-char* stream eof-error-p eof-value)))
(defmacro with-character-stream-semantics (&body body)
"Binds *CHAR-BUFFER* around BODY so that within BODY we can use
READ-CHAR* and friends \(see above) to simulate a character stream
although we're reading from a binary stream."
`(let ((*char-buffer* nil))
,@body))
|
c02383f6c17b90cc582ada9deec51b3d3a85c99295fe22655af13fdf363d9aa3 | restyled-io/restyled.io | JWT.hs | | Extension of @"GitHub . Auth"@ to support JWT - based authorization
module GitHub.Auth.JWT
( AuthJWT(..)
, authJWT
, authJWTMax
) where
import Prelude
import Control.Exception.Safe (throwString)
import Data.ByteString (ByteString)
import Data.Text.Encoding (encodeUtf8)
import Data.Time
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import GHC.Stack
import GitHub.Data
import GitHub.Data.Apps
import Network.HTTP.Simple (addRequestHeader)
import Network.HTTP.Types (hAuthorization)
import qualified Web.JWT as JWT
newtype AuthJWT = AuthJWT ByteString
instance AuthMethod AuthJWT where
endpoint (AuthJWT _) = Nothing
setAuthRequest (AuthJWT token) =
addRequestHeader hAuthorization $ "bearer " <> token
authJWT :: HasCallStack => NominalDiffTime -> Id App -> AppKey -> IO AuthJWT
authJWT expires githubAppId appKey = do
now <- getCurrentTime
signer <- maybe (throwString "Invalid RSA data") pure
=<< JWT.rsaKeySecret (unAppKey appKey)
pure $ AuthJWT $ encodeUtf8 $ JWT.encodeSigned
signer
mempty { JWT.alg = Just JWT.RS256 }
mempty
{ JWT.iat = numericDate now
, JWT.exp = numericDate $ addUTCTime expires now
, JWT.iss = JWT.stringOrURI $ toPathPart githubAppId
}
| Authorize via JWT , expiring in 9 minutes
--
10 minutes is the documented maximum , but I can reliably trigger a " too far
in the future " error , which I assume is due to clocks skew , so we treat 9
-- minutes as the real maximum.
--
authJWTMax :: HasCallStack => Id App -> AppKey -> IO AuthJWT
authJWTMax = authJWT $ 9 * 60
numericDate :: UTCTime -> Maybe JWT.NumericDate
numericDate = JWT.numericDate . utcTimeToPOSIXSeconds
| null | https://raw.githubusercontent.com/restyled-io/restyled.io/2486edb6c9b352118d36f8f7cb06432be7fd7c4c/src/GitHub/Auth/JWT.hs | haskell |
minutes as the real maximum.
| | Extension of @"GitHub . Auth"@ to support JWT - based authorization
module GitHub.Auth.JWT
( AuthJWT(..)
, authJWT
, authJWTMax
) where
import Prelude
import Control.Exception.Safe (throwString)
import Data.ByteString (ByteString)
import Data.Text.Encoding (encodeUtf8)
import Data.Time
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import GHC.Stack
import GitHub.Data
import GitHub.Data.Apps
import Network.HTTP.Simple (addRequestHeader)
import Network.HTTP.Types (hAuthorization)
import qualified Web.JWT as JWT
newtype AuthJWT = AuthJWT ByteString
instance AuthMethod AuthJWT where
endpoint (AuthJWT _) = Nothing
setAuthRequest (AuthJWT token) =
addRequestHeader hAuthorization $ "bearer " <> token
authJWT :: HasCallStack => NominalDiffTime -> Id App -> AppKey -> IO AuthJWT
authJWT expires githubAppId appKey = do
now <- getCurrentTime
signer <- maybe (throwString "Invalid RSA data") pure
=<< JWT.rsaKeySecret (unAppKey appKey)
pure $ AuthJWT $ encodeUtf8 $ JWT.encodeSigned
signer
mempty { JWT.alg = Just JWT.RS256 }
mempty
{ JWT.iat = numericDate now
, JWT.exp = numericDate $ addUTCTime expires now
, JWT.iss = JWT.stringOrURI $ toPathPart githubAppId
}
| Authorize via JWT , expiring in 9 minutes
10 minutes is the documented maximum , but I can reliably trigger a " too far
in the future " error , which I assume is due to clocks skew , so we treat 9
authJWTMax :: HasCallStack => Id App -> AppKey -> IO AuthJWT
authJWTMax = authJWT $ 9 * 60
numericDate :: UTCTime -> Maybe JWT.NumericDate
numericDate = JWT.numericDate . utcTimeToPOSIXSeconds
|
0a4778819df80b950c827fbd9ae9afd21856c6a255883931cdf05b0fb1d98d7d | losfair/Violet | Nat.hs | # LANGUAGE TemplateHaskell #
module Violet.TypeLevel.Nat where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Prelude
natT :: Integer -> TypeQ
natT n = pure (LitT (NumTyLit n))
| null | https://raw.githubusercontent.com/losfair/Violet/dcdd05f8dc08a438a157347f424966da73ccc9b8/src/Violet/TypeLevel/Nat.hs | haskell | # LANGUAGE TemplateHaskell #
module Violet.TypeLevel.Nat where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Prelude
natT :: Integer -> TypeQ
natT n = pure (LitT (NumTyLit n))
| |
0358f4e85be478d0879a31204f6aa3f1efcf6647b05d464a8bf19734028cc2b0 | BillHallahan/G2 | Test7.hs | -- cmd_line = (--no-keep-quals)
{-@ LIQUID "--short-names" @-}
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--prune-unsorted" @-}
# LANGUAGE DeriveGeneric #
module Combined () where
import qualified Data.Map as M
import Data.List (minimumBy, head)
data List a = Emp
| R a
deriving (Eq, Ord, Show)
@ measure size : : List a - > Int
size ( Emp ) = 0
size ( R x ) = 1
@
size (Emp) = 0
size (R x) = 1
@-}
{-@ invariant {v:List a | 0 <= size v} @-}
@ type ListN a N = { v : List a | size v = N } @
@ f : : [ { v : Int | v = = 1 } ] - > List { v : Int | v = = 1 } @
f :: [Int] -> List Int
f cs = kvsm
where
kvs = R (g cs)
kvsm = h kvs
g :: [Int] -> Int
g xs = minimumBy (\_ _ -> EQ) xs
h :: List Int -> List Int
h Emp = Emp
h (R _) = R 1
| null | https://raw.githubusercontent.com/BillHallahan/G2/4d287df8ed7ba13c06d96d4911b9eedf870e80a1/tests/LiquidInf/Artificial/Pos/Test7.hs | haskell | cmd_line = (--no-keep-quals)
@ LIQUID "--short-names" @
@ LIQUID "--no-termination" @
@ LIQUID "--prune-unsorted" @
@ invariant {v:List a | 0 <= size v} @ |
# LANGUAGE DeriveGeneric #
module Combined () where
import qualified Data.Map as M
import Data.List (minimumBy, head)
data List a = Emp
| R a
deriving (Eq, Ord, Show)
@ measure size : : List a - > Int
size ( Emp ) = 0
size ( R x ) = 1
@
size (Emp) = 0
size (R x) = 1
@-}
@ type ListN a N = { v : List a | size v = N } @
@ f : : [ { v : Int | v = = 1 } ] - > List { v : Int | v = = 1 } @
f :: [Int] -> List Int
f cs = kvsm
where
kvs = R (g cs)
kvsm = h kvs
g :: [Int] -> Int
g xs = minimumBy (\_ _ -> EQ) xs
h :: List Int -> List Int
h Emp = Emp
h (R _) = R 1
|
e18940053f4f6b36f36ee9293fdce91df3d511205aab8ab95e2adb4f71319749 | grzm/awyeah-api | interceptors.clj | Copyright ( c ) Cognitect , Inc.
;; All rights reserved.
(ns ^:skip-wiki com.grzm.awyeah.interceptors
"Impl, don't call directly."
(:require
[com.grzm.awyeah.service :as service]
[com.grzm.awyeah.util :as util]))
(set! *warn-on-reflection* true)
(defmulti modify-http-request (fn [service _op-map _http-request]
(service/service-name service)))
(defmethod modify-http-request :default [_service _op-map http-request] http-request)
(def md5-blacklist
"Set of ops that should not get the Content-MD5 header.
See -sdk-java-v2/blob/master/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/AddContentMd5HeaderInterceptor.java "
#{:PutObject :UploadPart})
(defmethod modify-http-request "s3" [service op-map http-request]
(if (and (= "md5" (get-in service [:metadata :checksumFormat]))
(not (md5-blacklist (:op op-map)))
(:body http-request))
(update http-request :headers assoc "Content-MD5" (-> http-request :body util/md5 util/base64-encode))
http-request))
(defmethod modify-http-request "apigatewaymanagementapi" [_service op-map http-request]
(if (= :PostToConnection (:op op-map))
(update http-request :uri str (-> op-map :request :ConnectionId))
http-request))
;; See -sdk-java-v2/blob/985ec92c0dfac868b33791fe4623296c68e2feab/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/internal/GlacierExecutionInterceptor.java#L40
(defmethod modify-http-request "glacier" [service _op-map http-request]
(assoc-in http-request
[:headers "x-amz-glacier-version"]
(get-in service [:metadata :apiVersion])))
| null | https://raw.githubusercontent.com/grzm/awyeah-api/1810bf624da2be58c77813106a1d51e32db11690/src/com/grzm/awyeah/interceptors.clj | clojure | All rights reserved.
See -sdk-java-v2/blob/985ec92c0dfac868b33791fe4623296c68e2feab/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/internal/GlacierExecutionInterceptor.java#L40 | Copyright ( c ) Cognitect , Inc.
(ns ^:skip-wiki com.grzm.awyeah.interceptors
"Impl, don't call directly."
(:require
[com.grzm.awyeah.service :as service]
[com.grzm.awyeah.util :as util]))
(set! *warn-on-reflection* true)
(defmulti modify-http-request (fn [service _op-map _http-request]
(service/service-name service)))
(defmethod modify-http-request :default [_service _op-map http-request] http-request)
(def md5-blacklist
"Set of ops that should not get the Content-MD5 header.
See -sdk-java-v2/blob/master/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/AddContentMd5HeaderInterceptor.java "
#{:PutObject :UploadPart})
(defmethod modify-http-request "s3" [service op-map http-request]
(if (and (= "md5" (get-in service [:metadata :checksumFormat]))
(not (md5-blacklist (:op op-map)))
(:body http-request))
(update http-request :headers assoc "Content-MD5" (-> http-request :body util/md5 util/base64-encode))
http-request))
(defmethod modify-http-request "apigatewaymanagementapi" [_service op-map http-request]
(if (= :PostToConnection (:op op-map))
(update http-request :uri str (-> op-map :request :ConnectionId))
http-request))
(defmethod modify-http-request "glacier" [service _op-map http-request]
(assoc-in http-request
[:headers "x-amz-glacier-version"]
(get-in service [:metadata :apiVersion])))
|
2542e9f8e4246a135b039fd4aba8fdb87d147cbd1f0255624a7a48cd6028b0a3 | tweag/ormolu | proc-lambdas-out.hs | {-# LANGUAGE Arrows #-}
foo = proc a -> \f b -> a -< f b -- Foo
bar =
proc x -> \f g h ->
\() ->
\(Left (x, y)) ->
-- Tuple value
f (g (h x)) -< y
| null | https://raw.githubusercontent.com/tweag/ormolu/11cda4c653bc67a6ff579531a441410626ab3bbd/data/examples/declaration/value/function/arrow/proc-lambdas-out.hs | haskell | # LANGUAGE Arrows #
Foo
Tuple value |
bar =
proc x -> \f g h ->
\() ->
\(Left (x, y)) ->
f (g (h x)) -< y
|
9d259c494c9560d48e72e5beb686ec41abf58d638e40dfb62517ec24f862aec8 | achirkin/vulkan | VK_NV_sample_mask_override_coverage.hs | # OPTIONS_HADDOCK not - home #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MagicHash #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE Strict #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_NV_sample_mask_override_coverage
* Vulkan extension : @VK_NV_sample_mask_override_coverage@
-- |
--
-- supported: @vulkan@
--
contact :
--
author :
--
-- type: @device@
--
-- Extension number: @95@
VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION,
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION,
VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME,
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION = 1
type VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION = 1
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME ::
CString
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME <-
(is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME -> True)
where
VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
= _VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
# INLINE _ VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME #
_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME :: CString
_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
= Ptr "VK_NV_sample_mask_override_coverage\NUL"#
{-# INLINE is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
#-}
is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME ::
CString -> Bool
is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
= (EQ ==) .
cmpCStrings _VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
type VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME =
"VK_NV_sample_mask_override_coverage"
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_NV_sample_mask_override_coverage.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE Strict #
# LANGUAGE ViewPatterns #
|
supported: @vulkan@
type: @device@
Extension number: @95@
# INLINE is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
# | # OPTIONS_HADDOCK not - home #
# LANGUAGE PatternSynonyms #
module Graphics.Vulkan.Ext.VK_NV_sample_mask_override_coverage
* Vulkan extension : @VK_NV_sample_mask_override_coverage@
contact :
author :
VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION,
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION,
VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME,
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION = 1
type VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION = 1
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME ::
CString
pattern VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME <-
(is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME -> True)
where
VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
= _VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
# INLINE _ VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME #
_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME :: CString
_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
= Ptr "VK_NV_sample_mask_override_coverage\NUL"#
is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME ::
CString -> Bool
is_VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
= (EQ ==) .
cmpCStrings _VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME
type VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME =
"VK_NV_sample_mask_override_coverage"
|
1f2771649fad04c26850859d9dc62e0076c1f7f4544cc81d72f1f383117744d3 | rabbitmq/rabbitmq-federation | unit_inbroker_SUITE.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(unit_inbroker_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("rabbit_federation.hrl").
-compile(export_all).
-define(US_NAME, <<"upstream">>).
-define(DS_NAME, <<"fed.downstream">>).
all() ->
[
{group, non_parallel_tests}
].
groups() ->
[
{non_parallel_tests, [], [
serialisation,
scratch_space,
remove_credentials,
get_connection_name,
upstream_validation,
upstream_set_validation
]}
].
%% -------------------------------------------------------------------
%% Testsuite setup/teardown.
%% -------------------------------------------------------------------
init_per_suite(Config) ->
rabbit_ct_helpers:log_environment(),
Config1 = rabbit_ct_helpers:set_config(Config, [
{rmq_nodename_suffix, ?MODULE}
]),
rabbit_ct_helpers:run_setup_steps(Config1,
rabbit_ct_broker_helpers:setup_steps() ++
rabbit_ct_client_helpers:setup_steps()).
end_per_suite(Config) ->
rabbit_ct_helpers:run_teardown_steps(Config,
rabbit_ct_client_helpers:teardown_steps() ++
rabbit_ct_broker_helpers:teardown_steps()).
init_per_group(_, Config) ->
Config.
end_per_group(_, Config) ->
Config.
init_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_started(Config, Testcase).
end_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_finished(Config, Testcase).
%% -------------------------------------------------------------------
%% Testcases.
%% -------------------------------------------------------------------
%% Test that we apply binding changes in the correct order even when
%% they arrive out of order.
serialisation(Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0,
?MODULE, serialisation1, []).
serialisation1() ->
with_exchanges(
fun(X) ->
[B1, B2, B3] = [b(K) || K <- [<<"1">>, <<"2">>, <<"3">>]],
remove_bindings(4, X, [B1, B3]),
add_binding(5, X, B1),
add_binding(1, X, B1),
add_binding(2, X, B2),
add_binding(3, X, B3),
List of lists because one for each link
Keys = rabbit_federation_exchange_link:list_routing_keys(
X#exchange.name),
[[<<"1">>, <<"2">>]] =:= Keys
end).
scratch_space(Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0,
?MODULE, scratch_space1, []).
scratch_space1() ->
A = <<"A">>,
B = <<"B">>,
DB = rabbit_federation_db,
with_exchanges(
fun(#exchange{name = N}) ->
DB:set_active_suffix(N, upstream(x), A),
DB:set_active_suffix(N, upstream(y), A),
DB:prune_scratch(N, [upstream(y), upstream(z)]),
DB:set_active_suffix(N, upstream(y), B),
DB:set_active_suffix(N, upstream(z), A),
none = DB:get_active_suffix(N, upstream(x), none),
B = DB:get_active_suffix(N, upstream(y), none),
A = DB:get_active_suffix(N, upstream(z), none)
end).
remove_credentials(Config) ->
Test0 = fun (In, Exp) ->
Act = rabbit_ct_broker_helpers:rpc(Config, 0,
rabbit_federation_upstream, remove_credentials, [In]),
Exp = Act
end,
Cat = fun (Bs) ->
list_to_binary(lists:append([binary_to_list(B) || B <- Bs]))
end,
Test = fun (Scheme, Rest) ->
Exp = Cat([Scheme, Rest]),
Test0(Exp, Exp),
Test0(Cat([Scheme, <<"user@">>, Rest]), Exp),
Test0(Cat([Scheme, <<"user:pass@">>, Rest]), Exp)
end,
Test(<<"amqp://">>, <<"">>),
Test(<<"amqp://">>, <<"localhost">>),
Test(<<"amqp://">>, <<"localhost/">>),
Test(<<"amqp://">>, <<"localhost/foo">>),
Test(<<"amqp://">>, <<"localhost:5672">>),
Test(<<"amqp://">>, <<"localhost:5672/foo">>),
Test(<<"amqps://">>, <<"localhost:5672/%2f">>),
ok.
get_connection_name(Config) ->
Amqqueue = rabbit_ct_broker_helpers:rpc(
Config, 0,
amqqueue, new, [rabbit_misc:r(<<"/">>, queue, <<"queue">>),
self(),
false,
false,
none,
[],
undefined,
#{},
classic]),
AmqqueueWithPolicy = amqqueue:set_policy(Amqqueue, [{name, <<"my.federation.policy">>}]),
AmqqueueWithEmptyPolicy = amqqueue:set_policy(Amqqueue, []),
<<"Federation link (upstream: my.upstream, policy: my.federation.policy)">> = rabbit_federation_link_util:get_connection_name(
#upstream{name = <<"my.upstream">>},
#upstream_params{x_or_q = AmqqueueWithPolicy}
),
<<"Federation link (upstream: my.upstream, policy: my.federation.policy)">> = rabbit_federation_link_util:get_connection_name(
#upstream{name = <<"my.upstream">>},
#upstream_params{x_or_q = #exchange{policy = [{name, <<"my.federation.policy">>}]}}
),
<<"Federation link">> = rabbit_federation_link_util:get_connection_name(
#upstream{},
#upstream_params{x_or_q = AmqqueueWithEmptyPolicy}
),
<<"Federation link">> = rabbit_federation_link_util:get_connection_name(
#upstream{},
#upstream_params{x_or_q = #exchange{policy = []}}
),
<<"Federation link">> = rabbit_federation_link_util:get_connection_name(
whatever,
whatever
),
ok.
upstream_set_validation(_Config) ->
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream-set">>,
<<"a-name">>,
[[{<<"upstream">>, <<"devtest1">>}],
[{<<"upstream">>, <<"devtest2">>}]],
<<"acting-user">>),
[[ok], [ok]]),
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream-set">>,
<<"a-name">>,
[#{<<"upstream">> => <<"devtest3">>},
#{<<"upstream">> => <<"devtest4">>}],
<<"acting-user">>),
[[ok], [ok]]),
ok.
upstream_validation(_Config) ->
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream">>,
<<"a-name">>,
[{<<"uri">>, <<"amqp">>}],
<<"acting-user">>),
[ok]),
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream">>,
<<"a-name">>,
#{<<"uri">> => <<"amqp">>},
<<"acting-user">>),
[ok]),
ok.
with_exchanges(Fun) ->
rabbit_exchange:declare(r(?US_NAME), fanout, false, false, false, [],
<<"acting-user">>),
X = rabbit_exchange:declare(r(?DS_NAME), fanout, false, false, false, [],
<<"acting-user">>),
Fun(X),
Delete downstream first or it will recreate the upstream
rabbit_exchange:delete(r(?DS_NAME), false, <<"acting-user">>),
rabbit_exchange:delete(r(?US_NAME), false, <<"acting-user">>),
ok.
add_binding(Ser, X, B) ->
rabbit_federation_exchange:add_binding(transaction, X, B),
rabbit_federation_exchange:add_binding(Ser, X, B).
remove_bindings(Ser, X, Bs) ->
rabbit_federation_exchange:remove_bindings(transaction, X, Bs),
rabbit_federation_exchange:remove_bindings(Ser, X, Bs).
r(Name) -> rabbit_misc:r(<<"/">>, exchange, Name).
b(Key) ->
#binding{source = ?DS_NAME, destination = <<"whatever">>,
key = Key, args = []}.
upstream(UpstreamName) ->
#upstream{name = atom_to_list(UpstreamName),
exchange_name = <<"upstream">>}.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-federation/960b8214487ae2495cd39afbbd3a2c4d9ea37985/test/unit_inbroker_SUITE.erl | erlang |
-------------------------------------------------------------------
Testsuite setup/teardown.
-------------------------------------------------------------------
-------------------------------------------------------------------
Testcases.
-------------------------------------------------------------------
Test that we apply binding changes in the correct order even when
they arrive out of order. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(unit_inbroker_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("rabbit_federation.hrl").
-compile(export_all).
-define(US_NAME, <<"upstream">>).
-define(DS_NAME, <<"fed.downstream">>).
all() ->
[
{group, non_parallel_tests}
].
groups() ->
[
{non_parallel_tests, [], [
serialisation,
scratch_space,
remove_credentials,
get_connection_name,
upstream_validation,
upstream_set_validation
]}
].
init_per_suite(Config) ->
rabbit_ct_helpers:log_environment(),
Config1 = rabbit_ct_helpers:set_config(Config, [
{rmq_nodename_suffix, ?MODULE}
]),
rabbit_ct_helpers:run_setup_steps(Config1,
rabbit_ct_broker_helpers:setup_steps() ++
rabbit_ct_client_helpers:setup_steps()).
end_per_suite(Config) ->
rabbit_ct_helpers:run_teardown_steps(Config,
rabbit_ct_client_helpers:teardown_steps() ++
rabbit_ct_broker_helpers:teardown_steps()).
init_per_group(_, Config) ->
Config.
end_per_group(_, Config) ->
Config.
init_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_started(Config, Testcase).
end_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_finished(Config, Testcase).
serialisation(Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0,
?MODULE, serialisation1, []).
serialisation1() ->
with_exchanges(
fun(X) ->
[B1, B2, B3] = [b(K) || K <- [<<"1">>, <<"2">>, <<"3">>]],
remove_bindings(4, X, [B1, B3]),
add_binding(5, X, B1),
add_binding(1, X, B1),
add_binding(2, X, B2),
add_binding(3, X, B3),
List of lists because one for each link
Keys = rabbit_federation_exchange_link:list_routing_keys(
X#exchange.name),
[[<<"1">>, <<"2">>]] =:= Keys
end).
scratch_space(Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0,
?MODULE, scratch_space1, []).
scratch_space1() ->
A = <<"A">>,
B = <<"B">>,
DB = rabbit_federation_db,
with_exchanges(
fun(#exchange{name = N}) ->
DB:set_active_suffix(N, upstream(x), A),
DB:set_active_suffix(N, upstream(y), A),
DB:prune_scratch(N, [upstream(y), upstream(z)]),
DB:set_active_suffix(N, upstream(y), B),
DB:set_active_suffix(N, upstream(z), A),
none = DB:get_active_suffix(N, upstream(x), none),
B = DB:get_active_suffix(N, upstream(y), none),
A = DB:get_active_suffix(N, upstream(z), none)
end).
remove_credentials(Config) ->
Test0 = fun (In, Exp) ->
Act = rabbit_ct_broker_helpers:rpc(Config, 0,
rabbit_federation_upstream, remove_credentials, [In]),
Exp = Act
end,
Cat = fun (Bs) ->
list_to_binary(lists:append([binary_to_list(B) || B <- Bs]))
end,
Test = fun (Scheme, Rest) ->
Exp = Cat([Scheme, Rest]),
Test0(Exp, Exp),
Test0(Cat([Scheme, <<"user@">>, Rest]), Exp),
Test0(Cat([Scheme, <<"user:pass@">>, Rest]), Exp)
end,
Test(<<"amqp://">>, <<"">>),
Test(<<"amqp://">>, <<"localhost">>),
Test(<<"amqp://">>, <<"localhost/">>),
Test(<<"amqp://">>, <<"localhost/foo">>),
Test(<<"amqp://">>, <<"localhost:5672">>),
Test(<<"amqp://">>, <<"localhost:5672/foo">>),
Test(<<"amqps://">>, <<"localhost:5672/%2f">>),
ok.
get_connection_name(Config) ->
Amqqueue = rabbit_ct_broker_helpers:rpc(
Config, 0,
amqqueue, new, [rabbit_misc:r(<<"/">>, queue, <<"queue">>),
self(),
false,
false,
none,
[],
undefined,
#{},
classic]),
AmqqueueWithPolicy = amqqueue:set_policy(Amqqueue, [{name, <<"my.federation.policy">>}]),
AmqqueueWithEmptyPolicy = amqqueue:set_policy(Amqqueue, []),
<<"Federation link (upstream: my.upstream, policy: my.federation.policy)">> = rabbit_federation_link_util:get_connection_name(
#upstream{name = <<"my.upstream">>},
#upstream_params{x_or_q = AmqqueueWithPolicy}
),
<<"Federation link (upstream: my.upstream, policy: my.federation.policy)">> = rabbit_federation_link_util:get_connection_name(
#upstream{name = <<"my.upstream">>},
#upstream_params{x_or_q = #exchange{policy = [{name, <<"my.federation.policy">>}]}}
),
<<"Federation link">> = rabbit_federation_link_util:get_connection_name(
#upstream{},
#upstream_params{x_or_q = AmqqueueWithEmptyPolicy}
),
<<"Federation link">> = rabbit_federation_link_util:get_connection_name(
#upstream{},
#upstream_params{x_or_q = #exchange{policy = []}}
),
<<"Federation link">> = rabbit_federation_link_util:get_connection_name(
whatever,
whatever
),
ok.
upstream_set_validation(_Config) ->
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream-set">>,
<<"a-name">>,
[[{<<"upstream">>, <<"devtest1">>}],
[{<<"upstream">>, <<"devtest2">>}]],
<<"acting-user">>),
[[ok], [ok]]),
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream-set">>,
<<"a-name">>,
[#{<<"upstream">> => <<"devtest3">>},
#{<<"upstream">> => <<"devtest4">>}],
<<"acting-user">>),
[[ok], [ok]]),
ok.
upstream_validation(_Config) ->
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream">>,
<<"a-name">>,
[{<<"uri">>, <<"amqp">>}],
<<"acting-user">>),
[ok]),
?assertEqual(rabbit_federation_parameters:validate(<<"/">>, <<"federation-upstream">>,
<<"a-name">>,
#{<<"uri">> => <<"amqp">>},
<<"acting-user">>),
[ok]),
ok.
with_exchanges(Fun) ->
rabbit_exchange:declare(r(?US_NAME), fanout, false, false, false, [],
<<"acting-user">>),
X = rabbit_exchange:declare(r(?DS_NAME), fanout, false, false, false, [],
<<"acting-user">>),
Fun(X),
Delete downstream first or it will recreate the upstream
rabbit_exchange:delete(r(?DS_NAME), false, <<"acting-user">>),
rabbit_exchange:delete(r(?US_NAME), false, <<"acting-user">>),
ok.
add_binding(Ser, X, B) ->
rabbit_federation_exchange:add_binding(transaction, X, B),
rabbit_federation_exchange:add_binding(Ser, X, B).
remove_bindings(Ser, X, Bs) ->
rabbit_federation_exchange:remove_bindings(transaction, X, Bs),
rabbit_federation_exchange:remove_bindings(Ser, X, Bs).
r(Name) -> rabbit_misc:r(<<"/">>, exchange, Name).
b(Key) ->
#binding{source = ?DS_NAME, destination = <<"whatever">>,
key = Key, args = []}.
upstream(UpstreamName) ->
#upstream{name = atom_to_list(UpstreamName),
exchange_name = <<"upstream">>}.
|
911341873e4e7360cded3d051c046bf5c5d97dc8a0842b3cb1e67e9bd4e7206f | binaryage/env-config | logging.cljs | (ns env-config.impl.logging)
(defn logp [level message]
(case level
:debug (js/console.log message)
:info (js/console.info message)
:warn (js/console.warn message)
:error (js/console.error message)
:fatal (js/console.error message)))
; -- public -----------------------------------------------------------------------------------------------------------------
(defn reporter [messages]
(doseq [[level message] messages]
(logp level message)))
| null | https://raw.githubusercontent.com/binaryage/env-config/27a99a5c2d5ca0941339508484853c45de555a49/src/lib/env_config/impl/logging.cljs | clojure | -- public ----------------------------------------------------------------------------------------------------------------- | (ns env-config.impl.logging)
(defn logp [level message]
(case level
:debug (js/console.log message)
:info (js/console.info message)
:warn (js/console.warn message)
:error (js/console.error message)
:fatal (js/console.error message)))
(defn reporter [messages]
(doseq [[level message] messages]
(logp level message)))
|
196d54a0896bef0a5cd51713e616dc597dc9f77a20a060cc5bb065265861e7a0 | bgusach/exercises-htdp2e | ex-092.rkt | #lang htdp/bsl
(require 2htdp/image)
(require 2htdp/universe)
(define cham-image (bitmap "images/cham.png"))
(define BACKGROUND-WIDTH 300)
(define BACKGROUND-HEIGHT 180)
(define BACKGROUND (empty-scene BACKGROUND-WIDTH BACKGROUND-HEIGHT))
(define SPEED 3)
(define HAPPINESS-SPEED -1)
A ChamColour is one of
; - "red"
; - "blue"
; - "green"
; interpretation: colour of the chameleon
A Position is a Number in [ 0 , 100 ]
interpretation : 0 leftmost position 100 rightmost position
A Happiness is a Number in [ 0 , 100 ]
interpretation : 0 minimum happiness , 100 maximum
(define-struct cham [pos colour happiness])
VCham is ( make - cham Position ChamColour Happiness )
; intepretation: state of the world defined by
; where is the chameleon, what colour it has and how happy it is
VCham - > Image
(define (render-world ws)
(place-image
(get-cham-image ws)
(cham-pos ws)
(/ BACKGROUND-HEIGHT 2)
(place-image/align
(make-happiness-bar (cham-happiness ws))
0
BACKGROUND-HEIGHT
"left"
"bottom"
BACKGROUND)))
VCham - > Image
; Returns an image that represents cham in the current state
(define (get-cham-image cham)
(overlay
(if (= (cham-happiness cham) 0)
(rotate 90 cham-image)
cham-image)
(rectangle
(image-width cham-image)
(image-height cham-image)
"solid"
(cham-colour cham))))
VCham - > VCham
(define (tock cham)
(cond
[(unhappy? cham) cham]
[else
(make-cham
(modulo (+ (cham-pos cham) SPEED) BACKGROUND-WIDTH)
(cham-colour cham)
(+ (cham-happiness cham) HAPPINESS-SPEED))]))
VCham - > Boolean
; Returns whether the cham is completely unhappy
(define (unhappy? cham)
(<= (cham-happiness cham) 0))
VCham - > Boolean
; Returns whether the cham is completely happy
(define (fulfilled? cham)
(>= (cham-happiness cham) 100))
; Happiness -> Image
; Given a level of happiness, returns an image representing it
(define (make-happiness-bar h)
(rectangle
(* BACKGROUND-WIDTH (/ h 100))
10
"solid"
(if (>= h 20) "olivedrab" "red")))
- > VCham
(define (on-key-press cham key)
(cond
[(and (key=? key "down") (not (fulfilled? cham)))
(make-cham
(cham-pos cham)
(cham-colour cham)
(+ (cham-happiness cham) 2))]
[(key=? key "r")
(make-cham
(cham-pos cham)
"red"
(cham-happiness cham))]
[(key=? key "b")
(make-cham
(cham-pos cham)
"blue"
(cham-happiness cham))]
[(key=? key "g")
(make-cham
(cham-pos cham)
"green"
(cham-happiness cham))]
[else cham]))
(define (main cham)
(big-bang cham
[to-draw render-world]
[on-key on-key-press]
[on-tick tock]))
(main (make-cham 0 "green" 100))
| null | https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/ex-092.rkt | racket | - "red"
- "blue"
- "green"
interpretation: colour of the chameleon
intepretation: state of the world defined by
where is the chameleon, what colour it has and how happy it is
Returns an image that represents cham in the current state
Returns whether the cham is completely unhappy
Returns whether the cham is completely happy
Happiness -> Image
Given a level of happiness, returns an image representing it | #lang htdp/bsl
(require 2htdp/image)
(require 2htdp/universe)
(define cham-image (bitmap "images/cham.png"))
(define BACKGROUND-WIDTH 300)
(define BACKGROUND-HEIGHT 180)
(define BACKGROUND (empty-scene BACKGROUND-WIDTH BACKGROUND-HEIGHT))
(define SPEED 3)
(define HAPPINESS-SPEED -1)
A ChamColour is one of
A Position is a Number in [ 0 , 100 ]
interpretation : 0 leftmost position 100 rightmost position
A Happiness is a Number in [ 0 , 100 ]
interpretation : 0 minimum happiness , 100 maximum
(define-struct cham [pos colour happiness])
VCham is ( make - cham Position ChamColour Happiness )
VCham - > Image
(define (render-world ws)
(place-image
(get-cham-image ws)
(cham-pos ws)
(/ BACKGROUND-HEIGHT 2)
(place-image/align
(make-happiness-bar (cham-happiness ws))
0
BACKGROUND-HEIGHT
"left"
"bottom"
BACKGROUND)))
VCham - > Image
(define (get-cham-image cham)
(overlay
(if (= (cham-happiness cham) 0)
(rotate 90 cham-image)
cham-image)
(rectangle
(image-width cham-image)
(image-height cham-image)
"solid"
(cham-colour cham))))
VCham - > VCham
(define (tock cham)
(cond
[(unhappy? cham) cham]
[else
(make-cham
(modulo (+ (cham-pos cham) SPEED) BACKGROUND-WIDTH)
(cham-colour cham)
(+ (cham-happiness cham) HAPPINESS-SPEED))]))
VCham - > Boolean
(define (unhappy? cham)
(<= (cham-happiness cham) 0))
VCham - > Boolean
(define (fulfilled? cham)
(>= (cham-happiness cham) 100))
(define (make-happiness-bar h)
(rectangle
(* BACKGROUND-WIDTH (/ h 100))
10
"solid"
(if (>= h 20) "olivedrab" "red")))
- > VCham
(define (on-key-press cham key)
(cond
[(and (key=? key "down") (not (fulfilled? cham)))
(make-cham
(cham-pos cham)
(cham-colour cham)
(+ (cham-happiness cham) 2))]
[(key=? key "r")
(make-cham
(cham-pos cham)
"red"
(cham-happiness cham))]
[(key=? key "b")
(make-cham
(cham-pos cham)
"blue"
(cham-happiness cham))]
[(key=? key "g")
(make-cham
(cham-pos cham)
"green"
(cham-happiness cham))]
[else cham]))
(define (main cham)
(big-bang cham
[to-draw render-world]
[on-key on-key-press]
[on-tick tock]))
(main (make-cham 0 "green" 100))
|
7e1f122d2691636a7096bf5e13cea198697ff7932bb34e1728833f9677172e6a | ekmett/succinct | Delta.hs | # LANGUAGE CPP #
-----------------------------------------------------------------------------
-- |
Copyright : ( C ) 2013 - 15
-- License : BSD-style (see the file LICENSE)
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Succinct.Internal.Delta
( Delta(..)
, minima
, bool
, bits
, byte
, e8, d8, n8
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.Bits
import Data.Int
import Data.Semigroup
import Data.Vector.Unboxed.Base as UB
import Data.Vector.Unboxed as U
import Data.Vector.Primitive as P
import Data.Word
-- | Δ-Range-Min
--
-- This provides a semigroup-based variant of the basic aggregation used
-- in < Grossi and Ottaviano's Range-Min tree>,
-- which is in turn a simplification of a
< Range > tree
data Delta = Delta
{ excess :: {-# UNPACK #-} !Int -- even when # bits is even, odd when it is odd
, delta :: {-# UNPACK #-} !Int -- minima = excess - delta
, nminima :: {-# UNPACK #-} !Int -- # of minima
} deriving Show
instance Semigroup Delta where
Delta e d n <> Delta e' d' n' = case compare d' (d + e) of
LT -> Delta (e + e') d' n'
EQ -> Delta (e + e') (d + e) (n + n')
GT -> Delta (e + e') (d + e) n
{-# INLINE (<>) #-}
minima :: Delta -> Int
minima (Delta e d _) = e - d
# INLINE minima #
bool :: Bool -> Delta
bool True = Delta 1 1 1
bool False = Delta (-1) 0 1
# INLINE bool #
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
bits :: FiniteBits a => a -> Delta
bits w = Prelude.foldr1 (<>) $ fmap (bool . testBit w) [0..finiteBitSize w - 1]
#else
bits :: Bits a => a -> Delta
bits w = Prelude.foldr1 (<>) $ fmap (bool . testBit w) [0..bitSize w - 1]
#endif
{-# SPECIALIZE bits :: Word64 -> Delta #-}
# SPECIALIZE bits : : Delta #
# SPECIALIZE bits : : > Delta #
e8s, d8s, n8s :: P.Vector Int8
(e8s, d8s, n8s) = case U.fromListN 256 $ fmap go [0..255 :: Word8] of
V_3 _ (V_Int8 es) (V_Int8 ds) (V_Int8 ns) -> (es, ds, ns)
where
go i = case bits i of
Delta e m n -> (fromIntegral e, fromIntegral m, fromIntegral n)
| Look up the ' Delta ' for a Word8 via LUTs
byte :: Word8 -> Delta
byte w = Delta (e8 w) (d8 w) (n8 w)
# INLINE byte #
e8 :: Word8 -> Int
e8 w = fromIntegral $ P.unsafeIndex e8s (fromIntegral w)
# INLINE e8 #
d8 :: Word8 -> Int
d8 w = fromIntegral $ P.unsafeIndex d8s (fromIntegral w)
# INLINE d8 #
n8 :: Word8 -> Int
n8 w = fromIntegral $ P.unsafeIndex n8s (fromIntegral w)
# INLINE n8 #
fwd_e8s : : P.Vector Word8
fwd_e8s = P.fromListN 2048 $ go < $ > [ 0 .. 7 ] < * > [ 0 .. 255 ] where
go d p = either i d i d $ Prelude.foldl step ( Right 8) [ 0 .. 7 ] where
step ( Left i ) _ = Left i
step ( Right r ) i
| r ' = = d = Left i
| otherwise = Right r '
where r ' = fromIntegral $ r + fromEnum ( testBit p ( fromIntegral i ) )
fwd_e8 : : Word8 - > Int - > Int
fwd_e8 w8 i = fromIntegral $ P.unsafeIndex fwd_e8s ( fromIntegral w8 + unsafeShiftL i 8)
fwd_e8s :: P.Vector Word8
fwd_e8s = P.fromListN 2048 $ go <$> [0..7] <*> [0..255] where
go d p = either id id $ Prelude.foldl step (Right 8) [0..7] where
step (Left i) _ = Left i
step (Right r) i
| r' == d = Left i
| otherwise = Right r'
where r' = fromIntegral $ r + fromEnum (testBit p (fromIntegral i))
fwd_e8 :: Word8 -> Int -> Int
fwd_e8 w8 i = fromIntegral $ P.unsafeIndex fwd_e8s (fromIntegral w8 + unsafeShiftL i 8)
-}
| null | https://raw.githubusercontent.com/ekmett/succinct/7e884138c2e943f5ca08f56b58b409d08b870ab9/src/Succinct/Internal/Delta.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : non-portable
---------------------------------------------------------------------------
| Δ-Range-Min
This provides a semigroup-based variant of the basic aggregation used
in < Grossi and Ottaviano's Range-Min tree>,
which is in turn a simplification of a
# UNPACK #
even when # bits is even, odd when it is odd
# UNPACK #
minima = excess - delta
# UNPACK #
# of minima
# INLINE (<>) #
# SPECIALIZE bits :: Word64 -> Delta # | # LANGUAGE CPP #
Copyright : ( C ) 2013 - 15
Maintainer : < >
module Succinct.Internal.Delta
( Delta(..)
, minima
, bool
, bits
, byte
, e8, d8, n8
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.Bits
import Data.Int
import Data.Semigroup
import Data.Vector.Unboxed.Base as UB
import Data.Vector.Unboxed as U
import Data.Vector.Primitive as P
import Data.Word
< Range > tree
data Delta = Delta
} deriving Show
instance Semigroup Delta where
Delta e d n <> Delta e' d' n' = case compare d' (d + e) of
LT -> Delta (e + e') d' n'
EQ -> Delta (e + e') (d + e) (n + n')
GT -> Delta (e + e') (d + e) n
minima :: Delta -> Int
minima (Delta e d _) = e - d
# INLINE minima #
bool :: Bool -> Delta
bool True = Delta 1 1 1
bool False = Delta (-1) 0 1
# INLINE bool #
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
bits :: FiniteBits a => a -> Delta
bits w = Prelude.foldr1 (<>) $ fmap (bool . testBit w) [0..finiteBitSize w - 1]
#else
bits :: Bits a => a -> Delta
bits w = Prelude.foldr1 (<>) $ fmap (bool . testBit w) [0..bitSize w - 1]
#endif
# SPECIALIZE bits : : Delta #
# SPECIALIZE bits : : > Delta #
e8s, d8s, n8s :: P.Vector Int8
(e8s, d8s, n8s) = case U.fromListN 256 $ fmap go [0..255 :: Word8] of
V_3 _ (V_Int8 es) (V_Int8 ds) (V_Int8 ns) -> (es, ds, ns)
where
go i = case bits i of
Delta e m n -> (fromIntegral e, fromIntegral m, fromIntegral n)
| Look up the ' Delta ' for a Word8 via LUTs
byte :: Word8 -> Delta
byte w = Delta (e8 w) (d8 w) (n8 w)
# INLINE byte #
e8 :: Word8 -> Int
e8 w = fromIntegral $ P.unsafeIndex e8s (fromIntegral w)
# INLINE e8 #
d8 :: Word8 -> Int
d8 w = fromIntegral $ P.unsafeIndex d8s (fromIntegral w)
# INLINE d8 #
n8 :: Word8 -> Int
n8 w = fromIntegral $ P.unsafeIndex n8s (fromIntegral w)
# INLINE n8 #
fwd_e8s : : P.Vector Word8
fwd_e8s = P.fromListN 2048 $ go < $ > [ 0 .. 7 ] < * > [ 0 .. 255 ] where
go d p = either i d i d $ Prelude.foldl step ( Right 8) [ 0 .. 7 ] where
step ( Left i ) _ = Left i
step ( Right r ) i
| r ' = = d = Left i
| otherwise = Right r '
where r ' = fromIntegral $ r + fromEnum ( testBit p ( fromIntegral i ) )
fwd_e8 : : Word8 - > Int - > Int
fwd_e8 w8 i = fromIntegral $ P.unsafeIndex fwd_e8s ( fromIntegral w8 + unsafeShiftL i 8)
fwd_e8s :: P.Vector Word8
fwd_e8s = P.fromListN 2048 $ go <$> [0..7] <*> [0..255] where
go d p = either id id $ Prelude.foldl step (Right 8) [0..7] where
step (Left i) _ = Left i
step (Right r) i
| r' == d = Left i
| otherwise = Right r'
where r' = fromIntegral $ r + fromEnum (testBit p (fromIntegral i))
fwd_e8 :: Word8 -> Int -> Int
fwd_e8 w8 i = fromIntegral $ P.unsafeIndex fwd_e8s (fromIntegral w8 + unsafeShiftL i 8)
-}
|
e68300273cb953e0c7ea58921c207baa292b0ee789718d3aa6bb2d9490ef9ce2 | esb-lwb/lwb | sat_test.clj | lwb Logic WorkBench -- Predicate Logic , tests
Copyright ( c ) 2016 - 2020 , THM . All rights reserved .
; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php ) .
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.sat-test
(:require [clojure.test :refer :all]
[lwb.pred.sat :refer :all]
[clojure.spec.test.alpha :as stest]))
(stest/instrument)
(deftest sat-intern-test1
(is (= (#'lwb.pred.sat/sat-intern 'R {'R [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(not R) {'R [:pred 0]} #{:e1 :e2} :one) {'R #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{[:e1]}, 'Q #{[:e1]}, 'S #{[:e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and R Q (not S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(or R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(impl R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(equiv R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(xor R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{[:e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and R (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and (not R) (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{}, 'S #{[:e1]}, :univ #{:e1 :e2}}))
)
(deftest sat-intern-test2
(is (= (#'lwb.pred.sat/sat-intern '(forall [x] (= x (f x))) {'f [:func 1]} #{:e1 :e2} :one) {'f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(exists [x y] (and (not (= x y)) (= x (f x)) (= y (f y)))) {'f [:func 1]} #{:e1 :e2} :all)
'({f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}})))
(is (= (#'lwb.pred.sat/sat-intern '(forall [x] (R x)) {'R [:pred 1]} #{:e1 :e2 :e3} :one)
{'R #{[:e3] [:e1] [:e2]} :univ #{:e1 :e2 :e3}}))
)
(run-tests)
| null | https://raw.githubusercontent.com/esb-lwb/lwb/bba51ada7f7316341733d37b0dc4848c4891ef3a/test/lwb/pred/sat_test.clj | clojure | The use and distribution terms for this software are covered by the
By using this software in any fashion, you are agreeing to be bound by
the terms of this license. | lwb Logic WorkBench -- Predicate Logic , tests
Copyright ( c ) 2016 - 2020 , THM . All rights reserved .
Eclipse Public License 1.0 ( -1.0.php ) .
(ns lwb.pred.sat-test
(:require [clojure.test :refer :all]
[lwb.pred.sat :refer :all]
[clojure.spec.test.alpha :as stest]))
(stest/instrument)
(deftest sat-intern-test1
(is (= (#'lwb.pred.sat/sat-intern 'R {'R [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(not R) {'R [:pred 0]} #{:e1 :e2} :one) {'R #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{[:e1]}, 'Q #{[:e1]}, 'S #{[:e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and R Q (not S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(or R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(impl R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(equiv R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(xor R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{[:e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and R (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(and (not R) (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one)
{'R #{}, 'Q #{}, 'S #{[:e1]}, :univ #{:e1 :e2}}))
)
(deftest sat-intern-test2
(is (= (#'lwb.pred.sat/sat-intern '(forall [x] (= x (f x))) {'f [:func 1]} #{:e1 :e2} :one) {'f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}}))
(is (= (#'lwb.pred.sat/sat-intern '(exists [x y] (and (not (= x y)) (= x (f x)) (= y (f y)))) {'f [:func 1]} #{:e1 :e2} :all)
'({f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}})))
(is (= (#'lwb.pred.sat/sat-intern '(forall [x] (R x)) {'R [:pred 1]} #{:e1 :e2 :e3} :one)
{'R #{[:e3] [:e1] [:e2]} :univ #{:e1 :e2 :e3}}))
)
(run-tests)
|
37aa5adc7f22d9acf0ef6d5be4aa36bb91e8686b93571799f1749e902f638635 | gilith/hol-light | prover9.ml | (* ========================================================================= *)
Interface to prover9 .
(* ========================================================================= *)
* * * NB : this is the " prover9 " command invoked by HOL Light .
* * * * If this does n't work , set an explicit path to the prover9 binary
* * *
**** If this doesn't work, set an explicit path to the prover9 binary
****)
let prover9 = "prover9";;
(* ------------------------------------------------------------------------- *)
Debugging mode ( true = keep the Prover9 input and output files )
(* ------------------------------------------------------------------------- *)
let prover9_debugging = ref false;;
(* ------------------------------------------------------------------------- *)
Prover9 options . Set to " " for the Prover9 default .
(* ------------------------------------------------------------------------- *)
let prover9_options = ref
("clear(auto_inference).\n"^
"clear(auto_denials).\n"^
"clear(auto_limits).\n"^
"set(neg_binary_resolution).\n"^
"set(binary_resolution).\n"^
"set(paramodulation).\n");;
(* ------------------------------------------------------------------------- *)
(* Find the variables, functions, and predicates excluding equality. *)
(* ------------------------------------------------------------------------- *)
let rec functions fvs tm (vacc,facc,racc as acc) =
if is_var tm then
if mem tm fvs then (vacc,insert tm facc,racc)
else (insert tm vacc,facc,racc)
else if is_abs tm then acc else
let f,args = strip_comb tm in
itlist (functions fvs) args (vacc,insert f facc,racc);;
let rec signature fvs tm (vacc,facc,racc as acc) =
if is_neg tm then signature fvs (rand tm) acc
else if is_conj tm || is_disj tm || is_imp tm || is_iff tm then
signature fvs (lhand tm) (signature fvs (rand tm) acc)
else if is_forall tm || is_exists tm || is_uexists tm then
signature fvs (body(rand tm)) acc
else if is_eq tm then
functions fvs (lhand tm) (functions fvs (rand tm) acc)
else if is_abs tm then acc else
let r,args = strip_comb tm in
itlist (functions fvs) args (vacc,facc,insert r racc);;
(* ------------------------------------------------------------------------- *)
Shadow first - order syntax . Literal sign is true = positive .
(* ------------------------------------------------------------------------- *)
type folterm = Variable of string | Function of string * folterm list;;
type literal = Literal of bool * string * folterm list;;
(* ------------------------------------------------------------------------- *)
Translate clause into shadow syntax .
(* ------------------------------------------------------------------------- *)
let rec translate_term (trans_var,trans_fun,trans_rel as trp) tm =
let f,args = strip_comb tm in
if defined trans_fun f then
Function(apply trans_fun f,map (translate_term trp) args)
else if is_var tm then Variable(apply trans_var tm)
else failwith("unknown function"^
(try fst(dest_const tm) with Failure _ -> "??"));;
let translate_atom (trans_var,trans_fun,trans_rel as trp) tm =
if is_eq tm then
Literal(true,"=",[translate_term trp (lhand tm);
translate_term trp (rand tm)])
else
let r,args = strip_comb tm in
Literal(true,apply trans_rel r,map (translate_term trp) args);;
let rec translate_clause trp tm =
if is_disj tm then
translate_clause trp (lhand tm) @ translate_clause trp (rand tm)
else if is_neg tm then
let Literal(s,r,args) = translate_atom trp (rand tm) in
[Literal(not s,r,args)]
else [translate_atom trp tm];;
(* ------------------------------------------------------------------------- *)
(* Create Prover9 input file for a set of clauses. *)
(* ------------------------------------------------------------------------- *)
let rec prover9_of_term tm =
match tm with
Variable(s) -> s
| Function(f,[]) -> f
| Function(f,args) ->
f^"("^
end_itlist (fun s t -> s^","^t) (map prover9_of_term args) ^
")";;
let prover9_of_literal lit =
match lit with
Literal(s,r,[]) -> if s then r else "-"^r
| Literal(s,"=",[l;r]) ->
(if s then "(" else "-(")^
(prover9_of_term l) ^ " = " ^ (prover9_of_term r)^")"
| Literal(s,r,args) ->
(if s then "" else "-")^r^"("^
end_itlist (fun s t -> s^","^t) (map prover9_of_term args) ^
")";;
let rec prover9_of_clause cls =
match cls with
[] -> failwith "prover9_of_clause: empty clause"
| [l] -> prover9_of_literal l
| l::ls -> prover9_of_literal l ^ " | " ^ prover9_of_clause ls;;
(* ------------------------------------------------------------------------- *)
(* Parse S-expressions. *)
(* ------------------------------------------------------------------------- *)
type sexp = Atom of string | List of sexp list;;
let atom inp =
match inp with
Resword "("::rst -> raise Noparse
| Resword ")"::rst -> raise Noparse
| Resword s::rst -> Atom s,rst
| Ident s::rst -> Atom s,rst
| [] -> raise Noparse;;
let rec sexpression inp =
( atom
||| (a (Resword "(") ++ many sexpression ++ a (Resword ")") >>
(fun ((_,l),_) -> List l)))
inp;;
(* ------------------------------------------------------------------------- *)
(* Skip to beginning of proof object. *)
(* ------------------------------------------------------------------------- *)
let rec skipheader i s =
if String.sub s i 28 = ";; BEGINNING OF PROOF OBJECT"
then String.sub s (i + 28) (String.length s - i - 28)
else skipheader (i + 1) s;;
(* ------------------------------------------------------------------------- *)
Parse a proof step .
(* ------------------------------------------------------------------------- *)
let parse_proofstep ps =
match ps with
List[Atom id; just; formula; Atom "NIL"] -> (id,just,formula)
| _ -> failwith "unexpected proofstep";;
(* ------------------------------------------------------------------------- *)
Convert sexp representation of formula to shadow syntax .
(* ------------------------------------------------------------------------- *)
let rec folterm_of_sexp sexp =
match sexp with
Atom(s) when String.sub s 0 1 = "v" -> Variable s
| Atom(s) -> Function(s,[])
| List(Atom f::args) -> Function(f,map folterm_of_sexp args)
| _ -> failwith "folterm_of_sexp: malformed sexpression term representation";;
let folatom_of_sexp sexp =
match sexp with
Atom(r) -> Literal(true,r,[])
| List(Atom r::args) -> Literal(true,r,map folterm_of_sexp args)
| _ -> failwith "folatom_of_sexp: malformed sexpression atom representation";;
let folliteral_of_sexp sexp =
match sexp with
List[Atom "not";sex] -> let Literal(s,r,args) = folatom_of_sexp sex in
Literal(not s,r,args)
| _ -> folatom_of_sexp sexp;;
let rec folclause_of_sexp sexp =
match sexp with
List[Atom "or";sex1;sex2] ->
folclause_of_sexp sex1 @ folclause_of_sexp sex2
| _ -> [folliteral_of_sexp sexp];;
(* ------------------------------------------------------------------------- *)
Convert shadow syntax back into HOL ( sometimes given expected type ) .
(* Make a crude type postcorrection for equations between variables based *)
(* on their types in other terms, if applicable. *)
(* It might be nicer to use preterms to get a systematic use of context, but *)
(* this is a pretty simple problem. *)
(* ------------------------------------------------------------------------- *)
let rec hol_of_folterm (btrans_fun,btrans_rel as trp) ty tm =
match tm with
Variable(x) -> variant (ran btrans_fun) (mk_var(x,ty))
| Function(fs,args) ->
let f = apply btrans_fun fs in
let tys,rty = nsplit dest_fun_ty args (type_of f) in
list_mk_comb(f,map2 (hol_of_folterm trp) tys args);;
let hol_of_folliteral (btrans_fun,btrans_rel as trp) lit =
match lit with
Literal(s,"false",[]) -> if s then mk_const("F",[])
else mk_neg(mk_const("F",[]))
| Literal(s,"=",[l;r]) ->
let tml_prov = hol_of_folterm trp aty l
and tmr_prov = hol_of_folterm trp aty r in
let ty = if type_of tml_prov <> aty then type_of tml_prov
else if type_of tmr_prov <> aty then type_of tmr_prov
else aty in
let ptm = mk_eq(hol_of_folterm trp ty l,hol_of_folterm trp ty r) in
if s then ptm else mk_neg ptm
| Literal(s,rs,args) ->
let r = apply btrans_rel rs in
let tys,rty = nsplit dest_fun_ty args (type_of r) in
let ptm = list_mk_comb(r,map2 (hol_of_folterm trp) tys args) in
if s then ptm else mk_neg ptm;;
let is_truevar (bf,_) tm = is_var tm && not(mem tm (ran bf));;
let rec hol_of_folclause trp cls =
match cls with
[] -> mk_const("F",[])
| [c] -> hol_of_folliteral trp c
| c::cs -> let rawcls = map (hol_of_folliteral trp) cls in
let is_truevar tm = is_var tm &&
not(mem tm (ran(fst trp))) &&
not(mem tm (ran(snd trp))) in
let und,dec = partition
(fun t -> is_eq t && is_truevar(lhs t) && is_truevar(rhs t))
rawcls in
if und = [] || dec = [] then list_mk_disj rawcls else
let cxt = map dest_var (filter is_truevar (freesl dec)) in
let correct t =
try let l,r = dest_eq t in
let ls = fst(dest_var l) and rs = fst(dest_var r) in
let ty = try assoc ls cxt with Failure _ -> assoc rs cxt in
mk_eq(mk_var(ls,ty),mk_var(rs,ty))
with Failure _ -> t in
list_mk_disj(map correct rawcls);;
(* ------------------------------------------------------------------------- *)
Composed map from sexp to HOL items .
(* ------------------------------------------------------------------------- *)
let hol_of_term trp ty sexp = hol_of_folterm trp ty (folterm_of_sexp sexp);;
let hol_of_literal trp sexp = hol_of_folliteral trp (folliteral_of_sexp sexp);;
let hol_of_clause trp sexp = hol_of_folclause trp (folclause_of_sexp sexp);;
(* ------------------------------------------------------------------------- *)
(* Follow paramodulation path *)
(* ------------------------------------------------------------------------- *)
let rec PARA_SUBS_CONV path eth tm =
match path with
[] -> if lhs(concl eth) = tm then eth else failwith "PARA_SUBS_CONV"
| n::rpt -> let f,args = strip_comb tm in
funpow (length args - n) RATOR_CONV (RAND_CONV
(PARA_SUBS_CONV rpt eth)) tm;;
(* ------------------------------------------------------------------------- *)
Pull forward disjunct in clause using prover9 / Ivy director string .
(* ------------------------------------------------------------------------- *)
let FRONT1_DISJ_CONV =
GEN_REWRITE_CONV I [TAUT `a \/ b \/ c <=> b \/ a \/ c`] ORELSEC
GEN_REWRITE_CONV I [TAUT `a \/ b <=> b \/ a`];;
let rec FRONT_DISJ_CONV l tm =
match l with
[] | ((Atom "1")::_) -> REFL tm
| (Atom "2")::t -> (RAND_CONV (FRONT_DISJ_CONV t) THENC
FRONT1_DISJ_CONV) tm
| _ -> failwith "unexpected director string in clause";;
(* ------------------------------------------------------------------------- *)
(* For using paramodulating equation, more convenient to put at the back. *)
(* ------------------------------------------------------------------------- *)
let AP_IMP =
let pp = MATCH_MP(TAUT `(a ==> b) ==> !x. x \/ a ==> x \/ b`) in
fun t -> SPEC t o pp;;
let rec PARA_BACK_CONV eqdir tm =
match eqdir with
[Atom "1"] when not(is_disj tm) -> REFL tm
| [Atom "2"] when not(is_disj tm) -> SYM_CONV tm
| Atom "2"::eqs -> RAND_CONV (PARA_BACK_CONV eqs) tm
| [Atom "1"; Atom f] when is_disj tm ->
let th1 = if f = "2" then LAND_CONV SYM_CONV tm else REFL tm in
let tm' = rand(concl th1) in
let djs = disjuncts tm' in
let th2 = DISJ_ACI_RULE(mk_eq(tm',list_mk_disj(tl djs @ [hd djs]))) in
TRANS th1 th2
| _ -> failwith "PARA_BACK_CONV";;
(* ------------------------------------------------------------------------- *)
(* Do direct resolution on front clauses. *)
(* ------------------------------------------------------------------------- *)
let RESOLVE =
let resrules = map (MATCH_MP o TAUT)
[`a /\ ~a ==> F`;
`~a /\ a ==> F`;
`a /\ (~a \/ b) ==> b`;
`~a /\ (a \/ b) ==> b`;
`(a \/ b) /\ ~a ==> b`;
`(~a \/ b) /\ a ==> b`;
`(a \/ b) /\ (~a \/ c) ==> b \/ c`;
`(~a \/ b) /\ (a \/ c) ==> b \/ c`] in
fun th1 th2 -> let th = CONJ th1 th2 in tryfind (fun f -> f th) resrules;;
(* ------------------------------------------------------------------------- *)
(* AC rearrangement of disjunction but maybe correcting proforma types in *)
(* the target term for equations between variables. *)
(* ------------------------------------------------------------------------- *)
let ACI_CORRECT th tm =
try EQ_MP (DISJ_ACI_RULE(mk_eq(concl th,tm))) th with Failure _ ->
let cxt = map dest_var (frees(concl th)) in
let rec correct t =
if is_disj t then mk_disj(correct(lhand t),correct(rand t))
else if is_neg t then mk_neg(correct(rand t)) else
(try let l,r = dest_eq t in
let ls = fst(dest_var l) and rs = fst(dest_var r) in
let ty = try assoc ls cxt with Failure _ -> assoc rs cxt in
mk_eq(mk_var(ls,ty),mk_var(rs,ty))
with Failure _ -> t) in
let tm' = correct tm in
EQ_MP (DISJ_ACI_RULE(mk_eq(concl th,tm'))) th;;
(* ------------------------------------------------------------------------- *)
(* Process proof step. *)
(* ------------------------------------------------------------------------- *)
let rec PROVER9_PATH_CONV l conv =
match l with
Atom "2"::t -> RAND_CONV(PROVER9_PATH_CONV t conv)
| Atom "1"::t -> LAND_CONV(PROVER9_PATH_CONV t conv)
| [] -> conv
| _ -> failwith "PROVER9_PATH_CONV:unknown path";;
let PROVER9_FLIP_CONV tm =
if is_neg tm then RAND_CONV SYM_CONV tm else SYM_CONV tm;;
let process_proofstep ths trp asms (lab,just,fm) =
let tm = hol_of_clause trp fm in
match just with
List[Atom "input"] ->
if is_eq tm && lhs tm = rhs tm then REFL(rand tm) else
tryfind (fun th -> PART_MATCH I th tm) ths
| List[Atom "flip"; Atom n; List path] ->
let th = apply asms n in
let nth = CONV_RULE(PROVER9_PATH_CONV path PROVER9_FLIP_CONV) th in
if concl nth = tm then nth
else failwith "Inconsistency from flip"
| List[Atom "instantiate"; Atom "0"; List[List[x;Atom".";y]]] ->
let th = REFL(hol_of_term trp aty y) in
if concl th = tm then th
else failwith "Inconsistency from instantiation of reflexivity"
| List[Atom "instantiate"; Atom n; List i] ->
let th = apply asms n
and ilist = map (fun (List[Atom x;Atom"."; y]) -> (y,x)) i in
let xs = map
(fun (y,x) -> find_term (fun v -> is_var v && fst(dest_var v) = x)
(concl th)) ilist in
let ys = map2
(fun (y,x) v -> hol_of_term trp (type_of v) y) ilist xs in
INST (zip ys xs) th
| List[Atom "paramod"; Atom eqid; List eqdir; Atom tmid; List dir] ->
let eth = CONV_RULE (PARA_BACK_CONV eqdir) (apply asms eqid)
and tth = apply asms tmid
and path = (map (fun (Atom s) -> int_of_string s) dir) in
let etm = concl eth in
let th =
if is_disj etm then
let djs = disjuncts etm in
let eq = last djs in
let fth = CONV_RULE (PARA_SUBS_CONV path (ASSUME eq)) tth in
MP (itlist AP_IMP (butlast djs) (DISCH eq fth)) eth
else CONV_RULE(PARA_SUBS_CONV path eth) tth in
if concl th = tm then th
else failwith "Inconsistency from paramodulation"
| List[Atom "resolve"; Atom l1; List path1; Atom l2; List path2] ->
let th1 = CONV_RULE (FRONT_DISJ_CONV path1) (apply asms l1)
and th2 = CONV_RULE (FRONT_DISJ_CONV path2) (apply asms l2) in
let th3 = RESOLVE th1 th2 in
ACI_CORRECT th3 tm
| List[Atom "propositional"; Atom l] ->
let th1 = apply asms l in
ACI_CORRECT th1 tm
| _ -> failwith "process_proofstep: no translation";;
let rec process_proofsteps ths trp asms steps =
match steps with
[] -> asms,[]
| ((lab,_,_) as st)::sts ->
(try let th = process_proofstep ths trp asms st in
process_proofsteps ths trp ((lab |-> th) asms) sts
with _ -> asms,steps);;
(* ------------------------------------------------------------------------- *)
(* Main refutation procedure for clauses *)
(* ------------------------------------------------------------------------- *)
let PROVER9_REFUTE ths =
let fvs = itlist (fun th -> union (freesl(hyp th))) ths [] in
let fovars,functions,relations =
signature fvs (end_itlist (curry mk_conj) (map concl ths)) ([],[],[]) in
let trans_var =
itlist2 (fun f n -> f |-> "x"^string_of_int n)
fovars (1--length fovars) undefined
and trans_fun =
itlist2 (fun f n -> f |-> "f"^string_of_int n)
functions (1--length functions) undefined
and trans_rel =
itlist2 (fun f n -> f |-> "R"^string_of_int n)
relations (1--length relations) undefined in
let cls =
map (translate_clause (trans_var,trans_fun,trans_rel) o concl) ths in
let p9cls = map (fun c -> prover9_of_clause c ^".\n") cls in
let p9str = "clear(bell).\n"^ !prover9_options ^
"formulas(sos).\n"^
itlist (^) p9cls
"end_of_list.\n" in
let filename_in = Filename.temp_file "prover9" ".in"
and filename_out = Filename.temp_file "prover9" ".out" in
let _ = file_of_string filename_in p9str in
let retcode = Sys.command
(prover9 ^ " -f " ^ filename_in ^ " | prooftrans ivy >" ^ filename_out) in
if retcode <> 0 then failwith "Prover9 call apparently failed" else
let p9proof = string_of_file filename_out in
let _ = if !prover9_debugging then ()
else (ignore(Sys.remove filename_in);
ignore(Sys.remove filename_out)) in
let List sexps,unp = sexpression(lex(explode(skipheader 0 p9proof))) in
(if unp <> [Ident ";;"; Ident "END"; Ident "OF";
Ident "PROOF"; Ident "OBJECT"]
then (Format.print_string "Unexpected proof object tail";
Format.print_newline())
else ());
let btrans_fun = itlist (fun (x,y) -> y |-> x) (graph trans_fun) undefined
and btrans_rel = itlist (fun (x,y) -> y |-> x) (graph trans_rel) undefined
and proof = map parse_proofstep sexps in
let asms,undone =
process_proofsteps ths (btrans_fun,btrans_rel) undefined proof in
find (fun th -> concl th = mk_const("F",[])) (map snd (graph asms));;
(* ------------------------------------------------------------------------- *)
(* Hence a prover. *)
(* ------------------------------------------------------------------------- *)
let PROVER9 =
let prule = MATCH_MP(TAUT `(~p ==> F) ==> p`)
and false_tm = `F` and true_tm = `T` in
let init_conv =
TOP_DEPTH_CONV BETA_CONV THENC
PRESIMP_CONV THENC
CONDS_ELIM_CONV THENC
NNFC_CONV THENC CNF_CONV THENC
DEPTH_BINOP_CONV `(/\)` (SKOLEM_CONV THENC PRENEX_CONV) THENC
GEN_REWRITE_CONV REDEPTH_CONV
[RIGHT_AND_EXISTS_THM; LEFT_AND_EXISTS_THM] THENC
GEN_REWRITE_CONV TOP_DEPTH_CONV [GSYM DISJ_ASSOC] THENC
GEN_REWRITE_CONV TOP_DEPTH_CONV [GSYM CONJ_ASSOC] in
fun tm ->
let tm' = mk_neg tm in
let ith = init_conv tm' in
let itm = rand(concl ith) in
if itm = true_tm then failwith "PROVER9: formula is trivially false" else
if itm = false_tm then prule(fst(EQ_IMP_RULE ith)) else
let evs,bod = strip_exists itm in
let ths = map SPEC_ALL (CONJUNCTS(ASSUME bod)) in
let ths' = end_itlist (@) (map (CONJUNCTS o CONV_RULE CNF_CONV) ths) in
let rth = PROVER9_REFUTE ths' in
let eth = itlist SIMPLE_CHOOSE evs rth in
let sth = PROVE_HYP (UNDISCH(fst(EQ_IMP_RULE ith))) eth in
prule(DISCH tm' sth);;
(* ------------------------------------------------------------------------- *)
(* Examples. *)
(* ------------------------------------------------------------------------- *)
let FRIEND_0 = time PROVER9
` ( ! x : P. ~friend(x , x ) ) /\ ~(a :P = b ) /\ ( ! x y. friend(x , y ) = = > friend(y , x ) )
= = > ( ! x. ? ) /\ ~friend(x , z ) ) \/
( ! x. ? z ) /\ ~friend(x , y ) /\ ~friend(x , z ) ) ` ; ;
let FRIEND_1 = time PROVER9
` ( ! x : P. ~friend(x , x ) ) /\ a IN s /\ b IN s /\ ~(a :P = b ) /\
( ! x y. friend(x , y ) = = > friend(y , x ) )
= = > ( ! IN s = = > ? y IN s /\ z IN s /\ friend(x , y ) /\ ~friend(x , z ) ) \/
( ! IN s = = > ? y IN s /\ z IN s /\
~(y = z ) /\ ~friend(x , y ) /\ ~friend(x , z ) ) ` ; ;
let LOS = time PROVER9
` ( ! x y , y ) /\ , z ) = = > P(x , z ) ) /\
( ! x , y ) /\ Q(y , z ) = = > Q(x , z ) ) /\
( ! x y. Q(x , y ) = = > Q(y , x ) ) /\
( ! x y. P(x , y ) \/ Q(x , y ) ) /\
~P(a , b ) /\ ~Q(c , d )
= = > F ` ; ;
let CONWAY_1 = time PROVER9
` ( ! x. 0 + x = x ) /\
( ! x y. x + y = y + x ) /\
( ! x ( y + z ) = ( x + y ) + z ) /\
( ! x. 1 * x = x ) /\ ( ! x. x * 1 = x ) /\
( ! x * ( y * z ) = ( x * y ) * z ) /\
( ! x. 0 * x = 0 ) /\ ( ! x. x * 0 = 0 ) /\
( ! x * ( y + z ) = ( x * y ) + ( x * z ) ) /\
( ! x ( x + y ) * z = ( x * z ) + ( y * z ) ) /\
( ! y ) = 1 + x * star(y * x ) * y ) /\
( ! ) = star(star(x ) * y ) * star(x ) )
= = > star(star(star(1 ) ) ) = star(star(1 ) ) ` ; ;
let CONWAY_2 = time PROVER9
` ( ! x. 0 + x = x ) /\
( ! x y. x + y = y + x ) /\
( ! x ( y + z ) = ( x + y ) + z ) /\
( ! x. 1 * x = x ) /\ ( ! x. x * 1 = x ) /\
( ! x * ( y * z ) = ( x * y ) * z ) /\
( ! x. 0 * x = 0 ) /\ ( ! x. x * 0 = 0 ) /\
( ! x * ( y + z ) = ( x * y ) + ( x * z ) ) /\
( ! x ( x + y ) * z = ( x * z ) + ( y * z ) ) /\
( ! y ) = 1 + x * star(y * x ) * y ) /\
( ! ) = star(star(x ) * y ) * star(x ) )
= = > ! a. star(star(star(star(a ) ) ) ) = star(star(star(a ) ) ) ` ; ;
let ECKMAN_HILTON_1 = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 1 + x = x ) /\
( ! x. x + 1 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a * b = a + b ` ; ;
let = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 1 + x = x ) /\
( ! x. x + 1 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a * b = b * a ` ; ;
let ECKMAN_HILTON_3 = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 0 + x = x ) /\
( ! x. x + 0 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a * b = b * a ` ; ;
let ECKMAN_HILTON_4 = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 0 + x = x ) /\
( ! x. x + 0 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a + b = a * b ` ; ;
let time PROVER9
` ( ! x ( x * y ) * z = ( x * z ) * ( y * z ) ) /\
( ! x y z. z * ( x * y ) = ( z * x ) * ( z * y ) )
= = > ! a b c. ( a * b ) * ( c * a ) = ( a * c ) * ( b * a ) ` ; ;
let MOORE_PENROSE_PSEUDOINVERSE_UNIQUE = time PROVER9
` X * A * X = X /\ transpose(A * X ) = A * X /\
A * X * A = A /\ transpose(X * A ) = X * A /\
Y * A * Y = Y /\ transpose(A * Y ) = A * Y /\
A * Y * A = A /\ transpose(Y * A ) = Y * A /\
( ! x ( x * y ) * z = x * ( y * z ) ) /\
( ! x y. transpose(x * y ) = transpose(y ) * transpose(x ) )
= = > X = Y ` ; ;
let FRIEND_0 = time PROVER9
`(!x:P. ~friend(x,x)) /\ ~(a:P = b) /\ (!x y. friend(x,y) ==> friend(y,x))
==> (!x. ?y z. friend(x,y) /\ ~friend(x,z)) \/
(!x. ?y z. ~(y = z) /\ ~friend(x,y) /\ ~friend(x,z))`;;
let FRIEND_1 = time PROVER9
`(!x:P. ~friend(x,x)) /\ a IN s /\ b IN s /\ ~(a:P = b) /\
(!x y. friend(x,y) ==> friend(y,x))
==> (!x. x IN s ==> ?y z. y IN s /\ z IN s /\ friend(x,y) /\ ~friend(x,z)) \/
(!x. x IN s ==> ?y z. y IN s /\ z IN s /\
~(y = z) /\ ~friend(x,y) /\ ~friend(x,z))`;;
let LOS = time PROVER9
`(!x y z. P(x,y) /\ P(y,z) ==> P(x,z)) /\
(!x y z. Q(x,y) /\ Q(y,z) ==> Q(x,z)) /\
(!x y. Q(x,y) ==> Q(y,x)) /\
(!x y. P(x,y) \/ Q(x,y)) /\
~P(a,b) /\ ~Q(c,d)
==> F`;;
let CONWAY_1 = time PROVER9
`(!x. 0 + x = x) /\
(!x y. x + y = y + x) /\
(!x y z. x + (y + z) = (x + y) + z) /\
(!x. 1 * x = x) /\ (!x. x * 1 = x) /\
(!x y z. x * (y * z) = (x * y) * z) /\
(!x. 0 * x = 0) /\ (!x. x * 0 = 0) /\
(!x y z. x * (y + z) = (x * y) + (x * z)) /\
(!x y z. (x + y) * z = (x * z) + (y * z)) /\
(!x y. star(x * y) = 1 + x * star(y * x) * y) /\
(!x y. star(x + y) = star(star(x) * y) * star(x))
==> star(star(star(1))) = star(star(1))`;;
let CONWAY_2 = time PROVER9
`(!x. 0 + x = x) /\
(!x y. x + y = y + x) /\
(!x y z. x + (y + z) = (x + y) + z) /\
(!x. 1 * x = x) /\ (!x. x * 1 = x) /\
(!x y z. x * (y * z) = (x * y) * z) /\
(!x. 0 * x = 0) /\ (!x. x * 0 = 0) /\
(!x y z. x * (y + z) = (x * y) + (x * z)) /\
(!x y z. (x + y) * z = (x * z) + (y * z)) /\
(!x y. star(x * y) = 1 + x * star(y * x) * y) /\
(!x y. star(x + y) = star(star(x) * y) * star(x))
==> !a. star(star(star(star(a)))) = star(star(star(a)))`;;
let ECKMAN_HILTON_1 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 1 + x = x) /\
(!x. x + 1 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a * b = a + b`;;
let ECKMAN_HILTON_2 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 1 + x = x) /\
(!x. x + 1 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a * b = b * a`;;
let ECKMAN_HILTON_3 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 0 + x = x) /\
(!x. x + 0 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a * b = b * a`;;
let ECKMAN_HILTON_4 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 0 + x = x) /\
(!x. x + 0 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a + b = a * b`;;
let DOUBLE_DISTRIB = time PROVER9
`(!x y z. (x * y) * z = (x * z) * (y * z)) /\
(!x y z. z * (x * y) = (z * x) * (z * y))
==> !a b c. (a * b) * (c * a) = (a * c) * (b * a)`;;
let MOORE_PENROSE_PSEUDOINVERSE_UNIQUE = time PROVER9
`X * A * X = X /\ transpose(A * X) = A * X /\
A * X * A = A /\ transpose(X * A) = X * A /\
Y * A * Y = Y /\ transpose(A * Y) = A * Y /\
A * Y * A = A /\ transpose(Y * A) = Y * A /\
(!x y z. (x * y) * z = x * (y * z)) /\
(!x y. transpose(x * y) = transpose(y) * transpose(x))
==> X = Y`;;
*)
| null | https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/Examples/prover9.ml | ocaml | =========================================================================
=========================================================================
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Find the variables, functions, and predicates excluding equality.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Create Prover9 input file for a set of clauses.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Parse S-expressions.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Skip to beginning of proof object.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Make a crude type postcorrection for equations between variables based
on their types in other terms, if applicable.
It might be nicer to use preterms to get a systematic use of context, but
this is a pretty simple problem.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Follow paramodulation path
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
For using paramodulating equation, more convenient to put at the back.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Do direct resolution on front clauses.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
AC rearrangement of disjunction but maybe correcting proforma types in
the target term for equations between variables.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Process proof step.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Main refutation procedure for clauses
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Hence a prover.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Examples.
------------------------------------------------------------------------- | Interface to prover9 .
* * * NB : this is the " prover9 " command invoked by HOL Light .
* * * * If this does n't work , set an explicit path to the prover9 binary
* * *
**** If this doesn't work, set an explicit path to the prover9 binary
****)
let prover9 = "prover9";;
Debugging mode ( true = keep the Prover9 input and output files )
let prover9_debugging = ref false;;
Prover9 options . Set to " " for the Prover9 default .
let prover9_options = ref
("clear(auto_inference).\n"^
"clear(auto_denials).\n"^
"clear(auto_limits).\n"^
"set(neg_binary_resolution).\n"^
"set(binary_resolution).\n"^
"set(paramodulation).\n");;
let rec functions fvs tm (vacc,facc,racc as acc) =
if is_var tm then
if mem tm fvs then (vacc,insert tm facc,racc)
else (insert tm vacc,facc,racc)
else if is_abs tm then acc else
let f,args = strip_comb tm in
itlist (functions fvs) args (vacc,insert f facc,racc);;
let rec signature fvs tm (vacc,facc,racc as acc) =
if is_neg tm then signature fvs (rand tm) acc
else if is_conj tm || is_disj tm || is_imp tm || is_iff tm then
signature fvs (lhand tm) (signature fvs (rand tm) acc)
else if is_forall tm || is_exists tm || is_uexists tm then
signature fvs (body(rand tm)) acc
else if is_eq tm then
functions fvs (lhand tm) (functions fvs (rand tm) acc)
else if is_abs tm then acc else
let r,args = strip_comb tm in
itlist (functions fvs) args (vacc,facc,insert r racc);;
Shadow first - order syntax . Literal sign is true = positive .
type folterm = Variable of string | Function of string * folterm list;;
type literal = Literal of bool * string * folterm list;;
Translate clause into shadow syntax .
let rec translate_term (trans_var,trans_fun,trans_rel as trp) tm =
let f,args = strip_comb tm in
if defined trans_fun f then
Function(apply trans_fun f,map (translate_term trp) args)
else if is_var tm then Variable(apply trans_var tm)
else failwith("unknown function"^
(try fst(dest_const tm) with Failure _ -> "??"));;
let translate_atom (trans_var,trans_fun,trans_rel as trp) tm =
if is_eq tm then
Literal(true,"=",[translate_term trp (lhand tm);
translate_term trp (rand tm)])
else
let r,args = strip_comb tm in
Literal(true,apply trans_rel r,map (translate_term trp) args);;
let rec translate_clause trp tm =
if is_disj tm then
translate_clause trp (lhand tm) @ translate_clause trp (rand tm)
else if is_neg tm then
let Literal(s,r,args) = translate_atom trp (rand tm) in
[Literal(not s,r,args)]
else [translate_atom trp tm];;
let rec prover9_of_term tm =
match tm with
Variable(s) -> s
| Function(f,[]) -> f
| Function(f,args) ->
f^"("^
end_itlist (fun s t -> s^","^t) (map prover9_of_term args) ^
")";;
let prover9_of_literal lit =
match lit with
Literal(s,r,[]) -> if s then r else "-"^r
| Literal(s,"=",[l;r]) ->
(if s then "(" else "-(")^
(prover9_of_term l) ^ " = " ^ (prover9_of_term r)^")"
| Literal(s,r,args) ->
(if s then "" else "-")^r^"("^
end_itlist (fun s t -> s^","^t) (map prover9_of_term args) ^
")";;
let rec prover9_of_clause cls =
match cls with
[] -> failwith "prover9_of_clause: empty clause"
| [l] -> prover9_of_literal l
| l::ls -> prover9_of_literal l ^ " | " ^ prover9_of_clause ls;;
type sexp = Atom of string | List of sexp list;;
let atom inp =
match inp with
Resword "("::rst -> raise Noparse
| Resword ")"::rst -> raise Noparse
| Resword s::rst -> Atom s,rst
| Ident s::rst -> Atom s,rst
| [] -> raise Noparse;;
let rec sexpression inp =
( atom
||| (a (Resword "(") ++ many sexpression ++ a (Resword ")") >>
(fun ((_,l),_) -> List l)))
inp;;
let rec skipheader i s =
if String.sub s i 28 = ";; BEGINNING OF PROOF OBJECT"
then String.sub s (i + 28) (String.length s - i - 28)
else skipheader (i + 1) s;;
Parse a proof step .
let parse_proofstep ps =
match ps with
List[Atom id; just; formula; Atom "NIL"] -> (id,just,formula)
| _ -> failwith "unexpected proofstep";;
Convert sexp representation of formula to shadow syntax .
let rec folterm_of_sexp sexp =
match sexp with
Atom(s) when String.sub s 0 1 = "v" -> Variable s
| Atom(s) -> Function(s,[])
| List(Atom f::args) -> Function(f,map folterm_of_sexp args)
| _ -> failwith "folterm_of_sexp: malformed sexpression term representation";;
let folatom_of_sexp sexp =
match sexp with
Atom(r) -> Literal(true,r,[])
| List(Atom r::args) -> Literal(true,r,map folterm_of_sexp args)
| _ -> failwith "folatom_of_sexp: malformed sexpression atom representation";;
let folliteral_of_sexp sexp =
match sexp with
List[Atom "not";sex] -> let Literal(s,r,args) = folatom_of_sexp sex in
Literal(not s,r,args)
| _ -> folatom_of_sexp sexp;;
let rec folclause_of_sexp sexp =
match sexp with
List[Atom "or";sex1;sex2] ->
folclause_of_sexp sex1 @ folclause_of_sexp sex2
| _ -> [folliteral_of_sexp sexp];;
Convert shadow syntax back into HOL ( sometimes given expected type ) .
let rec hol_of_folterm (btrans_fun,btrans_rel as trp) ty tm =
match tm with
Variable(x) -> variant (ran btrans_fun) (mk_var(x,ty))
| Function(fs,args) ->
let f = apply btrans_fun fs in
let tys,rty = nsplit dest_fun_ty args (type_of f) in
list_mk_comb(f,map2 (hol_of_folterm trp) tys args);;
let hol_of_folliteral (btrans_fun,btrans_rel as trp) lit =
match lit with
Literal(s,"false",[]) -> if s then mk_const("F",[])
else mk_neg(mk_const("F",[]))
| Literal(s,"=",[l;r]) ->
let tml_prov = hol_of_folterm trp aty l
and tmr_prov = hol_of_folterm trp aty r in
let ty = if type_of tml_prov <> aty then type_of tml_prov
else if type_of tmr_prov <> aty then type_of tmr_prov
else aty in
let ptm = mk_eq(hol_of_folterm trp ty l,hol_of_folterm trp ty r) in
if s then ptm else mk_neg ptm
| Literal(s,rs,args) ->
let r = apply btrans_rel rs in
let tys,rty = nsplit dest_fun_ty args (type_of r) in
let ptm = list_mk_comb(r,map2 (hol_of_folterm trp) tys args) in
if s then ptm else mk_neg ptm;;
let is_truevar (bf,_) tm = is_var tm && not(mem tm (ran bf));;
let rec hol_of_folclause trp cls =
match cls with
[] -> mk_const("F",[])
| [c] -> hol_of_folliteral trp c
| c::cs -> let rawcls = map (hol_of_folliteral trp) cls in
let is_truevar tm = is_var tm &&
not(mem tm (ran(fst trp))) &&
not(mem tm (ran(snd trp))) in
let und,dec = partition
(fun t -> is_eq t && is_truevar(lhs t) && is_truevar(rhs t))
rawcls in
if und = [] || dec = [] then list_mk_disj rawcls else
let cxt = map dest_var (filter is_truevar (freesl dec)) in
let correct t =
try let l,r = dest_eq t in
let ls = fst(dest_var l) and rs = fst(dest_var r) in
let ty = try assoc ls cxt with Failure _ -> assoc rs cxt in
mk_eq(mk_var(ls,ty),mk_var(rs,ty))
with Failure _ -> t in
list_mk_disj(map correct rawcls);;
Composed map from sexp to HOL items .
let hol_of_term trp ty sexp = hol_of_folterm trp ty (folterm_of_sexp sexp);;
let hol_of_literal trp sexp = hol_of_folliteral trp (folliteral_of_sexp sexp);;
let hol_of_clause trp sexp = hol_of_folclause trp (folclause_of_sexp sexp);;
let rec PARA_SUBS_CONV path eth tm =
match path with
[] -> if lhs(concl eth) = tm then eth else failwith "PARA_SUBS_CONV"
| n::rpt -> let f,args = strip_comb tm in
funpow (length args - n) RATOR_CONV (RAND_CONV
(PARA_SUBS_CONV rpt eth)) tm;;
Pull forward disjunct in clause using prover9 / Ivy director string .
let FRONT1_DISJ_CONV =
GEN_REWRITE_CONV I [TAUT `a \/ b \/ c <=> b \/ a \/ c`] ORELSEC
GEN_REWRITE_CONV I [TAUT `a \/ b <=> b \/ a`];;
let rec FRONT_DISJ_CONV l tm =
match l with
[] | ((Atom "1")::_) -> REFL tm
| (Atom "2")::t -> (RAND_CONV (FRONT_DISJ_CONV t) THENC
FRONT1_DISJ_CONV) tm
| _ -> failwith "unexpected director string in clause";;
let AP_IMP =
let pp = MATCH_MP(TAUT `(a ==> b) ==> !x. x \/ a ==> x \/ b`) in
fun t -> SPEC t o pp;;
let rec PARA_BACK_CONV eqdir tm =
match eqdir with
[Atom "1"] when not(is_disj tm) -> REFL tm
| [Atom "2"] when not(is_disj tm) -> SYM_CONV tm
| Atom "2"::eqs -> RAND_CONV (PARA_BACK_CONV eqs) tm
| [Atom "1"; Atom f] when is_disj tm ->
let th1 = if f = "2" then LAND_CONV SYM_CONV tm else REFL tm in
let tm' = rand(concl th1) in
let djs = disjuncts tm' in
let th2 = DISJ_ACI_RULE(mk_eq(tm',list_mk_disj(tl djs @ [hd djs]))) in
TRANS th1 th2
| _ -> failwith "PARA_BACK_CONV";;
let RESOLVE =
let resrules = map (MATCH_MP o TAUT)
[`a /\ ~a ==> F`;
`~a /\ a ==> F`;
`a /\ (~a \/ b) ==> b`;
`~a /\ (a \/ b) ==> b`;
`(a \/ b) /\ ~a ==> b`;
`(~a \/ b) /\ a ==> b`;
`(a \/ b) /\ (~a \/ c) ==> b \/ c`;
`(~a \/ b) /\ (a \/ c) ==> b \/ c`] in
fun th1 th2 -> let th = CONJ th1 th2 in tryfind (fun f -> f th) resrules;;
let ACI_CORRECT th tm =
try EQ_MP (DISJ_ACI_RULE(mk_eq(concl th,tm))) th with Failure _ ->
let cxt = map dest_var (frees(concl th)) in
let rec correct t =
if is_disj t then mk_disj(correct(lhand t),correct(rand t))
else if is_neg t then mk_neg(correct(rand t)) else
(try let l,r = dest_eq t in
let ls = fst(dest_var l) and rs = fst(dest_var r) in
let ty = try assoc ls cxt with Failure _ -> assoc rs cxt in
mk_eq(mk_var(ls,ty),mk_var(rs,ty))
with Failure _ -> t) in
let tm' = correct tm in
EQ_MP (DISJ_ACI_RULE(mk_eq(concl th,tm'))) th;;
let rec PROVER9_PATH_CONV l conv =
match l with
Atom "2"::t -> RAND_CONV(PROVER9_PATH_CONV t conv)
| Atom "1"::t -> LAND_CONV(PROVER9_PATH_CONV t conv)
| [] -> conv
| _ -> failwith "PROVER9_PATH_CONV:unknown path";;
let PROVER9_FLIP_CONV tm =
if is_neg tm then RAND_CONV SYM_CONV tm else SYM_CONV tm;;
let process_proofstep ths trp asms (lab,just,fm) =
let tm = hol_of_clause trp fm in
match just with
List[Atom "input"] ->
if is_eq tm && lhs tm = rhs tm then REFL(rand tm) else
tryfind (fun th -> PART_MATCH I th tm) ths
| List[Atom "flip"; Atom n; List path] ->
let th = apply asms n in
let nth = CONV_RULE(PROVER9_PATH_CONV path PROVER9_FLIP_CONV) th in
if concl nth = tm then nth
else failwith "Inconsistency from flip"
| List[Atom "instantiate"; Atom "0"; List[List[x;Atom".";y]]] ->
let th = REFL(hol_of_term trp aty y) in
if concl th = tm then th
else failwith "Inconsistency from instantiation of reflexivity"
| List[Atom "instantiate"; Atom n; List i] ->
let th = apply asms n
and ilist = map (fun (List[Atom x;Atom"."; y]) -> (y,x)) i in
let xs = map
(fun (y,x) -> find_term (fun v -> is_var v && fst(dest_var v) = x)
(concl th)) ilist in
let ys = map2
(fun (y,x) v -> hol_of_term trp (type_of v) y) ilist xs in
INST (zip ys xs) th
| List[Atom "paramod"; Atom eqid; List eqdir; Atom tmid; List dir] ->
let eth = CONV_RULE (PARA_BACK_CONV eqdir) (apply asms eqid)
and tth = apply asms tmid
and path = (map (fun (Atom s) -> int_of_string s) dir) in
let etm = concl eth in
let th =
if is_disj etm then
let djs = disjuncts etm in
let eq = last djs in
let fth = CONV_RULE (PARA_SUBS_CONV path (ASSUME eq)) tth in
MP (itlist AP_IMP (butlast djs) (DISCH eq fth)) eth
else CONV_RULE(PARA_SUBS_CONV path eth) tth in
if concl th = tm then th
else failwith "Inconsistency from paramodulation"
| List[Atom "resolve"; Atom l1; List path1; Atom l2; List path2] ->
let th1 = CONV_RULE (FRONT_DISJ_CONV path1) (apply asms l1)
and th2 = CONV_RULE (FRONT_DISJ_CONV path2) (apply asms l2) in
let th3 = RESOLVE th1 th2 in
ACI_CORRECT th3 tm
| List[Atom "propositional"; Atom l] ->
let th1 = apply asms l in
ACI_CORRECT th1 tm
| _ -> failwith "process_proofstep: no translation";;
let rec process_proofsteps ths trp asms steps =
match steps with
[] -> asms,[]
| ((lab,_,_) as st)::sts ->
(try let th = process_proofstep ths trp asms st in
process_proofsteps ths trp ((lab |-> th) asms) sts
with _ -> asms,steps);;
let PROVER9_REFUTE ths =
let fvs = itlist (fun th -> union (freesl(hyp th))) ths [] in
let fovars,functions,relations =
signature fvs (end_itlist (curry mk_conj) (map concl ths)) ([],[],[]) in
let trans_var =
itlist2 (fun f n -> f |-> "x"^string_of_int n)
fovars (1--length fovars) undefined
and trans_fun =
itlist2 (fun f n -> f |-> "f"^string_of_int n)
functions (1--length functions) undefined
and trans_rel =
itlist2 (fun f n -> f |-> "R"^string_of_int n)
relations (1--length relations) undefined in
let cls =
map (translate_clause (trans_var,trans_fun,trans_rel) o concl) ths in
let p9cls = map (fun c -> prover9_of_clause c ^".\n") cls in
let p9str = "clear(bell).\n"^ !prover9_options ^
"formulas(sos).\n"^
itlist (^) p9cls
"end_of_list.\n" in
let filename_in = Filename.temp_file "prover9" ".in"
and filename_out = Filename.temp_file "prover9" ".out" in
let _ = file_of_string filename_in p9str in
let retcode = Sys.command
(prover9 ^ " -f " ^ filename_in ^ " | prooftrans ivy >" ^ filename_out) in
if retcode <> 0 then failwith "Prover9 call apparently failed" else
let p9proof = string_of_file filename_out in
let _ = if !prover9_debugging then ()
else (ignore(Sys.remove filename_in);
ignore(Sys.remove filename_out)) in
let List sexps,unp = sexpression(lex(explode(skipheader 0 p9proof))) in
(if unp <> [Ident ";;"; Ident "END"; Ident "OF";
Ident "PROOF"; Ident "OBJECT"]
then (Format.print_string "Unexpected proof object tail";
Format.print_newline())
else ());
let btrans_fun = itlist (fun (x,y) -> y |-> x) (graph trans_fun) undefined
and btrans_rel = itlist (fun (x,y) -> y |-> x) (graph trans_rel) undefined
and proof = map parse_proofstep sexps in
let asms,undone =
process_proofsteps ths (btrans_fun,btrans_rel) undefined proof in
find (fun th -> concl th = mk_const("F",[])) (map snd (graph asms));;
let PROVER9 =
let prule = MATCH_MP(TAUT `(~p ==> F) ==> p`)
and false_tm = `F` and true_tm = `T` in
let init_conv =
TOP_DEPTH_CONV BETA_CONV THENC
PRESIMP_CONV THENC
CONDS_ELIM_CONV THENC
NNFC_CONV THENC CNF_CONV THENC
DEPTH_BINOP_CONV `(/\)` (SKOLEM_CONV THENC PRENEX_CONV) THENC
GEN_REWRITE_CONV REDEPTH_CONV
[RIGHT_AND_EXISTS_THM; LEFT_AND_EXISTS_THM] THENC
GEN_REWRITE_CONV TOP_DEPTH_CONV [GSYM DISJ_ASSOC] THENC
GEN_REWRITE_CONV TOP_DEPTH_CONV [GSYM CONJ_ASSOC] in
fun tm ->
let tm' = mk_neg tm in
let ith = init_conv tm' in
let itm = rand(concl ith) in
if itm = true_tm then failwith "PROVER9: formula is trivially false" else
if itm = false_tm then prule(fst(EQ_IMP_RULE ith)) else
let evs,bod = strip_exists itm in
let ths = map SPEC_ALL (CONJUNCTS(ASSUME bod)) in
let ths' = end_itlist (@) (map (CONJUNCTS o CONV_RULE CNF_CONV) ths) in
let rth = PROVER9_REFUTE ths' in
let eth = itlist SIMPLE_CHOOSE evs rth in
let sth = PROVE_HYP (UNDISCH(fst(EQ_IMP_RULE ith))) eth in
prule(DISCH tm' sth);;
let FRIEND_0 = time PROVER9
` ( ! x : P. ~friend(x , x ) ) /\ ~(a :P = b ) /\ ( ! x y. friend(x , y ) = = > friend(y , x ) )
= = > ( ! x. ? ) /\ ~friend(x , z ) ) \/
( ! x. ? z ) /\ ~friend(x , y ) /\ ~friend(x , z ) ) ` ; ;
let FRIEND_1 = time PROVER9
` ( ! x : P. ~friend(x , x ) ) /\ a IN s /\ b IN s /\ ~(a :P = b ) /\
( ! x y. friend(x , y ) = = > friend(y , x ) )
= = > ( ! IN s = = > ? y IN s /\ z IN s /\ friend(x , y ) /\ ~friend(x , z ) ) \/
( ! IN s = = > ? y IN s /\ z IN s /\
~(y = z ) /\ ~friend(x , y ) /\ ~friend(x , z ) ) ` ; ;
let LOS = time PROVER9
` ( ! x y , y ) /\ , z ) = = > P(x , z ) ) /\
( ! x , y ) /\ Q(y , z ) = = > Q(x , z ) ) /\
( ! x y. Q(x , y ) = = > Q(y , x ) ) /\
( ! x y. P(x , y ) \/ Q(x , y ) ) /\
~P(a , b ) /\ ~Q(c , d )
= = > F ` ; ;
let CONWAY_1 = time PROVER9
` ( ! x. 0 + x = x ) /\
( ! x y. x + y = y + x ) /\
( ! x ( y + z ) = ( x + y ) + z ) /\
( ! x. 1 * x = x ) /\ ( ! x. x * 1 = x ) /\
( ! x * ( y * z ) = ( x * y ) * z ) /\
( ! x. 0 * x = 0 ) /\ ( ! x. x * 0 = 0 ) /\
( ! x * ( y + z ) = ( x * y ) + ( x * z ) ) /\
( ! x ( x + y ) * z = ( x * z ) + ( y * z ) ) /\
( ! y ) = 1 + x * star(y * x ) * y ) /\
( ! ) = star(star(x ) * y ) * star(x ) )
= = > star(star(star(1 ) ) ) = star(star(1 ) ) ` ; ;
let CONWAY_2 = time PROVER9
` ( ! x. 0 + x = x ) /\
( ! x y. x + y = y + x ) /\
( ! x ( y + z ) = ( x + y ) + z ) /\
( ! x. 1 * x = x ) /\ ( ! x. x * 1 = x ) /\
( ! x * ( y * z ) = ( x * y ) * z ) /\
( ! x. 0 * x = 0 ) /\ ( ! x. x * 0 = 0 ) /\
( ! x * ( y + z ) = ( x * y ) + ( x * z ) ) /\
( ! x ( x + y ) * z = ( x * z ) + ( y * z ) ) /\
( ! y ) = 1 + x * star(y * x ) * y ) /\
( ! ) = star(star(x ) * y ) * star(x ) )
= = > ! a. star(star(star(star(a ) ) ) ) = star(star(star(a ) ) ) ` ; ;
let ECKMAN_HILTON_1 = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 1 + x = x ) /\
( ! x. x + 1 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a * b = a + b ` ; ;
let = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 1 + x = x ) /\
( ! x. x + 1 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a * b = b * a ` ; ;
let ECKMAN_HILTON_3 = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 0 + x = x ) /\
( ! x. x + 0 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a * b = b * a ` ; ;
let ECKMAN_HILTON_4 = time PROVER9
` ( ! x. 1 * x = x ) /\
( ! x. x * 1 = x ) /\
( ! x. 0 + x = x ) /\
( ! x. x + 0 = x ) /\
( ! w x ( w * x ) + ( y * z ) = ( w + y ) * ( x + z ) )
= = > ! a b. a + b = a * b ` ; ;
let time PROVER9
` ( ! x ( x * y ) * z = ( x * z ) * ( y * z ) ) /\
( ! x y z. z * ( x * y ) = ( z * x ) * ( z * y ) )
= = > ! a b c. ( a * b ) * ( c * a ) = ( a * c ) * ( b * a ) ` ; ;
let MOORE_PENROSE_PSEUDOINVERSE_UNIQUE = time PROVER9
` X * A * X = X /\ transpose(A * X ) = A * X /\
A * X * A = A /\ transpose(X * A ) = X * A /\
Y * A * Y = Y /\ transpose(A * Y ) = A * Y /\
A * Y * A = A /\ transpose(Y * A ) = Y * A /\
( ! x ( x * y ) * z = x * ( y * z ) ) /\
( ! x y. transpose(x * y ) = transpose(y ) * transpose(x ) )
= = > X = Y ` ; ;
let FRIEND_0 = time PROVER9
`(!x:P. ~friend(x,x)) /\ ~(a:P = b) /\ (!x y. friend(x,y) ==> friend(y,x))
==> (!x. ?y z. friend(x,y) /\ ~friend(x,z)) \/
(!x. ?y z. ~(y = z) /\ ~friend(x,y) /\ ~friend(x,z))`;;
let FRIEND_1 = time PROVER9
`(!x:P. ~friend(x,x)) /\ a IN s /\ b IN s /\ ~(a:P = b) /\
(!x y. friend(x,y) ==> friend(y,x))
==> (!x. x IN s ==> ?y z. y IN s /\ z IN s /\ friend(x,y) /\ ~friend(x,z)) \/
(!x. x IN s ==> ?y z. y IN s /\ z IN s /\
~(y = z) /\ ~friend(x,y) /\ ~friend(x,z))`;;
let LOS = time PROVER9
`(!x y z. P(x,y) /\ P(y,z) ==> P(x,z)) /\
(!x y z. Q(x,y) /\ Q(y,z) ==> Q(x,z)) /\
(!x y. Q(x,y) ==> Q(y,x)) /\
(!x y. P(x,y) \/ Q(x,y)) /\
~P(a,b) /\ ~Q(c,d)
==> F`;;
let CONWAY_1 = time PROVER9
`(!x. 0 + x = x) /\
(!x y. x + y = y + x) /\
(!x y z. x + (y + z) = (x + y) + z) /\
(!x. 1 * x = x) /\ (!x. x * 1 = x) /\
(!x y z. x * (y * z) = (x * y) * z) /\
(!x. 0 * x = 0) /\ (!x. x * 0 = 0) /\
(!x y z. x * (y + z) = (x * y) + (x * z)) /\
(!x y z. (x + y) * z = (x * z) + (y * z)) /\
(!x y. star(x * y) = 1 + x * star(y * x) * y) /\
(!x y. star(x + y) = star(star(x) * y) * star(x))
==> star(star(star(1))) = star(star(1))`;;
let CONWAY_2 = time PROVER9
`(!x. 0 + x = x) /\
(!x y. x + y = y + x) /\
(!x y z. x + (y + z) = (x + y) + z) /\
(!x. 1 * x = x) /\ (!x. x * 1 = x) /\
(!x y z. x * (y * z) = (x * y) * z) /\
(!x. 0 * x = 0) /\ (!x. x * 0 = 0) /\
(!x y z. x * (y + z) = (x * y) + (x * z)) /\
(!x y z. (x + y) * z = (x * z) + (y * z)) /\
(!x y. star(x * y) = 1 + x * star(y * x) * y) /\
(!x y. star(x + y) = star(star(x) * y) * star(x))
==> !a. star(star(star(star(a)))) = star(star(star(a)))`;;
let ECKMAN_HILTON_1 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 1 + x = x) /\
(!x. x + 1 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a * b = a + b`;;
let ECKMAN_HILTON_2 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 1 + x = x) /\
(!x. x + 1 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a * b = b * a`;;
let ECKMAN_HILTON_3 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 0 + x = x) /\
(!x. x + 0 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a * b = b * a`;;
let ECKMAN_HILTON_4 = time PROVER9
`(!x. 1 * x = x) /\
(!x. x * 1 = x) /\
(!x. 0 + x = x) /\
(!x. x + 0 = x) /\
(!w x y z. (w * x) + (y * z) = (w + y) * (x + z))
==> !a b. a + b = a * b`;;
let DOUBLE_DISTRIB = time PROVER9
`(!x y z. (x * y) * z = (x * z) * (y * z)) /\
(!x y z. z * (x * y) = (z * x) * (z * y))
==> !a b c. (a * b) * (c * a) = (a * c) * (b * a)`;;
let MOORE_PENROSE_PSEUDOINVERSE_UNIQUE = time PROVER9
`X * A * X = X /\ transpose(A * X) = A * X /\
A * X * A = A /\ transpose(X * A) = X * A /\
Y * A * Y = Y /\ transpose(A * Y) = A * Y /\
A * Y * A = A /\ transpose(Y * A) = Y * A /\
(!x y z. (x * y) * z = x * (y * z)) /\
(!x y. transpose(x * y) = transpose(y) * transpose(x))
==> X = Y`;;
*)
|
e7b0a6bbd0c1a112fb657497019779754dea2ac174b50767e01485bc4deefdea | cvogt/2020-07-01-haskell-game-demo | Wiring.hs | module Playtime.Wiring where
import Codec.Picture (DynamicImage)
import Data.Aeson
import GHC.Err (error)
import My.IO
import My.Prelude
import Playtime.Debug
import Playtime.EngineConfig
import Playtime.EngineState
import Playtime.Event
import Playtime.GL
import Playtime.Geometry
import Playtime.LiveCode
import Playtime.Texture
wireEngineConfig ::
forall a gs.
(Ord a, Show a, ToJSON gs, FromJSON gs) =>
((a -> Texture) -> EngineState -> gs -> Event -> IO gs) ->
((a -> Texture) -> EngineState -> gs -> [Sprite]) ->
Dim ->
Double ->
Maybe LiveCodeState ->
(a -> IO DynamicImage) ->
[a] ->
gs ->
IO EngineConfig
wireEngineConfig stepGameState visualize ecDim ecScale liveCodeState loadTx allTextures initialGameState = do
recoveredGameState <- for liveCodeState startLiveCode
gameStateMVar <- newMVar $ fromMaybe initialGameState $ join recoveredGameState
texturesMVar <- newMVar mempty
pure $
EngineConfig
{ ecStepGameState = \es event -> do
modifyMVar_ gameStateMVar $ \old_gs -> do
textures <- readTextures texturesMVar
new_gs <- stepGameState textures es old_gs event
for_ liveCodeState $ flip liveCodeSwitch new_gs
pure new_gs,
ecVisualize = \es -> do
textures <- readTextures texturesMVar
visualize textures es <$> readMVar gameStateMVar,
ecDim = ecDim,
ecScale = ecScale,
ecCheckIfContinue = pure . not . gameExitRequested,
ecGameDebugInfo = \EngineState {..} -> debugPrint <$> readMVar gameStateMVar
}
where
readTextures texturesMVar = do
textures' <- readMVar texturesMVar
textures <-
if null textures' then do
textures'' <- loadTextures
void $ swapMVar texturesMVar textures''
pure textures''
else
pure textures'
pure $ \t ->
fromMaybe (error $ "error loading texture " <> show t <> ", did you forget putting it into all_textures?") $
mapLookup t textures
loadTextures = do
lt' <- for allTextures $ \i -> (i,) <$> (either fail pure =<< runExceptT . loadTexture =<< loadTx i)
pure $ foldl (\m (k, v) -> mapInsert k v m) mempty lt'
-- NOTE: resurrect this when implementing dynamically loaded textures
updateTextureCache loadedTexturesMVar visualizations loadTx
updateTextureCache : : a = > MVar ( Map a Texture ) - > [ Sprite ] - > ( a - > IO DynamicImage ) - > IO ( )
-- updateTextureCache loadedTexturesMVar visualizations f' =
modifyMVar do
let f ( acc , loadedTextures ' ) = \(Sprite area t ) - > case t of
-- DynamicSprite ref ->
case mapLookup ref loadedTextures ' of
-- Nothing -> do
texture < - either fail pure = < < ( runExceptT . ) = < < f ' ref
pure ( TexturePlacements texture area : acc , mapInsert ref texture loadedTextures ' )
Just texture - > pure ( TexturePlacements texture area : acc , loadedTextures ' )
s@Rectangle { } - > pure ( s : acc , loadedTextures ' )
swap < $ > foldlM f ( [ ] , loadedTextures ) visualizations
| null | https://raw.githubusercontent.com/cvogt/2020-07-01-haskell-game-demo/f90fcd19ea79802774dcfafe8505415d6f8c8a8b/lib/Playtime/Wiring.hs | haskell | NOTE: resurrect this when implementing dynamically loaded textures
updateTextureCache loadedTexturesMVar visualizations f' =
DynamicSprite ref ->
Nothing -> do | module Playtime.Wiring where
import Codec.Picture (DynamicImage)
import Data.Aeson
import GHC.Err (error)
import My.IO
import My.Prelude
import Playtime.Debug
import Playtime.EngineConfig
import Playtime.EngineState
import Playtime.Event
import Playtime.GL
import Playtime.Geometry
import Playtime.LiveCode
import Playtime.Texture
wireEngineConfig ::
forall a gs.
(Ord a, Show a, ToJSON gs, FromJSON gs) =>
((a -> Texture) -> EngineState -> gs -> Event -> IO gs) ->
((a -> Texture) -> EngineState -> gs -> [Sprite]) ->
Dim ->
Double ->
Maybe LiveCodeState ->
(a -> IO DynamicImage) ->
[a] ->
gs ->
IO EngineConfig
wireEngineConfig stepGameState visualize ecDim ecScale liveCodeState loadTx allTextures initialGameState = do
recoveredGameState <- for liveCodeState startLiveCode
gameStateMVar <- newMVar $ fromMaybe initialGameState $ join recoveredGameState
texturesMVar <- newMVar mempty
pure $
EngineConfig
{ ecStepGameState = \es event -> do
modifyMVar_ gameStateMVar $ \old_gs -> do
textures <- readTextures texturesMVar
new_gs <- stepGameState textures es old_gs event
for_ liveCodeState $ flip liveCodeSwitch new_gs
pure new_gs,
ecVisualize = \es -> do
textures <- readTextures texturesMVar
visualize textures es <$> readMVar gameStateMVar,
ecDim = ecDim,
ecScale = ecScale,
ecCheckIfContinue = pure . not . gameExitRequested,
ecGameDebugInfo = \EngineState {..} -> debugPrint <$> readMVar gameStateMVar
}
where
readTextures texturesMVar = do
textures' <- readMVar texturesMVar
textures <-
if null textures' then do
textures'' <- loadTextures
void $ swapMVar texturesMVar textures''
pure textures''
else
pure textures'
pure $ \t ->
fromMaybe (error $ "error loading texture " <> show t <> ", did you forget putting it into all_textures?") $
mapLookup t textures
loadTextures = do
lt' <- for allTextures $ \i -> (i,) <$> (either fail pure =<< runExceptT . loadTexture =<< loadTx i)
pure $ foldl (\m (k, v) -> mapInsert k v m) mempty lt'
updateTextureCache loadedTexturesMVar visualizations loadTx
updateTextureCache : : a = > MVar ( Map a Texture ) - > [ Sprite ] - > ( a - > IO DynamicImage ) - > IO ( )
modifyMVar do
let f ( acc , loadedTextures ' ) = \(Sprite area t ) - > case t of
case mapLookup ref loadedTextures ' of
texture < - either fail pure = < < ( runExceptT . ) = < < f ' ref
pure ( TexturePlacements texture area : acc , mapInsert ref texture loadedTextures ' )
Just texture - > pure ( TexturePlacements texture area : acc , loadedTextures ' )
s@Rectangle { } - > pure ( s : acc , loadedTextures ' )
swap < $ > foldlM f ( [ ] , loadedTextures ) visualizations
|
6abb739dbbced9bb570ef2728747309a40ab2aab84a4e76acdd573c416ed95b9 | malcolmreynolds/GSLL | types.lisp | ;; Interpolation types
, Sun Nov 4 2007 - 17:41
Time - stamp : < 2009 - 02 - 16 09:46:04EST types.lisp >
$ Id$
(in-package :gsl)
(defmpar +linear-interpolation+ "gsl_interp_linear"
"Linear interpolation. This interpolation method does not require any
additional memory.")
(defmpar +polynomial-interpolation+ "gsl_interp_polynomial"
"Polynomial interpolation. This method should only be used for
interpolating small numbers of points because polynomial interpolation
introduces large oscillations, even for well-behaved datasets. The
number of terms in the interpolating polynomial is equal to the number
of points.")
(defmpar +cubic-spline-interpolation+ "gsl_interp_cspline"
"Cubic spline with natural boundary conditions. The resulting curve is
piecewise cubic on each interval, with matching first and second
derivatives at the supplied data-points. The second derivative is
chosen to be zero at the first point and last point.")
(defmpar +periodic-cubic-spline-interpolation+ "gsl_interp_cspline_periodic"
"Cubic spline with periodic boundary conditions. The resulting curve
is piecewise cubic on each interval, with matching first and second
derivatives at the supplied data-points. The derivatives at the first
and last points are also matched. Note that the last point in the
data must have the same y-value as the first point, otherwise the
resulting periodic interpolation will have a discontinuity at the
boundary.")
(defmpar +akima-interpolation+ "gsl_interp_akima"
"Non-rounded Akima spline with natural boundary conditions. This method
uses the non-rounded corner algorithm of Wodicka.")
(defmpar +periodic-akima-interpolation+ "gsl_interp_akima_periodic"
"Non-rounded Akima spline with periodic boundary conditions. This method
uses the non-rounded corner algorithm of Wodicka.")
(defmfun name ((interpolation interpolation))
"gsl_interp_name"
((interpolation :pointer))
:definition :method
:c-return :string
"The name of the interpolation type.")
(export 'minimum-size)
(defgeneric minimum-size (object)
"The minimum number of points required by the
interpolation. For example, Akima spline interpolation
requires a minimum of 5 points."))
(defmfun minimum-size ((object interpolation))
"gsl_interp_min_size"
((object :pointer))
:definition :method
:c-return :uint)
(defmfun name ((object spline))
"gsl_spline_name"
((object :pointer))
:definition :method
:c-return :string
"The name of the interpolation type.")
(defmfun minimum-size ((object spline))
"gsl_spline_min_size"
((object :pointer))
:definition :method
:c-return :uint)
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/interpolation/types.lisp | lisp | Interpolation types | , Sun Nov 4 2007 - 17:41
Time - stamp : < 2009 - 02 - 16 09:46:04EST types.lisp >
$ Id$
(in-package :gsl)
(defmpar +linear-interpolation+ "gsl_interp_linear"
"Linear interpolation. This interpolation method does not require any
additional memory.")
(defmpar +polynomial-interpolation+ "gsl_interp_polynomial"
"Polynomial interpolation. This method should only be used for
interpolating small numbers of points because polynomial interpolation
introduces large oscillations, even for well-behaved datasets. The
number of terms in the interpolating polynomial is equal to the number
of points.")
(defmpar +cubic-spline-interpolation+ "gsl_interp_cspline"
"Cubic spline with natural boundary conditions. The resulting curve is
piecewise cubic on each interval, with matching first and second
derivatives at the supplied data-points. The second derivative is
chosen to be zero at the first point and last point.")
(defmpar +periodic-cubic-spline-interpolation+ "gsl_interp_cspline_periodic"
"Cubic spline with periodic boundary conditions. The resulting curve
is piecewise cubic on each interval, with matching first and second
derivatives at the supplied data-points. The derivatives at the first
and last points are also matched. Note that the last point in the
data must have the same y-value as the first point, otherwise the
resulting periodic interpolation will have a discontinuity at the
boundary.")
(defmpar +akima-interpolation+ "gsl_interp_akima"
"Non-rounded Akima spline with natural boundary conditions. This method
uses the non-rounded corner algorithm of Wodicka.")
(defmpar +periodic-akima-interpolation+ "gsl_interp_akima_periodic"
"Non-rounded Akima spline with periodic boundary conditions. This method
uses the non-rounded corner algorithm of Wodicka.")
(defmfun name ((interpolation interpolation))
"gsl_interp_name"
((interpolation :pointer))
:definition :method
:c-return :string
"The name of the interpolation type.")
(export 'minimum-size)
(defgeneric minimum-size (object)
"The minimum number of points required by the
interpolation. For example, Akima spline interpolation
requires a minimum of 5 points."))
(defmfun minimum-size ((object interpolation))
"gsl_interp_min_size"
((object :pointer))
:definition :method
:c-return :uint)
(defmfun name ((object spline))
"gsl_spline_name"
((object :pointer))
:definition :method
:c-return :string
"The name of the interpolation type.")
(defmfun minimum-size ((object spline))
"gsl_spline_min_size"
((object :pointer))
:definition :method
:c-return :uint)
|
cbd055d8166b4ad9bf4d4fe78a9c14abc250f498d80eeba35994417191b3403d | herd/herdtools7 | ASLBase.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2015 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(* Authors: *)
, University College London , UK .
(****************************************************************************)
module A64B = AArch64Base
module AST = Asllib.AST
(*****************************************************************************)
(* *)
ASL preambule
(* *)
(*****************************************************************************)
type scope = AST.identifier * int
let pp_scope (enclosure, call_nb) = Printf.sprintf "%s.%d" enclosure call_nb
let arch_reg_to_int =
let rec index_of elt pos li =
match li with
| [] -> raise Not_found
| h :: _ when compare elt h == 0 -> pos
| _ :: t -> index_of elt (pos + 1) t
in
fun r -> index_of r 1 AArch64Base.gprs
(*****************************************************************************)
(* *)
Implem of archBase
(* *)
(*****************************************************************************)
(* Who am I ? *)
let arch = Archs.asl
let base_type = A64B.base_type
let endian = A64B.endian
(***********************************************)
(* Basic arch types and their basic operations *)
(***********************************************)
type reg = ASLLocalId of scope * AST.identifier | ArchReg of A64B.reg
let is_local = function ASLLocalId _ -> true | _ -> false
let to_arch_reg = function ASLLocalId _ -> assert false | ArchReg r -> r
let to_reg r = ArchReg r
let main_scope = ("main", 0)
let default_scope = main_scope
let scope_equal (s1, nb1) (s2, nb2) = String.equal s1 s2 && nb1 = nb2
let parse_local_id =
let ( let* ) = Option.bind in
let ( and* ) o1 o2 =
match (o1, o2) with Some x1, Some x2 -> Some (x1, x2) | _ -> None
in
let find_opt n s =
try Some (Str.matched_group n s) with Not_found -> None
in
let regexp =
Str.regexp {|\([A-Za-z0-9_-]+\)\.\([0-9]+\)\.\([A-Za-z0-9_-]+\)|}
in
fun s ->
if Str.string_match regexp s 0 then
let* x1 = find_opt 1 s and* x2 = find_opt 2 s and* x3 = find_opt 3 s in
Some (ASLLocalId ((x1, int_of_string x2), x3))
else Some (ASLLocalId (default_scope, s))
let parse_reg s =
match (A64B.parse_reg s, s) with
| Some r, _ -> Some (ArchReg r)
| None, "NZCV" -> Some (ArchReg AArch64Base.NZCV)
| None, _ -> parse_local_id s
(** A list of supported AArch64 registers. *)
let arch_regs = AArch64Base.NZCV :: List.map fst AArch64Base.xregs
let pp_reg = function
| ASLLocalId (scope, x) -> pp_scope scope ^ "." ^ x
| ArchReg r -> A64B.pp_reg r
let reg_compare r1 r2 =
match (r1, r2) with
| ArchReg r1, ArchReg r2 -> A64B.reg_compare r1 r2
| ASLLocalId ((c1, n1), x1), ASLLocalId ((c2, n2), x2) ->
if String.equal x1 x2 then
if String.equal c1 c2 then Int.compare n1 n2 else String.compare c1 c2
else String.compare x1 x2
| ArchReg _, ASLLocalId _ -> 1
| ASLLocalId _, ArchReg _ -> -1
let symb_reg_name = function
| ASLLocalId _ -> None
| ArchReg r -> A64B.symb_reg_name r
let symb_reg x = ArchReg (A64B.symb_reg x)
let type_reg _ = assert false
type barrier = A64B.barrier
let pp_barrier = A64B.pp_barrier
let barrier_compare = A64B.barrier_compare
type parsedInstruction = AST.t
type instruction = AST.t
let pp_instruction _ppmode ast = Asllib.PP.t_to_string ast
let dump_instruction a = pp_instruction PPMode.Ascii a
let dump_instruction_hash = Asllib.Serialize.t_to_string
let allowed_for_symb = List.map to_reg A64B.allowed_for_symb
let fold_regs _ ab _ = ab
let map_regs _ _ i = i
let fold_addrs _ a _ = a
let map_addrs _ i = i
let norm_ins i = i
let get_next _ = assert false
include Pseudo.Make (struct
type ins = instruction
type pins = parsedInstruction
type reg_arg = reg
let parsed_tr ast = ast
let get_naccesses _ = -1
let fold_labels k _f _i = k
let map_labels _f i = i
end)
let get_macro _ = assert false
let hash_pteval _ = assert false
(*****************************************************************************)
(* *)
(* ASL Utils *)
(* *)
(*****************************************************************************)
let memoize f =
let table = Hashtbl.create 17 in
fun s ->
match Hashtbl.find_opt table s with
| Some r -> r
| None ->
let r = f s in
let () = Hashtbl.add table s r in
r
let do_build_ast_from_file fname chan =
let lexbuf = Lexing.from_channel chan in
let () =
lexbuf.Lexing.lex_curr_p <-
{ lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = fname }
in
try Asllib.Parser.ast Asllib.Lexer.token lexbuf with
| Asllib.Parser.Error ->
Warn.fatal "%s: Cannot parse." (Pos.str_pos lexbuf.Lexing.lex_curr_p)
| Asllib.Lexer.LexerError ->
Warn.fatal "%s: unknown token." (Pos.str_pos lexbuf.Lexing.lex_curr_p)
let build_ast_from_file =
let protected_f s = Misc.input_protect (do_build_ast_from_file s) s in
memoize protected_f
let asl_generic_parser lexer lexbuf =
let ast =
try Asllib.Parser.ast lexer lexbuf with
| Asllib.Parser.Error -> raise Parsing.Parse_error
| Asllib.Lexer.LexerError ->
LexMisc.error "Unknown token in ASL program" lexbuf
in
([ (0, None, MiscParser.Main) ], [ [ Instruction ast ] ], MiscParser.NoExtra)
module Instr = Instr.No (struct
type instr = instruction
end)
| null | https://raw.githubusercontent.com/herd/herdtools7/daedd7431cb00884afea2ec39749222e2c367c6b/lib/ASLBase.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
Authors:
**************************************************************************
***************************************************************************
***************************************************************************
***************************************************************************
***************************************************************************
Who am I ?
*********************************************
Basic arch types and their basic operations
*********************************************
* A list of supported AArch64 registers.
***************************************************************************
ASL Utils
*************************************************************************** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2015 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
, University College London , UK .
module A64B = AArch64Base
module AST = Asllib.AST
ASL preambule
type scope = AST.identifier * int
let pp_scope (enclosure, call_nb) = Printf.sprintf "%s.%d" enclosure call_nb
let arch_reg_to_int =
let rec index_of elt pos li =
match li with
| [] -> raise Not_found
| h :: _ when compare elt h == 0 -> pos
| _ :: t -> index_of elt (pos + 1) t
in
fun r -> index_of r 1 AArch64Base.gprs
Implem of archBase
let arch = Archs.asl
let base_type = A64B.base_type
let endian = A64B.endian
type reg = ASLLocalId of scope * AST.identifier | ArchReg of A64B.reg
let is_local = function ASLLocalId _ -> true | _ -> false
let to_arch_reg = function ASLLocalId _ -> assert false | ArchReg r -> r
let to_reg r = ArchReg r
let main_scope = ("main", 0)
let default_scope = main_scope
let scope_equal (s1, nb1) (s2, nb2) = String.equal s1 s2 && nb1 = nb2
let parse_local_id =
let ( let* ) = Option.bind in
let ( and* ) o1 o2 =
match (o1, o2) with Some x1, Some x2 -> Some (x1, x2) | _ -> None
in
let find_opt n s =
try Some (Str.matched_group n s) with Not_found -> None
in
let regexp =
Str.regexp {|\([A-Za-z0-9_-]+\)\.\([0-9]+\)\.\([A-Za-z0-9_-]+\)|}
in
fun s ->
if Str.string_match regexp s 0 then
let* x1 = find_opt 1 s and* x2 = find_opt 2 s and* x3 = find_opt 3 s in
Some (ASLLocalId ((x1, int_of_string x2), x3))
else Some (ASLLocalId (default_scope, s))
let parse_reg s =
match (A64B.parse_reg s, s) with
| Some r, _ -> Some (ArchReg r)
| None, "NZCV" -> Some (ArchReg AArch64Base.NZCV)
| None, _ -> parse_local_id s
let arch_regs = AArch64Base.NZCV :: List.map fst AArch64Base.xregs
let pp_reg = function
| ASLLocalId (scope, x) -> pp_scope scope ^ "." ^ x
| ArchReg r -> A64B.pp_reg r
let reg_compare r1 r2 =
match (r1, r2) with
| ArchReg r1, ArchReg r2 -> A64B.reg_compare r1 r2
| ASLLocalId ((c1, n1), x1), ASLLocalId ((c2, n2), x2) ->
if String.equal x1 x2 then
if String.equal c1 c2 then Int.compare n1 n2 else String.compare c1 c2
else String.compare x1 x2
| ArchReg _, ASLLocalId _ -> 1
| ASLLocalId _, ArchReg _ -> -1
let symb_reg_name = function
| ASLLocalId _ -> None
| ArchReg r -> A64B.symb_reg_name r
let symb_reg x = ArchReg (A64B.symb_reg x)
let type_reg _ = assert false
type barrier = A64B.barrier
let pp_barrier = A64B.pp_barrier
let barrier_compare = A64B.barrier_compare
type parsedInstruction = AST.t
type instruction = AST.t
let pp_instruction _ppmode ast = Asllib.PP.t_to_string ast
let dump_instruction a = pp_instruction PPMode.Ascii a
let dump_instruction_hash = Asllib.Serialize.t_to_string
let allowed_for_symb = List.map to_reg A64B.allowed_for_symb
let fold_regs _ ab _ = ab
let map_regs _ _ i = i
let fold_addrs _ a _ = a
let map_addrs _ i = i
let norm_ins i = i
let get_next _ = assert false
include Pseudo.Make (struct
type ins = instruction
type pins = parsedInstruction
type reg_arg = reg
let parsed_tr ast = ast
let get_naccesses _ = -1
let fold_labels k _f _i = k
let map_labels _f i = i
end)
let get_macro _ = assert false
let hash_pteval _ = assert false
let memoize f =
let table = Hashtbl.create 17 in
fun s ->
match Hashtbl.find_opt table s with
| Some r -> r
| None ->
let r = f s in
let () = Hashtbl.add table s r in
r
let do_build_ast_from_file fname chan =
let lexbuf = Lexing.from_channel chan in
let () =
lexbuf.Lexing.lex_curr_p <-
{ lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = fname }
in
try Asllib.Parser.ast Asllib.Lexer.token lexbuf with
| Asllib.Parser.Error ->
Warn.fatal "%s: Cannot parse." (Pos.str_pos lexbuf.Lexing.lex_curr_p)
| Asllib.Lexer.LexerError ->
Warn.fatal "%s: unknown token." (Pos.str_pos lexbuf.Lexing.lex_curr_p)
let build_ast_from_file =
let protected_f s = Misc.input_protect (do_build_ast_from_file s) s in
memoize protected_f
let asl_generic_parser lexer lexbuf =
let ast =
try Asllib.Parser.ast lexer lexbuf with
| Asllib.Parser.Error -> raise Parsing.Parse_error
| Asllib.Lexer.LexerError ->
LexMisc.error "Unknown token in ASL program" lexbuf
in
([ (0, None, MiscParser.Main) ], [ [ Instruction ast ] ], MiscParser.NoExtra)
module Instr = Instr.No (struct
type instr = instruction
end)
|
97793827ff229c90db00f403c41c7e9096410530c6d7d779870f5c0604a64d3e | incoherentsoftware/defect-process | Data.hs | module Enemy.All.Axe.Data
( AxeEnemyData(..)
, mkAxeEnemyData
, rollWillUseAttackLunge
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import System.Random (randomRIO)
import Configs
import Configs.All.Enemy
import Configs.All.Enemy.Axe
import Enemy.All.Axe.AttackDescriptions
import Enemy.All.Axe.Behavior
import Enemy.All.Axe.Sprites
import FileCache
import Util
import Window.Graphics
data AxeEnemyData = AxeEnemyData
{ _attackCooldown :: Secs
, _sprites :: EnemySprites
, _attackDescs :: EnemyAttackDescriptions
, _behavior :: AxeEnemyBehavior
, _prevBehavior :: AxeEnemyBehavior
, _willUseAttackLunge :: Bool
, _config :: EnemyConfig
}
mkAxeEnemyData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m AxeEnemyData
mkAxeEnemyData = do
sprs <- mkEnemySprites
attackDescs <- mkEnemyAttackDescs
cfg <- _enemy <$> readConfigs
willUseAttackLunge <- rollWillUseAttackLunge cfg
return $ AxeEnemyData
{ _attackCooldown = _initialAttackCooldown $ _axe cfg
, _sprites = sprs
, _attackDescs = attackDescs
, _behavior = SpawnBehavior
, _prevBehavior = SpawnBehavior
, _willUseAttackLunge = willUseAttackLunge
, _config = cfg
}
rollWillUseAttackLunge :: MonadIO m => EnemyConfig -> m Bool
rollWillUseAttackLunge cfg = do
roll <- liftIO $ randomRIO (0.0, 1.0)
return $ roll <= _willUseLungeChance (_axe cfg)
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Enemy/All/Axe/Data.hs | haskell | module Enemy.All.Axe.Data
( AxeEnemyData(..)
, mkAxeEnemyData
, rollWillUseAttackLunge
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import System.Random (randomRIO)
import Configs
import Configs.All.Enemy
import Configs.All.Enemy.Axe
import Enemy.All.Axe.AttackDescriptions
import Enemy.All.Axe.Behavior
import Enemy.All.Axe.Sprites
import FileCache
import Util
import Window.Graphics
data AxeEnemyData = AxeEnemyData
{ _attackCooldown :: Secs
, _sprites :: EnemySprites
, _attackDescs :: EnemyAttackDescriptions
, _behavior :: AxeEnemyBehavior
, _prevBehavior :: AxeEnemyBehavior
, _willUseAttackLunge :: Bool
, _config :: EnemyConfig
}
mkAxeEnemyData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m AxeEnemyData
mkAxeEnemyData = do
sprs <- mkEnemySprites
attackDescs <- mkEnemyAttackDescs
cfg <- _enemy <$> readConfigs
willUseAttackLunge <- rollWillUseAttackLunge cfg
return $ AxeEnemyData
{ _attackCooldown = _initialAttackCooldown $ _axe cfg
, _sprites = sprs
, _attackDescs = attackDescs
, _behavior = SpawnBehavior
, _prevBehavior = SpawnBehavior
, _willUseAttackLunge = willUseAttackLunge
, _config = cfg
}
rollWillUseAttackLunge :: MonadIO m => EnemyConfig -> m Bool
rollWillUseAttackLunge cfg = do
roll <- liftIO $ randomRIO (0.0, 1.0)
return $ roll <= _willUseLungeChance (_axe cfg)
| |
3103b81138be9ab0244d7320a69a3a30b71bcb0ef5ade44fdb3b138ff8f75a48 | dfinity-side-projects/dhc | Parse.hs | # LANGUAGE CPP #
{-# LANGUAGE MultiWayIf #-}
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
module Hero.Parse (parseWasm, Wasm(..), ripWasm, elTable) where
#ifdef __HASTE__
import qualified Data.Map.Strict as IM
import qualified Data.Set as IS
#else
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
#endif
import Control.Arrow
import Control.Monad
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Data.Char
import Data.Int
import Data.Maybe
import Data.Word
import WasmOp
#ifdef __HASTE__
type IntMap = IM.Map Int
#endif
data ExternalKind = Function | Table | Memory | Global
type FuncType = ([WasmType], [WasmType])
data Wasm = Wasm
{ types :: [FuncType]
, imports :: [((String, String), FuncType)]
, decls :: [FuncType]
, tableSize :: Int
, memory :: [(Int, Maybe Int)]
, globalSection :: [((WasmType, Bool), [WasmOp])]
, exports :: [(String, Int)]
, start :: Maybe Int
, elemSection :: [(Int, [Int])]
, functions :: IntMap WasmFun
, dataSection :: [([WasmOp], [Word8])]
, dfnExports :: [(String, [WasmType])]
, martinTypes :: [[WasmType]]
, martinTypeMap :: [(Int, Int)]
, permaGlobals :: [(Int, WasmType)]
, persist :: [(Int, WasmType)]
, haskell :: String
} deriving Show
emptyWasm :: Wasm
emptyWasm = Wasm [] [] [] 0 [] [] [] Nothing [] IM.empty [] [] [] [] [] [] ""
data ByteParser a = ByteParser (ByteString -> Either String (a, ByteString))
instance Functor ByteParser where fmap = liftM
instance Applicative ByteParser where {pure = return; (<*>) = ap}
instance Monad ByteParser where
ByteParser f >>= g = ByteParser $ (good =<<) . f
where good (r, t) = let ByteParser gg = g r in gg t
return a = ByteParser $ \s -> Right (a, s)
next :: ByteParser Word8
next = ByteParser f where
f s | B.null s = Left "unexpected EOF"
| otherwise = Right (B.head s, B.tail s)
repNext :: Int -> ByteParser ByteString
repNext n = ByteParser f where
f s | B.length s < n = Left "missing bytes or size too large"
| otherwise = Right $ B.splitAt n s
isEof :: ByteParser Bool
isEof = ByteParser f where f s = Right (B.null s, s)
bad :: String -> ByteParser a
bad = ByteParser . const . Left
byteParse :: ByteParser a -> ByteString -> Either String a
byteParse (ByteParser f) s = f s >>= (\(w, t) ->
if B.null t then Right w else Left "expected EOF")
remainder :: ByteParser ByteString
remainder = ByteParser $ \s -> Right (s, "")
wasm :: ByteParser Wasm
wasm = do
let
rep getInt task = getInt >>= (`replicateM` task)
varuint = fromIntegral <$> f 1 0 where
f :: Integer -> Integer -> ByteParser Integer
f m acc = do
d <- fromIntegral <$> next
if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $ d*m + acc
varint = f 1 0 where
f :: Integer -> Integer -> ByteParser Integer
f m acc = do
d <- fromIntegral <$> next
if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $
if d >= 64 then d*m + acc - 128*m else d*m + acc
varuint1 = varuint
varuint7 = next
varuint32 = varuint
varint7 :: ByteParser Int
varint7 = do
c <- fromIntegral <$> next
when (c >= 128) $ error "bad varint7"
pure $ if c >= 64 then c - 128 else c
varint32 :: ByteParser Int32
varint32 = fromIntegral <$> varint
varint64 :: ByteParser Int64
varint64 = fromIntegral <$> varint
lstr :: ByteParser String
lstr = rep varuint32 $ chr . fromIntegral <$> next
allType = do
t <- varuint7
case lookup t [(0x7f, I32), (0x7e, I64), (0x7d, F32), (0x7c, F64), (0x70, AnyFunc), (0x60, Func), (0x40, Nada)] of
Just ty -> pure ty
Nothing -> bad $ "bad type: " ++ show t
valueType = do
t <- allType
when (t `notElem` [I32, I64, F32, F64]) $ bad "bad value_type"
pure t
blockType = do
t <- allType
when (t `notElem` [I32, I64, F32, F64, Nada]) $ bad "bad value_type"
pure t
elemType = do
t <- allType
when (t /= AnyFunc) $ bad "bad elem_type"
externalKind = do
k <- varuint7
pure $ case k of
0 -> Function
1 -> Table
2 -> Memory
3 -> Global
_ -> error "bad external_kind"
funcType = do
form <- varint7
when (form /= -32) $ bad "expected func type"
paramTypes <- rep varuint32 valueType
returnTypes <- rep varuint1 valueType
pure (paramTypes, returnTypes)
functionCount w = length (imports w) + length (decls w)
sectType w = do
t <- rep varuint32 funcType
pure w { types = t }
sectImport w = do
ms <- rep varuint32 $ do
moduleStr <- lstr
fieldStr <- lstr
k <- externalKind
case k of
Function -> do
t <- varuint32
when (t > length (types w)) $ bad "type out of range"
pure ((moduleStr, fieldStr), types w !! t)
_ -> error "TODO"
pure w { imports = ms }
sectExport w = do
es <- rep varuint32 $ do
fieldStr <- lstr
k <- externalKind
t <- varuint32
case k of
Function -> do
when (t > functionCount w) $ bad "function index out of range"
pure $ Just (fieldStr, t)
Global -> pure Nothing
Memory -> pure Nothing
Table -> pure Nothing
pure w { exports = catMaybes es }
sectFunction w = do
sigs <- rep varuint32 $ do
t <- varuint32
when (t > length (types w)) $ bad "type out of range"
pure $ types w !! t
pure w { decls = sigs }
sectTable w = do
n <- varuint32
when (n > 1) $ bad "MVP allows at most one table"
if n == 0 then pure w else do
elemType
flags <- varuint1
m <- varuint32
when (flags == 1) $ void varuint32 -- TODO: Record maximum.
pure w { tableSize = m }
sectMemory w = do
n <- varuint32
when (n > 1) $ bad "MVP allows at most one memory"
if n == 0 then pure w else do
flags <- varuint1
initial <- varuint32
if flags > 0 then do
m <- varuint32
pure w { memory = [(initial, Just m)] }
else pure w { memory = [(initial, Nothing)] }
globalType = do
ty <- valueType
muta <- varuint1
pure (ty, muta > 0)
sectGlobal w = do
gs <- rep varuint32 $ do
gt <- globalType
x <- codeBlock w
pure (gt, x)
pure w { globalSection = gs }
sectStart w = do
i <- varuint32
when (i > functionCount w) $ bad "function index out of range"
pure w { start = Just i }
sectElement w = do
es <- rep varuint32 $ do
index <- varuint32
when (index /= 0) $ bad "MVP allows at most one table"
~[I32_const offset] <- codeBlock w
ns <- rep varuint32 $ do
i <- varuint32
when (i > functionCount w) $ bad "function index out of range"
pure $ fromIntegral i
pure (fromIntegral offset, ns)
pure w { elemSection = es }
sectCode w = do
fs <- rep varuint32 $ do
_ <- varuint32 -- Size.
locals <- concat <$> rep varuint32 (replicate <$> varuint32 <*> valueType)
ops <- codeBlock w
pure (locals, ops)
pure w { functions = IM.fromList $ zip [length (imports w)..]
$ zipWith (\a (b, c) -> WasmFun a b c) (decls w) fs }
sectData w = do
ds <- rep varuint32 $ do
index <- varuint32
when (index /= 0) $ bad "MVP allows at most one memory"
offset <- codeBlock w
(,) offset <$> rep varuint32 next
pure w { dataSection = ds }
martinFuncType = do
form <- varint7
when (form /= -32) $ bad "expected func type"
paramTypes <- rep varuint32 martinValueType
z <- varuint1
when (z /= 0) $ bad "must have no return value"
pure paramTypes
martinValueType = do
t <- varuint7
maybe (bad $ "bad type: " ++ show t) pure $ lookup t
[ (0x7f, I32)
, (0x7e, I64)
, (0x7d, F32)
, (0x7c, F64)
AnyFunc in standard wasm .
, (0x6f, Ref "Actor")
, (0x6e, Ref "Module")
, (0x6d, Ref "Port")
, (0x6c, Ref "Databuf")
, (0x6b, Ref "Elem")
]
sectCustom w = do
name <- lstr
case name of
"types" -> do
t <- rep varuint32 martinFuncType
pure w { martinTypes = t }
"typeMap" -> do
tm <- rep varuint32 $ (,) <$> varuint32 <*> varuint32
pure w { martinTypeMap = tm }
"persist" -> do
g <- rep varuint32 $ do
tmp <- varuint7
when (tmp /= 3) $ bad "expect 3"
(,) <$> varuint32 <*> martinValueType
pure w { permaGlobals = g }
"dfndbg" -> remainder >> pure w
"dfnhs" -> do
Should be 1 .
s <- remainder
pure w { haskell = chr . fromIntegral <$> B.unpack s }
_ -> remainder >> pure w
codeBlock :: Wasm -> ByteParser [WasmOp]
codeBlock w = do
opcode <- fromIntegral <$> varuint7
s <- if
| Just s <- lookup opcode $ zeroOperandOps -> pure s
| Just s <- lookup opcode [(0x02, Block), (0x03, Loop)] -> do
bt <- blockType
bl <- codeBlock w
pure $ s bt bl
| Just s <- lookup opcode [(0x20, Get_local), (0x21, Set_local), (0x22, Tee_local), (0x23, Get_global), (0x24, Set_global)] -> do
v <- varuint32
pure $ s v
| Just s <- lookup opcode [(0x28, I32_load), (0x29, I64_load), (0x2a, F32_load), (0x2b, F64_load), (0x2c, I32_load8_s), (0x2d, I32_load8_u), (0x2e, I32_load16_s), (0x2f, I32_load16_u), (0x30, I64_load8_s), (0x31, I64_load8_u), (0x32, I64_load16_s), (0x33, I64_load16_u), (0x34, I64_load32_s), (0x35, I64_load32_u), (0x36, I32_store), (0x37, I64_store), (0x38, F32_store), (0x39, F64_store), (0x3a, I32_store8), (0x3b, I32_store16), (0x3c, I64_store8), (0x3d, I64_store16), (0x3e, I64_store32)] -> do
flags <- varuint32
offset <- varuint32
pure $ s flags offset
| Just s <- lookup opcode [(0x0c, Br), (0x0d, Br_if)] -> do
v <- varuint32
pure $ s v
| otherwise -> case opcode of
0x04 -> do
bt <- blockType
bl <- codeBlock w
case last bl of
Else -> do
bl2 <- codeBlock w
pure $ If bt (init bl) bl2
_ -> pure $ If bt bl []
0x05 -> pure Else
0x0e -> do
n <- varuint32
tgts <- replicateM n varuint32
defTgt <- varuint32
pure $ Br_table tgts defTgt
0x41 -> do
i32 <- varint32
pure $ I32_const i32
0x42 -> do
i64 <- varint64
pure $ I64_const i64
0x10 -> do
i <- varuint32
pure $ Call i
0x11 -> do
i <- varuint32
~ 0 <- varuint1
when (i >= length (types w)) $ bad "Call_indirect index out of range"
pure $ Call_indirect $ types w !! i
_ -> bad ("bad opcode " ++ show opcode)
if
| Else <- s -> pure [Else]
| End <- s -> pure []
| otherwise -> (s:) <$> codeBlock w
sect w = isEof >>= \b -> if b then pure w else do
n <- varuint7
m <- varuint32
s <- repNext m
let
f = case n of
1 -> sectType
2 -> sectImport
3 -> sectFunction
4 -> sectTable
5 -> sectMemory
6 -> sectGlobal
7 -> sectExport
8 -> sectStart
9 -> sectElement
10 -> sectCode
11 -> sectData
0 -> sectCustom
_ -> pure
case byteParse (f w) s of
Left err -> bad err
Right w1 -> sect w1
header <- repNext 8 -- Header and version.
if header /= "\000asm\001\000\000\000" then
bad "bad header or version"
else sect emptyWasm -- Sections.
parseWasm :: B.ByteString -> Either String Wasm
parseWasm b = do
w@Wasm{imports, exports, martinTypeMap, martinTypes} <- byteParse wasm b
let
findType k
| Just mt <- lookup (k - length imports) martinTypeMap = martinTypes!!mt
-- Outputs make no sense for dfn, but we support them so we can use this
-- code more generally.
| k < length imports = fst $ snd $ imports !! k
| otherwise = fst $ decls w !! (k - length imports)
pure w { dfnExports = second findType <$> exports }
ripWasm :: [String] -> Wasm -> ([(String, Int)], [(Int, WasmFun)])
ripWasm es w = (zip es idxs, fMap)
where
Just idxs = mapM (`lookup` exports w) es
reachable = IS.elems $ followCalls idxs $ funBody <$> functions w
fMap = (\i -> (i, functions w IM.! i)) <$> reachable
-- Returns elements of table as
-- association list of slot to (function index, function type).
elTable :: Wasm -> [(Int, (Int, [WasmType]))]
elTable (Wasm {martinTypes, martinTypeMap, elemSection, imports})
= second (\n -> (n, maybe (error "BUG! missing type")
(martinTypes!!) $ lookup (n - length imports) martinTypeMap)) <$> es where
es = concatMap (\(offset, ns) -> zip [offset..] ns) elemSection
| null | https://raw.githubusercontent.com/dfinity-side-projects/dhc/60ac6c85ca02b53c0fdd1f5852c1eaf35f97d579/src/Hero/Parse.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
TODO: Record maximum.
Size.
Header and version.
Sections.
Outputs make no sense for dfn, but we support them so we can use this
code more generally.
Returns elements of table as
association list of slot to (function index, function type). | # LANGUAGE CPP #
# LANGUAGE NamedFieldPuns #
module Hero.Parse (parseWasm, Wasm(..), ripWasm, elTable) where
#ifdef __HASTE__
import qualified Data.Map.Strict as IM
import qualified Data.Set as IS
#else
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
#endif
import Control.Arrow
import Control.Monad
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Data.Char
import Data.Int
import Data.Maybe
import Data.Word
import WasmOp
#ifdef __HASTE__
type IntMap = IM.Map Int
#endif
data ExternalKind = Function | Table | Memory | Global
type FuncType = ([WasmType], [WasmType])
data Wasm = Wasm
{ types :: [FuncType]
, imports :: [((String, String), FuncType)]
, decls :: [FuncType]
, tableSize :: Int
, memory :: [(Int, Maybe Int)]
, globalSection :: [((WasmType, Bool), [WasmOp])]
, exports :: [(String, Int)]
, start :: Maybe Int
, elemSection :: [(Int, [Int])]
, functions :: IntMap WasmFun
, dataSection :: [([WasmOp], [Word8])]
, dfnExports :: [(String, [WasmType])]
, martinTypes :: [[WasmType]]
, martinTypeMap :: [(Int, Int)]
, permaGlobals :: [(Int, WasmType)]
, persist :: [(Int, WasmType)]
, haskell :: String
} deriving Show
emptyWasm :: Wasm
emptyWasm = Wasm [] [] [] 0 [] [] [] Nothing [] IM.empty [] [] [] [] [] [] ""
data ByteParser a = ByteParser (ByteString -> Either String (a, ByteString))
instance Functor ByteParser where fmap = liftM
instance Applicative ByteParser where {pure = return; (<*>) = ap}
instance Monad ByteParser where
ByteParser f >>= g = ByteParser $ (good =<<) . f
where good (r, t) = let ByteParser gg = g r in gg t
return a = ByteParser $ \s -> Right (a, s)
next :: ByteParser Word8
next = ByteParser f where
f s | B.null s = Left "unexpected EOF"
| otherwise = Right (B.head s, B.tail s)
repNext :: Int -> ByteParser ByteString
repNext n = ByteParser f where
f s | B.length s < n = Left "missing bytes or size too large"
| otherwise = Right $ B.splitAt n s
isEof :: ByteParser Bool
isEof = ByteParser f where f s = Right (B.null s, s)
bad :: String -> ByteParser a
bad = ByteParser . const . Left
byteParse :: ByteParser a -> ByteString -> Either String a
byteParse (ByteParser f) s = f s >>= (\(w, t) ->
if B.null t then Right w else Left "expected EOF")
remainder :: ByteParser ByteString
remainder = ByteParser $ \s -> Right (s, "")
wasm :: ByteParser Wasm
wasm = do
let
rep getInt task = getInt >>= (`replicateM` task)
varuint = fromIntegral <$> f 1 0 where
f :: Integer -> Integer -> ByteParser Integer
f m acc = do
d <- fromIntegral <$> next
if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $ d*m + acc
varint = f 1 0 where
f :: Integer -> Integer -> ByteParser Integer
f m acc = do
d <- fromIntegral <$> next
if d > 127 then f (m * 128) $ (d - 128) * m + acc else pure $
if d >= 64 then d*m + acc - 128*m else d*m + acc
varuint1 = varuint
varuint7 = next
varuint32 = varuint
varint7 :: ByteParser Int
varint7 = do
c <- fromIntegral <$> next
when (c >= 128) $ error "bad varint7"
pure $ if c >= 64 then c - 128 else c
varint32 :: ByteParser Int32
varint32 = fromIntegral <$> varint
varint64 :: ByteParser Int64
varint64 = fromIntegral <$> varint
lstr :: ByteParser String
lstr = rep varuint32 $ chr . fromIntegral <$> next
allType = do
t <- varuint7
case lookup t [(0x7f, I32), (0x7e, I64), (0x7d, F32), (0x7c, F64), (0x70, AnyFunc), (0x60, Func), (0x40, Nada)] of
Just ty -> pure ty
Nothing -> bad $ "bad type: " ++ show t
valueType = do
t <- allType
when (t `notElem` [I32, I64, F32, F64]) $ bad "bad value_type"
pure t
blockType = do
t <- allType
when (t `notElem` [I32, I64, F32, F64, Nada]) $ bad "bad value_type"
pure t
elemType = do
t <- allType
when (t /= AnyFunc) $ bad "bad elem_type"
externalKind = do
k <- varuint7
pure $ case k of
0 -> Function
1 -> Table
2 -> Memory
3 -> Global
_ -> error "bad external_kind"
funcType = do
form <- varint7
when (form /= -32) $ bad "expected func type"
paramTypes <- rep varuint32 valueType
returnTypes <- rep varuint1 valueType
pure (paramTypes, returnTypes)
functionCount w = length (imports w) + length (decls w)
sectType w = do
t <- rep varuint32 funcType
pure w { types = t }
sectImport w = do
ms <- rep varuint32 $ do
moduleStr <- lstr
fieldStr <- lstr
k <- externalKind
case k of
Function -> do
t <- varuint32
when (t > length (types w)) $ bad "type out of range"
pure ((moduleStr, fieldStr), types w !! t)
_ -> error "TODO"
pure w { imports = ms }
sectExport w = do
es <- rep varuint32 $ do
fieldStr <- lstr
k <- externalKind
t <- varuint32
case k of
Function -> do
when (t > functionCount w) $ bad "function index out of range"
pure $ Just (fieldStr, t)
Global -> pure Nothing
Memory -> pure Nothing
Table -> pure Nothing
pure w { exports = catMaybes es }
sectFunction w = do
sigs <- rep varuint32 $ do
t <- varuint32
when (t > length (types w)) $ bad "type out of range"
pure $ types w !! t
pure w { decls = sigs }
sectTable w = do
n <- varuint32
when (n > 1) $ bad "MVP allows at most one table"
if n == 0 then pure w else do
elemType
flags <- varuint1
m <- varuint32
pure w { tableSize = m }
sectMemory w = do
n <- varuint32
when (n > 1) $ bad "MVP allows at most one memory"
if n == 0 then pure w else do
flags <- varuint1
initial <- varuint32
if flags > 0 then do
m <- varuint32
pure w { memory = [(initial, Just m)] }
else pure w { memory = [(initial, Nothing)] }
globalType = do
ty <- valueType
muta <- varuint1
pure (ty, muta > 0)
sectGlobal w = do
gs <- rep varuint32 $ do
gt <- globalType
x <- codeBlock w
pure (gt, x)
pure w { globalSection = gs }
sectStart w = do
i <- varuint32
when (i > functionCount w) $ bad "function index out of range"
pure w { start = Just i }
sectElement w = do
es <- rep varuint32 $ do
index <- varuint32
when (index /= 0) $ bad "MVP allows at most one table"
~[I32_const offset] <- codeBlock w
ns <- rep varuint32 $ do
i <- varuint32
when (i > functionCount w) $ bad "function index out of range"
pure $ fromIntegral i
pure (fromIntegral offset, ns)
pure w { elemSection = es }
sectCode w = do
fs <- rep varuint32 $ do
locals <- concat <$> rep varuint32 (replicate <$> varuint32 <*> valueType)
ops <- codeBlock w
pure (locals, ops)
pure w { functions = IM.fromList $ zip [length (imports w)..]
$ zipWith (\a (b, c) -> WasmFun a b c) (decls w) fs }
sectData w = do
ds <- rep varuint32 $ do
index <- varuint32
when (index /= 0) $ bad "MVP allows at most one memory"
offset <- codeBlock w
(,) offset <$> rep varuint32 next
pure w { dataSection = ds }
martinFuncType = do
form <- varint7
when (form /= -32) $ bad "expected func type"
paramTypes <- rep varuint32 martinValueType
z <- varuint1
when (z /= 0) $ bad "must have no return value"
pure paramTypes
martinValueType = do
t <- varuint7
maybe (bad $ "bad type: " ++ show t) pure $ lookup t
[ (0x7f, I32)
, (0x7e, I64)
, (0x7d, F32)
, (0x7c, F64)
AnyFunc in standard wasm .
, (0x6f, Ref "Actor")
, (0x6e, Ref "Module")
, (0x6d, Ref "Port")
, (0x6c, Ref "Databuf")
, (0x6b, Ref "Elem")
]
sectCustom w = do
name <- lstr
case name of
"types" -> do
t <- rep varuint32 martinFuncType
pure w { martinTypes = t }
"typeMap" -> do
tm <- rep varuint32 $ (,) <$> varuint32 <*> varuint32
pure w { martinTypeMap = tm }
"persist" -> do
g <- rep varuint32 $ do
tmp <- varuint7
when (tmp /= 3) $ bad "expect 3"
(,) <$> varuint32 <*> martinValueType
pure w { permaGlobals = g }
"dfndbg" -> remainder >> pure w
"dfnhs" -> do
Should be 1 .
s <- remainder
pure w { haskell = chr . fromIntegral <$> B.unpack s }
_ -> remainder >> pure w
codeBlock :: Wasm -> ByteParser [WasmOp]
codeBlock w = do
opcode <- fromIntegral <$> varuint7
s <- if
| Just s <- lookup opcode $ zeroOperandOps -> pure s
| Just s <- lookup opcode [(0x02, Block), (0x03, Loop)] -> do
bt <- blockType
bl <- codeBlock w
pure $ s bt bl
| Just s <- lookup opcode [(0x20, Get_local), (0x21, Set_local), (0x22, Tee_local), (0x23, Get_global), (0x24, Set_global)] -> do
v <- varuint32
pure $ s v
| Just s <- lookup opcode [(0x28, I32_load), (0x29, I64_load), (0x2a, F32_load), (0x2b, F64_load), (0x2c, I32_load8_s), (0x2d, I32_load8_u), (0x2e, I32_load16_s), (0x2f, I32_load16_u), (0x30, I64_load8_s), (0x31, I64_load8_u), (0x32, I64_load16_s), (0x33, I64_load16_u), (0x34, I64_load32_s), (0x35, I64_load32_u), (0x36, I32_store), (0x37, I64_store), (0x38, F32_store), (0x39, F64_store), (0x3a, I32_store8), (0x3b, I32_store16), (0x3c, I64_store8), (0x3d, I64_store16), (0x3e, I64_store32)] -> do
flags <- varuint32
offset <- varuint32
pure $ s flags offset
| Just s <- lookup opcode [(0x0c, Br), (0x0d, Br_if)] -> do
v <- varuint32
pure $ s v
| otherwise -> case opcode of
0x04 -> do
bt <- blockType
bl <- codeBlock w
case last bl of
Else -> do
bl2 <- codeBlock w
pure $ If bt (init bl) bl2
_ -> pure $ If bt bl []
0x05 -> pure Else
0x0e -> do
n <- varuint32
tgts <- replicateM n varuint32
defTgt <- varuint32
pure $ Br_table tgts defTgt
0x41 -> do
i32 <- varint32
pure $ I32_const i32
0x42 -> do
i64 <- varint64
pure $ I64_const i64
0x10 -> do
i <- varuint32
pure $ Call i
0x11 -> do
i <- varuint32
~ 0 <- varuint1
when (i >= length (types w)) $ bad "Call_indirect index out of range"
pure $ Call_indirect $ types w !! i
_ -> bad ("bad opcode " ++ show opcode)
if
| Else <- s -> pure [Else]
| End <- s -> pure []
| otherwise -> (s:) <$> codeBlock w
sect w = isEof >>= \b -> if b then pure w else do
n <- varuint7
m <- varuint32
s <- repNext m
let
f = case n of
1 -> sectType
2 -> sectImport
3 -> sectFunction
4 -> sectTable
5 -> sectMemory
6 -> sectGlobal
7 -> sectExport
8 -> sectStart
9 -> sectElement
10 -> sectCode
11 -> sectData
0 -> sectCustom
_ -> pure
case byteParse (f w) s of
Left err -> bad err
Right w1 -> sect w1
if header /= "\000asm\001\000\000\000" then
bad "bad header or version"
parseWasm :: B.ByteString -> Either String Wasm
parseWasm b = do
w@Wasm{imports, exports, martinTypeMap, martinTypes} <- byteParse wasm b
let
findType k
| Just mt <- lookup (k - length imports) martinTypeMap = martinTypes!!mt
| k < length imports = fst $ snd $ imports !! k
| otherwise = fst $ decls w !! (k - length imports)
pure w { dfnExports = second findType <$> exports }
ripWasm :: [String] -> Wasm -> ([(String, Int)], [(Int, WasmFun)])
ripWasm es w = (zip es idxs, fMap)
where
Just idxs = mapM (`lookup` exports w) es
reachable = IS.elems $ followCalls idxs $ funBody <$> functions w
fMap = (\i -> (i, functions w IM.! i)) <$> reachable
elTable :: Wasm -> [(Int, (Int, [WasmType]))]
elTable (Wasm {martinTypes, martinTypeMap, elemSection, imports})
= second (\n -> (n, maybe (error "BUG! missing type")
(martinTypes!!) $ lookup (n - length imports) martinTypeMap)) <$> es where
es = concatMap (\(offset, ns) -> zip [offset..] ns) elemSection
|
e899d1f142d2594158265e829e382ee7e32915b1ee01c22c706507ef53a92ab7 | haskell/haskell-language-server | GoldenShowMapChar.expected.hs | test :: Show a => a -> (String -> b) -> b
test a f = f (show a)
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/GoldenShowMapChar.expected.hs | haskell | test :: Show a => a -> (String -> b) -> b
test a f = f (show a)
| |
510585bcff1877d4eefc8875c84f8f59751ff6de9a4c234c94adfe0e977acac1 | input-output-hk/ouroboros-network | NodeToNode.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NamedFieldPuns #
# LANGUAGE QuantifiedConstraints #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
-- | Intended for qualified import
module Ouroboros.Consensus.Network.NodeToNode (
-- * Handlers
Handlers (..)
, mkHandlers
-- * Codecs
, Codecs (..)
, defaultCodecs
, identityCodecs
-- * Byte Limits
, ByteLimits
, byteLimits
, noByteLimits
-- * Tracers
, Tracers
, Tracers' (..)
, nullTracers
, showTracers
-- * Applications
, Apps (..)
, ClientApp
, ServerApp
, mkApps
-- ** Projections
, initiator
, initiatorAndResponder
-- * Re-exports
, ChainSyncTimeout (..)
) where
import Codec.CBOR.Decoding (Decoder)
import Codec.CBOR.Encoding (Encoding)
import Codec.CBOR.Read (DeserialiseFailure)
import Control.Monad.Class.MonadTime (MonadTime)
import Control.Monad.Class.MonadTimer (MonadTimer)
import Control.Tracer
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BSL
import Data.Int (Int64)
import Data.Map.Strict (Map)
import Data.Void (Void)
import Network.TypedProtocol.Codec
import Ouroboros.Network.AnchoredFragment (AnchoredFragment)
import Ouroboros.Network.Block (Serialised (..), decodePoint,
decodeTip, encodePoint, encodeTip)
import Ouroboros.Network.BlockFetch
import Ouroboros.Network.BlockFetch.Client (BlockFetchClient,
blockFetchClient)
import Ouroboros.Network.Channel
import Ouroboros.Network.DeltaQ
import Ouroboros.Network.Driver
import Ouroboros.Network.Driver.Limits
import Ouroboros.Network.KeepAlive
import Ouroboros.Network.Mux
import Ouroboros.Network.NodeToNode
import Ouroboros.Network.NodeToNode.Version (isPipeliningEnabled)
import Ouroboros.Network.PeerSelection.PeerMetric.Type
(FetchedMetricsTracer, HeaderMetricsTracer,
ReportPeerMetrics (..))
import Ouroboros.Network.Protocol.BlockFetch.Codec
import Ouroboros.Network.Protocol.BlockFetch.Server (BlockFetchServer,
blockFetchServerPeer)
import Ouroboros.Network.Protocol.BlockFetch.Type (BlockFetch (..))
import Ouroboros.Network.Protocol.ChainSync.ClientPipelined
import Ouroboros.Network.Protocol.ChainSync.Codec
import Ouroboros.Network.Protocol.ChainSync.PipelineDecision
import Ouroboros.Network.Protocol.ChainSync.Server
import Ouroboros.Network.Protocol.ChainSync.Type
import Ouroboros.Network.Protocol.KeepAlive.Client
import Ouroboros.Network.Protocol.KeepAlive.Codec
import Ouroboros.Network.Protocol.KeepAlive.Server
import Ouroboros.Network.Protocol.KeepAlive.Type
import Ouroboros.Network.Protocol.TxSubmission2.Client
import Ouroboros.Network.Protocol.TxSubmission2.Codec
import Ouroboros.Network.Protocol.TxSubmission2.Server
import Ouroboros.Network.Protocol.TxSubmission2.Type
import Ouroboros.Network.TxSubmission.Inbound
import Ouroboros.Network.TxSubmission.Mempool.Reader
(mapTxSubmissionMempoolReader)
import Ouroboros.Network.TxSubmission.Outbound
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Ledger.SupportsMempool
import Ouroboros.Consensus.Ledger.SupportsProtocol
import Ouroboros.Consensus.MiniProtocol.BlockFetch.Server
import Ouroboros.Consensus.MiniProtocol.ChainSync.Client
import Ouroboros.Consensus.MiniProtocol.ChainSync.Server
import Ouroboros.Consensus.Node.ExitPolicy
import Ouroboros.Consensus.Node.NetworkProtocolVersion
import Ouroboros.Consensus.Node.Run
import Ouroboros.Consensus.Node.Serialisation
import qualified Ouroboros.Consensus.Node.Tracers as Node
import Ouroboros.Consensus.NodeKernel
import qualified Ouroboros.Consensus.Storage.ChainDB.API as ChainDB
import Ouroboros.Consensus.Util (ShowProxy)
import Ouroboros.Consensus.Util.IOLike
import Ouroboros.Consensus.Util.Orphans ()
import Ouroboros.Consensus.Util.ResourceRegistry
import Ouroboros.Consensus.Storage.Serialisation (SerialisedHeader)
{-------------------------------------------------------------------------------
Handlers
-------------------------------------------------------------------------------}
-- | Protocol handlers for node-to-node (remote) communication
data Handlers m peer blk = Handlers {
hChainSyncClient
:: peer
-> NodeToNodeVersion
-> ControlMessageSTM m
-> HeaderMetricsTracer m
-> StrictTVar m (AnchoredFragment (Header blk))
-> ChainSyncClientPipelined (Header blk) (Point blk) (Tip blk) m ChainSyncClientResult
-- TODO: we should consider either bundling these context parameters
-- into a record, or extending the protocol handler representation
-- to support bracket-style initialisation so that we could have the
-- closure include these and not need to be explicit about them here.
, hChainSyncServer
:: NodeToNodeVersion
-> ChainDB.Follower m blk (ChainDB.WithPoint blk (SerialisedHeader blk))
-> ChainSyncServer (SerialisedHeader blk) (Point blk) (Tip blk) m ()
TODO block fetch client does not have GADT view of the handlers .
, hBlockFetchClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> FetchedMetricsTracer m
-> BlockFetchClient (Header blk) blk m ()
, hBlockFetchServer
:: NodeToNodeVersion
-> ResourceRegistry m
-> BlockFetchServer (Serialised blk) (Point blk) m ()
, hTxSubmissionClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> peer
-> TxSubmissionClient (GenTxId blk) (GenTx blk) m ()
, hTxSubmissionServer
:: NodeToNodeVersion
-> peer
-> TxSubmissionServerPipelined (GenTxId blk) (GenTx blk) m ()
, hKeepAliveClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> peer
-> StrictTVar m (Map peer PeerGSV)
-> KeepAliveInterval
-> KeepAliveClient m ()
, hKeepAliveServer
:: NodeToNodeVersion
-> peer
-> KeepAliveServer m ()
}
mkHandlers
:: forall m blk remotePeer localPeer.
( IOLike m
, MonadTime m
, MonadTimer m
, LedgerSupportsMempool blk
, HasTxId (GenTx blk)
, LedgerSupportsProtocol blk
, Ord remotePeer
)
=> NodeKernelArgs m remotePeer localPeer blk
-> NodeKernel m remotePeer localPeer blk
-> Handlers m remotePeer blk
mkHandlers
NodeKernelArgs {keepAliveRng, miniProtocolParameters}
NodeKernel {getChainDB, getMempool, getTopLevelConfig, getTracers = tracers} =
Handlers {
hChainSyncClient = \peer ->
chainSyncClient
(pipelineDecisionLowHighMark
(chainSyncPipeliningLowMark miniProtocolParameters)
(chainSyncPipeliningHighMark miniProtocolParameters))
(contramap (TraceLabelPeer peer) (Node.chainSyncClientTracer tracers))
getTopLevelConfig
(defaultChainDbView getChainDB)
, hChainSyncServer = \_version ->
chainSyncHeadersServer
(Node.chainSyncServerHeaderTracer tracers)
getChainDB
, hBlockFetchClient =
blockFetchClient
, hBlockFetchServer = \version ->
blockFetchServer
(Node.blockFetchServerTracer tracers)
getChainDB
version
, hTxSubmissionClient = \version controlMessageSTM peer ->
txSubmissionOutbound
(contramap (TraceLabelPeer peer) (Node.txOutboundTracer tracers))
(txSubmissionMaxUnacked miniProtocolParameters)
(mapTxSubmissionMempoolReader txForgetValidated $ getMempoolReader getMempool)
version
controlMessageSTM
, hTxSubmissionServer = \version peer ->
txSubmissionInbound
(contramap (TraceLabelPeer peer) (Node.txInboundTracer tracers))
(txSubmissionMaxUnacked miniProtocolParameters)
(mapTxSubmissionMempoolReader txForgetValidated $ getMempoolReader getMempool)
(getMempoolWriter getMempool)
version
, hKeepAliveClient = \_version -> keepAliveClient (Node.keepAliveClientTracer tracers) keepAliveRng
, hKeepAliveServer = \_version _peer -> keepAliveServer
}
{-------------------------------------------------------------------------------
Codecs
-------------------------------------------------------------------------------}
-- | Node-to-node protocol codecs needed to run 'Handlers'.
data Codecs blk e m bCS bSCS bBF bSBF bTX bKA = Codecs {
cChainSyncCodec :: Codec (ChainSync (Header blk) (Point blk) (Tip blk)) e m bCS
, cChainSyncCodecSerialised :: Codec (ChainSync (SerialisedHeader blk) (Point blk) (Tip blk)) e m bSCS
, cBlockFetchCodec :: Codec (BlockFetch blk (Point blk)) e m bBF
, cBlockFetchCodecSerialised :: Codec (BlockFetch (Serialised blk) (Point blk)) e m bSBF
, cTxSubmission2Codec :: Codec (TxSubmission2 (GenTxId blk) (GenTx blk)) e m bTX
, cKeepAliveCodec :: Codec KeepAlive e m bKA
}
-- | Protocol codecs for the node-to-node protocols
defaultCodecs :: forall m blk. (IOLike m, SerialiseNodeToNodeConstraints blk)
=> CodecConfig blk
-> BlockNodeToNodeVersion blk
-> NodeToNodeVersion
-> Codecs blk DeserialiseFailure m
ByteString ByteString ByteString ByteString ByteString ByteString
defaultCodecs ccfg version _nodeToNodeVersion = Codecs {
cChainSyncCodec =
codecChainSync
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
(encodeTip (encodeRawHash p))
(decodeTip (decodeRawHash p))
, cChainSyncCodecSerialised =
codecChainSync
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
(encodeTip (encodeRawHash p))
(decodeTip (decodeRawHash p))
, cBlockFetchCodec =
codecBlockFetch
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
, cBlockFetchCodecSerialised =
codecBlockFetch
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
, cTxSubmission2Codec =
codecTxSubmission2
enc
dec
enc
dec
, cKeepAliveCodec = codecKeepAlive_v2
}
where
p :: Proxy blk
p = Proxy
enc :: SerialiseNodeToNode blk a => a -> Encoding
enc = encodeNodeToNode ccfg version
dec :: SerialiseNodeToNode blk a => forall s. Decoder s a
dec = decodeNodeToNode ccfg version
-- | Identity codecs used in tests.
identityCodecs :: Monad m
=> Codecs blk CodecFailure m
(AnyMessage (ChainSync (Header blk) (Point blk) (Tip blk)))
(AnyMessage (ChainSync (SerialisedHeader blk) (Point blk) (Tip blk)))
(AnyMessage (BlockFetch blk (Point blk)))
(AnyMessage (BlockFetch (Serialised blk) (Point blk)))
(AnyMessage (TxSubmission2 (GenTxId blk) (GenTx blk)))
(AnyMessage KeepAlive)
identityCodecs = Codecs {
cChainSyncCodec = codecChainSyncId
, cChainSyncCodecSerialised = codecChainSyncId
, cBlockFetchCodec = codecBlockFetchId
, cBlockFetchCodecSerialised = codecBlockFetchId
, cTxSubmission2Codec = codecTxSubmission2Id
, cKeepAliveCodec = codecKeepAliveId
}
------------------------------------------------------------------------------
Tracers
------------------------------------------------------------------------------
Tracers
-------------------------------------------------------------------------------}
| A record of ' Tracer 's for the different protocols .
type Tracers m peer blk e =
Tracers' peer blk e (Tracer m)
data Tracers' peer blk e f = Tracers {
tChainSyncTracer :: f (TraceLabelPeer peer (TraceSendRecv (ChainSync (Header blk) (Point blk) (Tip blk))))
, tChainSyncSerialisedTracer :: f (TraceLabelPeer peer (TraceSendRecv (ChainSync (SerialisedHeader blk) (Point blk) (Tip blk))))
, tBlockFetchTracer :: f (TraceLabelPeer peer (TraceSendRecv (BlockFetch blk (Point blk))))
, tBlockFetchSerialisedTracer :: f (TraceLabelPeer peer (TraceSendRecv (BlockFetch (Serialised blk) (Point blk))))
, tTxSubmission2Tracer :: f (TraceLabelPeer peer (TraceSendRecv (TxSubmission2 (GenTxId blk) (GenTx blk))))
}
instance (forall a. Semigroup (f a)) => Semigroup (Tracers' peer blk e f) where
l <> r = Tracers {
tChainSyncTracer = f tChainSyncTracer
, tChainSyncSerialisedTracer = f tChainSyncSerialisedTracer
, tBlockFetchTracer = f tBlockFetchTracer
, tBlockFetchSerialisedTracer = f tBlockFetchSerialisedTracer
, tTxSubmission2Tracer = f tTxSubmission2Tracer
}
where
f :: forall a. Semigroup a
=> (Tracers' peer blk e f -> a)
-> a
f prj = prj l <> prj r
-- | Use a 'nullTracer' for each protocol.
nullTracers :: Monad m => Tracers m peer blk e
nullTracers = Tracers {
tChainSyncTracer = nullTracer
, tChainSyncSerialisedTracer = nullTracer
, tBlockFetchTracer = nullTracer
, tBlockFetchSerialisedTracer = nullTracer
, tTxSubmission2Tracer = nullTracer
}
showTracers :: ( Show blk
, Show peer
, Show (Header blk)
, Show (GenTx blk)
, Show (GenTxId blk)
, HasHeader blk
, HasNestedContent Header blk
)
=> Tracer m String -> Tracers m peer blk e
showTracers tr = Tracers {
tChainSyncTracer = showTracing tr
, tChainSyncSerialisedTracer = showTracing tr
, tBlockFetchTracer = showTracing tr
, tBlockFetchSerialisedTracer = showTracing tr
, tTxSubmission2Tracer = showTracing tr
}
{-------------------------------------------------------------------------------
Applications
-------------------------------------------------------------------------------}
-- | A node-to-node application
type ClientApp m peer bytes a =
NodeToNodeVersion
-> ControlMessageSTM m
-> peer
-> Channel m bytes
-> m (a, Maybe bytes)
type ServerApp m peer bytes a =
NodeToNodeVersion
-> peer
-> Channel m bytes
-> m (a, Maybe bytes)
-- | Applications for the node-to-node protocols
--
See ' Network . Mux . Types . MuxApplication '
data Apps m peer bCS bBF bTX bKA a b = Apps {
-- | Start a chain sync client that communicates with the given upstream
-- node.
aChainSyncClient :: ClientApp m peer bCS a
-- | Start a chain sync server.
, aChainSyncServer :: ServerApp m peer bCS b
-- | Start a block fetch client that communicates with the given
-- upstream node.
, aBlockFetchClient :: ClientApp m peer bBF a
-- | Start a block fetch server.
, aBlockFetchServer :: ServerApp m peer bBF b
-- | Start a transaction submission v2 client that communicates with the
-- given upstream node.
, aTxSubmission2Client :: ClientApp m peer bTX a
-- | Start a transaction submission v2 server.
, aTxSubmission2Server :: ServerApp m peer bTX b
-- | Start a keep-alive client.
, aKeepAliveClient :: ClientApp m peer bKA a
-- | Start a keep-alive server.
, aKeepAliveServer :: ServerApp m peer bKA b
}
-- | Per mini-protocol byte limits; For each mini-protocol they provide
-- per-state byte size limits, i.e. how much data can arrive from the network.
--
-- They don't depend on the instantiation of the protocol parameters (which
block type is used , etc . ) , hence the use of ' RankNTypes ' .
--
data ByteLimits bCS bBF bTX bKA = ByteLimits {
blChainSync :: forall header point tip.
ProtocolSizeLimits
(ChainSync header point tip)
bCS
, blBlockFetch :: forall block point.
ProtocolSizeLimits
(BlockFetch block point)
bBF
, blTxSubmission2 :: forall txid tx.
ProtocolSizeLimits
(TxSubmission2 txid tx)
bTX
, blKeepAlive :: ProtocolSizeLimits
KeepAlive
bKA
}
noByteLimits :: ByteLimits bCS bBF bTX bKA
noByteLimits = ByteLimits {
blChainSync = byteLimitsChainSync (const 0)
, blBlockFetch = byteLimitsBlockFetch (const 0)
, blTxSubmission2 = byteLimitsTxSubmission2 (const 0)
, blKeepAlive = byteLimitsKeepAlive (const 0)
}
byteLimits :: ByteLimits ByteString ByteString ByteString ByteString
byteLimits = ByteLimits {
blChainSync = byteLimitsChainSync size
, blBlockFetch = byteLimitsBlockFetch size
, blTxSubmission2 = byteLimitsTxSubmission2 size
, blKeepAlive = byteLimitsKeepAlive size
}
where
size :: ByteString -> Word
size = (fromIntegral :: Int64 -> Word)
. BSL.length
-- | Construct the 'NetworkApplication' for the node-to-node protocols
mkApps
:: forall m remotePeer localPeer blk e bCS bBF bTX bKA.
( IOLike m
, MonadTimer m
, Ord remotePeer
, Exception e
, LedgerSupportsProtocol blk
, ShowProxy blk
, ShowProxy (Header blk)
, ShowProxy (TxId (GenTx blk))
, ShowProxy (GenTx blk)
)
=> NodeKernel m remotePeer localPeer blk -- ^ Needed for bracketing only
-> Tracers m remotePeer blk e
-> (NodeToNodeVersion -> Codecs blk e m bCS bCS bBF bBF bTX bKA)
-> ByteLimits bCS bBF bTX bKA
-> m ChainSyncTimeout
-> ReportPeerMetrics m remotePeer
-> Handlers m remotePeer blk
-> Apps m remotePeer bCS bBF bTX bKA NodeToNodeInitiatorResult ()
mkApps kernel Tracers {..} mkCodecs ByteLimits {..} genChainSyncTimeout ReportPeerMetrics {..} Handlers {..} =
Apps {..}
where
aChainSyncClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bCS
-> m (NodeToNodeInitiatorResult, Maybe bCS)
aChainSyncClient version controlMessageSTM them channel = do
labelThisThread "ChainSyncClient"
-- Note that it is crucial that we sync with the fetch client "outside"
-- of registering the state for the sync client. This is needed to
-- maintain a state invariant required by the block fetch logic: that for
-- each candidate chain there is a corresponding block fetch client that
-- can be used to fetch blocks for that chain.
bracketSyncWithFetchClient
(getFetchClientRegistry kernel) them $
bracketChainSyncClient
(contramap (TraceLabelPeer them) (Node.chainSyncClientTracer (getTracers kernel)))
(defaultChainDbView (getChainDB kernel))
(getNodeCandidates kernel)
them
version $ \varCandidate -> do
chainSyncTimeout <- genChainSyncTimeout
(r, trailing) <-
runPipelinedPeerWithLimits
(contramap (TraceLabelPeer them) tChainSyncTracer)
(cChainSyncCodec (mkCodecs version))
blChainSync
(timeLimitsChainSync chainSyncTimeout)
channel
$ chainSyncClientPeerPipelined
$ hChainSyncClient them version controlMessageSTM
(TraceLabelPeer them `contramap` reportHeader)
varCandidate
return (ChainSyncInitiatorResult r, trailing)
aChainSyncServer
:: NodeToNodeVersion
-> remotePeer
-> Channel m bCS
-> m ((), Maybe bCS)
aChainSyncServer version them channel = do
labelThisThread "ChainSyncServer"
chainSyncTimeout <- genChainSyncTimeout
bracketWithPrivateRegistry
(chainSyncHeaderServerFollower
(getChainDB kernel)
( case isPipeliningEnabled version of
ReceivingTentativeBlocks -> ChainDB.TentativeChain
NotReceivingTentativeBlocks -> ChainDB.SelectedChain
)
)
ChainDB.followerClose
$ \flr ->
runPeerWithLimits
(contramap (TraceLabelPeer them) tChainSyncSerialisedTracer)
(cChainSyncCodecSerialised (mkCodecs version))
blChainSync
(timeLimitsChainSync chainSyncTimeout)
channel
$ chainSyncServerPeer
$ hChainSyncServer version flr
aBlockFetchClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bBF
-> m (NodeToNodeInitiatorResult, Maybe bBF)
aBlockFetchClient version controlMessageSTM them channel = do
labelThisThread "BlockFetchClient"
bracketFetchClient (getFetchClientRegistry kernel) version
isPipeliningEnabled them $ \clientCtx -> do
((), trailing) <- runPipelinedPeerWithLimits
(contramap (TraceLabelPeer them) tBlockFetchTracer)
(cBlockFetchCodec (mkCodecs version))
blBlockFetch
timeLimitsBlockFetch
channel
$ hBlockFetchClient version controlMessageSTM
(TraceLabelPeer them `contramap` reportFetch) clientCtx
return (NoInitiatorResult, trailing)
aBlockFetchServer
:: NodeToNodeVersion
-> remotePeer
-> Channel m bBF
-> m ((), Maybe bBF)
aBlockFetchServer version them channel = do
labelThisThread "BlockFetchServer"
withRegistry $ \registry ->
runPeerWithLimits
(contramap (TraceLabelPeer them) tBlockFetchSerialisedTracer)
(cBlockFetchCodecSerialised (mkCodecs version))
blBlockFetch
timeLimitsBlockFetch
channel
$ blockFetchServerPeer
$ hBlockFetchServer version registry
aTxSubmission2Client
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bTX
-> m (NodeToNodeInitiatorResult, Maybe bTX)
aTxSubmission2Client version controlMessageSTM them channel = do
labelThisThread "TxSubmissionClient"
((), trailing) <- runPeerWithLimits
(contramap (TraceLabelPeer them) tTxSubmission2Tracer)
(cTxSubmission2Codec (mkCodecs version))
blTxSubmission2
timeLimitsTxSubmission2
channel
(txSubmissionClientPeer (hTxSubmissionClient version controlMessageSTM them))
return (NoInitiatorResult, trailing)
aTxSubmission2Server
:: NodeToNodeVersion
-> remotePeer
-> Channel m bTX
-> m ((), Maybe bTX)
aTxSubmission2Server version them channel = do
labelThisThread "TxSubmissionServer"
runPipelinedPeerWithLimits
(contramap (TraceLabelPeer them) tTxSubmission2Tracer)
(cTxSubmission2Codec (mkCodecs version))
blTxSubmission2
timeLimitsTxSubmission2
channel
(txSubmissionServerPeerPipelined (hTxSubmissionServer version them))
aKeepAliveClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bKA
-> m (NodeToNodeInitiatorResult, Maybe bKA)
aKeepAliveClient version controlMessageSTM them channel = do
labelThisThread "KeepAliveClient"
let kacApp = \dqCtx ->
runPeerWithLimits
nullTracer
(cKeepAliveCodec (mkCodecs version))
blKeepAlive
timeLimitsKeepAlive
channel
$ keepAliveClientPeer
$ hKeepAliveClient version controlMessageSTM them dqCtx
(KeepAliveInterval 10)
((), trailing) <- bracketKeepAliveClient (getFetchClientRegistry kernel) them kacApp
return (NoInitiatorResult, trailing)
aKeepAliveServer
:: NodeToNodeVersion
-> remotePeer
-> Channel m bKA
-> m ((), Maybe bKA)
aKeepAliveServer version _them channel = do
labelThisThread "KeepAliveServer"
runPeerWithLimits
nullTracer
(cKeepAliveCodec (mkCodecs version))
TODO : Real Bytelimits , see # 1727
timeLimitsKeepAlive
channel
$ keepAliveServerPeer
$ keepAliveServer
{-------------------------------------------------------------------------------
Projections from 'Apps'
-------------------------------------------------------------------------------}
-- | A projection from 'NetworkApplication' to a client-side
-- 'OuroborosApplication' for the node-to-node protocols.
--
-- Implementation note: network currently doesn't enable protocols conditional
on the protocol version , but it eventually may ; this is why @_version@ is
-- currently unused.
initiator
:: MiniProtocolParameters
-> NodeToNodeVersion
-> Apps m (ConnectionId peer) b b b b a c
-> OuroborosBundle 'InitiatorMode peer b m a Void
initiator miniProtocolParameters version Apps {..} =
nodeToNodeProtocols
miniProtocolParameters
TODO : currently consensus is using ' ConnectionId ' for its ' peer ' type .
-- This is currently ok, as we might accept multiple connections from the
-- same ip address, however this will change when we will switch to
-- p2p-governor & connection-manager. Then consenus can use peer's ip
address & port number , rather than ' ConnectionId ' ( which is
-- a quadruple uniquely determinaing a connection).
(\them controlMessageSTM -> NodeToNodeProtocols {
chainSyncProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aChainSyncClient version controlMessageSTM them))),
blockFetchProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aBlockFetchClient version controlMessageSTM them))),
txSubmissionProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aTxSubmission2Client version controlMessageSTM them))),
keepAliveProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aKeepAliveClient version controlMessageSTM them)))
})
version
-- | A bi-directional network applicaiton.
--
-- Implementation note: network currently doesn't enable protocols conditional
on the protocol version , but it eventually may ; this is why @_version@ is
-- currently unused.
initiatorAndResponder
:: MiniProtocolParameters
-> NodeToNodeVersion
-> Apps m (ConnectionId peer) b b b b a c
-> OuroborosBundle 'InitiatorResponderMode peer b m a c
initiatorAndResponder miniProtocolParameters version Apps {..} =
nodeToNodeProtocols
miniProtocolParameters
(\them controlMessageSTM -> NodeToNodeProtocols {
chainSyncProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aChainSyncClient version controlMessageSTM them))
(MuxPeerRaw (aChainSyncServer version them))),
blockFetchProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aBlockFetchClient version controlMessageSTM them))
(MuxPeerRaw (aBlockFetchServer version them))),
txSubmissionProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aTxSubmission2Client version controlMessageSTM them))
(MuxPeerRaw (aTxSubmission2Server version them))),
keepAliveProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aKeepAliveClient version controlMessageSTM them))
(MuxPeerRaw (aKeepAliveServer version them)))
})
version
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/2793b6993c8f6ed158f432055fa4ef581acdb661/ouroboros-consensus-diffusion/src/Ouroboros/Consensus/Network/NodeToNode.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
| Intended for qualified import
* Handlers
* Codecs
* Byte Limits
* Tracers
* Applications
** Projections
* Re-exports
------------------------------------------------------------------------------
Handlers
------------------------------------------------------------------------------
| Protocol handlers for node-to-node (remote) communication
TODO: we should consider either bundling these context parameters
into a record, or extending the protocol handler representation
to support bracket-style initialisation so that we could have the
closure include these and not need to be explicit about them here.
------------------------------------------------------------------------------
Codecs
------------------------------------------------------------------------------
| Node-to-node protocol codecs needed to run 'Handlers'.
| Protocol codecs for the node-to-node protocols
| Identity codecs used in tests.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Use a 'nullTracer' for each protocol.
------------------------------------------------------------------------------
Applications
------------------------------------------------------------------------------
| A node-to-node application
| Applications for the node-to-node protocols
| Start a chain sync client that communicates with the given upstream
node.
| Start a chain sync server.
| Start a block fetch client that communicates with the given
upstream node.
| Start a block fetch server.
| Start a transaction submission v2 client that communicates with the
given upstream node.
| Start a transaction submission v2 server.
| Start a keep-alive client.
| Start a keep-alive server.
| Per mini-protocol byte limits; For each mini-protocol they provide
per-state byte size limits, i.e. how much data can arrive from the network.
They don't depend on the instantiation of the protocol parameters (which
| Construct the 'NetworkApplication' for the node-to-node protocols
^ Needed for bracketing only
Note that it is crucial that we sync with the fetch client "outside"
of registering the state for the sync client. This is needed to
maintain a state invariant required by the block fetch logic: that for
each candidate chain there is a corresponding block fetch client that
can be used to fetch blocks for that chain.
------------------------------------------------------------------------------
Projections from 'Apps'
------------------------------------------------------------------------------
| A projection from 'NetworkApplication' to a client-side
'OuroborosApplication' for the node-to-node protocols.
Implementation note: network currently doesn't enable protocols conditional
currently unused.
This is currently ok, as we might accept multiple connections from the
same ip address, however this will change when we will switch to
p2p-governor & connection-manager. Then consenus can use peer's ip
a quadruple uniquely determinaing a connection).
| A bi-directional network applicaiton.
Implementation note: network currently doesn't enable protocols conditional
currently unused. | # LANGUAGE NamedFieldPuns #
# LANGUAGE QuantifiedConstraints #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module Ouroboros.Consensus.Network.NodeToNode (
Handlers (..)
, mkHandlers
, Codecs (..)
, defaultCodecs
, identityCodecs
, ByteLimits
, byteLimits
, noByteLimits
, Tracers
, Tracers' (..)
, nullTracers
, showTracers
, Apps (..)
, ClientApp
, ServerApp
, mkApps
, initiator
, initiatorAndResponder
, ChainSyncTimeout (..)
) where
import Codec.CBOR.Decoding (Decoder)
import Codec.CBOR.Encoding (Encoding)
import Codec.CBOR.Read (DeserialiseFailure)
import Control.Monad.Class.MonadTime (MonadTime)
import Control.Monad.Class.MonadTimer (MonadTimer)
import Control.Tracer
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BSL
import Data.Int (Int64)
import Data.Map.Strict (Map)
import Data.Void (Void)
import Network.TypedProtocol.Codec
import Ouroboros.Network.AnchoredFragment (AnchoredFragment)
import Ouroboros.Network.Block (Serialised (..), decodePoint,
decodeTip, encodePoint, encodeTip)
import Ouroboros.Network.BlockFetch
import Ouroboros.Network.BlockFetch.Client (BlockFetchClient,
blockFetchClient)
import Ouroboros.Network.Channel
import Ouroboros.Network.DeltaQ
import Ouroboros.Network.Driver
import Ouroboros.Network.Driver.Limits
import Ouroboros.Network.KeepAlive
import Ouroboros.Network.Mux
import Ouroboros.Network.NodeToNode
import Ouroboros.Network.NodeToNode.Version (isPipeliningEnabled)
import Ouroboros.Network.PeerSelection.PeerMetric.Type
(FetchedMetricsTracer, HeaderMetricsTracer,
ReportPeerMetrics (..))
import Ouroboros.Network.Protocol.BlockFetch.Codec
import Ouroboros.Network.Protocol.BlockFetch.Server (BlockFetchServer,
blockFetchServerPeer)
import Ouroboros.Network.Protocol.BlockFetch.Type (BlockFetch (..))
import Ouroboros.Network.Protocol.ChainSync.ClientPipelined
import Ouroboros.Network.Protocol.ChainSync.Codec
import Ouroboros.Network.Protocol.ChainSync.PipelineDecision
import Ouroboros.Network.Protocol.ChainSync.Server
import Ouroboros.Network.Protocol.ChainSync.Type
import Ouroboros.Network.Protocol.KeepAlive.Client
import Ouroboros.Network.Protocol.KeepAlive.Codec
import Ouroboros.Network.Protocol.KeepAlive.Server
import Ouroboros.Network.Protocol.KeepAlive.Type
import Ouroboros.Network.Protocol.TxSubmission2.Client
import Ouroboros.Network.Protocol.TxSubmission2.Codec
import Ouroboros.Network.Protocol.TxSubmission2.Server
import Ouroboros.Network.Protocol.TxSubmission2.Type
import Ouroboros.Network.TxSubmission.Inbound
import Ouroboros.Network.TxSubmission.Mempool.Reader
(mapTxSubmissionMempoolReader)
import Ouroboros.Network.TxSubmission.Outbound
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Ledger.SupportsMempool
import Ouroboros.Consensus.Ledger.SupportsProtocol
import Ouroboros.Consensus.MiniProtocol.BlockFetch.Server
import Ouroboros.Consensus.MiniProtocol.ChainSync.Client
import Ouroboros.Consensus.MiniProtocol.ChainSync.Server
import Ouroboros.Consensus.Node.ExitPolicy
import Ouroboros.Consensus.Node.NetworkProtocolVersion
import Ouroboros.Consensus.Node.Run
import Ouroboros.Consensus.Node.Serialisation
import qualified Ouroboros.Consensus.Node.Tracers as Node
import Ouroboros.Consensus.NodeKernel
import qualified Ouroboros.Consensus.Storage.ChainDB.API as ChainDB
import Ouroboros.Consensus.Util (ShowProxy)
import Ouroboros.Consensus.Util.IOLike
import Ouroboros.Consensus.Util.Orphans ()
import Ouroboros.Consensus.Util.ResourceRegistry
import Ouroboros.Consensus.Storage.Serialisation (SerialisedHeader)
data Handlers m peer blk = Handlers {
hChainSyncClient
:: peer
-> NodeToNodeVersion
-> ControlMessageSTM m
-> HeaderMetricsTracer m
-> StrictTVar m (AnchoredFragment (Header blk))
-> ChainSyncClientPipelined (Header blk) (Point blk) (Tip blk) m ChainSyncClientResult
, hChainSyncServer
:: NodeToNodeVersion
-> ChainDB.Follower m blk (ChainDB.WithPoint blk (SerialisedHeader blk))
-> ChainSyncServer (SerialisedHeader blk) (Point blk) (Tip blk) m ()
TODO block fetch client does not have GADT view of the handlers .
, hBlockFetchClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> FetchedMetricsTracer m
-> BlockFetchClient (Header blk) blk m ()
, hBlockFetchServer
:: NodeToNodeVersion
-> ResourceRegistry m
-> BlockFetchServer (Serialised blk) (Point blk) m ()
, hTxSubmissionClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> peer
-> TxSubmissionClient (GenTxId blk) (GenTx blk) m ()
, hTxSubmissionServer
:: NodeToNodeVersion
-> peer
-> TxSubmissionServerPipelined (GenTxId blk) (GenTx blk) m ()
, hKeepAliveClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> peer
-> StrictTVar m (Map peer PeerGSV)
-> KeepAliveInterval
-> KeepAliveClient m ()
, hKeepAliveServer
:: NodeToNodeVersion
-> peer
-> KeepAliveServer m ()
}
mkHandlers
:: forall m blk remotePeer localPeer.
( IOLike m
, MonadTime m
, MonadTimer m
, LedgerSupportsMempool blk
, HasTxId (GenTx blk)
, LedgerSupportsProtocol blk
, Ord remotePeer
)
=> NodeKernelArgs m remotePeer localPeer blk
-> NodeKernel m remotePeer localPeer blk
-> Handlers m remotePeer blk
mkHandlers
NodeKernelArgs {keepAliveRng, miniProtocolParameters}
NodeKernel {getChainDB, getMempool, getTopLevelConfig, getTracers = tracers} =
Handlers {
hChainSyncClient = \peer ->
chainSyncClient
(pipelineDecisionLowHighMark
(chainSyncPipeliningLowMark miniProtocolParameters)
(chainSyncPipeliningHighMark miniProtocolParameters))
(contramap (TraceLabelPeer peer) (Node.chainSyncClientTracer tracers))
getTopLevelConfig
(defaultChainDbView getChainDB)
, hChainSyncServer = \_version ->
chainSyncHeadersServer
(Node.chainSyncServerHeaderTracer tracers)
getChainDB
, hBlockFetchClient =
blockFetchClient
, hBlockFetchServer = \version ->
blockFetchServer
(Node.blockFetchServerTracer tracers)
getChainDB
version
, hTxSubmissionClient = \version controlMessageSTM peer ->
txSubmissionOutbound
(contramap (TraceLabelPeer peer) (Node.txOutboundTracer tracers))
(txSubmissionMaxUnacked miniProtocolParameters)
(mapTxSubmissionMempoolReader txForgetValidated $ getMempoolReader getMempool)
version
controlMessageSTM
, hTxSubmissionServer = \version peer ->
txSubmissionInbound
(contramap (TraceLabelPeer peer) (Node.txInboundTracer tracers))
(txSubmissionMaxUnacked miniProtocolParameters)
(mapTxSubmissionMempoolReader txForgetValidated $ getMempoolReader getMempool)
(getMempoolWriter getMempool)
version
, hKeepAliveClient = \_version -> keepAliveClient (Node.keepAliveClientTracer tracers) keepAliveRng
, hKeepAliveServer = \_version _peer -> keepAliveServer
}
data Codecs blk e m bCS bSCS bBF bSBF bTX bKA = Codecs {
cChainSyncCodec :: Codec (ChainSync (Header blk) (Point blk) (Tip blk)) e m bCS
, cChainSyncCodecSerialised :: Codec (ChainSync (SerialisedHeader blk) (Point blk) (Tip blk)) e m bSCS
, cBlockFetchCodec :: Codec (BlockFetch blk (Point blk)) e m bBF
, cBlockFetchCodecSerialised :: Codec (BlockFetch (Serialised blk) (Point blk)) e m bSBF
, cTxSubmission2Codec :: Codec (TxSubmission2 (GenTxId blk) (GenTx blk)) e m bTX
, cKeepAliveCodec :: Codec KeepAlive e m bKA
}
defaultCodecs :: forall m blk. (IOLike m, SerialiseNodeToNodeConstraints blk)
=> CodecConfig blk
-> BlockNodeToNodeVersion blk
-> NodeToNodeVersion
-> Codecs blk DeserialiseFailure m
ByteString ByteString ByteString ByteString ByteString ByteString
defaultCodecs ccfg version _nodeToNodeVersion = Codecs {
cChainSyncCodec =
codecChainSync
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
(encodeTip (encodeRawHash p))
(decodeTip (decodeRawHash p))
, cChainSyncCodecSerialised =
codecChainSync
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
(encodeTip (encodeRawHash p))
(decodeTip (decodeRawHash p))
, cBlockFetchCodec =
codecBlockFetch
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
, cBlockFetchCodecSerialised =
codecBlockFetch
enc
dec
(encodePoint (encodeRawHash p))
(decodePoint (decodeRawHash p))
, cTxSubmission2Codec =
codecTxSubmission2
enc
dec
enc
dec
, cKeepAliveCodec = codecKeepAlive_v2
}
where
p :: Proxy blk
p = Proxy
enc :: SerialiseNodeToNode blk a => a -> Encoding
enc = encodeNodeToNode ccfg version
dec :: SerialiseNodeToNode blk a => forall s. Decoder s a
dec = decodeNodeToNode ccfg version
identityCodecs :: Monad m
=> Codecs blk CodecFailure m
(AnyMessage (ChainSync (Header blk) (Point blk) (Tip blk)))
(AnyMessage (ChainSync (SerialisedHeader blk) (Point blk) (Tip blk)))
(AnyMessage (BlockFetch blk (Point blk)))
(AnyMessage (BlockFetch (Serialised blk) (Point blk)))
(AnyMessage (TxSubmission2 (GenTxId blk) (GenTx blk)))
(AnyMessage KeepAlive)
identityCodecs = Codecs {
cChainSyncCodec = codecChainSyncId
, cChainSyncCodecSerialised = codecChainSyncId
, cBlockFetchCodec = codecBlockFetchId
, cBlockFetchCodecSerialised = codecBlockFetchId
, cTxSubmission2Codec = codecTxSubmission2Id
, cKeepAliveCodec = codecKeepAliveId
}
Tracers
Tracers
| A record of ' Tracer 's for the different protocols .
type Tracers m peer blk e =
Tracers' peer blk e (Tracer m)
data Tracers' peer blk e f = Tracers {
tChainSyncTracer :: f (TraceLabelPeer peer (TraceSendRecv (ChainSync (Header blk) (Point blk) (Tip blk))))
, tChainSyncSerialisedTracer :: f (TraceLabelPeer peer (TraceSendRecv (ChainSync (SerialisedHeader blk) (Point blk) (Tip blk))))
, tBlockFetchTracer :: f (TraceLabelPeer peer (TraceSendRecv (BlockFetch blk (Point blk))))
, tBlockFetchSerialisedTracer :: f (TraceLabelPeer peer (TraceSendRecv (BlockFetch (Serialised blk) (Point blk))))
, tTxSubmission2Tracer :: f (TraceLabelPeer peer (TraceSendRecv (TxSubmission2 (GenTxId blk) (GenTx blk))))
}
instance (forall a. Semigroup (f a)) => Semigroup (Tracers' peer blk e f) where
l <> r = Tracers {
tChainSyncTracer = f tChainSyncTracer
, tChainSyncSerialisedTracer = f tChainSyncSerialisedTracer
, tBlockFetchTracer = f tBlockFetchTracer
, tBlockFetchSerialisedTracer = f tBlockFetchSerialisedTracer
, tTxSubmission2Tracer = f tTxSubmission2Tracer
}
where
f :: forall a. Semigroup a
=> (Tracers' peer blk e f -> a)
-> a
f prj = prj l <> prj r
nullTracers :: Monad m => Tracers m peer blk e
nullTracers = Tracers {
tChainSyncTracer = nullTracer
, tChainSyncSerialisedTracer = nullTracer
, tBlockFetchTracer = nullTracer
, tBlockFetchSerialisedTracer = nullTracer
, tTxSubmission2Tracer = nullTracer
}
showTracers :: ( Show blk
, Show peer
, Show (Header blk)
, Show (GenTx blk)
, Show (GenTxId blk)
, HasHeader blk
, HasNestedContent Header blk
)
=> Tracer m String -> Tracers m peer blk e
showTracers tr = Tracers {
tChainSyncTracer = showTracing tr
, tChainSyncSerialisedTracer = showTracing tr
, tBlockFetchTracer = showTracing tr
, tBlockFetchSerialisedTracer = showTracing tr
, tTxSubmission2Tracer = showTracing tr
}
type ClientApp m peer bytes a =
NodeToNodeVersion
-> ControlMessageSTM m
-> peer
-> Channel m bytes
-> m (a, Maybe bytes)
type ServerApp m peer bytes a =
NodeToNodeVersion
-> peer
-> Channel m bytes
-> m (a, Maybe bytes)
See ' Network . Mux . Types . MuxApplication '
data Apps m peer bCS bBF bTX bKA a b = Apps {
aChainSyncClient :: ClientApp m peer bCS a
, aChainSyncServer :: ServerApp m peer bCS b
, aBlockFetchClient :: ClientApp m peer bBF a
, aBlockFetchServer :: ServerApp m peer bBF b
, aTxSubmission2Client :: ClientApp m peer bTX a
, aTxSubmission2Server :: ServerApp m peer bTX b
, aKeepAliveClient :: ClientApp m peer bKA a
, aKeepAliveServer :: ServerApp m peer bKA b
}
block type is used , etc . ) , hence the use of ' RankNTypes ' .
data ByteLimits bCS bBF bTX bKA = ByteLimits {
blChainSync :: forall header point tip.
ProtocolSizeLimits
(ChainSync header point tip)
bCS
, blBlockFetch :: forall block point.
ProtocolSizeLimits
(BlockFetch block point)
bBF
, blTxSubmission2 :: forall txid tx.
ProtocolSizeLimits
(TxSubmission2 txid tx)
bTX
, blKeepAlive :: ProtocolSizeLimits
KeepAlive
bKA
}
noByteLimits :: ByteLimits bCS bBF bTX bKA
noByteLimits = ByteLimits {
blChainSync = byteLimitsChainSync (const 0)
, blBlockFetch = byteLimitsBlockFetch (const 0)
, blTxSubmission2 = byteLimitsTxSubmission2 (const 0)
, blKeepAlive = byteLimitsKeepAlive (const 0)
}
byteLimits :: ByteLimits ByteString ByteString ByteString ByteString
byteLimits = ByteLimits {
blChainSync = byteLimitsChainSync size
, blBlockFetch = byteLimitsBlockFetch size
, blTxSubmission2 = byteLimitsTxSubmission2 size
, blKeepAlive = byteLimitsKeepAlive size
}
where
size :: ByteString -> Word
size = (fromIntegral :: Int64 -> Word)
. BSL.length
mkApps
:: forall m remotePeer localPeer blk e bCS bBF bTX bKA.
( IOLike m
, MonadTimer m
, Ord remotePeer
, Exception e
, LedgerSupportsProtocol blk
, ShowProxy blk
, ShowProxy (Header blk)
, ShowProxy (TxId (GenTx blk))
, ShowProxy (GenTx blk)
)
-> Tracers m remotePeer blk e
-> (NodeToNodeVersion -> Codecs blk e m bCS bCS bBF bBF bTX bKA)
-> ByteLimits bCS bBF bTX bKA
-> m ChainSyncTimeout
-> ReportPeerMetrics m remotePeer
-> Handlers m remotePeer blk
-> Apps m remotePeer bCS bBF bTX bKA NodeToNodeInitiatorResult ()
mkApps kernel Tracers {..} mkCodecs ByteLimits {..} genChainSyncTimeout ReportPeerMetrics {..} Handlers {..} =
Apps {..}
where
aChainSyncClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bCS
-> m (NodeToNodeInitiatorResult, Maybe bCS)
aChainSyncClient version controlMessageSTM them channel = do
labelThisThread "ChainSyncClient"
bracketSyncWithFetchClient
(getFetchClientRegistry kernel) them $
bracketChainSyncClient
(contramap (TraceLabelPeer them) (Node.chainSyncClientTracer (getTracers kernel)))
(defaultChainDbView (getChainDB kernel))
(getNodeCandidates kernel)
them
version $ \varCandidate -> do
chainSyncTimeout <- genChainSyncTimeout
(r, trailing) <-
runPipelinedPeerWithLimits
(contramap (TraceLabelPeer them) tChainSyncTracer)
(cChainSyncCodec (mkCodecs version))
blChainSync
(timeLimitsChainSync chainSyncTimeout)
channel
$ chainSyncClientPeerPipelined
$ hChainSyncClient them version controlMessageSTM
(TraceLabelPeer them `contramap` reportHeader)
varCandidate
return (ChainSyncInitiatorResult r, trailing)
aChainSyncServer
:: NodeToNodeVersion
-> remotePeer
-> Channel m bCS
-> m ((), Maybe bCS)
aChainSyncServer version them channel = do
labelThisThread "ChainSyncServer"
chainSyncTimeout <- genChainSyncTimeout
bracketWithPrivateRegistry
(chainSyncHeaderServerFollower
(getChainDB kernel)
( case isPipeliningEnabled version of
ReceivingTentativeBlocks -> ChainDB.TentativeChain
NotReceivingTentativeBlocks -> ChainDB.SelectedChain
)
)
ChainDB.followerClose
$ \flr ->
runPeerWithLimits
(contramap (TraceLabelPeer them) tChainSyncSerialisedTracer)
(cChainSyncCodecSerialised (mkCodecs version))
blChainSync
(timeLimitsChainSync chainSyncTimeout)
channel
$ chainSyncServerPeer
$ hChainSyncServer version flr
aBlockFetchClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bBF
-> m (NodeToNodeInitiatorResult, Maybe bBF)
aBlockFetchClient version controlMessageSTM them channel = do
labelThisThread "BlockFetchClient"
bracketFetchClient (getFetchClientRegistry kernel) version
isPipeliningEnabled them $ \clientCtx -> do
((), trailing) <- runPipelinedPeerWithLimits
(contramap (TraceLabelPeer them) tBlockFetchTracer)
(cBlockFetchCodec (mkCodecs version))
blBlockFetch
timeLimitsBlockFetch
channel
$ hBlockFetchClient version controlMessageSTM
(TraceLabelPeer them `contramap` reportFetch) clientCtx
return (NoInitiatorResult, trailing)
aBlockFetchServer
:: NodeToNodeVersion
-> remotePeer
-> Channel m bBF
-> m ((), Maybe bBF)
aBlockFetchServer version them channel = do
labelThisThread "BlockFetchServer"
withRegistry $ \registry ->
runPeerWithLimits
(contramap (TraceLabelPeer them) tBlockFetchSerialisedTracer)
(cBlockFetchCodecSerialised (mkCodecs version))
blBlockFetch
timeLimitsBlockFetch
channel
$ blockFetchServerPeer
$ hBlockFetchServer version registry
aTxSubmission2Client
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bTX
-> m (NodeToNodeInitiatorResult, Maybe bTX)
aTxSubmission2Client version controlMessageSTM them channel = do
labelThisThread "TxSubmissionClient"
((), trailing) <- runPeerWithLimits
(contramap (TraceLabelPeer them) tTxSubmission2Tracer)
(cTxSubmission2Codec (mkCodecs version))
blTxSubmission2
timeLimitsTxSubmission2
channel
(txSubmissionClientPeer (hTxSubmissionClient version controlMessageSTM them))
return (NoInitiatorResult, trailing)
aTxSubmission2Server
:: NodeToNodeVersion
-> remotePeer
-> Channel m bTX
-> m ((), Maybe bTX)
aTxSubmission2Server version them channel = do
labelThisThread "TxSubmissionServer"
runPipelinedPeerWithLimits
(contramap (TraceLabelPeer them) tTxSubmission2Tracer)
(cTxSubmission2Codec (mkCodecs version))
blTxSubmission2
timeLimitsTxSubmission2
channel
(txSubmissionServerPeerPipelined (hTxSubmissionServer version them))
aKeepAliveClient
:: NodeToNodeVersion
-> ControlMessageSTM m
-> remotePeer
-> Channel m bKA
-> m (NodeToNodeInitiatorResult, Maybe bKA)
aKeepAliveClient version controlMessageSTM them channel = do
labelThisThread "KeepAliveClient"
let kacApp = \dqCtx ->
runPeerWithLimits
nullTracer
(cKeepAliveCodec (mkCodecs version))
blKeepAlive
timeLimitsKeepAlive
channel
$ keepAliveClientPeer
$ hKeepAliveClient version controlMessageSTM them dqCtx
(KeepAliveInterval 10)
((), trailing) <- bracketKeepAliveClient (getFetchClientRegistry kernel) them kacApp
return (NoInitiatorResult, trailing)
aKeepAliveServer
:: NodeToNodeVersion
-> remotePeer
-> Channel m bKA
-> m ((), Maybe bKA)
aKeepAliveServer version _them channel = do
labelThisThread "KeepAliveServer"
runPeerWithLimits
nullTracer
(cKeepAliveCodec (mkCodecs version))
TODO : Real Bytelimits , see # 1727
timeLimitsKeepAlive
channel
$ keepAliveServerPeer
$ keepAliveServer
on the protocol version , but it eventually may ; this is why @_version@ is
initiator
:: MiniProtocolParameters
-> NodeToNodeVersion
-> Apps m (ConnectionId peer) b b b b a c
-> OuroborosBundle 'InitiatorMode peer b m a Void
initiator miniProtocolParameters version Apps {..} =
nodeToNodeProtocols
miniProtocolParameters
TODO : currently consensus is using ' ConnectionId ' for its ' peer ' type .
address & port number , rather than ' ConnectionId ' ( which is
(\them controlMessageSTM -> NodeToNodeProtocols {
chainSyncProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aChainSyncClient version controlMessageSTM them))),
blockFetchProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aBlockFetchClient version controlMessageSTM them))),
txSubmissionProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aTxSubmission2Client version controlMessageSTM them))),
keepAliveProtocol =
(InitiatorProtocolOnly (MuxPeerRaw (aKeepAliveClient version controlMessageSTM them)))
})
version
on the protocol version , but it eventually may ; this is why @_version@ is
initiatorAndResponder
:: MiniProtocolParameters
-> NodeToNodeVersion
-> Apps m (ConnectionId peer) b b b b a c
-> OuroborosBundle 'InitiatorResponderMode peer b m a c
initiatorAndResponder miniProtocolParameters version Apps {..} =
nodeToNodeProtocols
miniProtocolParameters
(\them controlMessageSTM -> NodeToNodeProtocols {
chainSyncProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aChainSyncClient version controlMessageSTM them))
(MuxPeerRaw (aChainSyncServer version them))),
blockFetchProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aBlockFetchClient version controlMessageSTM them))
(MuxPeerRaw (aBlockFetchServer version them))),
txSubmissionProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aTxSubmission2Client version controlMessageSTM them))
(MuxPeerRaw (aTxSubmission2Server version them))),
keepAliveProtocol =
(InitiatorAndResponderProtocol
(MuxPeerRaw (aKeepAliveClient version controlMessageSTM them))
(MuxPeerRaw (aKeepAliveServer version them)))
})
version
|
c210fee4bc0926c20b87577d1527ecf683c1c0d5a37ddb44cb9a7dc4fd80824c | clojure-emacs/sayid | plugin.clj | (ns sayid.plugin
(:require
[clojure.java.io :as io]))
(def version
"The current version of sayid as a string."
(-> (or (io/resource "META-INF/leiningen/com.billpiel/sayid/project.clj")
"project.clj")
slurp
read-string
(nth 2)))
(defn middleware
[project]
(-> project
(update-in [:dependencies]
(fnil into [])
[['com.billpiel/sayid version]])
(update-in [:repl-options :nrepl-middleware]
(fnil into [])
['com.billpiel.sayid.nrepl-middleware/wrap-sayid])))
| null | https://raw.githubusercontent.com/clojure-emacs/sayid/27f35778de9509067716a7bed14306787334a589/src/sayid/plugin.clj | clojure | (ns sayid.plugin
(:require
[clojure.java.io :as io]))
(def version
"The current version of sayid as a string."
(-> (or (io/resource "META-INF/leiningen/com.billpiel/sayid/project.clj")
"project.clj")
slurp
read-string
(nth 2)))
(defn middleware
[project]
(-> project
(update-in [:dependencies]
(fnil into [])
[['com.billpiel/sayid version]])
(update-in [:repl-options :nrepl-middleware]
(fnil into [])
['com.billpiel.sayid.nrepl-middleware/wrap-sayid])))
| |
4cb4b2801786a1bc996df310ee9a25270e9a6b4697122b590fbf00550755502a | gulige/neuroevo | xor_send_output.erl | -module(xor_send_output).
-export([act/5]).
-include_lib("ne_common/src/include/common.hrl").
-include("records.hrl").
The function simply forwards the Output vector to the XOR simulator , and waits for the resulting Fitness and EndFlag from the simulation process .
act(ExoSelf_PId, Output, VL, _Parameters, Scape) ->
Scape ! {self(), action, Output},
receive
{Scape, Fitness, HaltFlag} ->
{Fitness, HaltFlag}
end.
| null | https://raw.githubusercontent.com/gulige/neuroevo/09e67928c2417f2b27ec6522acc82f8b3c844949/apps/neuroevo/src/actuators/xor_send_output.erl | erlang | -module(xor_send_output).
-export([act/5]).
-include_lib("ne_common/src/include/common.hrl").
-include("records.hrl").
The function simply forwards the Output vector to the XOR simulator , and waits for the resulting Fitness and EndFlag from the simulation process .
act(ExoSelf_PId, Output, VL, _Parameters, Scape) ->
Scape ! {self(), action, Output},
receive
{Scape, Fitness, HaltFlag} ->
{Fitness, HaltFlag}
end.
| |
46304962eada9b8ff07f84f4b1c1954fc07487535bc3a6a5cd2c5c89ab2dab7a | zotonic/zotonic | z_dispatcher.erl | @author < >
2009 - 2012
%% @doc Manage dispatch lists (aka definitions for url patterns). Constructs named urls from dispatch lists.
Copyright 2009 - 2012
%%
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(z_dispatcher).
-author("Marc Worrell <>").
-behaviour(gen_server).
%% gen_server exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start_link/1]).
%% z_dispatch exports
-export([
dispatcher_args/0,
url_for/2,
url_for/3,
url_for/4,
hostname/1,
hostname_port/1,
hostname_ssl_port/1,
abs_url/2,
dispatchinfo/1,
update/1,
reload/1,
reload/2,
drop_port/1
]).
-include_lib("zotonic.hrl").
-record(state, {
dispatchlist :: list(),
lookup :: dict:dict(),
context :: z:context(),
site :: atom(),
hostname :: binary() | undefined,
hostname_port :: binary() | undefined,
hostname_ssl_port :: binary() | undefined,
smtphost :: binary() | undefined,
hostalias :: list( binary() ),
redirect = true
}).
-record(dispatch_url, {url, dispatch_options}).
%%====================================================================
%% API
%%====================================================================
%% @doc A list of dispatch rule arguments that shouldn't be considered with redirects.
%% Used by controller_file_id and controller_redirect
%% TODO: this behaviour should be changed to an _inclusive_ list instead of a filter list
dispatcher_args() ->
[
is_permanent, dispatch, q, qargs,
zotonic_dispatch, ssl, protocol, session_id, set_session_id,
zotonic_dispatch_file, zotonic_dispatch_module,
auth_options, auth_expires, csp_nonce
].
) - > { ok , Pid } | ignore | { error , Error }
%% @doc Starts the dispatch server
start_link(Site) ->
Name = z_utils:name_for_site(?MODULE, Site),
gen_server:start_link({local, Name}, ?MODULE, Site, []).
( ) , Context ) - > iolist ( )
%% @doc Construct an uri from a named dispatch, assuming no parameters. Use html escape.
url_for(Name, #context{dispatcher=Dispatcher} = Context) ->
return_url(
opt_abs_url(
rewrite(gen_server:call(Dispatcher, {'url_for', Name, [], html}),
Name, [], Context),
Name, [], Context)).
( ) , , Context ) - > iolist ( )
( )
%% @doc Construct an uri from a named dispatch and the parameters. Use html escape.
url_for(Name, Args, #context{dispatcher=Dispatcher} = Context) ->
Args1 = append_extra_args(Args, Context),
return_url(
opt_abs_url(
rewrite(gen_server:call(Dispatcher, {'url_for', Name, Args1, html}),
Name, Args1, Context),
Name, Args1, Context)).
( ) , , atom ( ) , Context ) - > iolist ( )
= proplist ( )
%% @doc Construct an uri from a named dispatch and the parameters
url_for(Name, Args, Escape, #context{dispatcher=Dispatcher} = Context) ->
Args1 = append_extra_args(Args, Context),
return_url(
opt_abs_url(
rewrite(gen_server:call(Dispatcher, {'url_for', Name, Args1, Escape}),
Name, Args1, Context),
Name, Args1, Context)).
%% @doc Fetch the preferred hostname for this site
-spec hostname( z:context() ) -> binary() | undefined.
hostname(#context{ dispatcher = Dispatcher }) ->
try
gen_server:call(Dispatcher, 'hostname', infinity)
catch
exit:{noproc, {gen_server, call, _}} ->
undefined
end.
%% @doc Fetch the preferred hostname, including port, for this site
-spec hostname_port( z:context() ) -> binary() | undefined.
hostname_port(#context{dispatcher=Dispatcher}) ->
try
gen_server:call(Dispatcher, 'hostname_port', infinity)
catch
exit:{noproc, {gen_server, call, _}} ->
undefined
end.
%% @doc Fetch the preferred hostname for SSL, including port, for this site
-spec hostname_ssl_port( z:context() ) -> binary() | undefined.
hostname_ssl_port(#context{dispatcher=Dispatcher}) ->
try
gen_server:call(Dispatcher, 'hostname_ssl_port', infinity)
catch
exit:{noproc, {gen_server, call, _}} ->
undefined
end.
%% @doc Make the url an absolute url
abs_url(Url, Context) ->
abs_url(Url, undefined, [], Context).
%% @doc Fetch the dispatchlist for the site.
-spec dispatchinfo( z:context() | pid() | atom() ) ->
{ok, {atom(), binary()|string(), binary()|string(), list(), boolean(), list()}}
| {error, noproc}.
dispatchinfo(#context{dispatcher=Dispatcher}) ->
dispatchinfo(Dispatcher);
dispatchinfo(Server) when is_pid(Server) orelse is_atom(Server) ->
try
DispatchInfo = gen_server:call(Server, 'dispatchinfo', infinity),
{ok, DispatchInfo}
catch
exit:{noproc, {gen_server, call, _}} ->
{error, noproc}
end.
%% @doc Update the dispatch list but don't reload it yet. Used when flushing all sites, see z:flush/0
update(#context{dispatcher=Dispatcher}) ->
gen_server:call(Dispatcher, 'reload', infinity).
%% @doc Reload all dispatch lists. Finds new dispatch lists and adds them to the dispatcher
reload(#context{dispatcher=Dispatcher}) ->
gen_server:call(Dispatcher, 'reload', infinity),
z_sites_dispatcher:update_dispatchinfo().
reload(module_ready, Context) ->
reload(Context).
%%====================================================================
%% Support routines, called outside the gen_server
%%====================================================================
%% @doc Rewrite the generated urls. Checks for zotonic_http_accept and checks modules.
rewrite(#dispatch_url{url = undefined} = D, _Dispatch, _Args, _Context) ->
D;
rewrite(#dispatch_url{url = Url} = D, Dispatch, Args, Context) ->
Url1 = iolist_to_binary(Url),
Url2 = check_http_options(Url1, Args),
D#dispatch_url{
url = z_notifier:foldl(#url_rewrite{dispatch = Dispatch, args = Args}, Url2, Context)
}.
check_http_options(Url, Args) ->
case lists:keyfind(zotonic_http_accept, 1, Args) of
{zotonic_http_accept, undefined} ->
Url;
{zotonic_http_accept, Mime} ->
Mime1 = cow_qs:urlencode(z_convert:to_binary(Mime)),
<<"/http-accept/", Mime1/binary, Url/binary>>;
false ->
Url
end.
%% @doc Optionally make the url an absolute url
opt_abs_url(#dispatch_url{url=undefined} = D, _Dispatch, _Args, _Context) ->
D;
opt_abs_url(#dispatch_url{url=Url, dispatch_options=DispatchOptions} = D, Dispatch, Args, Context) ->
case use_absolute_url(Args, DispatchOptions, Context) of
true -> D#dispatch_url{url=abs_url(Url, Dispatch, DispatchOptions, Context)};
false -> D
end.
abs_url(Url, Dispatch, DispatchOptions, Context) ->
case z_notifier:first(#url_abs{dispatch=Dispatch, url=Url, dispatch_options=DispatchOptions}, Context) of
undefined -> z_convert:to_binary(z_context:abs_url(Url, Context));
AbsUrl -> z_convert:to_binary(AbsUrl)
end.
%% @doc Convenience function, just return the generated Url
return_url(#dispatch_url{url=Url}) -> Url.
%% @doc Check if an url should be made an absolute url
use_absolute_url(Args, Options, Context) ->
case to_bool(proplists:get_value(absolute_url, Args)) of
false -> false;
true -> true;
undefined ->
case to_bool(proplists:get_value(absolute_url, Options)) of
false -> false;
true -> true;
undefined ->
case to_bool(z_context:get(absolute_url, Context)) of
false -> false;
true -> true;
undefined -> false
end
end
end.
to_bool(undefined) -> undefined;
to_bool(N) -> z_convert:to_bool(N).
%%====================================================================
%% gen_server callbacks
%%====================================================================
) - > { ok , State } |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% @doc Initiates the server, loads the dispatch list into the webmachine dispatcher
init(Site) ->
logger:set_process_metadata(#{
site => Site,
module => ?MODULE
}),
Context = z_context:new(Site),
Hostname0 = m_site:get(hostname, Context),
Hostname = drop_port(Hostname0),
Smtphost = drop_port(m_site:get(smtphost, Context)),
HostAlias = case m_site:get(hostalias, Context) of
undefined -> [];
HA -> HA
end,
Alias = lists:filtermap(
fun(Alias) ->
case drop_port(Alias) of
undefined -> false;
Alias1 -> {true, Alias1}
end
end,
HostAlias),
process_flag(trap_exit, true),
IsRedirect = case m_site:get(redirect, Context) of
undefined -> true;
R -> z_convert:to_bool(R)
end,
State = #state{
dispatchlist = [],
lookup = dict:new(),
context = Context,
site = Site,
smtphost = Smtphost,
hostname = Hostname,
hostname_port = add_port(Hostname, http, z_config:get(port)),
hostname_ssl_port = add_port(Hostname, https, z_config:get(ssl_port)),
hostalias = Alias,
redirect = IsRedirect
},
z_notifier:observe(module_ready, {?MODULE, reload}, Context),
{ok, State}.
% @doc Drop the portnumber from the hostname
%
-spec drop_port( undefined | none | string() | binary() ) -> undefined | binary().
drop_port(undefined) -> undefined;
drop_port(none) -> undefined;
drop_port(<<>>) -> undefined;
drop_port(Hostname) when is_binary(Hostname) ->
hd(binary:split(Hostname, <<":">>));
drop_port(Hostname) when is_list(Hostname) ->
drop_port(z_convert:to_binary(Hostname)).
-spec add_port( binary() | undefined, http | https, pos_integer() ) -> binary().
add_port(undefined, _Protocol, _Port) -> undefined;
add_port(_Hostname, _Protocol, none) -> undefined;
add_port(Hostname, http, 80) -> Hostname;
add_port(Hostname, https, 443) -> Hostname;
add_port(Hostname, _, Port) ->
iolist_to_binary([ Hostname, $:, integer_to_list(Port) ]).
, From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
@doc Create the url for the dispatch rule with name and arguments .
handle_call({'url_for', Name, Args, Escape}, _From, State) ->
Uri = make_url_for(Name, Args, Escape, State#state.lookup),
{reply, Uri, State};
%% @doc Return the preferred hostname for the site
handle_call('hostname', _From, State) ->
{reply, State#state.hostname, State};
%% @doc Return the preferred hostname, and port, for the site
handle_call('hostname_port', _From, State) ->
{reply, State#state.hostname_port, State};
%% @doc Return the preferred hostname for ssl, and port, for the site
handle_call('hostname_ssl_port', _From, State) ->
{reply, State#state.hostname_ssl_port, State};
%% @doc Return the dispatchinfo for the site {site, hostname, smtphost, hostaliases, redirect, dispatchlist}
handle_call('dispatchinfo', _From, State) ->
{reply,
{State#state.site, State#state.hostname, State#state.smtphost,
State#state.hostalias, State#state.redirect, State#state.dispatchlist},
State};
%% @doc Reload the dispatch list, signal the sites supervisor that the dispatch list has been changed.
%% The site supervisor will collect all dispatch lists and send them at once to webmachine.
handle_call('reload', _From, State) ->
State1 = reload_dispatch_list(State),
{reply, ok, State1}.
@spec handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
handle_cast(_Msg, State) ->
{noreply, State}.
, State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% @doc Handling all non call/cast messages
handle_info(_Info, State) ->
{noreply, State}.
, State ) - > void ( )
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
terminate(_Reason, State) ->
z_notifier:detach(module_ready, State#state.context),
ok.
, State , Extra ) - > { ok , NewState }
%% @doc Convert process state when code is changed
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%====================================================================
%% support functions
%%====================================================================
%% @doc Reload the dispatch list and send it to the webmachine dispatcher.
reload_dispatch_list(#state{context=Context} = State) ->
DispatchList = try
collect_dispatch_lists(Context)
catch
_:{error, _Msg} ->
State#state.dispatchlist
end,
LookupDict = dispatch_for_uri_lookup(DispatchList),
State#state{dispatchlist=DispatchList, lookup=LookupDict}.
%% @doc Collect all dispatch lists. Checks priv/dispatch for all dispatch list definitions.
collect_dispatch_lists(Context) ->
ModDispOnPrio = lists:concat(
lists:map(
fun({Mod, ModFiles}) ->
lists:sort( [ {F, Mod} || F <- ModFiles ] )
end,
z_module_indexer:dispatch(Context))
),
Dispatch = lists:map(fun get_file_dispatch/1, ModDispOnPrio),
lists:flatten(Dispatch).
@doc Read a dispatch file , the file should contain a valid Erlang dispatch datastructure .
@spec get_file_dispatch(filename ( ) ) - > DispatchList
get_file_dispatch({File, Mod}) ->
try
case filelib:is_regular(File)
andalso not zotonic_filewatcher_handler:is_file_blocked(File)
of
true ->
Basename = filename:basename(File),
case Basename of
"." ++ _ ->
[];
_Other ->
{ok, Disp} = file:consult(File),
add_mod_to_options(Disp, Mod, filename:basename(File))
end;
false ->
[]
end
catch
M:E ->
?LOG_ERROR(#{
text => <<"File dispatch error">>,
in => zotonic_core,
file => File,
result => M,
reason => E
}),
throw({error, "Parse error in " ++ z_convert:to_list(File)})
end.
add_mod_to_options(Disp, Mod, Filename) ->
F = z_convert:to_binary(Filename),
lists:map(
fun(Ds) ->
lists:map(
fun({Name, Path, Controller, Opts}) ->
Opts1 = [
{zotonic_dispatch_module, Mod},
{zotonic_dispatch_file, F}
| Opts
],
{Name, Path, Controller, Opts1}
end,
Ds)
end,
Disp).
%% @doc Transform the dispatchlist into a datastructure for building uris from name/vars
Datastructure needed is : name - > [ vars , pattern ]
dispatch_for_uri_lookup(DispatchList) ->
dispatch_for_uri_lookup1(DispatchList, dict:new()).
dispatch_for_uri_lookup1([], Dict) ->
Dict;
dispatch_for_uri_lookup1([{Name, Pattern, Controller, DispatchOptions}|T], Dict)
when is_atom(Name), is_list(Pattern), is_atom(Controller), is_list(DispatchOptions) ->
Vars = lists:foldl(fun(A, Acc) when is_atom(A) -> [A|Acc];
({A,_RegExp}, Acc) when is_atom(A) -> [A|Acc];
(_, Acc) -> Acc
end,
[],
Pattern),
Dict1 = case dict:is_key(Name, Dict) of
true -> dict:append(Name, {length(Vars), Vars, Pattern, DispatchOptions}, Dict);
false -> dict:store(Name, [{length(Vars), Vars, Pattern, DispatchOptions}], Dict)
end,
dispatch_for_uri_lookup1(T, Dict1);
dispatch_for_uri_lookup1([IllegalDispatch|T], Dict) ->
?LOG_ERROR(#{
text => <<"Dispatcher dropping malformed dispatch rule">>,
in => zotonic_core,
result => error,
reason => malformed,
dispatch_rule => IllegalDispatch
}),
dispatch_for_uri_lookup1(T, Dict).
%% @doc Make an uri for the named dispatch with the given parameters
make_url_for(Name, Args, Escape, UriLookup) ->
Name1 = z_convert:to_atom(Name),
Args1 = filter_empty_args(Args),
case dict:find(Name1, UriLookup) of
{ok, Patterns} ->
case make_url_for1(Args1, Patterns, Escape, undefined) of
#dispatch_url{ url = undefined } = DispUrl when Name =/= image->
?LOG_INFO(#{
text => <<"Dispatcher make_url_for failed">>,
in => zotonic_core,
dispatch_rule => Name1,
args => Args1,
patterns => Patterns,
escape => Escape
}),
DispUrl;
DispUrl ->
DispUrl
end;
error ->
#dispatch_url{}
end.
%% @doc Filter out empty dispatch arguments before making an URL.
filter_empty_args(Args) ->
lists:filter(
fun
({_, <<>>}) -> false;
({_, []}) -> false;
({_, undefined}) -> false;
({absolute_url, _}) -> false;
(absolute_url) -> false;
({zotonic_http_accept, _}) -> false;
(_) -> true
end, Args).
%% @doc Try to match all patterns with the arguments
make_url_for1(_Args, [], _Escape, undefined) ->
#dispatch_url{};
make_url_for1(Args, [], Escape, {QueryStringArgs, Pattern, DispOpts}) ->
ReplArgs = fun
('*') -> path_argval('*', Args);
(V) when is_atom(V) -> path_argval(V, Args);
({V, _Pattern}) when is_atom(V) ->
mochiweb_util:quote_plus(path_argval(V, Args));
(S) ->
S
end,
UriParts = lists:map(ReplArgs, Pattern),
Uri = [$/ | lists:join($/, UriParts)],
case QueryStringArgs of
[] ->
#dispatch_url{
url=z_convert:to_binary(Uri),
dispatch_options=DispOpts
};
_ ->
Sep = case Escape of
xml -> "&";
html -> "&";
_ -> $&
end,
#dispatch_url{
url=z_convert:to_binary([Uri, $?, urlencode(QueryStringArgs, Sep)]),
dispatch_options=DispOpts
}
end;
make_url_for1(Args, [Pattern|T], Escape, Best) ->
Best1 = select_best_pattern(Args, Pattern, Best),
make_url_for1(Args, T, Escape, Best1).
path_argval('*', Args) ->
case proplists:get_value(star, Args) of
undefined -> <<>>;
L when is_list(L) ->
List1 = [ cow_qs:urlencode(z_convert:to_binary(B)) || B <- L ],
lists:join($/, List1);
V ->
z_convert:to_binary(V)
end;
path_argval(Arg, Args) ->
B = z_convert:to_binary(proplists:get_value(Arg, Args, <<"-">>)),
cow_qs:urlencode(B).
select_best_pattern(Args, {PCount, PArgs, Pattern, DispOpts}, Best) ->
if
length(Args) >= PCount ->
Check if all PArgs are part of
{PathArgs, QueryStringArgs} = lists:partition(
fun
({star,_}) -> lists:member('*', PArgs);
({A,_}) -> lists:member(A, PArgs)
end, Args),
case length(PathArgs) of
PCount ->
% Could fill all path args, this match satisfies
select_best_pattern1({QueryStringArgs,Pattern,DispOpts}, Best);
_ ->
Best
end;
true ->
Best
end.
select_best_pattern1(A, undefined) ->
A;
select_best_pattern1({AQS, _APat, _AOpts}=A, {BQS, _BPat, _BOpts}=B) ->
if
length(BQS) > length(AQS) -> A;
true -> B
end.
@spec urlencode([{Key , Value } ] , Join ) - > string ( )
%% @doc URL encode the property list.
urlencode(Props, Join) ->
RevPairs = lists:foldl(fun ({K, V}, Acc) ->
[[mochiweb_util:quote_plus(K), $=, mochiweb_util:quote_plus(V)] | Acc]
end, [], Props),
lists:flatten(revjoin(RevPairs, Join, [])).
revjoin([], _Separator, Acc) ->
Acc;
revjoin([S | Rest], Separator, []) ->
revjoin(Rest, Separator, [S]);
revjoin([S | Rest], Separator, Acc) ->
revjoin(Rest, Separator, [S, Separator | Acc]).
@doc Append extra arguments to the url , depending if ' qargs ' or ' ' is set .
append_extra_args(Args, Context) when is_map(Args) ->
append_extra_args(maps:to_list(Args), Context);
append_extra_args(Args, Context) ->
append_qargs(append_varargs(Args, Context), Context).
%% @doc Append all query arguments iff they are not mentioned in the arglist and if qargs parameter is set
append_qargs(Args, Context) ->
case proplists:get_value(qargs, Args) of
undefined ->
Args;
false ->
proplists:delete(qargs, Args);
true ->
Args1 = proplists:delete(qargs, Args),
merge_qargs(z_context:get_qargs(Context), Args1);
L when is_list(L) ->
Args1 = proplists:delete(qargs, Args),
merge_qargs(L, Args1);
M when is_map(M) ->
Args1 = proplists:delete(qargs, Args),
merge_qargs(maps:to_list(M), Args1)
end.
merge_qargs([], Args) ->
Args;
merge_qargs(Qs, Args) ->
Ks = [ z_convert:to_binary(A) || {A, _} <- Args ],
lists:foldr(
fun({A, _} = AV, Acc) ->
case lists:member(A, Ks) of
true ->
Acc;
false ->
[ AV | Acc ]
end
end,
Args,
Qs).
@doc Append all argument , names are given in a list .
append_varargs(Args, Context) ->
case proplists:get_value(varargs, Args) of
undefined ->
Args;
Varargs ->
append_varargs(Varargs, proplists:delete(varargs, Args), Context)
end.
append_varargs([], Args, _Context) ->
Args;
append_varargs([{Name, Value}|Varargs], Args, Context) ->
append_varargs(Varargs, append_vararg(Name, Value, Args), Context);
append_varargs([[Name, Value]|Varargs], Args, Context) ->
append_varargs(Varargs, append_vararg(Name, Value, Args), Context);
append_varargs([Name|Varargs], Args, Context) ->
Key = z_convert:to_atom(Name),
append_varargs(Varargs, append_vararg(Key, z_context:get(Key, Context), Args), Context).
append_vararg(Name, Value, Args) ->
Key = z_convert:to_atom(Name),
case proplists:is_defined(Key, Args) of
true -> Args;
false -> [{Key, Value}|Args]
end.
| null | https://raw.githubusercontent.com/zotonic/zotonic/0f977d08bfbf4b2441eab9d1c41dd25286ff164f/apps/zotonic_core/src/support/z_dispatcher.erl | erlang | @doc Manage dispatch lists (aka definitions for url patterns). Constructs named urls from dispatch lists.
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.
gen_server exports
z_dispatch exports
====================================================================
API
====================================================================
@doc A list of dispatch rule arguments that shouldn't be considered with redirects.
Used by controller_file_id and controller_redirect
TODO: this behaviour should be changed to an _inclusive_ list instead of a filter list
@doc Starts the dispatch server
@doc Construct an uri from a named dispatch, assuming no parameters. Use html escape.
@doc Construct an uri from a named dispatch and the parameters. Use html escape.
@doc Construct an uri from a named dispatch and the parameters
@doc Fetch the preferred hostname for this site
@doc Fetch the preferred hostname, including port, for this site
@doc Fetch the preferred hostname for SSL, including port, for this site
@doc Make the url an absolute url
@doc Fetch the dispatchlist for the site.
@doc Update the dispatch list but don't reload it yet. Used when flushing all sites, see z:flush/0
@doc Reload all dispatch lists. Finds new dispatch lists and adds them to the dispatcher
====================================================================
Support routines, called outside the gen_server
====================================================================
@doc Rewrite the generated urls. Checks for zotonic_http_accept and checks modules.
@doc Optionally make the url an absolute url
@doc Convenience function, just return the generated Url
@doc Check if an url should be made an absolute url
====================================================================
gen_server callbacks
====================================================================
ignore |
{stop, Reason}
@doc Initiates the server, loads the dispatch list into the webmachine dispatcher
@doc Drop the portnumber from the hostname
{stop, Reason, Reply, State} |
{stop, Reason, State}
@doc Return the preferred hostname for the site
@doc Return the preferred hostname, and port, for the site
@doc Return the preferred hostname for ssl, and port, for the site
@doc Return the dispatchinfo for the site {site, hostname, smtphost, hostaliases, redirect, dispatchlist}
@doc Reload the dispatch list, signal the sites supervisor that the dispatch list has been changed.
The site supervisor will collect all dispatch lists and send them at once to webmachine.
{stop, Reason, State}
{stop, Reason, State}
@doc Handling all non call/cast messages
@doc This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
@doc Convert process state when code is changed
====================================================================
support functions
====================================================================
@doc Reload the dispatch list and send it to the webmachine dispatcher.
@doc Collect all dispatch lists. Checks priv/dispatch for all dispatch list definitions.
@doc Transform the dispatchlist into a datastructure for building uris from name/vars
@doc Make an uri for the named dispatch with the given parameters
@doc Filter out empty dispatch arguments before making an URL.
@doc Try to match all patterns with the arguments
Could fill all path args, this match satisfies
@doc URL encode the property list.
@doc Append all query arguments iff they are not mentioned in the arglist and if qargs parameter is set | @author < >
2009 - 2012
Copyright 2009 - 2012
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(z_dispatcher).
-author("Marc Worrell <>").
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start_link/1]).
-export([
dispatcher_args/0,
url_for/2,
url_for/3,
url_for/4,
hostname/1,
hostname_port/1,
hostname_ssl_port/1,
abs_url/2,
dispatchinfo/1,
update/1,
reload/1,
reload/2,
drop_port/1
]).
-include_lib("zotonic.hrl").
-record(state, {
dispatchlist :: list(),
lookup :: dict:dict(),
context :: z:context(),
site :: atom(),
hostname :: binary() | undefined,
hostname_port :: binary() | undefined,
hostname_ssl_port :: binary() | undefined,
smtphost :: binary() | undefined,
hostalias :: list( binary() ),
redirect = true
}).
-record(dispatch_url, {url, dispatch_options}).
dispatcher_args() ->
[
is_permanent, dispatch, q, qargs,
zotonic_dispatch, ssl, protocol, session_id, set_session_id,
zotonic_dispatch_file, zotonic_dispatch_module,
auth_options, auth_expires, csp_nonce
].
) - > { ok , Pid } | ignore | { error , Error }
start_link(Site) ->
Name = z_utils:name_for_site(?MODULE, Site),
gen_server:start_link({local, Name}, ?MODULE, Site, []).
( ) , Context ) - > iolist ( )
url_for(Name, #context{dispatcher=Dispatcher} = Context) ->
return_url(
opt_abs_url(
rewrite(gen_server:call(Dispatcher, {'url_for', Name, [], html}),
Name, [], Context),
Name, [], Context)).
( ) , , Context ) - > iolist ( )
( )
url_for(Name, Args, #context{dispatcher=Dispatcher} = Context) ->
Args1 = append_extra_args(Args, Context),
return_url(
opt_abs_url(
rewrite(gen_server:call(Dispatcher, {'url_for', Name, Args1, html}),
Name, Args1, Context),
Name, Args1, Context)).
( ) , , atom ( ) , Context ) - > iolist ( )
= proplist ( )
url_for(Name, Args, Escape, #context{dispatcher=Dispatcher} = Context) ->
Args1 = append_extra_args(Args, Context),
return_url(
opt_abs_url(
rewrite(gen_server:call(Dispatcher, {'url_for', Name, Args1, Escape}),
Name, Args1, Context),
Name, Args1, Context)).
-spec hostname( z:context() ) -> binary() | undefined.
hostname(#context{ dispatcher = Dispatcher }) ->
try
gen_server:call(Dispatcher, 'hostname', infinity)
catch
exit:{noproc, {gen_server, call, _}} ->
undefined
end.
-spec hostname_port( z:context() ) -> binary() | undefined.
hostname_port(#context{dispatcher=Dispatcher}) ->
try
gen_server:call(Dispatcher, 'hostname_port', infinity)
catch
exit:{noproc, {gen_server, call, _}} ->
undefined
end.
-spec hostname_ssl_port( z:context() ) -> binary() | undefined.
hostname_ssl_port(#context{dispatcher=Dispatcher}) ->
try
gen_server:call(Dispatcher, 'hostname_ssl_port', infinity)
catch
exit:{noproc, {gen_server, call, _}} ->
undefined
end.
abs_url(Url, Context) ->
abs_url(Url, undefined, [], Context).
-spec dispatchinfo( z:context() | pid() | atom() ) ->
{ok, {atom(), binary()|string(), binary()|string(), list(), boolean(), list()}}
| {error, noproc}.
dispatchinfo(#context{dispatcher=Dispatcher}) ->
dispatchinfo(Dispatcher);
dispatchinfo(Server) when is_pid(Server) orelse is_atom(Server) ->
try
DispatchInfo = gen_server:call(Server, 'dispatchinfo', infinity),
{ok, DispatchInfo}
catch
exit:{noproc, {gen_server, call, _}} ->
{error, noproc}
end.
update(#context{dispatcher=Dispatcher}) ->
gen_server:call(Dispatcher, 'reload', infinity).
reload(#context{dispatcher=Dispatcher}) ->
gen_server:call(Dispatcher, 'reload', infinity),
z_sites_dispatcher:update_dispatchinfo().
reload(module_ready, Context) ->
reload(Context).
rewrite(#dispatch_url{url = undefined} = D, _Dispatch, _Args, _Context) ->
D;
rewrite(#dispatch_url{url = Url} = D, Dispatch, Args, Context) ->
Url1 = iolist_to_binary(Url),
Url2 = check_http_options(Url1, Args),
D#dispatch_url{
url = z_notifier:foldl(#url_rewrite{dispatch = Dispatch, args = Args}, Url2, Context)
}.
check_http_options(Url, Args) ->
case lists:keyfind(zotonic_http_accept, 1, Args) of
{zotonic_http_accept, undefined} ->
Url;
{zotonic_http_accept, Mime} ->
Mime1 = cow_qs:urlencode(z_convert:to_binary(Mime)),
<<"/http-accept/", Mime1/binary, Url/binary>>;
false ->
Url
end.
opt_abs_url(#dispatch_url{url=undefined} = D, _Dispatch, _Args, _Context) ->
D;
opt_abs_url(#dispatch_url{url=Url, dispatch_options=DispatchOptions} = D, Dispatch, Args, Context) ->
case use_absolute_url(Args, DispatchOptions, Context) of
true -> D#dispatch_url{url=abs_url(Url, Dispatch, DispatchOptions, Context)};
false -> D
end.
abs_url(Url, Dispatch, DispatchOptions, Context) ->
case z_notifier:first(#url_abs{dispatch=Dispatch, url=Url, dispatch_options=DispatchOptions}, Context) of
undefined -> z_convert:to_binary(z_context:abs_url(Url, Context));
AbsUrl -> z_convert:to_binary(AbsUrl)
end.
return_url(#dispatch_url{url=Url}) -> Url.
use_absolute_url(Args, Options, Context) ->
case to_bool(proplists:get_value(absolute_url, Args)) of
false -> false;
true -> true;
undefined ->
case to_bool(proplists:get_value(absolute_url, Options)) of
false -> false;
true -> true;
undefined ->
case to_bool(z_context:get(absolute_url, Context)) of
false -> false;
true -> true;
undefined -> false
end
end
end.
to_bool(undefined) -> undefined;
to_bool(N) -> z_convert:to_bool(N).
) - > { ok , State } |
{ ok , State , Timeout } |
init(Site) ->
logger:set_process_metadata(#{
site => Site,
module => ?MODULE
}),
Context = z_context:new(Site),
Hostname0 = m_site:get(hostname, Context),
Hostname = drop_port(Hostname0),
Smtphost = drop_port(m_site:get(smtphost, Context)),
HostAlias = case m_site:get(hostalias, Context) of
undefined -> [];
HA -> HA
end,
Alias = lists:filtermap(
fun(Alias) ->
case drop_port(Alias) of
undefined -> false;
Alias1 -> {true, Alias1}
end
end,
HostAlias),
process_flag(trap_exit, true),
IsRedirect = case m_site:get(redirect, Context) of
undefined -> true;
R -> z_convert:to_bool(R)
end,
State = #state{
dispatchlist = [],
lookup = dict:new(),
context = Context,
site = Site,
smtphost = Smtphost,
hostname = Hostname,
hostname_port = add_port(Hostname, http, z_config:get(port)),
hostname_ssl_port = add_port(Hostname, https, z_config:get(ssl_port)),
hostalias = Alias,
redirect = IsRedirect
},
z_notifier:observe(module_ready, {?MODULE, reload}, Context),
{ok, State}.
-spec drop_port( undefined | none | string() | binary() ) -> undefined | binary().
drop_port(undefined) -> undefined;
drop_port(none) -> undefined;
drop_port(<<>>) -> undefined;
drop_port(Hostname) when is_binary(Hostname) ->
hd(binary:split(Hostname, <<":">>));
drop_port(Hostname) when is_list(Hostname) ->
drop_port(z_convert:to_binary(Hostname)).
-spec add_port( binary() | undefined, http | https, pos_integer() ) -> binary().
add_port(undefined, _Protocol, _Port) -> undefined;
add_port(_Hostname, _Protocol, none) -> undefined;
add_port(Hostname, http, 80) -> Hostname;
add_port(Hostname, https, 443) -> Hostname;
add_port(Hostname, _, Port) ->
iolist_to_binary([ Hostname, $:, integer_to_list(Port) ]).
, From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
@doc Create the url for the dispatch rule with name and arguments .
handle_call({'url_for', Name, Args, Escape}, _From, State) ->
Uri = make_url_for(Name, Args, Escape, State#state.lookup),
{reply, Uri, State};
handle_call('hostname', _From, State) ->
{reply, State#state.hostname, State};
handle_call('hostname_port', _From, State) ->
{reply, State#state.hostname_port, State};
handle_call('hostname_ssl_port', _From, State) ->
{reply, State#state.hostname_ssl_port, State};
handle_call('dispatchinfo', _From, State) ->
{reply,
{State#state.site, State#state.hostname, State#state.smtphost,
State#state.hostalias, State#state.redirect, State#state.dispatchlist},
State};
handle_call('reload', _From, State) ->
State1 = reload_dispatch_list(State),
{reply, ok, State1}.
@spec handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(_Msg, State) ->
{noreply, State}.
, State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info(_Info, State) ->
{noreply, State}.
, State ) - > void ( )
terminate(_Reason, State) ->
z_notifier:detach(module_ready, State#state.context),
ok.
, State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
reload_dispatch_list(#state{context=Context} = State) ->
DispatchList = try
collect_dispatch_lists(Context)
catch
_:{error, _Msg} ->
State#state.dispatchlist
end,
LookupDict = dispatch_for_uri_lookup(DispatchList),
State#state{dispatchlist=DispatchList, lookup=LookupDict}.
collect_dispatch_lists(Context) ->
ModDispOnPrio = lists:concat(
lists:map(
fun({Mod, ModFiles}) ->
lists:sort( [ {F, Mod} || F <- ModFiles ] )
end,
z_module_indexer:dispatch(Context))
),
Dispatch = lists:map(fun get_file_dispatch/1, ModDispOnPrio),
lists:flatten(Dispatch).
@doc Read a dispatch file , the file should contain a valid Erlang dispatch datastructure .
@spec get_file_dispatch(filename ( ) ) - > DispatchList
get_file_dispatch({File, Mod}) ->
try
case filelib:is_regular(File)
andalso not zotonic_filewatcher_handler:is_file_blocked(File)
of
true ->
Basename = filename:basename(File),
case Basename of
"." ++ _ ->
[];
_Other ->
{ok, Disp} = file:consult(File),
add_mod_to_options(Disp, Mod, filename:basename(File))
end;
false ->
[]
end
catch
M:E ->
?LOG_ERROR(#{
text => <<"File dispatch error">>,
in => zotonic_core,
file => File,
result => M,
reason => E
}),
throw({error, "Parse error in " ++ z_convert:to_list(File)})
end.
add_mod_to_options(Disp, Mod, Filename) ->
F = z_convert:to_binary(Filename),
lists:map(
fun(Ds) ->
lists:map(
fun({Name, Path, Controller, Opts}) ->
Opts1 = [
{zotonic_dispatch_module, Mod},
{zotonic_dispatch_file, F}
| Opts
],
{Name, Path, Controller, Opts1}
end,
Ds)
end,
Disp).
Datastructure needed is : name - > [ vars , pattern ]
dispatch_for_uri_lookup(DispatchList) ->
dispatch_for_uri_lookup1(DispatchList, dict:new()).
dispatch_for_uri_lookup1([], Dict) ->
Dict;
dispatch_for_uri_lookup1([{Name, Pattern, Controller, DispatchOptions}|T], Dict)
when is_atom(Name), is_list(Pattern), is_atom(Controller), is_list(DispatchOptions) ->
Vars = lists:foldl(fun(A, Acc) when is_atom(A) -> [A|Acc];
({A,_RegExp}, Acc) when is_atom(A) -> [A|Acc];
(_, Acc) -> Acc
end,
[],
Pattern),
Dict1 = case dict:is_key(Name, Dict) of
true -> dict:append(Name, {length(Vars), Vars, Pattern, DispatchOptions}, Dict);
false -> dict:store(Name, [{length(Vars), Vars, Pattern, DispatchOptions}], Dict)
end,
dispatch_for_uri_lookup1(T, Dict1);
dispatch_for_uri_lookup1([IllegalDispatch|T], Dict) ->
?LOG_ERROR(#{
text => <<"Dispatcher dropping malformed dispatch rule">>,
in => zotonic_core,
result => error,
reason => malformed,
dispatch_rule => IllegalDispatch
}),
dispatch_for_uri_lookup1(T, Dict).
make_url_for(Name, Args, Escape, UriLookup) ->
Name1 = z_convert:to_atom(Name),
Args1 = filter_empty_args(Args),
case dict:find(Name1, UriLookup) of
{ok, Patterns} ->
case make_url_for1(Args1, Patterns, Escape, undefined) of
#dispatch_url{ url = undefined } = DispUrl when Name =/= image->
?LOG_INFO(#{
text => <<"Dispatcher make_url_for failed">>,
in => zotonic_core,
dispatch_rule => Name1,
args => Args1,
patterns => Patterns,
escape => Escape
}),
DispUrl;
DispUrl ->
DispUrl
end;
error ->
#dispatch_url{}
end.
filter_empty_args(Args) ->
lists:filter(
fun
({_, <<>>}) -> false;
({_, []}) -> false;
({_, undefined}) -> false;
({absolute_url, _}) -> false;
(absolute_url) -> false;
({zotonic_http_accept, _}) -> false;
(_) -> true
end, Args).
make_url_for1(_Args, [], _Escape, undefined) ->
#dispatch_url{};
make_url_for1(Args, [], Escape, {QueryStringArgs, Pattern, DispOpts}) ->
ReplArgs = fun
('*') -> path_argval('*', Args);
(V) when is_atom(V) -> path_argval(V, Args);
({V, _Pattern}) when is_atom(V) ->
mochiweb_util:quote_plus(path_argval(V, Args));
(S) ->
S
end,
UriParts = lists:map(ReplArgs, Pattern),
Uri = [$/ | lists:join($/, UriParts)],
case QueryStringArgs of
[] ->
#dispatch_url{
url=z_convert:to_binary(Uri),
dispatch_options=DispOpts
};
_ ->
Sep = case Escape of
xml -> "&";
html -> "&";
_ -> $&
end,
#dispatch_url{
url=z_convert:to_binary([Uri, $?, urlencode(QueryStringArgs, Sep)]),
dispatch_options=DispOpts
}
end;
make_url_for1(Args, [Pattern|T], Escape, Best) ->
Best1 = select_best_pattern(Args, Pattern, Best),
make_url_for1(Args, T, Escape, Best1).
path_argval('*', Args) ->
case proplists:get_value(star, Args) of
undefined -> <<>>;
L when is_list(L) ->
List1 = [ cow_qs:urlencode(z_convert:to_binary(B)) || B <- L ],
lists:join($/, List1);
V ->
z_convert:to_binary(V)
end;
path_argval(Arg, Args) ->
B = z_convert:to_binary(proplists:get_value(Arg, Args, <<"-">>)),
cow_qs:urlencode(B).
select_best_pattern(Args, {PCount, PArgs, Pattern, DispOpts}, Best) ->
if
length(Args) >= PCount ->
Check if all PArgs are part of
{PathArgs, QueryStringArgs} = lists:partition(
fun
({star,_}) -> lists:member('*', PArgs);
({A,_}) -> lists:member(A, PArgs)
end, Args),
case length(PathArgs) of
PCount ->
select_best_pattern1({QueryStringArgs,Pattern,DispOpts}, Best);
_ ->
Best
end;
true ->
Best
end.
select_best_pattern1(A, undefined) ->
A;
select_best_pattern1({AQS, _APat, _AOpts}=A, {BQS, _BPat, _BOpts}=B) ->
if
length(BQS) > length(AQS) -> A;
true -> B
end.
@spec urlencode([{Key , Value } ] , Join ) - > string ( )
urlencode(Props, Join) ->
RevPairs = lists:foldl(fun ({K, V}, Acc) ->
[[mochiweb_util:quote_plus(K), $=, mochiweb_util:quote_plus(V)] | Acc]
end, [], Props),
lists:flatten(revjoin(RevPairs, Join, [])).
revjoin([], _Separator, Acc) ->
Acc;
revjoin([S | Rest], Separator, []) ->
revjoin(Rest, Separator, [S]);
revjoin([S | Rest], Separator, Acc) ->
revjoin(Rest, Separator, [S, Separator | Acc]).
@doc Append extra arguments to the url , depending if ' qargs ' or ' ' is set .
append_extra_args(Args, Context) when is_map(Args) ->
append_extra_args(maps:to_list(Args), Context);
append_extra_args(Args, Context) ->
append_qargs(append_varargs(Args, Context), Context).
append_qargs(Args, Context) ->
case proplists:get_value(qargs, Args) of
undefined ->
Args;
false ->
proplists:delete(qargs, Args);
true ->
Args1 = proplists:delete(qargs, Args),
merge_qargs(z_context:get_qargs(Context), Args1);
L when is_list(L) ->
Args1 = proplists:delete(qargs, Args),
merge_qargs(L, Args1);
M when is_map(M) ->
Args1 = proplists:delete(qargs, Args),
merge_qargs(maps:to_list(M), Args1)
end.
merge_qargs([], Args) ->
Args;
merge_qargs(Qs, Args) ->
Ks = [ z_convert:to_binary(A) || {A, _} <- Args ],
lists:foldr(
fun({A, _} = AV, Acc) ->
case lists:member(A, Ks) of
true ->
Acc;
false ->
[ AV | Acc ]
end
end,
Args,
Qs).
@doc Append all argument , names are given in a list .
append_varargs(Args, Context) ->
case proplists:get_value(varargs, Args) of
undefined ->
Args;
Varargs ->
append_varargs(Varargs, proplists:delete(varargs, Args), Context)
end.
append_varargs([], Args, _Context) ->
Args;
append_varargs([{Name, Value}|Varargs], Args, Context) ->
append_varargs(Varargs, append_vararg(Name, Value, Args), Context);
append_varargs([[Name, Value]|Varargs], Args, Context) ->
append_varargs(Varargs, append_vararg(Name, Value, Args), Context);
append_varargs([Name|Varargs], Args, Context) ->
Key = z_convert:to_atom(Name),
append_varargs(Varargs, append_vararg(Key, z_context:get(Key, Context), Args), Context).
append_vararg(Name, Value, Args) ->
Key = z_convert:to_atom(Name),
case proplists:is_defined(Key, Args) of
true -> Args;
false -> [{Key, Value}|Args]
end.
|
0e1d6183af269b05b4501dc24543abfc8edd5bf65455bc0696127aad2dedda13 | fyquah/hardcaml_arty | uart.ml | open Base
open Hardcaml
open Signal
module Byte_with_valid = struct
module Pre = struct
include With_valid
let t =
{ valid = ("valid", 1)
; value = ("value", 8)
}
;;
end
include Pre
include Hardcaml.Interface.Make(Pre)
end
type counter =
{ counter : Signal.t option
; last_cycle_trigger : Signal.t
; halfway_trigger : Signal.t
}
let trigger_of_cycles ~clock ~clear ~cycles_per_trigger ~active =
assert (cycles_per_trigger > 2);
let spec = Reg_spec.create ~clock ~clear () in
let cycle_cnt = wire (Int.ceil_log2 cycles_per_trigger) in
let max_cycle_cnt = (cycles_per_trigger - 1) in
let next =
mux2 (~:active |: (cycle_cnt ==:. max_cycle_cnt))
(zero (width cycle_cnt))
(cycle_cnt +:. 1)
in
cycle_cnt <== reg spec ~enable:vdd next;
{ counter = Some cycle_cnt
; last_cycle_trigger =
active &: (cycle_cnt ==:. max_cycle_cnt)
; halfway_trigger =
active &: (cycle_cnt ==:. (cycles_per_trigger / 2))
}
;;
module Tx_state_machine = struct
module States = struct
type t =
| S_idle
| S_start_bit
| S_data_bits
| S_stop_bit
[@@deriving sexp_of, compare, enumerate]
end
let create ~clock ~clear ~cycles_per_bit (byte_with_valid : Signal.t Byte_with_valid.t) =
let spec = Reg_spec.create ~clock ~clear () in
let sm = Always.State_machine.create (module States) spec ~enable:vdd in
let increment_cycle_counter = Always.Variable.reg spec ~enable:vdd ~width:1 in
let { counter = _; last_cycle_trigger = trigger; halfway_trigger = _ } =
trigger_of_cycles
~cycles_per_trigger:cycles_per_bit
~clock ~clear ~active:increment_cycle_counter.value
in
let byte_cnt = Always.Variable.reg spec ~enable:vdd ~width:3 in
let output = Always.Variable.wire ~default:vdd in
let data_latched =
reg spec ~enable:(sm.is S_idle &: byte_with_valid.valid)
byte_with_valid.value
|> Signal.bits_lsb
in
ignore (sm.current -- "tx_state" : Signal.t);
ignore (byte_cnt.value -- "tx_byte_cnt" : Signal.t);
Always.(compile [
sm.switch [
S_idle, [
when_ byte_with_valid.valid [
increment_cycle_counter <--. 1;
sm.set_next S_start_bit;
]
];
S_start_bit, [
output <--. 0;
when_ trigger [
byte_cnt <--. 0;
sm.set_next S_data_bits;
];
];
S_data_bits, [
output <-- mux byte_cnt.value data_latched;
when_ trigger [
byte_cnt <-- (byte_cnt.value +:. 1);
when_ (byte_cnt.value ==:. 7) [
sm.set_next S_stop_bit;
]
];
];
S_stop_bit, [
output <--. 1;
when_ trigger [
increment_cycle_counter <--. 0;
sm.set_next S_idle;
]
]
]
]);
output.value
;;
end
module Rx_state_machine = struct
module States = struct
type t =
| S_idle
| S_start_bit
| S_data_bits
(* | S_wait_for_stop_bit *)
| S_stop_bit
[@@deriving sexp_of, compare, enumerate]
end
let rec shift_register ~enable ~spec ~n x =
if n = 0 then
[]
else
let d = (reg spec ~enable x) in
d :: shift_register ~enable ~spec ~n:(n - 1) d
;;
let create ~clock ~clear ~cycles_per_bit (rx_data_raw : Signal.t) =
let spec = Reg_spec.create ~clock ~clear () in
let sm = Always.State_machine.create (module States) spec ~enable:vdd in
let increment_cycle_counter = Always.Variable.reg spec ~enable:vdd ~width:1 in
let cycles_elapsed_for_bit =
trigger_of_cycles
~cycles_per_trigger:cycles_per_bit
~clock ~clear ~active:increment_cycle_counter.value
in
let byte_cnt = Always.Variable.reg spec ~enable:vdd ~width:3 in
let consume_data_bit = Always.Variable.wire ~default:gnd in
let valid = Always.Variable.wire ~default:gnd in
ignore (sm.current -- "rx_state" : Signal.t);
ignore (byte_cnt.value -- "rx_byte_cnt" : Signal.t);
Always.(compile [
sm.switch [
S_idle, [
byte_cnt <--. 0;
when_ (rx_data_raw ==:. 0) [
increment_cycle_counter <-- vdd;
sm.set_next S_start_bit;
]
];
S_start_bit, [
if_ cycles_elapsed_for_bit.halfway_trigger [
when_ (rx_data_raw ==:. 1) [
increment_cycle_counter <-- gnd;
sm.set_next S_idle;
]
] @@ elif cycles_elapsed_for_bit.last_cycle_trigger [
sm.set_next S_data_bits
] @@ [
]
];
S_data_bits, [
consume_data_bit <-- cycles_elapsed_for_bit.halfway_trigger;
when_ cycles_elapsed_for_bit.last_cycle_trigger [
byte_cnt <-- byte_cnt.value +:. 1;
when_ (byte_cnt.value ==:. 7) [
sm.set_next S_stop_bit;
]
];
];
(*
S_wait_for_stop_bit, [
if_ rx_data_raw [
sm.set_next S_stop_bit;
] @@ elif cycles_elapsed_for_bit.last_cycle_trigger [
(* Overrun, drop frame. *)
increment_cycle_counter <-- gnd;
sm.set_next S_idle;
] @@ [
]
];
*)
S_stop_bit, [
when_ cycles_elapsed_for_bit.last_cycle_trigger [
valid <--. 1;
increment_cycle_counter <-- gnd;
sm.set_next S_idle;
]
]
]]);
{ With_valid.
valid = valid.value
; value =
Signal.concat_msb
(shift_register ~enable:consume_data_bit.value ~spec ~n:8
rx_data_raw)
}
;;
end
type t =
{ mutable tx_data_user : Signal.t Byte_with_valid.t option
; mutable rx_data_user : Signal.t Byte_with_valid.t option
}
let create () =
{ tx_data_user = None; rx_data_user = None }
;;
let set_tx_data_user t tx_data_user =
match t.tx_data_user with
| None -> t.tx_data_user <- Some tx_data_user
| Some _ -> raise_s [%message "Cannot call set_tx_data_user multiple times"]
;;
let get_rx_data_user t =
match t.rx_data_user with
| None ->
let ret = (Byte_with_valid.Of_signal.wires ()) in
t.rx_data_user <- Some ret; ret
| Some rx_data_user -> rx_data_user
;;
let complete t ~clock ~clear ~rx_data_raw =
begin match t.rx_data_user with
| None -> ()
| Some dest ->
let src =
Rx_state_machine.create
~cycles_per_bit:((166_667_000 / 115_200)) ~clock ~clear
rx_data_raw
in
dest.valid <== src.valid;
dest.value <== src.value;
end;
begin match t.tx_data_user with
| None ->
`Tx_data_raw Signal.vdd
| Some tx_data_user ->
`Tx_data_raw (Tx_state_machine.create
~cycles_per_bit:((166_667_000 / 115_200))
~clock
~clear
tx_data_user)
end;
;;
module Expert = struct
let create_tx_state_machine = Tx_state_machine.create
let create_rx_state_machine = Rx_state_machine.create
end
| null | https://raw.githubusercontent.com/fyquah/hardcaml_arty/aba3de22a26e2a609d5972174782bd1a7069e8a5/src/infrastructure/uart.ml | ocaml | | S_wait_for_stop_bit
S_wait_for_stop_bit, [
if_ rx_data_raw [
sm.set_next S_stop_bit;
] @@ elif cycles_elapsed_for_bit.last_cycle_trigger [
(* Overrun, drop frame. | open Base
open Hardcaml
open Signal
module Byte_with_valid = struct
module Pre = struct
include With_valid
let t =
{ valid = ("valid", 1)
; value = ("value", 8)
}
;;
end
include Pre
include Hardcaml.Interface.Make(Pre)
end
type counter =
{ counter : Signal.t option
; last_cycle_trigger : Signal.t
; halfway_trigger : Signal.t
}
let trigger_of_cycles ~clock ~clear ~cycles_per_trigger ~active =
assert (cycles_per_trigger > 2);
let spec = Reg_spec.create ~clock ~clear () in
let cycle_cnt = wire (Int.ceil_log2 cycles_per_trigger) in
let max_cycle_cnt = (cycles_per_trigger - 1) in
let next =
mux2 (~:active |: (cycle_cnt ==:. max_cycle_cnt))
(zero (width cycle_cnt))
(cycle_cnt +:. 1)
in
cycle_cnt <== reg spec ~enable:vdd next;
{ counter = Some cycle_cnt
; last_cycle_trigger =
active &: (cycle_cnt ==:. max_cycle_cnt)
; halfway_trigger =
active &: (cycle_cnt ==:. (cycles_per_trigger / 2))
}
;;
module Tx_state_machine = struct
module States = struct
type t =
| S_idle
| S_start_bit
| S_data_bits
| S_stop_bit
[@@deriving sexp_of, compare, enumerate]
end
let create ~clock ~clear ~cycles_per_bit (byte_with_valid : Signal.t Byte_with_valid.t) =
let spec = Reg_spec.create ~clock ~clear () in
let sm = Always.State_machine.create (module States) spec ~enable:vdd in
let increment_cycle_counter = Always.Variable.reg spec ~enable:vdd ~width:1 in
let { counter = _; last_cycle_trigger = trigger; halfway_trigger = _ } =
trigger_of_cycles
~cycles_per_trigger:cycles_per_bit
~clock ~clear ~active:increment_cycle_counter.value
in
let byte_cnt = Always.Variable.reg spec ~enable:vdd ~width:3 in
let output = Always.Variable.wire ~default:vdd in
let data_latched =
reg spec ~enable:(sm.is S_idle &: byte_with_valid.valid)
byte_with_valid.value
|> Signal.bits_lsb
in
ignore (sm.current -- "tx_state" : Signal.t);
ignore (byte_cnt.value -- "tx_byte_cnt" : Signal.t);
Always.(compile [
sm.switch [
S_idle, [
when_ byte_with_valid.valid [
increment_cycle_counter <--. 1;
sm.set_next S_start_bit;
]
];
S_start_bit, [
output <--. 0;
when_ trigger [
byte_cnt <--. 0;
sm.set_next S_data_bits;
];
];
S_data_bits, [
output <-- mux byte_cnt.value data_latched;
when_ trigger [
byte_cnt <-- (byte_cnt.value +:. 1);
when_ (byte_cnt.value ==:. 7) [
sm.set_next S_stop_bit;
]
];
];
S_stop_bit, [
output <--. 1;
when_ trigger [
increment_cycle_counter <--. 0;
sm.set_next S_idle;
]
]
]
]);
output.value
;;
end
module Rx_state_machine = struct
module States = struct
type t =
| S_idle
| S_start_bit
| S_data_bits
| S_stop_bit
[@@deriving sexp_of, compare, enumerate]
end
let rec shift_register ~enable ~spec ~n x =
if n = 0 then
[]
else
let d = (reg spec ~enable x) in
d :: shift_register ~enable ~spec ~n:(n - 1) d
;;
let create ~clock ~clear ~cycles_per_bit (rx_data_raw : Signal.t) =
let spec = Reg_spec.create ~clock ~clear () in
let sm = Always.State_machine.create (module States) spec ~enable:vdd in
let increment_cycle_counter = Always.Variable.reg spec ~enable:vdd ~width:1 in
let cycles_elapsed_for_bit =
trigger_of_cycles
~cycles_per_trigger:cycles_per_bit
~clock ~clear ~active:increment_cycle_counter.value
in
let byte_cnt = Always.Variable.reg spec ~enable:vdd ~width:3 in
let consume_data_bit = Always.Variable.wire ~default:gnd in
let valid = Always.Variable.wire ~default:gnd in
ignore (sm.current -- "rx_state" : Signal.t);
ignore (byte_cnt.value -- "rx_byte_cnt" : Signal.t);
Always.(compile [
sm.switch [
S_idle, [
byte_cnt <--. 0;
when_ (rx_data_raw ==:. 0) [
increment_cycle_counter <-- vdd;
sm.set_next S_start_bit;
]
];
S_start_bit, [
if_ cycles_elapsed_for_bit.halfway_trigger [
when_ (rx_data_raw ==:. 1) [
increment_cycle_counter <-- gnd;
sm.set_next S_idle;
]
] @@ elif cycles_elapsed_for_bit.last_cycle_trigger [
sm.set_next S_data_bits
] @@ [
]
];
S_data_bits, [
consume_data_bit <-- cycles_elapsed_for_bit.halfway_trigger;
when_ cycles_elapsed_for_bit.last_cycle_trigger [
byte_cnt <-- byte_cnt.value +:. 1;
when_ (byte_cnt.value ==:. 7) [
sm.set_next S_stop_bit;
]
];
];
increment_cycle_counter <-- gnd;
sm.set_next S_idle;
] @@ [
]
];
*)
S_stop_bit, [
when_ cycles_elapsed_for_bit.last_cycle_trigger [
valid <--. 1;
increment_cycle_counter <-- gnd;
sm.set_next S_idle;
]
]
]]);
{ With_valid.
valid = valid.value
; value =
Signal.concat_msb
(shift_register ~enable:consume_data_bit.value ~spec ~n:8
rx_data_raw)
}
;;
end
type t =
{ mutable tx_data_user : Signal.t Byte_with_valid.t option
; mutable rx_data_user : Signal.t Byte_with_valid.t option
}
let create () =
{ tx_data_user = None; rx_data_user = None }
;;
let set_tx_data_user t tx_data_user =
match t.tx_data_user with
| None -> t.tx_data_user <- Some tx_data_user
| Some _ -> raise_s [%message "Cannot call set_tx_data_user multiple times"]
;;
let get_rx_data_user t =
match t.rx_data_user with
| None ->
let ret = (Byte_with_valid.Of_signal.wires ()) in
t.rx_data_user <- Some ret; ret
| Some rx_data_user -> rx_data_user
;;
let complete t ~clock ~clear ~rx_data_raw =
begin match t.rx_data_user with
| None -> ()
| Some dest ->
let src =
Rx_state_machine.create
~cycles_per_bit:((166_667_000 / 115_200)) ~clock ~clear
rx_data_raw
in
dest.valid <== src.valid;
dest.value <== src.value;
end;
begin match t.tx_data_user with
| None ->
`Tx_data_raw Signal.vdd
| Some tx_data_user ->
`Tx_data_raw (Tx_state_machine.create
~cycles_per_bit:((166_667_000 / 115_200))
~clock
~clear
tx_data_user)
end;
;;
module Expert = struct
let create_tx_state_machine = Tx_state_machine.create
let create_rx_state_machine = Rx_state_machine.create
end
|
3f8d1b392243251c117f384d9c76388ec22ba90e315b43c2af18aea10a2f8325 | Isaac-DeFrain/KFramework | constants.ml | type sort =
|SortProcCell
|SortBoundsCell
|SortBool
|SortK
|SortMap
|SortSumCell
|SortParCellFragment
|SortKVariable
|SortKCell
|SortBytes
|SortKItem
|SortStringBuffer
|SortName
|SortTCell
|SortInt
|SortProcCellBag
|SortBoundsCellOpt
|SortKConfigVar
|SortBoundCell
|SortSumCellFragment
|SortProcCellFragment
|SortProc
|SortKCellOpt
|SortString
|SortFloat
|SortSummandCellBag
|SortSumCellOpt
|SortTCellFragment
|SortBoundCellBag
|SortParCellOpt
|SortSet
|SortParCell
|SortMInt
|SortId
|SortNormProc
|SortCell
|SortSummandCell
|SortList
|SortBoundsCellFragment
type klabel =
|Lbl_ProcCellBag_
|Lbl_'_LT_Eqls'Int__INT
|LblnotBool_
|LblMap'Coln'lookup
|LblnoKCell
|LblsignExtendBitRangeInt
|Lbl_'EqlsEqls'Bool__BOOL
|LblisSet
|LblintersectSet
|Lbl_in_keys'LPar'_'RPar'_MAP
|LblfindChar
|LblSet'Coln'in
|LblisK
|LblString2Int
|Lbl_'_LT_Eqls'Set__SET
|Lbl'_LT_'proc'_GT_Hyph'fragment
|LblmakeList
|Lbl_'LSqB'_'_LT_Hyph'undef'RSqB'
|Lbl'Hash'Bottom
|LblisNormProc
|Lbl_'EqlsEqls'Int_
|Lbl_andThenBool__BOOL
|LblnoBoundsCell
|LblinitProcCell
|LblisString
|Lbl_'Perc'Int__INT
|Lbl_'_GT__GT_'Int__INT
|LblisList
|LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING
|Lbl_SummandCellBag_
|LblPar
|Lbl_'Xor_'Int__INT
|LblfindString
|Lbl'_LT_'k'_GT_'
|LblabsInt
|Lbl_'_GT_'String__STRING
|Lbl_'EqlsEqls'String__STRING
|LblisKConfigVar
|LblnoParCell
|LblisSumCell
|LblisCell
|Lblvalues
|Lbl'_LT_'proc'_GT_'
|LblList'Coln'get
|Lbl'_LT_'summand'_GT_'
|LblSetItem
|LblunsignedBytes
|Lbl'_LT_'sum'_GT_'
|Lbl_'_LT_'Int__INT
|Lbl'Stop'List
|LblNil_PI'Hyph'SYNTAX
|LblrandInt
|LblisFloat
|LblisParCellOpt
|LblinitBoundsCell
|Lblkeys_list'LPar'_'RPar'_MAP
|LblfreshId
|LblchrChar
|Lbl_orElseBool__BOOL
|Lbl_divInt__INT
|LblList'Coln'range
|LblisProc
|Lbl_'Plus'Int_
|LblisKCell
|LblProcCellBagItem
|Lbl_orBool__BOOL
|LblinitParCell
|Lbl_'_GT_Eqls'Int__INT
|LblNew
|LblnoSumCell
|LblupdateMap
|LblInt2String
|Lbl_'EqlsSlshEqls'K_
|LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING
|Lbl_'_GT_'Int__INT
|LblfillList
|Lbl_BoundCellBag_
|LblisProcCellBag
|LblSummandCellBagItem
|LblbitRangeInt
|Lbl'Stop'ProcCellBag
|Lbl_'_LT_'String__STRING
|Lbl'_LT_'sum'_GT_Hyph'fragment
|Lbl_List_
|Lbl'Hash'ThreadLocal
|Lbl_'PipeHyph_GT_'_
|Lbl_'Hyph'Map__MAP
|Lbl_xorBool__BOOL
|Lbl_'EqlsEqls'K_
|Lbl_'LSqB'_'RSqB'_SUBSTITUTION
|LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING
|LblinitBoundCell
|Lbl'Stop'Map
|Lbl_'EqlsSlshEqls'String__STRING
|LblbigEndianBytes
|LblisBoundsCellOpt
|LblisSummandCellBag
|LblId2String
|LblisInt
|LblMap'Coln'choice
|LblisProcCellFragment
|Lbl_Set_
|Lbl_impliesBool__BOOL
|Lbl_'Star'Int__INT
|Lbl'_LT_'T'_GT_'
|Lbl'Hash'Thread
|LblmaxInt'LPar'_'Comm'_'RPar'_INT
|LblisBool
|Lbl'Tild'Int__INT
|Lbl_'_LT_Eqls'String__STRING
|LblordChar
|Lbl_modInt__INT
|LblrfindChar
|Lbl_Map_
|Lbl_'Hyph'Int__INT
|LbldirectionalityChar
|LblFloat2String
|LblinitKCell
|LblsizeList
|Lbl'Stop'Set
|LblString2Id
|Lbl_'EqlsSlshEqls'Bool__BOOL
|LblisBoundsCell
|Lbl'_LT_'bounds'_GT_Hyph'fragment
|LblremoveAll
|LblisTCell
|Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION
|Lbl_andBool_
|Lbl'_LT_'par'_GT_'
|LbllengthString
|LblinitTCell
|LblReplication
|LblsignedBytes
|LblFloatFormat
|Lbl_'Plus'String__STRING
|Lbl_'Xor_Perc'Int___INT
|Lbl_'Pipe'Int__INT
|LblisKVariable
|Lbl_dividesInt__INT
|LblinitSumCell
|LblrfindString
|Lbl'_LT_'T'_GT_Hyph'fragment
|LblupdateList
|LblSet'Coln'choice
|LblisSumCellFragment
|LblcategoryChar
|LblisSumCellOpt
|LblSet'Coln'difference
|LblisName
|LblfreshInt
|LblisParCellFragment
|LblisKCellOpt
|Lbl'Stop'SummandCellBag
|Lbl_xorInt__INT
|LblString2Float
|LblMap'Coln'lookupOrDefault
|Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL
|Lbl_'And'Int__INT
|LblisProcCell
|LblisParCell
|LbllittleEndianBytes
|LblBoundCellBagItem
|Lbl_'_LT__LT_'Int__INT
|Lbllog2Int
|Lbl_'EqlsSlshEqls'Int__INT
|Lbl'_LT_'par'_GT_Hyph'fragment
|LblBase2String
|LblListItem
|Lbl_'_GT_Eqls'String__STRING
|Lbl_'_LT_Eqls'Map__MAP
|LblnewUUID_STRING
|LblsizeMap
|LblisBoundCellBag
|LblisId
|LblsubstrString
|Lblsize
|LblisSummandCell
|Lblproject'Coln'Proc
|LblSend
|LblinitSummandCell
|Lbl_inList_
|LblisBoundCell
|LblminInt'LPar'_'Comm'_'RPar'_INT
|LblisMap
|LblsrandInt
|LblisKItem
|LblReceive
|LblisBoundsCellFragment
|Lbl'Stop'BoundCellBag
|LblList'Coln'set
|LblString2Base
|Lbl'_LT_'bound'_GT_'
|LblisTCellFragment
|Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING
|Lbl_'Slsh'Int__INT
|Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP
|Lblkeys
|LblOr
|Lbl'_LT_'bounds'_GT_'
let print_sort(c: sort) : string = match c with
|SortProcCell -> "ProcCell"
|SortBoundsCell -> "BoundsCell"
|SortBool -> "Bool"
|SortK -> "K"
|SortMap -> "Map"
|SortSumCell -> "SumCell"
|SortParCellFragment -> "ParCellFragment"
|SortKVariable -> "KVariable"
|SortKCell -> "KCell"
|SortBytes -> "Bytes"
|SortKItem -> "KItem"
|SortStringBuffer -> "StringBuffer"
|SortName -> "Name"
|SortTCell -> "TCell"
|SortInt -> "Int"
|SortProcCellBag -> "ProcCellBag"
|SortBoundsCellOpt -> "BoundsCellOpt"
|SortKConfigVar -> "KConfigVar"
|SortBoundCell -> "BoundCell"
|SortSumCellFragment -> "SumCellFragment"
|SortProcCellFragment -> "ProcCellFragment"
|SortProc -> "Proc"
|SortKCellOpt -> "KCellOpt"
|SortString -> "String"
|SortFloat -> "Float"
|SortSummandCellBag -> "SummandCellBag"
|SortSumCellOpt -> "SumCellOpt"
|SortTCellFragment -> "TCellFragment"
|SortBoundCellBag -> "BoundCellBag"
|SortParCellOpt -> "ParCellOpt"
|SortSet -> "Set"
|SortParCell -> "ParCell"
|SortMInt -> "MInt"
|SortId -> "Id"
|SortNormProc -> "NormProc"
|SortCell -> "Cell"
|SortSummandCell -> "SummandCell"
|SortList -> "List"
|SortBoundsCellFragment -> "BoundsCellFragment"
let print_klabel(c: klabel) : string = match c with
|Lbl_ProcCellBag_ -> "`_ProcCellBag_`"
|Lbl_'_LT_Eqls'Int__INT -> "`_<=Int__INT`"
|LblnotBool_ -> "`notBool_`"
|LblMap'Coln'lookup -> "`Map:lookup`"
|LblnoKCell -> "noKCell"
|LblsignExtendBitRangeInt -> "signExtendBitRangeInt"
|Lbl_'EqlsEqls'Bool__BOOL -> "`_==Bool__BOOL`"
|LblisSet -> "isSet"
|LblintersectSet -> "intersectSet"
|Lbl_in_keys'LPar'_'RPar'_MAP -> "`_in_keys(_)_MAP`"
|LblfindChar -> "findChar"
|LblSet'Coln'in -> "`Set:in`"
|LblisK -> "isK"
|LblString2Int -> "`String2Int`"
|Lbl_'_LT_Eqls'Set__SET -> "`_<=Set__SET`"
|Lbl'_LT_'proc'_GT_Hyph'fragment -> "`<proc>-fragment`"
|LblmakeList -> "makeList"
|Lbl_'LSqB'_'_LT_Hyph'undef'RSqB' -> "`_[_<-undef]`"
|Lbl'Hash'Bottom -> "#Bottom"
|LblisNormProc -> "isNormProc"
|Lbl_'EqlsEqls'Int_ -> "`_==Int_`"
|Lbl_andThenBool__BOOL -> "`_andThenBool__BOOL`"
|LblnoBoundsCell -> "noBoundsCell"
|LblinitProcCell -> "initProcCell"
|LblisString -> "isString"
|Lbl_'Perc'Int__INT -> "`_%Int__INT`"
|Lbl_'_GT__GT_'Int__INT -> "`_>>Int__INT`"
|LblisList -> "isList"
|LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "`replaceAll(_,_,_)_STRING`"
|Lbl_SummandCellBag_ -> "`_SummandCellBag_`"
|LblPar -> "`Par`"
|Lbl_'Xor_'Int__INT -> "`_^Int__INT`"
|LblfindString -> "findString"
|Lbl'_LT_'k'_GT_' -> "`<k>`"
|LblabsInt -> "absInt"
|Lbl_'_GT_'String__STRING -> "`_>String__STRING`"
|Lbl_'EqlsEqls'String__STRING -> "`_==String__STRING`"
|LblisKConfigVar -> "isKConfigVar"
|LblnoParCell -> "noParCell"
|LblisSumCell -> "isSumCell"
|LblisCell -> "isCell"
|Lblvalues -> "values"
|Lbl'_LT_'proc'_GT_' -> "`<proc>`"
|LblList'Coln'get -> "`List:get`"
|Lbl'_LT_'summand'_GT_' -> "`<summand>`"
|LblSetItem -> "`SetItem`"
|LblunsignedBytes -> "unsignedBytes"
|Lbl'_LT_'sum'_GT_' -> "`<sum>`"
|Lbl_'_LT_'Int__INT -> "`_<Int__INT`"
|Lbl'Stop'List -> "`.List`"
|LblNil_PI'Hyph'SYNTAX -> "`Nil_PI-SYNTAX`"
|LblrandInt -> "randInt"
|LblisFloat -> "isFloat"
|LblisParCellOpt -> "isParCellOpt"
|LblinitBoundsCell -> "initBoundsCell"
|Lblkeys_list'LPar'_'RPar'_MAP -> "`keys_list(_)_MAP`"
|LblfreshId -> "freshId"
|LblchrChar -> "chrChar"
|Lbl_orElseBool__BOOL -> "`_orElseBool__BOOL`"
|Lbl_divInt__INT -> "`_divInt__INT`"
|LblList'Coln'range -> "`List:range`"
|LblisProc -> "isProc"
|Lbl_'Plus'Int_ -> "`_+Int_`"
|LblisKCell -> "isKCell"
|LblProcCellBagItem -> "`ProcCellBagItem`"
|Lbl_orBool__BOOL -> "`_orBool__BOOL`"
|LblinitParCell -> "initParCell"
|Lbl_'_GT_Eqls'Int__INT -> "`_>=Int__INT`"
|LblNew -> "`New`"
|LblnoSumCell -> "noSumCell"
|LblupdateMap -> "updateMap"
|LblInt2String -> "`Int2String`"
|Lbl_'EqlsSlshEqls'K_ -> "`_=/=K_`"
|LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING -> "`countAllOccurrences(_,_)_STRING`"
|Lbl_'_GT_'Int__INT -> "`_>Int__INT`"
|LblfillList -> "fillList"
|Lbl_BoundCellBag_ -> "`_BoundCellBag_`"
|LblisProcCellBag -> "isProcCellBag"
|LblSummandCellBagItem -> "`SummandCellBagItem`"
|LblbitRangeInt -> "bitRangeInt"
|Lbl'Stop'ProcCellBag -> "`.ProcCellBag`"
|Lbl_'_LT_'String__STRING -> "`_<String__STRING`"
|Lbl'_LT_'sum'_GT_Hyph'fragment -> "`<sum>-fragment`"
|Lbl_List_ -> "`_List_`"
|Lbl'Hash'ThreadLocal -> "#ThreadLocal"
|Lbl_'PipeHyph_GT_'_ -> "`_|->_`"
|Lbl_'Hyph'Map__MAP -> "`_-Map__MAP`"
|Lbl_xorBool__BOOL -> "`_xorBool__BOOL`"
|Lbl_'EqlsEqls'K_ -> "`_==K_`"
|Lbl_'LSqB'_'RSqB'_SUBSTITUTION -> "`_[_]_SUBSTITUTION`"
|LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "`replaceFirst(_,_,_)_STRING`"
|LblinitBoundCell -> "initBoundCell"
|Lbl'Stop'Map -> "`.Map`"
|Lbl_'EqlsSlshEqls'String__STRING -> "`_=/=String__STRING`"
|LblbigEndianBytes -> "bigEndianBytes"
|LblisBoundsCellOpt -> "isBoundsCellOpt"
|LblisSummandCellBag -> "isSummandCellBag"
|LblId2String -> "`Id2String`"
|LblisInt -> "isInt"
|LblMap'Coln'choice -> "`Map:choice`"
|LblisProcCellFragment -> "isProcCellFragment"
|Lbl_Set_ -> "`_Set_`"
|Lbl_impliesBool__BOOL -> "`_impliesBool__BOOL`"
|Lbl_'Star'Int__INT -> "`_*Int__INT`"
|Lbl'_LT_'T'_GT_' -> "`<T>`"
|Lbl'Hash'Thread -> "#Thread"
|LblmaxInt'LPar'_'Comm'_'RPar'_INT -> "`maxInt(_,_)_INT`"
|LblisBool -> "isBool"
|Lbl'Tild'Int__INT -> "`~Int__INT`"
|Lbl_'_LT_Eqls'String__STRING -> "`_<=String__STRING`"
|LblordChar -> "ordChar"
|Lbl_modInt__INT -> "`_modInt__INT`"
|LblrfindChar -> "rfindChar"
|Lbl_Map_ -> "`_Map_`"
|Lbl_'Hyph'Int__INT -> "`_-Int__INT`"
|LbldirectionalityChar -> "directionalityChar"
|LblFloat2String -> "`Float2String`"
|LblinitKCell -> "initKCell"
|LblsizeList -> "sizeList"
|Lbl'Stop'Set -> "`.Set`"
|LblString2Id -> "`String2Id`"
|Lbl_'EqlsSlshEqls'Bool__BOOL -> "`_=/=Bool__BOOL`"
|LblisBoundsCell -> "isBoundsCell"
|Lbl'_LT_'bounds'_GT_Hyph'fragment -> "`<bounds>-fragment`"
|LblremoveAll -> "removeAll"
|LblisTCell -> "isTCell"
|Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION -> "`_[_/_]_SUBSTITUTION`"
|Lbl_andBool_ -> "`_andBool_`"
|Lbl'_LT_'par'_GT_' -> "`<par>`"
|LbllengthString -> "lengthString"
|LblinitTCell -> "initTCell"
|LblReplication -> "`Replication`"
|LblsignedBytes -> "signedBytes"
|LblFloatFormat -> "`FloatFormat`"
|Lbl_'Plus'String__STRING -> "`_+String__STRING`"
|Lbl_'Xor_Perc'Int___INT -> "`_^%Int___INT`"
|Lbl_'Pipe'Int__INT -> "`_|Int__INT`"
|LblisKVariable -> "isKVariable"
|Lbl_dividesInt__INT -> "`_dividesInt__INT`"
|LblinitSumCell -> "initSumCell"
|LblrfindString -> "rfindString"
|Lbl'_LT_'T'_GT_Hyph'fragment -> "`<T>-fragment`"
|LblupdateList -> "updateList"
|LblSet'Coln'choice -> "`Set:choice`"
|LblisSumCellFragment -> "isSumCellFragment"
|LblcategoryChar -> "categoryChar"
|LblisSumCellOpt -> "isSumCellOpt"
|LblSet'Coln'difference -> "`Set:difference`"
|LblisName -> "isName"
|LblfreshInt -> "freshInt"
|LblisParCellFragment -> "isParCellFragment"
|LblisKCellOpt -> "isKCellOpt"
|Lbl'Stop'SummandCellBag -> "`.SummandCellBag`"
|Lbl_xorInt__INT -> "`_xorInt__INT`"
|LblString2Float -> "`String2Float`"
|LblMap'Coln'lookupOrDefault -> "`Map:lookupOrDefault`"
|Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL -> "`#if_#then_#else_#fi_K-EQUAL`"
|Lbl_'And'Int__INT -> "`_&Int__INT`"
|LblisProcCell -> "isProcCell"
|LblisParCell -> "isParCell"
|LbllittleEndianBytes -> "littleEndianBytes"
|LblBoundCellBagItem -> "`BoundCellBagItem`"
|Lbl_'_LT__LT_'Int__INT -> "`_<<Int__INT`"
|Lbllog2Int -> "log2Int"
|Lbl_'EqlsSlshEqls'Int__INT -> "`_=/=Int__INT`"
|Lbl'_LT_'par'_GT_Hyph'fragment -> "`<par>-fragment`"
|LblBase2String -> "`Base2String`"
|LblListItem -> "`ListItem`"
|Lbl_'_GT_Eqls'String__STRING -> "`_>=String__STRING`"
|Lbl_'_LT_Eqls'Map__MAP -> "`_<=Map__MAP`"
|LblnewUUID_STRING -> "`newUUID_STRING`"
|LblsizeMap -> "sizeMap"
|LblisBoundCellBag -> "isBoundCellBag"
|LblisId -> "isId"
|LblsubstrString -> "substrString"
|Lblsize -> "size"
|LblisSummandCell -> "isSummandCell"
|Lblproject'Coln'Proc -> "`project:Proc`"
|LblSend -> "`Send`"
|LblinitSummandCell -> "initSummandCell"
|Lbl_inList_ -> "`_inList_`"
|LblisBoundCell -> "isBoundCell"
|LblminInt'LPar'_'Comm'_'RPar'_INT -> "`minInt(_,_)_INT`"
|LblisMap -> "isMap"
|LblsrandInt -> "srandInt"
|LblisKItem -> "isKItem"
|LblReceive -> "`Receive`"
|LblisBoundsCellFragment -> "isBoundsCellFragment"
|Lbl'Stop'BoundCellBag -> "`.BoundCellBag`"
|LblList'Coln'set -> "`List:set`"
|LblString2Base -> "`String2Base`"
|Lbl'_LT_'bound'_GT_' -> "`<bound>`"
|LblisTCellFragment -> "isTCellFragment"
|Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING -> "`replace(_,_,_,_)_STRING`"
|Lbl_'Slsh'Int__INT -> "`_/Int__INT`"
|Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP -> "`_[_<-_]_MAP`"
|Lblkeys -> "keys"
|LblOr -> "`Or`"
|Lbl'_LT_'bounds'_GT_' -> "`<bounds>`"
let print_klabel_string(c: klabel) : string = match c with
|Lbl_ProcCellBag_ -> "_ProcCellBag_"
|Lbl_'_LT_Eqls'Int__INT -> "_<=Int__INT"
|LblnotBool_ -> "notBool_"
|LblMap'Coln'lookup -> "Map:lookup"
|LblnoKCell -> "noKCell"
|LblsignExtendBitRangeInt -> "signExtendBitRangeInt"
|Lbl_'EqlsEqls'Bool__BOOL -> "_==Bool__BOOL"
|LblisSet -> "isSet"
|LblintersectSet -> "intersectSet"
|Lbl_in_keys'LPar'_'RPar'_MAP -> "_in_keys(_)_MAP"
|LblfindChar -> "findChar"
|LblSet'Coln'in -> "Set:in"
|LblisK -> "isK"
|LblString2Int -> "String2Int"
|Lbl_'_LT_Eqls'Set__SET -> "_<=Set__SET"
|Lbl'_LT_'proc'_GT_Hyph'fragment -> "<proc>-fragment"
|LblmakeList -> "makeList"
|Lbl_'LSqB'_'_LT_Hyph'undef'RSqB' -> "_[_<-undef]"
|Lbl'Hash'Bottom -> "#Bottom"
|LblisNormProc -> "isNormProc"
|Lbl_'EqlsEqls'Int_ -> "_==Int_"
|Lbl_andThenBool__BOOL -> "_andThenBool__BOOL"
|LblnoBoundsCell -> "noBoundsCell"
|LblinitProcCell -> "initProcCell"
|LblisString -> "isString"
|Lbl_'Perc'Int__INT -> "_%Int__INT"
|Lbl_'_GT__GT_'Int__INT -> "_>>Int__INT"
|LblisList -> "isList"
|LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "replaceAll(_,_,_)_STRING"
|Lbl_SummandCellBag_ -> "_SummandCellBag_"
|LblPar -> "Par"
|Lbl_'Xor_'Int__INT -> "_^Int__INT"
|LblfindString -> "findString"
|Lbl'_LT_'k'_GT_' -> "<k>"
|LblabsInt -> "absInt"
|Lbl_'_GT_'String__STRING -> "_>String__STRING"
|Lbl_'EqlsEqls'String__STRING -> "_==String__STRING"
|LblisKConfigVar -> "isKConfigVar"
|LblnoParCell -> "noParCell"
|LblisSumCell -> "isSumCell"
|LblisCell -> "isCell"
|Lblvalues -> "values"
|Lbl'_LT_'proc'_GT_' -> "<proc>"
|LblList'Coln'get -> "List:get"
|Lbl'_LT_'summand'_GT_' -> "<summand>"
|LblSetItem -> "SetItem"
|LblunsignedBytes -> "unsignedBytes"
|Lbl'_LT_'sum'_GT_' -> "<sum>"
|Lbl_'_LT_'Int__INT -> "_<Int__INT"
|Lbl'Stop'List -> ".List"
|LblNil_PI'Hyph'SYNTAX -> "Nil_PI-SYNTAX"
|LblrandInt -> "randInt"
|LblisFloat -> "isFloat"
|LblisParCellOpt -> "isParCellOpt"
|LblinitBoundsCell -> "initBoundsCell"
|Lblkeys_list'LPar'_'RPar'_MAP -> "keys_list(_)_MAP"
|LblfreshId -> "freshId"
|LblchrChar -> "chrChar"
|Lbl_orElseBool__BOOL -> "_orElseBool__BOOL"
|Lbl_divInt__INT -> "_divInt__INT"
|LblList'Coln'range -> "List:range"
|LblisProc -> "isProc"
|Lbl_'Plus'Int_ -> "_+Int_"
|LblisKCell -> "isKCell"
|LblProcCellBagItem -> "ProcCellBagItem"
|Lbl_orBool__BOOL -> "_orBool__BOOL"
|LblinitParCell -> "initParCell"
|Lbl_'_GT_Eqls'Int__INT -> "_>=Int__INT"
|LblNew -> "New"
|LblnoSumCell -> "noSumCell"
|LblupdateMap -> "updateMap"
|LblInt2String -> "Int2String"
|Lbl_'EqlsSlshEqls'K_ -> "_=/=K_"
|LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING -> "countAllOccurrences(_,_)_STRING"
|Lbl_'_GT_'Int__INT -> "_>Int__INT"
|LblfillList -> "fillList"
|Lbl_BoundCellBag_ -> "_BoundCellBag_"
|LblisProcCellBag -> "isProcCellBag"
|LblSummandCellBagItem -> "SummandCellBagItem"
|LblbitRangeInt -> "bitRangeInt"
|Lbl'Stop'ProcCellBag -> ".ProcCellBag"
|Lbl_'_LT_'String__STRING -> "_<String__STRING"
|Lbl'_LT_'sum'_GT_Hyph'fragment -> "<sum>-fragment"
|Lbl_List_ -> "_List_"
|Lbl'Hash'ThreadLocal -> "#ThreadLocal"
|Lbl_'PipeHyph_GT_'_ -> "_|->_"
|Lbl_'Hyph'Map__MAP -> "_-Map__MAP"
|Lbl_xorBool__BOOL -> "_xorBool__BOOL"
|Lbl_'EqlsEqls'K_ -> "_==K_"
|Lbl_'LSqB'_'RSqB'_SUBSTITUTION -> "_[_]_SUBSTITUTION"
|LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "replaceFirst(_,_,_)_STRING"
|LblinitBoundCell -> "initBoundCell"
|Lbl'Stop'Map -> ".Map"
|Lbl_'EqlsSlshEqls'String__STRING -> "_=/=String__STRING"
|LblbigEndianBytes -> "bigEndianBytes"
|LblisBoundsCellOpt -> "isBoundsCellOpt"
|LblisSummandCellBag -> "isSummandCellBag"
|LblId2String -> "Id2String"
|LblisInt -> "isInt"
|LblMap'Coln'choice -> "Map:choice"
|LblisProcCellFragment -> "isProcCellFragment"
|Lbl_Set_ -> "_Set_"
|Lbl_impliesBool__BOOL -> "_impliesBool__BOOL"
|Lbl_'Star'Int__INT -> "_*Int__INT"
|Lbl'_LT_'T'_GT_' -> "<T>"
|Lbl'Hash'Thread -> "#Thread"
|LblmaxInt'LPar'_'Comm'_'RPar'_INT -> "maxInt(_,_)_INT"
|LblisBool -> "isBool"
|Lbl'Tild'Int__INT -> "~Int__INT"
|Lbl_'_LT_Eqls'String__STRING -> "_<=String__STRING"
|LblordChar -> "ordChar"
|Lbl_modInt__INT -> "_modInt__INT"
|LblrfindChar -> "rfindChar"
|Lbl_Map_ -> "_Map_"
|Lbl_'Hyph'Int__INT -> "_-Int__INT"
|LbldirectionalityChar -> "directionalityChar"
|LblFloat2String -> "Float2String"
|LblinitKCell -> "initKCell"
|LblsizeList -> "sizeList"
|Lbl'Stop'Set -> ".Set"
|LblString2Id -> "String2Id"
|Lbl_'EqlsSlshEqls'Bool__BOOL -> "_=/=Bool__BOOL"
|LblisBoundsCell -> "isBoundsCell"
|Lbl'_LT_'bounds'_GT_Hyph'fragment -> "<bounds>-fragment"
|LblremoveAll -> "removeAll"
|LblisTCell -> "isTCell"
|Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION -> "_[_/_]_SUBSTITUTION"
|Lbl_andBool_ -> "_andBool_"
|Lbl'_LT_'par'_GT_' -> "<par>"
|LbllengthString -> "lengthString"
|LblinitTCell -> "initTCell"
|LblReplication -> "Replication"
|LblsignedBytes -> "signedBytes"
|LblFloatFormat -> "FloatFormat"
|Lbl_'Plus'String__STRING -> "_+String__STRING"
|Lbl_'Xor_Perc'Int___INT -> "_^%Int___INT"
|Lbl_'Pipe'Int__INT -> "_|Int__INT"
|LblisKVariable -> "isKVariable"
|Lbl_dividesInt__INT -> "_dividesInt__INT"
|LblinitSumCell -> "initSumCell"
|LblrfindString -> "rfindString"
|Lbl'_LT_'T'_GT_Hyph'fragment -> "<T>-fragment"
|LblupdateList -> "updateList"
|LblSet'Coln'choice -> "Set:choice"
|LblisSumCellFragment -> "isSumCellFragment"
|LblcategoryChar -> "categoryChar"
|LblisSumCellOpt -> "isSumCellOpt"
|LblSet'Coln'difference -> "Set:difference"
|LblisName -> "isName"
|LblfreshInt -> "freshInt"
|LblisParCellFragment -> "isParCellFragment"
|LblisKCellOpt -> "isKCellOpt"
|Lbl'Stop'SummandCellBag -> ".SummandCellBag"
|Lbl_xorInt__INT -> "_xorInt__INT"
|LblString2Float -> "String2Float"
|LblMap'Coln'lookupOrDefault -> "Map:lookupOrDefault"
|Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL -> "#if_#then_#else_#fi_K-EQUAL"
|Lbl_'And'Int__INT -> "_&Int__INT"
|LblisProcCell -> "isProcCell"
|LblisParCell -> "isParCell"
|LbllittleEndianBytes -> "littleEndianBytes"
|LblBoundCellBagItem -> "BoundCellBagItem"
|Lbl_'_LT__LT_'Int__INT -> "_<<Int__INT"
|Lbllog2Int -> "log2Int"
|Lbl_'EqlsSlshEqls'Int__INT -> "_=/=Int__INT"
|Lbl'_LT_'par'_GT_Hyph'fragment -> "<par>-fragment"
|LblBase2String -> "Base2String"
|LblListItem -> "ListItem"
|Lbl_'_GT_Eqls'String__STRING -> "_>=String__STRING"
|Lbl_'_LT_Eqls'Map__MAP -> "_<=Map__MAP"
|LblnewUUID_STRING -> "newUUID_STRING"
|LblsizeMap -> "sizeMap"
|LblisBoundCellBag -> "isBoundCellBag"
|LblisId -> "isId"
|LblsubstrString -> "substrString"
|Lblsize -> "size"
|LblisSummandCell -> "isSummandCell"
|Lblproject'Coln'Proc -> "project:Proc"
|LblSend -> "Send"
|LblinitSummandCell -> "initSummandCell"
|Lbl_inList_ -> "_inList_"
|LblisBoundCell -> "isBoundCell"
|LblminInt'LPar'_'Comm'_'RPar'_INT -> "minInt(_,_)_INT"
|LblisMap -> "isMap"
|LblsrandInt -> "srandInt"
|LblisKItem -> "isKItem"
|LblReceive -> "Receive"
|LblisBoundsCellFragment -> "isBoundsCellFragment"
|Lbl'Stop'BoundCellBag -> ".BoundCellBag"
|LblList'Coln'set -> "List:set"
|LblString2Base -> "String2Base"
|Lbl'_LT_'bound'_GT_' -> "<bound>"
|LblisTCellFragment -> "isTCellFragment"
|Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING -> "replace(_,_,_,_)_STRING"
|Lbl_'Slsh'Int__INT -> "_/Int__INT"
|Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP -> "_[_<-_]_MAP"
|Lblkeys -> "keys"
|LblOr -> "Or"
|Lbl'_LT_'bounds'_GT_' -> "<bounds>"
let parse_sort(c: string) : sort = match c with
|"ProcCell" -> SortProcCell
|"BoundsCell" -> SortBoundsCell
|"Bool" -> SortBool
|"K" -> SortK
|"Map" -> SortMap
|"SumCell" -> SortSumCell
|"ParCellFragment" -> SortParCellFragment
|"KVariable" -> SortKVariable
|"KCell" -> SortKCell
|"Bytes" -> SortBytes
|"KItem" -> SortKItem
|"StringBuffer" -> SortStringBuffer
|"Name" -> SortName
|"TCell" -> SortTCell
|"Int" -> SortInt
|"ProcCellBag" -> SortProcCellBag
|"BoundsCellOpt" -> SortBoundsCellOpt
|"KConfigVar" -> SortKConfigVar
|"BoundCell" -> SortBoundCell
|"SumCellFragment" -> SortSumCellFragment
|"ProcCellFragment" -> SortProcCellFragment
|"Proc" -> SortProc
|"KCellOpt" -> SortKCellOpt
|"String" -> SortString
|"Float" -> SortFloat
|"SummandCellBag" -> SortSummandCellBag
|"SumCellOpt" -> SortSumCellOpt
|"TCellFragment" -> SortTCellFragment
|"BoundCellBag" -> SortBoundCellBag
|"ParCellOpt" -> SortParCellOpt
|"Set" -> SortSet
|"ParCell" -> SortParCell
|"MInt" -> SortMInt
|"Id" -> SortId
|"NormProc" -> SortNormProc
|"Cell" -> SortCell
|"SummandCell" -> SortSummandCell
|"List" -> SortList
|"BoundsCellFragment" -> SortBoundsCellFragment
| _ -> invalid_arg ("parse_sort: " ^ c)
let parse_klabel(c: string) : klabel = match c with
|"_ProcCellBag_" -> Lbl_ProcCellBag_
|"_<=Int__INT" -> Lbl_'_LT_Eqls'Int__INT
|"notBool_" -> LblnotBool_
|"Map:lookup" -> LblMap'Coln'lookup
|"noKCell" -> LblnoKCell
|"signExtendBitRangeInt" -> LblsignExtendBitRangeInt
|"_==Bool__BOOL" -> Lbl_'EqlsEqls'Bool__BOOL
|"isSet" -> LblisSet
|"intersectSet" -> LblintersectSet
|"_in_keys(_)_MAP" -> Lbl_in_keys'LPar'_'RPar'_MAP
|"findChar" -> LblfindChar
|"Set:in" -> LblSet'Coln'in
|"isK" -> LblisK
|"String2Int" -> LblString2Int
|"_<=Set__SET" -> Lbl_'_LT_Eqls'Set__SET
|"<proc>-fragment" -> Lbl'_LT_'proc'_GT_Hyph'fragment
|"makeList" -> LblmakeList
|"_[_<-undef]" -> Lbl_'LSqB'_'_LT_Hyph'undef'RSqB'
|"#Bottom" -> Lbl'Hash'Bottom
|"isNormProc" -> LblisNormProc
|"_==Int_" -> Lbl_'EqlsEqls'Int_
|"_andThenBool__BOOL" -> Lbl_andThenBool__BOOL
|"noBoundsCell" -> LblnoBoundsCell
|"initProcCell" -> LblinitProcCell
|"isString" -> LblisString
|"_%Int__INT" -> Lbl_'Perc'Int__INT
|"_>>Int__INT" -> Lbl_'_GT__GT_'Int__INT
|"isList" -> LblisList
|"replaceAll(_,_,_)_STRING" -> LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING
|"_SummandCellBag_" -> Lbl_SummandCellBag_
|"Par" -> LblPar
|"_^Int__INT" -> Lbl_'Xor_'Int__INT
|"findString" -> LblfindString
|"<k>" -> Lbl'_LT_'k'_GT_'
|"absInt" -> LblabsInt
|"_>String__STRING" -> Lbl_'_GT_'String__STRING
|"_==String__STRING" -> Lbl_'EqlsEqls'String__STRING
|"isKConfigVar" -> LblisKConfigVar
|"noParCell" -> LblnoParCell
|"isSumCell" -> LblisSumCell
|"isCell" -> LblisCell
|"values" -> Lblvalues
|"<proc>" -> Lbl'_LT_'proc'_GT_'
|"List:get" -> LblList'Coln'get
|"<summand>" -> Lbl'_LT_'summand'_GT_'
|"SetItem" -> LblSetItem
|"unsignedBytes" -> LblunsignedBytes
|"<sum>" -> Lbl'_LT_'sum'_GT_'
|"_<Int__INT" -> Lbl_'_LT_'Int__INT
|".List" -> Lbl'Stop'List
|"Nil_PI-SYNTAX" -> LblNil_PI'Hyph'SYNTAX
|"randInt" -> LblrandInt
|"isFloat" -> LblisFloat
|"isParCellOpt" -> LblisParCellOpt
|"initBoundsCell" -> LblinitBoundsCell
|"keys_list(_)_MAP" -> Lblkeys_list'LPar'_'RPar'_MAP
|"freshId" -> LblfreshId
|"chrChar" -> LblchrChar
|"_orElseBool__BOOL" -> Lbl_orElseBool__BOOL
|"_divInt__INT" -> Lbl_divInt__INT
|"List:range" -> LblList'Coln'range
|"isProc" -> LblisProc
|"_+Int_" -> Lbl_'Plus'Int_
|"isKCell" -> LblisKCell
|"ProcCellBagItem" -> LblProcCellBagItem
|"_orBool__BOOL" -> Lbl_orBool__BOOL
|"initParCell" -> LblinitParCell
|"_>=Int__INT" -> Lbl_'_GT_Eqls'Int__INT
|"New" -> LblNew
|"noSumCell" -> LblnoSumCell
|"updateMap" -> LblupdateMap
|"Int2String" -> LblInt2String
|"_=/=K_" -> Lbl_'EqlsSlshEqls'K_
|"countAllOccurrences(_,_)_STRING" -> LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING
|"_>Int__INT" -> Lbl_'_GT_'Int__INT
|"fillList" -> LblfillList
|"_BoundCellBag_" -> Lbl_BoundCellBag_
|"isProcCellBag" -> LblisProcCellBag
|"SummandCellBagItem" -> LblSummandCellBagItem
|"bitRangeInt" -> LblbitRangeInt
|".ProcCellBag" -> Lbl'Stop'ProcCellBag
|"_<String__STRING" -> Lbl_'_LT_'String__STRING
|"<sum>-fragment" -> Lbl'_LT_'sum'_GT_Hyph'fragment
|"_List_" -> Lbl_List_
|"#ThreadLocal" -> Lbl'Hash'ThreadLocal
|"_|->_" -> Lbl_'PipeHyph_GT_'_
|"_-Map__MAP" -> Lbl_'Hyph'Map__MAP
|"_xorBool__BOOL" -> Lbl_xorBool__BOOL
|"_==K_" -> Lbl_'EqlsEqls'K_
|"_[_]_SUBSTITUTION" -> Lbl_'LSqB'_'RSqB'_SUBSTITUTION
|"replaceFirst(_,_,_)_STRING" -> LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING
|"initBoundCell" -> LblinitBoundCell
|".Map" -> Lbl'Stop'Map
|"_=/=String__STRING" -> Lbl_'EqlsSlshEqls'String__STRING
|"bigEndianBytes" -> LblbigEndianBytes
|"isBoundsCellOpt" -> LblisBoundsCellOpt
|"isSummandCellBag" -> LblisSummandCellBag
|"Id2String" -> LblId2String
|"isInt" -> LblisInt
|"Map:choice" -> LblMap'Coln'choice
|"isProcCellFragment" -> LblisProcCellFragment
|"_Set_" -> Lbl_Set_
|"_impliesBool__BOOL" -> Lbl_impliesBool__BOOL
|"_*Int__INT" -> Lbl_'Star'Int__INT
|"<T>" -> Lbl'_LT_'T'_GT_'
|"#Thread" -> Lbl'Hash'Thread
|"maxInt(_,_)_INT" -> LblmaxInt'LPar'_'Comm'_'RPar'_INT
|"isBool" -> LblisBool
|"~Int__INT" -> Lbl'Tild'Int__INT
|"_<=String__STRING" -> Lbl_'_LT_Eqls'String__STRING
|"ordChar" -> LblordChar
|"_modInt__INT" -> Lbl_modInt__INT
|"rfindChar" -> LblrfindChar
|"_Map_" -> Lbl_Map_
|"_-Int__INT" -> Lbl_'Hyph'Int__INT
|"directionalityChar" -> LbldirectionalityChar
|"Float2String" -> LblFloat2String
|"initKCell" -> LblinitKCell
|"sizeList" -> LblsizeList
|".Set" -> Lbl'Stop'Set
|"String2Id" -> LblString2Id
|"_=/=Bool__BOOL" -> Lbl_'EqlsSlshEqls'Bool__BOOL
|"isBoundsCell" -> LblisBoundsCell
|"<bounds>-fragment" -> Lbl'_LT_'bounds'_GT_Hyph'fragment
|"removeAll" -> LblremoveAll
|"isTCell" -> LblisTCell
|"_[_/_]_SUBSTITUTION" -> Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION
|"_andBool_" -> Lbl_andBool_
|"<par>" -> Lbl'_LT_'par'_GT_'
|"lengthString" -> LbllengthString
|"initTCell" -> LblinitTCell
|"Replication" -> LblReplication
|"signedBytes" -> LblsignedBytes
|"FloatFormat" -> LblFloatFormat
|"_+String__STRING" -> Lbl_'Plus'String__STRING
|"_^%Int___INT" -> Lbl_'Xor_Perc'Int___INT
|"_|Int__INT" -> Lbl_'Pipe'Int__INT
|"isKVariable" -> LblisKVariable
|"_dividesInt__INT" -> Lbl_dividesInt__INT
|"initSumCell" -> LblinitSumCell
|"rfindString" -> LblrfindString
|"<T>-fragment" -> Lbl'_LT_'T'_GT_Hyph'fragment
|"updateList" -> LblupdateList
|"Set:choice" -> LblSet'Coln'choice
|"isSumCellFragment" -> LblisSumCellFragment
|"categoryChar" -> LblcategoryChar
|"isSumCellOpt" -> LblisSumCellOpt
|"Set:difference" -> LblSet'Coln'difference
|"isName" -> LblisName
|"freshInt" -> LblfreshInt
|"isParCellFragment" -> LblisParCellFragment
|"isKCellOpt" -> LblisKCellOpt
|".SummandCellBag" -> Lbl'Stop'SummandCellBag
|"_xorInt__INT" -> Lbl_xorInt__INT
|"String2Float" -> LblString2Float
|"Map:lookupOrDefault" -> LblMap'Coln'lookupOrDefault
|"#if_#then_#else_#fi_K-EQUAL" -> Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL
|"_&Int__INT" -> Lbl_'And'Int__INT
|"isProcCell" -> LblisProcCell
|"isParCell" -> LblisParCell
|"littleEndianBytes" -> LbllittleEndianBytes
|"BoundCellBagItem" -> LblBoundCellBagItem
|"_<<Int__INT" -> Lbl_'_LT__LT_'Int__INT
|"log2Int" -> Lbllog2Int
|"_=/=Int__INT" -> Lbl_'EqlsSlshEqls'Int__INT
|"<par>-fragment" -> Lbl'_LT_'par'_GT_Hyph'fragment
|"Base2String" -> LblBase2String
|"ListItem" -> LblListItem
|"_>=String__STRING" -> Lbl_'_GT_Eqls'String__STRING
|"_<=Map__MAP" -> Lbl_'_LT_Eqls'Map__MAP
|"newUUID_STRING" -> LblnewUUID_STRING
|"sizeMap" -> LblsizeMap
|"isBoundCellBag" -> LblisBoundCellBag
|"isId" -> LblisId
|"substrString" -> LblsubstrString
|"size" -> Lblsize
|"isSummandCell" -> LblisSummandCell
|"project:Proc" -> Lblproject'Coln'Proc
|"Send" -> LblSend
|"initSummandCell" -> LblinitSummandCell
|"_inList_" -> Lbl_inList_
|"isBoundCell" -> LblisBoundCell
|"minInt(_,_)_INT" -> LblminInt'LPar'_'Comm'_'RPar'_INT
|"isMap" -> LblisMap
|"srandInt" -> LblsrandInt
|"isKItem" -> LblisKItem
|"Receive" -> LblReceive
|"isBoundsCellFragment" -> LblisBoundsCellFragment
|".BoundCellBag" -> Lbl'Stop'BoundCellBag
|"List:set" -> LblList'Coln'set
|"String2Base" -> LblString2Base
|"<bound>" -> Lbl'_LT_'bound'_GT_'
|"isTCellFragment" -> LblisTCellFragment
|"replace(_,_,_,_)_STRING" -> Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING
|"_/Int__INT" -> Lbl_'Slsh'Int__INT
|"_[_<-_]_MAP" -> Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP
|"keys" -> Lblkeys
|"Or" -> LblOr
|"<bounds>" -> Lbl'_LT_'bounds'_GT_'
| _ -> invalid_arg ("parse_klabel: " ^ c)
let collection_for (c: klabel) : klabel = match c with
|LblSetItem -> Lbl_Set_
|Lbl_ProcCellBag_ -> Lbl_ProcCellBag_
|Lbl'Stop'Set -> Lbl_Set_
|Lbl'Stop'BoundCellBag -> Lbl_BoundCellBag_
|Lbl_BoundCellBag_ -> Lbl_BoundCellBag_
|LblBoundCellBagItem -> Lbl_BoundCellBag_
|LblProcCellBagItem -> Lbl_ProcCellBag_
|Lbl'_LT_'bound'_GT_' -> Lbl_BoundCellBag_
|LblListItem -> Lbl_List_
|Lbl_Map_ -> Lbl_Map_
|LblSummandCellBagItem -> Lbl_SummandCellBag_
|Lbl_SummandCellBag_ -> Lbl_SummandCellBag_
|Lbl'Stop'SummandCellBag -> Lbl_SummandCellBag_
|Lbl'Stop'ProcCellBag -> Lbl_ProcCellBag_
|Lbl'Stop'List -> Lbl_List_
|Lbl_Set_ -> Lbl_Set_
|Lbl'_LT_'proc'_GT_' -> Lbl_ProcCellBag_
|Lbl_List_ -> Lbl_List_
|Lbl'Stop'Map -> Lbl_Map_
|Lbl_'PipeHyph_GT_'_ -> Lbl_Map_
|Lbl'_LT_'summand'_GT_' -> Lbl_SummandCellBag_
| _ -> invalid_arg "collection_for"
let unit_for (c: klabel) : klabel = match c with
|Lbl_ProcCellBag_ -> Lbl'Stop'ProcCellBag
|Lbl_Set_ -> Lbl'Stop'Set
|Lbl_List_ -> Lbl'Stop'List
|Lbl_BoundCellBag_ -> Lbl'Stop'BoundCellBag
|Lbl_Map_ -> Lbl'Stop'Map
|Lbl_SummandCellBag_ -> Lbl'Stop'SummandCellBag
| _ -> invalid_arg "unit_for"
let el_for (c: klabel) : klabel = match c with
|Lbl_ProcCellBag_ -> LblProcCellBagItem
|Lbl_Set_ -> LblSetItem
|Lbl_List_ -> LblListItem
|Lbl_BoundCellBag_ -> LblBoundCellBagItem
|Lbl_Map_ -> Lbl_'PipeHyph_GT_'_
|Lbl_SummandCellBag_ -> LblSummandCellBagItem
| _ -> invalid_arg "el_for"
let unit_for_array (c: sort) : klabel = match c with
| _ -> invalid_arg "unit_for_array"
let el_for_array (c: sort) : klabel = match c with
| _ -> invalid_arg "el_for_array"
module Dynarray : sig
type 'a t
val make : int -> 'a -> 'a t
val length : 'a t -> int
val get : 'a t -> int -> 'a
val set : 'a t -> int -> 'a -> unit
val compare : ('a list -> 'a list -> int) -> 'a t -> 'a t -> int
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val fold_right : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val iteri : (int -> 'a -> unit) -> 'a t -> unit
end = struct
type 'a t = { size: int; mutable arr: 'a array; default: 'a }
let make size default = { size=size; arr=Array.make (min size 10) default; default=default}
let length arr = arr.size
let get arr idx = if idx >= Array.length arr.arr && idx < arr.size then arr.default else Array.get arr.arr idx
let calc_size arr at_least = let double = Array.length arr.arr * 2 in
let at_most = if double > arr.size then arr.size else double in
if at_least > at_most then at_least else at_most
let upgrade_size arr size = let old = arr.arr in arr.arr <- Array.make size arr.default; Array.blit old 0 arr.arr 0 (Array.length old)
let set arr idx value= if idx >= Array.length arr.arr && idx < arr.size then upgrade_size arr (calc_size arr (idx + 1));
Array.set arr.arr idx value
let compare_arr f a b = let smaller,larger = if Array.length a.arr < Array.length b.arr then a,b else b,a in
upgrade_size smaller (Array.length larger.arr);
f (Array.to_list a.arr) (Array.to_list b.arr)
let compare f a b = let v = Pervasives.compare a.size b.size in if v = 0 then compare_arr f a b else v
let fold_left f init arr = snd (Array.fold_left (fun (i,x) a -> if i > 0 then (i - 1, f x a) else (0,x)) (arr.size,init) arr.arr)
let fold_right f arr init = snd (Array.fold_right (fun a (i,x) -> if i > 0 then (i - 1, x) else (0, f a x)) arr.arr (Array.length arr.arr - arr.size, init))
let iteri f arr = Array.iteri (fun i a -> if i < arr.size then f i a else ()) arr.arr
end
module type S =
sig
type m
type s
type t = kitem list
and kitem = KToken of sort * string
| InjectedKLabel of klabel
| Map of sort * klabel * m
| List of sort * klabel * t list
| Set of sort * klabel * s
| Array of sort * t * t Dynarray.t
| Int of Z.t
| Float of Gmp.FR.t * int * int
| String of string
| Bytes of bytes
| StringBuffer of Buffer.t
| Bool of bool
| MInt of int * Z.t
| ThreadLocal
| Thread of t * t * t * t
| Bottom
| KApply0 of klabel
| KApply1 of klabel * t
| KApply2 of klabel * t * t
| KApply3 of klabel * t * t * t
| KApply4 of klabel * t * t * t * t
val compare : t -> t -> int
val compare_kitem : kitem -> kitem -> int
val compare_klist : t list -> t list -> int
val equal_k : t -> t -> bool
val hash_k : t -> int
val hash_k_param : int -> t -> int
end
module rec K : (S with type m = K.t Map.Make(K).t and type s = Set.Make(K).t) =
struct
module KMap = Map.Make(K)
module KSet = Set.Make(K)
type m = K.t KMap.t
and s = KSet.t
and t = kitem list
and kitem = KToken of sort * string
| InjectedKLabel of klabel
| Map of sort * klabel * m
| List of sort * klabel * t list
| Set of sort * klabel * s
| Array of sort * t * t Dynarray.t
| Int of Z.t
| Float of Gmp.FR.t * int * int
| String of string
| Bytes of bytes
| StringBuffer of Buffer.t
| Bool of bool
| MInt of int * Z.t
| ThreadLocal
| Thread of t * t * t * t
| Bottom
| KApply0 of klabel
| KApply1 of klabel * t
| KApply2 of klabel * t * t
| KApply3 of klabel * t * t * t
| KApply4 of klabel * t * t * t * t
let rec hash_k c = match c with
| [] -> 1
| hd :: tl -> (hash_k tl) * 31 + hash_kitem hd
and hash_kitem c = match c with
| KApply0(lbl) -> (Hashtbl.hash lbl)
| KApply1(lbl,k0) -> ((Hashtbl.hash lbl)) * 37 + hash_k k0
| KApply2(lbl,k0,k1) -> (((Hashtbl.hash lbl)) * 37 + hash_k k0) * 37 + hash_k k1
| KApply3(lbl,k0,k1,k2) -> ((((Hashtbl.hash lbl)) * 37 + hash_k k0) * 37 + hash_k k1) * 37 + hash_k k2
| KApply4(lbl,k0,k1,k2,k3) -> (((((Hashtbl.hash lbl)) * 37 + hash_k k0) * 37 + hash_k k1) * 37 + hash_k k2) * 37 + hash_k k3
| KToken(s, st) -> Hashtbl.hash s * 41 + Hashtbl.hash st
| InjectedKLabel kl -> Hashtbl.hash kl
| Map(_,k,m) -> Hashtbl.hash k * 43 + KMap.fold (fun k v accum -> accum + (hash_k k lxor hash_k v)) m 0
| List(_,k,l) -> Hashtbl.hash k * 47 + hash_klist l
| Set(_,k,s) -> Hashtbl.hash k * 53 + KSet.fold (fun k accum -> accum + hash_k k) s 0
| Array(k,_,l) -> Hashtbl.hash k * 61 + (Dynarray.length l)
| Int i -> Z.hash i
| Float (f,_,_) -> Hashtbl.hash (Gmp.FR.to_float f)
| String s -> Hashtbl.hash s
| StringBuffer s -> Hashtbl.hash (Buffer.contents s)
| Bytes b -> Hashtbl.hash b
| Bool b -> Hashtbl.hash b
| MInt (w,i) -> Hashtbl.hash w * 67 + Z.hash i
| Bottom -> 1
| ThreadLocal -> 2
| Thread(k1,k2,k3,k4) -> ((((Hashtbl.hash Lbl'Hash'Thread) * 37 + hash_k k1) * 37 + hash_k k2) * 37 + hash_k k3) * 36 + hash_k k4
and hash_klist c = match c with
| [] -> 1
| hd :: tl -> (hash_klist tl) * 59 + hash_k hd
let rec hash_k_param_fld ((l,max) as lmax) = function
| [] -> lmax
| h::t -> if max < 0 then lmax else hash_k_param_fld (h::l,max-1) t
let hash_k_param_add_kitem k max =
hash_k_param_fld max k
let rec qfld l1 h max = match l1 with
| [] -> let (l2,max) = max in if l2 = [] then h else qfld l2 h ([],max)
| ki :: kq -> match ki with
| KApply0(lbl) ->
qfld kq (31*h + Hashtbl.hash lbl) (
max)
| KApply1(lbl,k0) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
max))
| KApply2(lbl,k0,k1) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
hash_k_param_add_kitem k1 (
max)))
| KApply3(lbl,k0,k1,k2) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
hash_k_param_add_kitem k1 (
hash_k_param_add_kitem k2 (
max))))
| KApply4(lbl,k0,k1,k2,k3) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
hash_k_param_add_kitem k1 (
hash_k_param_add_kitem k2 (
hash_k_param_add_kitem k3 (
max)))))
| KToken(s, st) ->
qfld kq (31*h + Hashtbl.hash s * 41 + Hashtbl.hash st) (
max)
| InjectedKLabel lbl ->
qfld kq (31*h + Hashtbl.hash lbl) (
max)
| Map(_,lbl,m) ->
qfld kq (31*h + 43 * Hashtbl.hash lbl) (
KMap.fold (fun k v max -> hash_k_param_add_kitem v (hash_k_param_add_kitem k max)) m max)
| List(_,lbl,l) ->
qfld kq (31*h + 47 * Hashtbl.hash lbl) (
List.fold_left (fun max k -> hash_k_param_add_kitem k max) max l)
| Set(_,lbl,s) ->
qfld kq (31*h + 53 * Hashtbl.hash lbl) (
KSet.fold (fun k max -> hash_k_param_add_kitem k max) s max)
| Array(lbl,_,l) ->
qfld kq (31*h + 61 * Hashtbl.hash lbl + Dynarray.length l) (
max)
| Int i -> qfld kq (31*h + Z.hash i) (
max)
| Float (f,_,_) -> qfld kq (31*h + Hashtbl.hash (Gmp.FR.to_float f)) (
max)
| String s -> qfld kq (31*h + Hashtbl.hash s) (
max)
| Bytes b -> qfld kq (31*h + Hashtbl.hash b) (
max)
| StringBuffer s -> qfld kq (31*h + Hashtbl.hash (Buffer.contents s)) (
max)
| Bool b -> qfld kq (31*h + Hashtbl.hash b) (
max)
| MInt (w,i) -> qfld kq ((31*h + (Hashtbl.hash w))*67 + Z.hash i) (
max)
| Bottom -> qfld kq (31*h + 1) (
max)
| ThreadLocal -> qfld kq (31*h + 2) (
max)
| Thread(k1,k2,k3,k4) -> qfld kq (31*h + Hashtbl.hash Lbl'Hash'Thread) (hash_k_param_add_kitem k1 (hash_k_param_add_kitem k2 (hash_k_param_add_kitem k3 (hash_k_param_add_kitem k4 max))))
let hash_k_param max k =
qfld [] 0 (hash_k_param_add_kitem k ([],max))
let rec equal_k c1 c2 = if c1 == c2 then true else match (c1, c2) with
| [], [] -> true
| (hd1 :: tl1), (hd2 :: tl2) -> equal_kitem hd1 hd2 && equal_k tl1 tl2
| _ -> false
and equal_kitem c1 c2 = if c1 == c2 then true else match (c1, c2) with
| KApply0(lbl1),KApply0(lbl2) -> lbl1 = lbl2
| KApply1(lbl1,k0_1),KApply1(lbl2,k0_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2
| KApply2(lbl1,k0_1,k1_1),KApply2(lbl2,k0_2,k1_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2 && equal_k k1_1 k1_2
| KApply3(lbl1,k0_1,k1_1,k2_1),KApply3(lbl2,k0_2,k1_2,k2_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2 && equal_k k1_1 k1_2 && equal_k k2_1 k2_2
| KApply4(lbl1,k0_1,k1_1,k2_1,k3_1),KApply4(lbl2,k0_2,k1_2,k2_2,k3_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2 && equal_k k1_1 k1_2 && equal_k k2_1 k2_2 && equal_k k3_1 k3_2
| (KToken(s1, st1)), (KToken(s2, st2)) -> s1 = s2 && st1 = st2
| (InjectedKLabel kl1), (InjectedKLabel kl2) -> kl1 = kl2
| (Map (_,k1,m1)), (Map (_,k2,m2)) -> k1 = k2 && KMap.cardinal m1 = KMap.cardinal m2 && (KMap.equal) (equal_k) m1 m2
| (List (_,k1,l1)), (List (_,k2,l2)) -> k1 = k2 && equal_klist l1 l2
| (Set (_,k1,s1)), (Set (_,k2,s2)) -> k1 = k2 && KSet.cardinal s1 = KSet.cardinal s2 && (KSet.equal) s1 s2
| (Array (s1,k1,l1)), (Array (s2,k2,l2)) -> s1 = s2 && equal_k k1 k2 && l1 == l2
| (Int i1), (Int i2) -> Z.equal i1 i2
| (Float (f1,e1,p1)), (Float (f2,e2,p2)) -> e1 = e2 && p1 = p2 && Gmp.FR.compare f1 f2 = 0
| (String s1), (String s2) -> s1 = s2
| (Bytes b1), (Bytes b2) -> b1 == b2
| (StringBuffer s1), (StringBuffer s2) -> s1 == s2
| (Bool b1), (Bool b2) -> b1 = b2
| (MInt (w1,i1)), (MInt (w2,i2)) -> w1 = w2 && Z.equal i1 i2
| Bottom, Bottom -> true
| _ -> false
and equal_klist c1 c2 = if c1 == c2 then true else match (c1, c2) with
| [], [] -> true
| (hd1 :: tl1), (hd2 :: tl2) -> equal_k hd1 hd2 && equal_klist tl1 tl2
| _ -> false
let rec compare c1 c2 = if c1 == c2 then 0 else match (c1, c2) with
| [], [] -> 0
| (hd1 :: tl1), (hd2 :: tl2) -> let v = compare_kitem hd1 hd2 in if v = 0 then compare tl1 tl2 else v
| (_ :: _), _ -> -1
| _ -> 1
and compare_kitem c1 c2 = if c1 == c2 then 0 else match (c1, c2) with
| KApply0(lbl1),KApply0(lbl2) -> Pervasives.compare lbl1 lbl2
| KApply1(lbl1,k0_1),KApply1(lbl2,k0_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then compare k0_1 k0_2
else v)
| KApply2(lbl1,k0_1,k1_1),KApply2(lbl2,k0_2,k1_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then (let v = compare k0_1 k0_2 in if v = 0 then compare k1_1 k1_2
else v)
else v)
| KApply3(lbl1,k0_1,k1_1,k2_1),KApply3(lbl2,k0_2,k1_2,k2_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then (let v = compare k0_1 k0_2 in if v = 0 then (let v = compare k1_1 k1_2 in if v = 0 then compare k2_1 k2_2
else v)
else v)
else v)
| KApply4(lbl1,k0_1,k1_1,k2_1,k3_1),KApply4(lbl2,k0_2,k1_2,k2_2,k3_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then (let v = compare k0_1 k0_2 in if v = 0 then (let v = compare k1_1 k1_2 in if v = 0 then (let v = compare k2_1 k2_2 in if v = 0 then compare k3_1 k3_2
else v)
else v)
else v)
else v)
| (KToken(s1, st1)), (KToken(s2, st2)) -> let v = Pervasives.compare s1 s2 in if v = 0 then Pervasives.compare st1 st2 else v
| (InjectedKLabel kl1), (InjectedKLabel kl2) -> Pervasives.compare kl1 kl2
| (Map (_,k1,m1)), (Map (_,k2,m2)) -> let v = Pervasives.compare k1 k2 in if v = 0 then (KMap.compare) compare m1 m2 else v
| (List (_,k1,l1)), (List (_,k2,l2)) -> let v = Pervasives.compare k1 k2 in if v = 0 then compare_klist l1 l2 else v
| (Set (_,k1,s1)), (Set (_,k2,s2)) -> let v = Pervasives.compare k1 k2 in if v = 0 then (KSet.compare) s1 s2 else v
| (Array (s1,k1,l1)), (Array (s2,k2,l2)) -> let v = Pervasives.compare s1 s2 in if v = 0 then let v = compare k1 k2 in if v = 0 then Dynarray.compare compare_klist l1 l2 else v else v
| (Int i1), (Int i2) -> Z.compare i1 i2
| (Float (f1,e1,p1)), (Float (f2,e2,p2)) -> let v = e2 - e1 in if v = 0 then let v2 = p2 - p1 in if v2 = 0 then Gmp.FR.compare f1 f2 else v2 else v
| (String s1), (String s2) -> Pervasives.compare s1 s2
| (Bytes b1), (Bytes b2) -> Pervasives.compare b1 b2
| (StringBuffer s1), (StringBuffer s2) -> Pervasives.compare (Buffer.contents s1) (Buffer.contents s2)
| (Bool b1), (Bool b2) -> if b1 = b2 then 0 else if b1 then -1 else 1
| (MInt (w1,i1)), (MInt (w2,i2)) -> let v = Pervasives.compare w1 w2 in if v = 0 then Z.compare i1 i2 else v
| Bottom, Bottom -> 0
| ThreadLocal, ThreadLocal -> 0
| Thread (k11, k12, k13, k14), Thread (k21, k22, k23, k24) -> let v = compare k11 k21 in if v = 0 then let v = compare k12 k22 in if v = 0 then let v = compare k13 k23 in if v = 0 then compare k14 k24 else v else v else v
| KApply0 _, _ -> -1
| _, KApply0 _ -> 1
| KApply1 _, _ -> -1
| _, KApply1 _ -> 1
| KApply2 _, _ -> -1
| _, KApply2 _ -> 1
| KApply3 _, _ -> -1
| _, KApply3 _ -> 1
| KApply4 _, _ -> -1
| _, KApply4 _ -> 1
| KToken(_, _), _ -> -1
| _, KToken(_, _) -> 1
| InjectedKLabel(_), _ -> -1
| _, InjectedKLabel(_) -> 1
| Map(_), _ -> -1
| _, Map(_) -> 1
| List(_), _ -> -1
| _, List(_) -> 1
| Set(_), _ -> -1
| _, Set(_) -> 1
| Array(_), _ -> -1
| _, Array(_) -> 1
| Int(_), _ -> -1
| _, Int(_) -> 1
| Float(_), _ -> -1
| _, Float(_) -> 1
| String(_), _ -> -1
| _, String(_) -> 1
| Bytes(_), _ -> -1
| _, Bytes(_) -> 1
| StringBuffer(_), _ -> -1
| _, StringBuffer(_) -> 1
| Bool(_), _ -> -1
| _, Bool(_) -> 1
| MInt _, _ -> -1
| _, MInt _ -> 1
| Bottom, _ -> -1
| _, Bottom -> 1
| ThreadLocal, _ -> -1
| _, ThreadLocal -> 1
and compare_klist c1 c2 = match (c1, c2) with
| [], [] -> 0
| (hd1 :: tl1), (hd2 :: tl2) -> let v = compare hd1 hd2 in if v = 0 then compare_klist tl1 tl2 else v
| (_ :: _), _ -> -1
| _ -> 1
end
type normal_kitem = KApply of klabel * K.t list
| KItem of K.kitem
open K
let normalize (k: kitem) : normal_kitem = match k with
| KApply0(lbl) -> KApply (lbl, [])
| KApply1(lbl,k0) -> KApply (lbl, [k0])
| KApply2(lbl,k0,k1) -> KApply (lbl, [k0; k1])
| KApply3(lbl,k0,k1,k2) -> KApply (lbl, [k0; k1; k2])
| KApply4(lbl,k0,k1,k2,k3) -> KApply (lbl, [k0; k1; k2; k3])
| v -> KItem v
let denormalize (k: normal_kitem) : kitem = match k with
| KApply (lbl, []) -> KApply0(lbl)
| KApply (lbl, [k0]) -> KApply1(lbl,k0)
| KApply (lbl, [k0; k1]) -> KApply2(lbl,k0,k1)
| KApply (lbl, [k0; k1; k2]) -> KApply3(lbl,k0,k1,k2)
| KApply (lbl, [k0; k1; k2; k3]) -> KApply4(lbl,k0,k1,k2,k3)
| KItem v -> v
| KApply (_, _) -> invalid_arg "denormalize"
type k = K.t
let denormalize0 (c: unit) : k list = match c with () -> []
let normalize0 (c: k list) = match c with [] -> ()
| _ -> invalid_arg "normalize0"
let denormalize1 (c: k) : k list = match c with (k0) -> [k0]
let normalize1 (c: k list) = match c with [k0] -> (k0)
| _ -> invalid_arg "normalize1"
let denormalize2 (c: k * k) : k list = match c with (k0,k1) -> [k0; k1]
let normalize2 (c: k list) = match c with [k0; k1] -> (k0,k1)
| _ -> invalid_arg "normalize2"
let denormalize3 (c: k * k * k) : k list = match c with (k0,k1,k2) -> [k0; k1; k2]
let normalize3 (c: k list) = match c with [k0; k1; k2] -> (k0,k1,k2)
| _ -> invalid_arg "normalize3"
let denormalize4 (c: k * k * k * k) : k list = match c with (k0,k1,k2,k3) -> [k0; k1; k2; k3]
let normalize4 (c: k list) = match c with [k0; k1; k2; k3] -> (k0,k1,k2,k3)
| _ -> invalid_arg "normalize4"
let int0 = lazy (Int (Z.of_string "0"))
let int1 = lazy (Int (Z.of_string "1"))
let int'Hyph'1 = lazy (Int (Z.of_string "-1"))
let constnoKCell = KApply0(LblnoKCell)
let const'Hash'Bottom = KApply0(Lbl'Hash'Bottom)
let const'Stop'Map = KApply0(Lbl'Stop'Map)
let constnoSumCell = KApply0(LblnoSumCell)
let constnewUUID_STRING = KApply0(LblnewUUID_STRING)
let const'Stop'BoundCellBag = KApply0(Lbl'Stop'BoundCellBag)
let const'Stop'Set = KApply0(Lbl'Stop'Set)
let const'Stop'List = KApply0(Lbl'Stop'List)
let constinitBoundsCell = KApply0(LblinitBoundsCell)
let constinitSummandCell = KApply0(LblinitSummandCell)
let constnoParCell = KApply0(LblnoParCell)
let constnoBoundsCell = KApply0(LblnoBoundsCell)
let constNil_PI'Hyph'SYNTAX = KApply0(LblNil_PI'Hyph'SYNTAX)
let const'Stop'ProcCellBag = KApply0(Lbl'Stop'ProcCellBag)
let constinitBoundCell = KApply0(LblinitBoundCell)
let const'Hash'ThreadLocal = KApply0(Lbl'Hash'ThreadLocal)
let constinitSumCell = KApply0(LblinitSumCell)
let const'Stop'SummandCellBag = KApply0(Lbl'Stop'SummandCellBag)
let val_for (c: klabel) (k : k) (v : k) : normal_kitem = match c with
|_ -> KApply((el_for c), [k;v])
| null | https://raw.githubusercontent.com/Isaac-DeFrain/KFramework/54e6b833f104222ef24ea75551dc97c0ae4f588c/Languages/Pi-Calc/pi-kompiled/constants.ml | ocaml | type sort =
|SortProcCell
|SortBoundsCell
|SortBool
|SortK
|SortMap
|SortSumCell
|SortParCellFragment
|SortKVariable
|SortKCell
|SortBytes
|SortKItem
|SortStringBuffer
|SortName
|SortTCell
|SortInt
|SortProcCellBag
|SortBoundsCellOpt
|SortKConfigVar
|SortBoundCell
|SortSumCellFragment
|SortProcCellFragment
|SortProc
|SortKCellOpt
|SortString
|SortFloat
|SortSummandCellBag
|SortSumCellOpt
|SortTCellFragment
|SortBoundCellBag
|SortParCellOpt
|SortSet
|SortParCell
|SortMInt
|SortId
|SortNormProc
|SortCell
|SortSummandCell
|SortList
|SortBoundsCellFragment
type klabel =
|Lbl_ProcCellBag_
|Lbl_'_LT_Eqls'Int__INT
|LblnotBool_
|LblMap'Coln'lookup
|LblnoKCell
|LblsignExtendBitRangeInt
|Lbl_'EqlsEqls'Bool__BOOL
|LblisSet
|LblintersectSet
|Lbl_in_keys'LPar'_'RPar'_MAP
|LblfindChar
|LblSet'Coln'in
|LblisK
|LblString2Int
|Lbl_'_LT_Eqls'Set__SET
|Lbl'_LT_'proc'_GT_Hyph'fragment
|LblmakeList
|Lbl_'LSqB'_'_LT_Hyph'undef'RSqB'
|Lbl'Hash'Bottom
|LblisNormProc
|Lbl_'EqlsEqls'Int_
|Lbl_andThenBool__BOOL
|LblnoBoundsCell
|LblinitProcCell
|LblisString
|Lbl_'Perc'Int__INT
|Lbl_'_GT__GT_'Int__INT
|LblisList
|LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING
|Lbl_SummandCellBag_
|LblPar
|Lbl_'Xor_'Int__INT
|LblfindString
|Lbl'_LT_'k'_GT_'
|LblabsInt
|Lbl_'_GT_'String__STRING
|Lbl_'EqlsEqls'String__STRING
|LblisKConfigVar
|LblnoParCell
|LblisSumCell
|LblisCell
|Lblvalues
|Lbl'_LT_'proc'_GT_'
|LblList'Coln'get
|Lbl'_LT_'summand'_GT_'
|LblSetItem
|LblunsignedBytes
|Lbl'_LT_'sum'_GT_'
|Lbl_'_LT_'Int__INT
|Lbl'Stop'List
|LblNil_PI'Hyph'SYNTAX
|LblrandInt
|LblisFloat
|LblisParCellOpt
|LblinitBoundsCell
|Lblkeys_list'LPar'_'RPar'_MAP
|LblfreshId
|LblchrChar
|Lbl_orElseBool__BOOL
|Lbl_divInt__INT
|LblList'Coln'range
|LblisProc
|Lbl_'Plus'Int_
|LblisKCell
|LblProcCellBagItem
|Lbl_orBool__BOOL
|LblinitParCell
|Lbl_'_GT_Eqls'Int__INT
|LblNew
|LblnoSumCell
|LblupdateMap
|LblInt2String
|Lbl_'EqlsSlshEqls'K_
|LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING
|Lbl_'_GT_'Int__INT
|LblfillList
|Lbl_BoundCellBag_
|LblisProcCellBag
|LblSummandCellBagItem
|LblbitRangeInt
|Lbl'Stop'ProcCellBag
|Lbl_'_LT_'String__STRING
|Lbl'_LT_'sum'_GT_Hyph'fragment
|Lbl_List_
|Lbl'Hash'ThreadLocal
|Lbl_'PipeHyph_GT_'_
|Lbl_'Hyph'Map__MAP
|Lbl_xorBool__BOOL
|Lbl_'EqlsEqls'K_
|Lbl_'LSqB'_'RSqB'_SUBSTITUTION
|LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING
|LblinitBoundCell
|Lbl'Stop'Map
|Lbl_'EqlsSlshEqls'String__STRING
|LblbigEndianBytes
|LblisBoundsCellOpt
|LblisSummandCellBag
|LblId2String
|LblisInt
|LblMap'Coln'choice
|LblisProcCellFragment
|Lbl_Set_
|Lbl_impliesBool__BOOL
|Lbl_'Star'Int__INT
|Lbl'_LT_'T'_GT_'
|Lbl'Hash'Thread
|LblmaxInt'LPar'_'Comm'_'RPar'_INT
|LblisBool
|Lbl'Tild'Int__INT
|Lbl_'_LT_Eqls'String__STRING
|LblordChar
|Lbl_modInt__INT
|LblrfindChar
|Lbl_Map_
|Lbl_'Hyph'Int__INT
|LbldirectionalityChar
|LblFloat2String
|LblinitKCell
|LblsizeList
|Lbl'Stop'Set
|LblString2Id
|Lbl_'EqlsSlshEqls'Bool__BOOL
|LblisBoundsCell
|Lbl'_LT_'bounds'_GT_Hyph'fragment
|LblremoveAll
|LblisTCell
|Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION
|Lbl_andBool_
|Lbl'_LT_'par'_GT_'
|LbllengthString
|LblinitTCell
|LblReplication
|LblsignedBytes
|LblFloatFormat
|Lbl_'Plus'String__STRING
|Lbl_'Xor_Perc'Int___INT
|Lbl_'Pipe'Int__INT
|LblisKVariable
|Lbl_dividesInt__INT
|LblinitSumCell
|LblrfindString
|Lbl'_LT_'T'_GT_Hyph'fragment
|LblupdateList
|LblSet'Coln'choice
|LblisSumCellFragment
|LblcategoryChar
|LblisSumCellOpt
|LblSet'Coln'difference
|LblisName
|LblfreshInt
|LblisParCellFragment
|LblisKCellOpt
|Lbl'Stop'SummandCellBag
|Lbl_xorInt__INT
|LblString2Float
|LblMap'Coln'lookupOrDefault
|Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL
|Lbl_'And'Int__INT
|LblisProcCell
|LblisParCell
|LbllittleEndianBytes
|LblBoundCellBagItem
|Lbl_'_LT__LT_'Int__INT
|Lbllog2Int
|Lbl_'EqlsSlshEqls'Int__INT
|Lbl'_LT_'par'_GT_Hyph'fragment
|LblBase2String
|LblListItem
|Lbl_'_GT_Eqls'String__STRING
|Lbl_'_LT_Eqls'Map__MAP
|LblnewUUID_STRING
|LblsizeMap
|LblisBoundCellBag
|LblisId
|LblsubstrString
|Lblsize
|LblisSummandCell
|Lblproject'Coln'Proc
|LblSend
|LblinitSummandCell
|Lbl_inList_
|LblisBoundCell
|LblminInt'LPar'_'Comm'_'RPar'_INT
|LblisMap
|LblsrandInt
|LblisKItem
|LblReceive
|LblisBoundsCellFragment
|Lbl'Stop'BoundCellBag
|LblList'Coln'set
|LblString2Base
|Lbl'_LT_'bound'_GT_'
|LblisTCellFragment
|Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING
|Lbl_'Slsh'Int__INT
|Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP
|Lblkeys
|LblOr
|Lbl'_LT_'bounds'_GT_'
let print_sort(c: sort) : string = match c with
|SortProcCell -> "ProcCell"
|SortBoundsCell -> "BoundsCell"
|SortBool -> "Bool"
|SortK -> "K"
|SortMap -> "Map"
|SortSumCell -> "SumCell"
|SortParCellFragment -> "ParCellFragment"
|SortKVariable -> "KVariable"
|SortKCell -> "KCell"
|SortBytes -> "Bytes"
|SortKItem -> "KItem"
|SortStringBuffer -> "StringBuffer"
|SortName -> "Name"
|SortTCell -> "TCell"
|SortInt -> "Int"
|SortProcCellBag -> "ProcCellBag"
|SortBoundsCellOpt -> "BoundsCellOpt"
|SortKConfigVar -> "KConfigVar"
|SortBoundCell -> "BoundCell"
|SortSumCellFragment -> "SumCellFragment"
|SortProcCellFragment -> "ProcCellFragment"
|SortProc -> "Proc"
|SortKCellOpt -> "KCellOpt"
|SortString -> "String"
|SortFloat -> "Float"
|SortSummandCellBag -> "SummandCellBag"
|SortSumCellOpt -> "SumCellOpt"
|SortTCellFragment -> "TCellFragment"
|SortBoundCellBag -> "BoundCellBag"
|SortParCellOpt -> "ParCellOpt"
|SortSet -> "Set"
|SortParCell -> "ParCell"
|SortMInt -> "MInt"
|SortId -> "Id"
|SortNormProc -> "NormProc"
|SortCell -> "Cell"
|SortSummandCell -> "SummandCell"
|SortList -> "List"
|SortBoundsCellFragment -> "BoundsCellFragment"
let print_klabel(c: klabel) : string = match c with
|Lbl_ProcCellBag_ -> "`_ProcCellBag_`"
|Lbl_'_LT_Eqls'Int__INT -> "`_<=Int__INT`"
|LblnotBool_ -> "`notBool_`"
|LblMap'Coln'lookup -> "`Map:lookup`"
|LblnoKCell -> "noKCell"
|LblsignExtendBitRangeInt -> "signExtendBitRangeInt"
|Lbl_'EqlsEqls'Bool__BOOL -> "`_==Bool__BOOL`"
|LblisSet -> "isSet"
|LblintersectSet -> "intersectSet"
|Lbl_in_keys'LPar'_'RPar'_MAP -> "`_in_keys(_)_MAP`"
|LblfindChar -> "findChar"
|LblSet'Coln'in -> "`Set:in`"
|LblisK -> "isK"
|LblString2Int -> "`String2Int`"
|Lbl_'_LT_Eqls'Set__SET -> "`_<=Set__SET`"
|Lbl'_LT_'proc'_GT_Hyph'fragment -> "`<proc>-fragment`"
|LblmakeList -> "makeList"
|Lbl_'LSqB'_'_LT_Hyph'undef'RSqB' -> "`_[_<-undef]`"
|Lbl'Hash'Bottom -> "#Bottom"
|LblisNormProc -> "isNormProc"
|Lbl_'EqlsEqls'Int_ -> "`_==Int_`"
|Lbl_andThenBool__BOOL -> "`_andThenBool__BOOL`"
|LblnoBoundsCell -> "noBoundsCell"
|LblinitProcCell -> "initProcCell"
|LblisString -> "isString"
|Lbl_'Perc'Int__INT -> "`_%Int__INT`"
|Lbl_'_GT__GT_'Int__INT -> "`_>>Int__INT`"
|LblisList -> "isList"
|LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "`replaceAll(_,_,_)_STRING`"
|Lbl_SummandCellBag_ -> "`_SummandCellBag_`"
|LblPar -> "`Par`"
|Lbl_'Xor_'Int__INT -> "`_^Int__INT`"
|LblfindString -> "findString"
|Lbl'_LT_'k'_GT_' -> "`<k>`"
|LblabsInt -> "absInt"
|Lbl_'_GT_'String__STRING -> "`_>String__STRING`"
|Lbl_'EqlsEqls'String__STRING -> "`_==String__STRING`"
|LblisKConfigVar -> "isKConfigVar"
|LblnoParCell -> "noParCell"
|LblisSumCell -> "isSumCell"
|LblisCell -> "isCell"
|Lblvalues -> "values"
|Lbl'_LT_'proc'_GT_' -> "`<proc>`"
|LblList'Coln'get -> "`List:get`"
|Lbl'_LT_'summand'_GT_' -> "`<summand>`"
|LblSetItem -> "`SetItem`"
|LblunsignedBytes -> "unsignedBytes"
|Lbl'_LT_'sum'_GT_' -> "`<sum>`"
|Lbl_'_LT_'Int__INT -> "`_<Int__INT`"
|Lbl'Stop'List -> "`.List`"
|LblNil_PI'Hyph'SYNTAX -> "`Nil_PI-SYNTAX`"
|LblrandInt -> "randInt"
|LblisFloat -> "isFloat"
|LblisParCellOpt -> "isParCellOpt"
|LblinitBoundsCell -> "initBoundsCell"
|Lblkeys_list'LPar'_'RPar'_MAP -> "`keys_list(_)_MAP`"
|LblfreshId -> "freshId"
|LblchrChar -> "chrChar"
|Lbl_orElseBool__BOOL -> "`_orElseBool__BOOL`"
|Lbl_divInt__INT -> "`_divInt__INT`"
|LblList'Coln'range -> "`List:range`"
|LblisProc -> "isProc"
|Lbl_'Plus'Int_ -> "`_+Int_`"
|LblisKCell -> "isKCell"
|LblProcCellBagItem -> "`ProcCellBagItem`"
|Lbl_orBool__BOOL -> "`_orBool__BOOL`"
|LblinitParCell -> "initParCell"
|Lbl_'_GT_Eqls'Int__INT -> "`_>=Int__INT`"
|LblNew -> "`New`"
|LblnoSumCell -> "noSumCell"
|LblupdateMap -> "updateMap"
|LblInt2String -> "`Int2String`"
|Lbl_'EqlsSlshEqls'K_ -> "`_=/=K_`"
|LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING -> "`countAllOccurrences(_,_)_STRING`"
|Lbl_'_GT_'Int__INT -> "`_>Int__INT`"
|LblfillList -> "fillList"
|Lbl_BoundCellBag_ -> "`_BoundCellBag_`"
|LblisProcCellBag -> "isProcCellBag"
|LblSummandCellBagItem -> "`SummandCellBagItem`"
|LblbitRangeInt -> "bitRangeInt"
|Lbl'Stop'ProcCellBag -> "`.ProcCellBag`"
|Lbl_'_LT_'String__STRING -> "`_<String__STRING`"
|Lbl'_LT_'sum'_GT_Hyph'fragment -> "`<sum>-fragment`"
|Lbl_List_ -> "`_List_`"
|Lbl'Hash'ThreadLocal -> "#ThreadLocal"
|Lbl_'PipeHyph_GT_'_ -> "`_|->_`"
|Lbl_'Hyph'Map__MAP -> "`_-Map__MAP`"
|Lbl_xorBool__BOOL -> "`_xorBool__BOOL`"
|Lbl_'EqlsEqls'K_ -> "`_==K_`"
|Lbl_'LSqB'_'RSqB'_SUBSTITUTION -> "`_[_]_SUBSTITUTION`"
|LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "`replaceFirst(_,_,_)_STRING`"
|LblinitBoundCell -> "initBoundCell"
|Lbl'Stop'Map -> "`.Map`"
|Lbl_'EqlsSlshEqls'String__STRING -> "`_=/=String__STRING`"
|LblbigEndianBytes -> "bigEndianBytes"
|LblisBoundsCellOpt -> "isBoundsCellOpt"
|LblisSummandCellBag -> "isSummandCellBag"
|LblId2String -> "`Id2String`"
|LblisInt -> "isInt"
|LblMap'Coln'choice -> "`Map:choice`"
|LblisProcCellFragment -> "isProcCellFragment"
|Lbl_Set_ -> "`_Set_`"
|Lbl_impliesBool__BOOL -> "`_impliesBool__BOOL`"
|Lbl_'Star'Int__INT -> "`_*Int__INT`"
|Lbl'_LT_'T'_GT_' -> "`<T>`"
|Lbl'Hash'Thread -> "#Thread"
|LblmaxInt'LPar'_'Comm'_'RPar'_INT -> "`maxInt(_,_)_INT`"
|LblisBool -> "isBool"
|Lbl'Tild'Int__INT -> "`~Int__INT`"
|Lbl_'_LT_Eqls'String__STRING -> "`_<=String__STRING`"
|LblordChar -> "ordChar"
|Lbl_modInt__INT -> "`_modInt__INT`"
|LblrfindChar -> "rfindChar"
|Lbl_Map_ -> "`_Map_`"
|Lbl_'Hyph'Int__INT -> "`_-Int__INT`"
|LbldirectionalityChar -> "directionalityChar"
|LblFloat2String -> "`Float2String`"
|LblinitKCell -> "initKCell"
|LblsizeList -> "sizeList"
|Lbl'Stop'Set -> "`.Set`"
|LblString2Id -> "`String2Id`"
|Lbl_'EqlsSlshEqls'Bool__BOOL -> "`_=/=Bool__BOOL`"
|LblisBoundsCell -> "isBoundsCell"
|Lbl'_LT_'bounds'_GT_Hyph'fragment -> "`<bounds>-fragment`"
|LblremoveAll -> "removeAll"
|LblisTCell -> "isTCell"
|Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION -> "`_[_/_]_SUBSTITUTION`"
|Lbl_andBool_ -> "`_andBool_`"
|Lbl'_LT_'par'_GT_' -> "`<par>`"
|LbllengthString -> "lengthString"
|LblinitTCell -> "initTCell"
|LblReplication -> "`Replication`"
|LblsignedBytes -> "signedBytes"
|LblFloatFormat -> "`FloatFormat`"
|Lbl_'Plus'String__STRING -> "`_+String__STRING`"
|Lbl_'Xor_Perc'Int___INT -> "`_^%Int___INT`"
|Lbl_'Pipe'Int__INT -> "`_|Int__INT`"
|LblisKVariable -> "isKVariable"
|Lbl_dividesInt__INT -> "`_dividesInt__INT`"
|LblinitSumCell -> "initSumCell"
|LblrfindString -> "rfindString"
|Lbl'_LT_'T'_GT_Hyph'fragment -> "`<T>-fragment`"
|LblupdateList -> "updateList"
|LblSet'Coln'choice -> "`Set:choice`"
|LblisSumCellFragment -> "isSumCellFragment"
|LblcategoryChar -> "categoryChar"
|LblisSumCellOpt -> "isSumCellOpt"
|LblSet'Coln'difference -> "`Set:difference`"
|LblisName -> "isName"
|LblfreshInt -> "freshInt"
|LblisParCellFragment -> "isParCellFragment"
|LblisKCellOpt -> "isKCellOpt"
|Lbl'Stop'SummandCellBag -> "`.SummandCellBag`"
|Lbl_xorInt__INT -> "`_xorInt__INT`"
|LblString2Float -> "`String2Float`"
|LblMap'Coln'lookupOrDefault -> "`Map:lookupOrDefault`"
|Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL -> "`#if_#then_#else_#fi_K-EQUAL`"
|Lbl_'And'Int__INT -> "`_&Int__INT`"
|LblisProcCell -> "isProcCell"
|LblisParCell -> "isParCell"
|LbllittleEndianBytes -> "littleEndianBytes"
|LblBoundCellBagItem -> "`BoundCellBagItem`"
|Lbl_'_LT__LT_'Int__INT -> "`_<<Int__INT`"
|Lbllog2Int -> "log2Int"
|Lbl_'EqlsSlshEqls'Int__INT -> "`_=/=Int__INT`"
|Lbl'_LT_'par'_GT_Hyph'fragment -> "`<par>-fragment`"
|LblBase2String -> "`Base2String`"
|LblListItem -> "`ListItem`"
|Lbl_'_GT_Eqls'String__STRING -> "`_>=String__STRING`"
|Lbl_'_LT_Eqls'Map__MAP -> "`_<=Map__MAP`"
|LblnewUUID_STRING -> "`newUUID_STRING`"
|LblsizeMap -> "sizeMap"
|LblisBoundCellBag -> "isBoundCellBag"
|LblisId -> "isId"
|LblsubstrString -> "substrString"
|Lblsize -> "size"
|LblisSummandCell -> "isSummandCell"
|Lblproject'Coln'Proc -> "`project:Proc`"
|LblSend -> "`Send`"
|LblinitSummandCell -> "initSummandCell"
|Lbl_inList_ -> "`_inList_`"
|LblisBoundCell -> "isBoundCell"
|LblminInt'LPar'_'Comm'_'RPar'_INT -> "`minInt(_,_)_INT`"
|LblisMap -> "isMap"
|LblsrandInt -> "srandInt"
|LblisKItem -> "isKItem"
|LblReceive -> "`Receive`"
|LblisBoundsCellFragment -> "isBoundsCellFragment"
|Lbl'Stop'BoundCellBag -> "`.BoundCellBag`"
|LblList'Coln'set -> "`List:set`"
|LblString2Base -> "`String2Base`"
|Lbl'_LT_'bound'_GT_' -> "`<bound>`"
|LblisTCellFragment -> "isTCellFragment"
|Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING -> "`replace(_,_,_,_)_STRING`"
|Lbl_'Slsh'Int__INT -> "`_/Int__INT`"
|Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP -> "`_[_<-_]_MAP`"
|Lblkeys -> "keys"
|LblOr -> "`Or`"
|Lbl'_LT_'bounds'_GT_' -> "`<bounds>`"
let print_klabel_string(c: klabel) : string = match c with
|Lbl_ProcCellBag_ -> "_ProcCellBag_"
|Lbl_'_LT_Eqls'Int__INT -> "_<=Int__INT"
|LblnotBool_ -> "notBool_"
|LblMap'Coln'lookup -> "Map:lookup"
|LblnoKCell -> "noKCell"
|LblsignExtendBitRangeInt -> "signExtendBitRangeInt"
|Lbl_'EqlsEqls'Bool__BOOL -> "_==Bool__BOOL"
|LblisSet -> "isSet"
|LblintersectSet -> "intersectSet"
|Lbl_in_keys'LPar'_'RPar'_MAP -> "_in_keys(_)_MAP"
|LblfindChar -> "findChar"
|LblSet'Coln'in -> "Set:in"
|LblisK -> "isK"
|LblString2Int -> "String2Int"
|Lbl_'_LT_Eqls'Set__SET -> "_<=Set__SET"
|Lbl'_LT_'proc'_GT_Hyph'fragment -> "<proc>-fragment"
|LblmakeList -> "makeList"
|Lbl_'LSqB'_'_LT_Hyph'undef'RSqB' -> "_[_<-undef]"
|Lbl'Hash'Bottom -> "#Bottom"
|LblisNormProc -> "isNormProc"
|Lbl_'EqlsEqls'Int_ -> "_==Int_"
|Lbl_andThenBool__BOOL -> "_andThenBool__BOOL"
|LblnoBoundsCell -> "noBoundsCell"
|LblinitProcCell -> "initProcCell"
|LblisString -> "isString"
|Lbl_'Perc'Int__INT -> "_%Int__INT"
|Lbl_'_GT__GT_'Int__INT -> "_>>Int__INT"
|LblisList -> "isList"
|LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "replaceAll(_,_,_)_STRING"
|Lbl_SummandCellBag_ -> "_SummandCellBag_"
|LblPar -> "Par"
|Lbl_'Xor_'Int__INT -> "_^Int__INT"
|LblfindString -> "findString"
|Lbl'_LT_'k'_GT_' -> "<k>"
|LblabsInt -> "absInt"
|Lbl_'_GT_'String__STRING -> "_>String__STRING"
|Lbl_'EqlsEqls'String__STRING -> "_==String__STRING"
|LblisKConfigVar -> "isKConfigVar"
|LblnoParCell -> "noParCell"
|LblisSumCell -> "isSumCell"
|LblisCell -> "isCell"
|Lblvalues -> "values"
|Lbl'_LT_'proc'_GT_' -> "<proc>"
|LblList'Coln'get -> "List:get"
|Lbl'_LT_'summand'_GT_' -> "<summand>"
|LblSetItem -> "SetItem"
|LblunsignedBytes -> "unsignedBytes"
|Lbl'_LT_'sum'_GT_' -> "<sum>"
|Lbl_'_LT_'Int__INT -> "_<Int__INT"
|Lbl'Stop'List -> ".List"
|LblNil_PI'Hyph'SYNTAX -> "Nil_PI-SYNTAX"
|LblrandInt -> "randInt"
|LblisFloat -> "isFloat"
|LblisParCellOpt -> "isParCellOpt"
|LblinitBoundsCell -> "initBoundsCell"
|Lblkeys_list'LPar'_'RPar'_MAP -> "keys_list(_)_MAP"
|LblfreshId -> "freshId"
|LblchrChar -> "chrChar"
|Lbl_orElseBool__BOOL -> "_orElseBool__BOOL"
|Lbl_divInt__INT -> "_divInt__INT"
|LblList'Coln'range -> "List:range"
|LblisProc -> "isProc"
|Lbl_'Plus'Int_ -> "_+Int_"
|LblisKCell -> "isKCell"
|LblProcCellBagItem -> "ProcCellBagItem"
|Lbl_orBool__BOOL -> "_orBool__BOOL"
|LblinitParCell -> "initParCell"
|Lbl_'_GT_Eqls'Int__INT -> "_>=Int__INT"
|LblNew -> "New"
|LblnoSumCell -> "noSumCell"
|LblupdateMap -> "updateMap"
|LblInt2String -> "Int2String"
|Lbl_'EqlsSlshEqls'K_ -> "_=/=K_"
|LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING -> "countAllOccurrences(_,_)_STRING"
|Lbl_'_GT_'Int__INT -> "_>Int__INT"
|LblfillList -> "fillList"
|Lbl_BoundCellBag_ -> "_BoundCellBag_"
|LblisProcCellBag -> "isProcCellBag"
|LblSummandCellBagItem -> "SummandCellBagItem"
|LblbitRangeInt -> "bitRangeInt"
|Lbl'Stop'ProcCellBag -> ".ProcCellBag"
|Lbl_'_LT_'String__STRING -> "_<String__STRING"
|Lbl'_LT_'sum'_GT_Hyph'fragment -> "<sum>-fragment"
|Lbl_List_ -> "_List_"
|Lbl'Hash'ThreadLocal -> "#ThreadLocal"
|Lbl_'PipeHyph_GT_'_ -> "_|->_"
|Lbl_'Hyph'Map__MAP -> "_-Map__MAP"
|Lbl_xorBool__BOOL -> "_xorBool__BOOL"
|Lbl_'EqlsEqls'K_ -> "_==K_"
|Lbl_'LSqB'_'RSqB'_SUBSTITUTION -> "_[_]_SUBSTITUTION"
|LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING -> "replaceFirst(_,_,_)_STRING"
|LblinitBoundCell -> "initBoundCell"
|Lbl'Stop'Map -> ".Map"
|Lbl_'EqlsSlshEqls'String__STRING -> "_=/=String__STRING"
|LblbigEndianBytes -> "bigEndianBytes"
|LblisBoundsCellOpt -> "isBoundsCellOpt"
|LblisSummandCellBag -> "isSummandCellBag"
|LblId2String -> "Id2String"
|LblisInt -> "isInt"
|LblMap'Coln'choice -> "Map:choice"
|LblisProcCellFragment -> "isProcCellFragment"
|Lbl_Set_ -> "_Set_"
|Lbl_impliesBool__BOOL -> "_impliesBool__BOOL"
|Lbl_'Star'Int__INT -> "_*Int__INT"
|Lbl'_LT_'T'_GT_' -> "<T>"
|Lbl'Hash'Thread -> "#Thread"
|LblmaxInt'LPar'_'Comm'_'RPar'_INT -> "maxInt(_,_)_INT"
|LblisBool -> "isBool"
|Lbl'Tild'Int__INT -> "~Int__INT"
|Lbl_'_LT_Eqls'String__STRING -> "_<=String__STRING"
|LblordChar -> "ordChar"
|Lbl_modInt__INT -> "_modInt__INT"
|LblrfindChar -> "rfindChar"
|Lbl_Map_ -> "_Map_"
|Lbl_'Hyph'Int__INT -> "_-Int__INT"
|LbldirectionalityChar -> "directionalityChar"
|LblFloat2String -> "Float2String"
|LblinitKCell -> "initKCell"
|LblsizeList -> "sizeList"
|Lbl'Stop'Set -> ".Set"
|LblString2Id -> "String2Id"
|Lbl_'EqlsSlshEqls'Bool__BOOL -> "_=/=Bool__BOOL"
|LblisBoundsCell -> "isBoundsCell"
|Lbl'_LT_'bounds'_GT_Hyph'fragment -> "<bounds>-fragment"
|LblremoveAll -> "removeAll"
|LblisTCell -> "isTCell"
|Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION -> "_[_/_]_SUBSTITUTION"
|Lbl_andBool_ -> "_andBool_"
|Lbl'_LT_'par'_GT_' -> "<par>"
|LbllengthString -> "lengthString"
|LblinitTCell -> "initTCell"
|LblReplication -> "Replication"
|LblsignedBytes -> "signedBytes"
|LblFloatFormat -> "FloatFormat"
|Lbl_'Plus'String__STRING -> "_+String__STRING"
|Lbl_'Xor_Perc'Int___INT -> "_^%Int___INT"
|Lbl_'Pipe'Int__INT -> "_|Int__INT"
|LblisKVariable -> "isKVariable"
|Lbl_dividesInt__INT -> "_dividesInt__INT"
|LblinitSumCell -> "initSumCell"
|LblrfindString -> "rfindString"
|Lbl'_LT_'T'_GT_Hyph'fragment -> "<T>-fragment"
|LblupdateList -> "updateList"
|LblSet'Coln'choice -> "Set:choice"
|LblisSumCellFragment -> "isSumCellFragment"
|LblcategoryChar -> "categoryChar"
|LblisSumCellOpt -> "isSumCellOpt"
|LblSet'Coln'difference -> "Set:difference"
|LblisName -> "isName"
|LblfreshInt -> "freshInt"
|LblisParCellFragment -> "isParCellFragment"
|LblisKCellOpt -> "isKCellOpt"
|Lbl'Stop'SummandCellBag -> ".SummandCellBag"
|Lbl_xorInt__INT -> "_xorInt__INT"
|LblString2Float -> "String2Float"
|LblMap'Coln'lookupOrDefault -> "Map:lookupOrDefault"
|Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL -> "#if_#then_#else_#fi_K-EQUAL"
|Lbl_'And'Int__INT -> "_&Int__INT"
|LblisProcCell -> "isProcCell"
|LblisParCell -> "isParCell"
|LbllittleEndianBytes -> "littleEndianBytes"
|LblBoundCellBagItem -> "BoundCellBagItem"
|Lbl_'_LT__LT_'Int__INT -> "_<<Int__INT"
|Lbllog2Int -> "log2Int"
|Lbl_'EqlsSlshEqls'Int__INT -> "_=/=Int__INT"
|Lbl'_LT_'par'_GT_Hyph'fragment -> "<par>-fragment"
|LblBase2String -> "Base2String"
|LblListItem -> "ListItem"
|Lbl_'_GT_Eqls'String__STRING -> "_>=String__STRING"
|Lbl_'_LT_Eqls'Map__MAP -> "_<=Map__MAP"
|LblnewUUID_STRING -> "newUUID_STRING"
|LblsizeMap -> "sizeMap"
|LblisBoundCellBag -> "isBoundCellBag"
|LblisId -> "isId"
|LblsubstrString -> "substrString"
|Lblsize -> "size"
|LblisSummandCell -> "isSummandCell"
|Lblproject'Coln'Proc -> "project:Proc"
|LblSend -> "Send"
|LblinitSummandCell -> "initSummandCell"
|Lbl_inList_ -> "_inList_"
|LblisBoundCell -> "isBoundCell"
|LblminInt'LPar'_'Comm'_'RPar'_INT -> "minInt(_,_)_INT"
|LblisMap -> "isMap"
|LblsrandInt -> "srandInt"
|LblisKItem -> "isKItem"
|LblReceive -> "Receive"
|LblisBoundsCellFragment -> "isBoundsCellFragment"
|Lbl'Stop'BoundCellBag -> ".BoundCellBag"
|LblList'Coln'set -> "List:set"
|LblString2Base -> "String2Base"
|Lbl'_LT_'bound'_GT_' -> "<bound>"
|LblisTCellFragment -> "isTCellFragment"
|Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING -> "replace(_,_,_,_)_STRING"
|Lbl_'Slsh'Int__INT -> "_/Int__INT"
|Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP -> "_[_<-_]_MAP"
|Lblkeys -> "keys"
|LblOr -> "Or"
|Lbl'_LT_'bounds'_GT_' -> "<bounds>"
let parse_sort(c: string) : sort = match c with
|"ProcCell" -> SortProcCell
|"BoundsCell" -> SortBoundsCell
|"Bool" -> SortBool
|"K" -> SortK
|"Map" -> SortMap
|"SumCell" -> SortSumCell
|"ParCellFragment" -> SortParCellFragment
|"KVariable" -> SortKVariable
|"KCell" -> SortKCell
|"Bytes" -> SortBytes
|"KItem" -> SortKItem
|"StringBuffer" -> SortStringBuffer
|"Name" -> SortName
|"TCell" -> SortTCell
|"Int" -> SortInt
|"ProcCellBag" -> SortProcCellBag
|"BoundsCellOpt" -> SortBoundsCellOpt
|"KConfigVar" -> SortKConfigVar
|"BoundCell" -> SortBoundCell
|"SumCellFragment" -> SortSumCellFragment
|"ProcCellFragment" -> SortProcCellFragment
|"Proc" -> SortProc
|"KCellOpt" -> SortKCellOpt
|"String" -> SortString
|"Float" -> SortFloat
|"SummandCellBag" -> SortSummandCellBag
|"SumCellOpt" -> SortSumCellOpt
|"TCellFragment" -> SortTCellFragment
|"BoundCellBag" -> SortBoundCellBag
|"ParCellOpt" -> SortParCellOpt
|"Set" -> SortSet
|"ParCell" -> SortParCell
|"MInt" -> SortMInt
|"Id" -> SortId
|"NormProc" -> SortNormProc
|"Cell" -> SortCell
|"SummandCell" -> SortSummandCell
|"List" -> SortList
|"BoundsCellFragment" -> SortBoundsCellFragment
| _ -> invalid_arg ("parse_sort: " ^ c)
let parse_klabel(c: string) : klabel = match c with
|"_ProcCellBag_" -> Lbl_ProcCellBag_
|"_<=Int__INT" -> Lbl_'_LT_Eqls'Int__INT
|"notBool_" -> LblnotBool_
|"Map:lookup" -> LblMap'Coln'lookup
|"noKCell" -> LblnoKCell
|"signExtendBitRangeInt" -> LblsignExtendBitRangeInt
|"_==Bool__BOOL" -> Lbl_'EqlsEqls'Bool__BOOL
|"isSet" -> LblisSet
|"intersectSet" -> LblintersectSet
|"_in_keys(_)_MAP" -> Lbl_in_keys'LPar'_'RPar'_MAP
|"findChar" -> LblfindChar
|"Set:in" -> LblSet'Coln'in
|"isK" -> LblisK
|"String2Int" -> LblString2Int
|"_<=Set__SET" -> Lbl_'_LT_Eqls'Set__SET
|"<proc>-fragment" -> Lbl'_LT_'proc'_GT_Hyph'fragment
|"makeList" -> LblmakeList
|"_[_<-undef]" -> Lbl_'LSqB'_'_LT_Hyph'undef'RSqB'
|"#Bottom" -> Lbl'Hash'Bottom
|"isNormProc" -> LblisNormProc
|"_==Int_" -> Lbl_'EqlsEqls'Int_
|"_andThenBool__BOOL" -> Lbl_andThenBool__BOOL
|"noBoundsCell" -> LblnoBoundsCell
|"initProcCell" -> LblinitProcCell
|"isString" -> LblisString
|"_%Int__INT" -> Lbl_'Perc'Int__INT
|"_>>Int__INT" -> Lbl_'_GT__GT_'Int__INT
|"isList" -> LblisList
|"replaceAll(_,_,_)_STRING" -> LblreplaceAll'LPar'_'Comm'_'Comm'_'RPar'_STRING
|"_SummandCellBag_" -> Lbl_SummandCellBag_
|"Par" -> LblPar
|"_^Int__INT" -> Lbl_'Xor_'Int__INT
|"findString" -> LblfindString
|"<k>" -> Lbl'_LT_'k'_GT_'
|"absInt" -> LblabsInt
|"_>String__STRING" -> Lbl_'_GT_'String__STRING
|"_==String__STRING" -> Lbl_'EqlsEqls'String__STRING
|"isKConfigVar" -> LblisKConfigVar
|"noParCell" -> LblnoParCell
|"isSumCell" -> LblisSumCell
|"isCell" -> LblisCell
|"values" -> Lblvalues
|"<proc>" -> Lbl'_LT_'proc'_GT_'
|"List:get" -> LblList'Coln'get
|"<summand>" -> Lbl'_LT_'summand'_GT_'
|"SetItem" -> LblSetItem
|"unsignedBytes" -> LblunsignedBytes
|"<sum>" -> Lbl'_LT_'sum'_GT_'
|"_<Int__INT" -> Lbl_'_LT_'Int__INT
|".List" -> Lbl'Stop'List
|"Nil_PI-SYNTAX" -> LblNil_PI'Hyph'SYNTAX
|"randInt" -> LblrandInt
|"isFloat" -> LblisFloat
|"isParCellOpt" -> LblisParCellOpt
|"initBoundsCell" -> LblinitBoundsCell
|"keys_list(_)_MAP" -> Lblkeys_list'LPar'_'RPar'_MAP
|"freshId" -> LblfreshId
|"chrChar" -> LblchrChar
|"_orElseBool__BOOL" -> Lbl_orElseBool__BOOL
|"_divInt__INT" -> Lbl_divInt__INT
|"List:range" -> LblList'Coln'range
|"isProc" -> LblisProc
|"_+Int_" -> Lbl_'Plus'Int_
|"isKCell" -> LblisKCell
|"ProcCellBagItem" -> LblProcCellBagItem
|"_orBool__BOOL" -> Lbl_orBool__BOOL
|"initParCell" -> LblinitParCell
|"_>=Int__INT" -> Lbl_'_GT_Eqls'Int__INT
|"New" -> LblNew
|"noSumCell" -> LblnoSumCell
|"updateMap" -> LblupdateMap
|"Int2String" -> LblInt2String
|"_=/=K_" -> Lbl_'EqlsSlshEqls'K_
|"countAllOccurrences(_,_)_STRING" -> LblcountAllOccurrences'LPar'_'Comm'_'RPar'_STRING
|"_>Int__INT" -> Lbl_'_GT_'Int__INT
|"fillList" -> LblfillList
|"_BoundCellBag_" -> Lbl_BoundCellBag_
|"isProcCellBag" -> LblisProcCellBag
|"SummandCellBagItem" -> LblSummandCellBagItem
|"bitRangeInt" -> LblbitRangeInt
|".ProcCellBag" -> Lbl'Stop'ProcCellBag
|"_<String__STRING" -> Lbl_'_LT_'String__STRING
|"<sum>-fragment" -> Lbl'_LT_'sum'_GT_Hyph'fragment
|"_List_" -> Lbl_List_
|"#ThreadLocal" -> Lbl'Hash'ThreadLocal
|"_|->_" -> Lbl_'PipeHyph_GT_'_
|"_-Map__MAP" -> Lbl_'Hyph'Map__MAP
|"_xorBool__BOOL" -> Lbl_xorBool__BOOL
|"_==K_" -> Lbl_'EqlsEqls'K_
|"_[_]_SUBSTITUTION" -> Lbl_'LSqB'_'RSqB'_SUBSTITUTION
|"replaceFirst(_,_,_)_STRING" -> LblreplaceFirst'LPar'_'Comm'_'Comm'_'RPar'_STRING
|"initBoundCell" -> LblinitBoundCell
|".Map" -> Lbl'Stop'Map
|"_=/=String__STRING" -> Lbl_'EqlsSlshEqls'String__STRING
|"bigEndianBytes" -> LblbigEndianBytes
|"isBoundsCellOpt" -> LblisBoundsCellOpt
|"isSummandCellBag" -> LblisSummandCellBag
|"Id2String" -> LblId2String
|"isInt" -> LblisInt
|"Map:choice" -> LblMap'Coln'choice
|"isProcCellFragment" -> LblisProcCellFragment
|"_Set_" -> Lbl_Set_
|"_impliesBool__BOOL" -> Lbl_impliesBool__BOOL
|"_*Int__INT" -> Lbl_'Star'Int__INT
|"<T>" -> Lbl'_LT_'T'_GT_'
|"#Thread" -> Lbl'Hash'Thread
|"maxInt(_,_)_INT" -> LblmaxInt'LPar'_'Comm'_'RPar'_INT
|"isBool" -> LblisBool
|"~Int__INT" -> Lbl'Tild'Int__INT
|"_<=String__STRING" -> Lbl_'_LT_Eqls'String__STRING
|"ordChar" -> LblordChar
|"_modInt__INT" -> Lbl_modInt__INT
|"rfindChar" -> LblrfindChar
|"_Map_" -> Lbl_Map_
|"_-Int__INT" -> Lbl_'Hyph'Int__INT
|"directionalityChar" -> LbldirectionalityChar
|"Float2String" -> LblFloat2String
|"initKCell" -> LblinitKCell
|"sizeList" -> LblsizeList
|".Set" -> Lbl'Stop'Set
|"String2Id" -> LblString2Id
|"_=/=Bool__BOOL" -> Lbl_'EqlsSlshEqls'Bool__BOOL
|"isBoundsCell" -> LblisBoundsCell
|"<bounds>-fragment" -> Lbl'_LT_'bounds'_GT_Hyph'fragment
|"removeAll" -> LblremoveAll
|"isTCell" -> LblisTCell
|"_[_/_]_SUBSTITUTION" -> Lbl_'LSqB'_'Slsh'_'RSqB'_SUBSTITUTION
|"_andBool_" -> Lbl_andBool_
|"<par>" -> Lbl'_LT_'par'_GT_'
|"lengthString" -> LbllengthString
|"initTCell" -> LblinitTCell
|"Replication" -> LblReplication
|"signedBytes" -> LblsignedBytes
|"FloatFormat" -> LblFloatFormat
|"_+String__STRING" -> Lbl_'Plus'String__STRING
|"_^%Int___INT" -> Lbl_'Xor_Perc'Int___INT
|"_|Int__INT" -> Lbl_'Pipe'Int__INT
|"isKVariable" -> LblisKVariable
|"_dividesInt__INT" -> Lbl_dividesInt__INT
|"initSumCell" -> LblinitSumCell
|"rfindString" -> LblrfindString
|"<T>-fragment" -> Lbl'_LT_'T'_GT_Hyph'fragment
|"updateList" -> LblupdateList
|"Set:choice" -> LblSet'Coln'choice
|"isSumCellFragment" -> LblisSumCellFragment
|"categoryChar" -> LblcategoryChar
|"isSumCellOpt" -> LblisSumCellOpt
|"Set:difference" -> LblSet'Coln'difference
|"isName" -> LblisName
|"freshInt" -> LblfreshInt
|"isParCellFragment" -> LblisParCellFragment
|"isKCellOpt" -> LblisKCellOpt
|".SummandCellBag" -> Lbl'Stop'SummandCellBag
|"_xorInt__INT" -> Lbl_xorInt__INT
|"String2Float" -> LblString2Float
|"Map:lookupOrDefault" -> LblMap'Coln'lookupOrDefault
|"#if_#then_#else_#fi_K-EQUAL" -> Lbl'Hash'if_'Hash'then_'Hash'else_'Hash'fi_K'Hyph'EQUAL
|"_&Int__INT" -> Lbl_'And'Int__INT
|"isProcCell" -> LblisProcCell
|"isParCell" -> LblisParCell
|"littleEndianBytes" -> LbllittleEndianBytes
|"BoundCellBagItem" -> LblBoundCellBagItem
|"_<<Int__INT" -> Lbl_'_LT__LT_'Int__INT
|"log2Int" -> Lbllog2Int
|"_=/=Int__INT" -> Lbl_'EqlsSlshEqls'Int__INT
|"<par>-fragment" -> Lbl'_LT_'par'_GT_Hyph'fragment
|"Base2String" -> LblBase2String
|"ListItem" -> LblListItem
|"_>=String__STRING" -> Lbl_'_GT_Eqls'String__STRING
|"_<=Map__MAP" -> Lbl_'_LT_Eqls'Map__MAP
|"newUUID_STRING" -> LblnewUUID_STRING
|"sizeMap" -> LblsizeMap
|"isBoundCellBag" -> LblisBoundCellBag
|"isId" -> LblisId
|"substrString" -> LblsubstrString
|"size" -> Lblsize
|"isSummandCell" -> LblisSummandCell
|"project:Proc" -> Lblproject'Coln'Proc
|"Send" -> LblSend
|"initSummandCell" -> LblinitSummandCell
|"_inList_" -> Lbl_inList_
|"isBoundCell" -> LblisBoundCell
|"minInt(_,_)_INT" -> LblminInt'LPar'_'Comm'_'RPar'_INT
|"isMap" -> LblisMap
|"srandInt" -> LblsrandInt
|"isKItem" -> LblisKItem
|"Receive" -> LblReceive
|"isBoundsCellFragment" -> LblisBoundsCellFragment
|".BoundCellBag" -> Lbl'Stop'BoundCellBag
|"List:set" -> LblList'Coln'set
|"String2Base" -> LblString2Base
|"<bound>" -> Lbl'_LT_'bound'_GT_'
|"isTCellFragment" -> LblisTCellFragment
|"replace(_,_,_,_)_STRING" -> Lblreplace'LPar'_'Comm'_'Comm'_'Comm'_'RPar'_STRING
|"_/Int__INT" -> Lbl_'Slsh'Int__INT
|"_[_<-_]_MAP" -> Lbl_'LSqB'_'_LT_Hyph'_'RSqB'_MAP
|"keys" -> Lblkeys
|"Or" -> LblOr
|"<bounds>" -> Lbl'_LT_'bounds'_GT_'
| _ -> invalid_arg ("parse_klabel: " ^ c)
let collection_for (c: klabel) : klabel = match c with
|LblSetItem -> Lbl_Set_
|Lbl_ProcCellBag_ -> Lbl_ProcCellBag_
|Lbl'Stop'Set -> Lbl_Set_
|Lbl'Stop'BoundCellBag -> Lbl_BoundCellBag_
|Lbl_BoundCellBag_ -> Lbl_BoundCellBag_
|LblBoundCellBagItem -> Lbl_BoundCellBag_
|LblProcCellBagItem -> Lbl_ProcCellBag_
|Lbl'_LT_'bound'_GT_' -> Lbl_BoundCellBag_
|LblListItem -> Lbl_List_
|Lbl_Map_ -> Lbl_Map_
|LblSummandCellBagItem -> Lbl_SummandCellBag_
|Lbl_SummandCellBag_ -> Lbl_SummandCellBag_
|Lbl'Stop'SummandCellBag -> Lbl_SummandCellBag_
|Lbl'Stop'ProcCellBag -> Lbl_ProcCellBag_
|Lbl'Stop'List -> Lbl_List_
|Lbl_Set_ -> Lbl_Set_
|Lbl'_LT_'proc'_GT_' -> Lbl_ProcCellBag_
|Lbl_List_ -> Lbl_List_
|Lbl'Stop'Map -> Lbl_Map_
|Lbl_'PipeHyph_GT_'_ -> Lbl_Map_
|Lbl'_LT_'summand'_GT_' -> Lbl_SummandCellBag_
| _ -> invalid_arg "collection_for"
let unit_for (c: klabel) : klabel = match c with
|Lbl_ProcCellBag_ -> Lbl'Stop'ProcCellBag
|Lbl_Set_ -> Lbl'Stop'Set
|Lbl_List_ -> Lbl'Stop'List
|Lbl_BoundCellBag_ -> Lbl'Stop'BoundCellBag
|Lbl_Map_ -> Lbl'Stop'Map
|Lbl_SummandCellBag_ -> Lbl'Stop'SummandCellBag
| _ -> invalid_arg "unit_for"
let el_for (c: klabel) : klabel = match c with
|Lbl_ProcCellBag_ -> LblProcCellBagItem
|Lbl_Set_ -> LblSetItem
|Lbl_List_ -> LblListItem
|Lbl_BoundCellBag_ -> LblBoundCellBagItem
|Lbl_Map_ -> Lbl_'PipeHyph_GT_'_
|Lbl_SummandCellBag_ -> LblSummandCellBagItem
| _ -> invalid_arg "el_for"
let unit_for_array (c: sort) : klabel = match c with
| _ -> invalid_arg "unit_for_array"
let el_for_array (c: sort) : klabel = match c with
| _ -> invalid_arg "el_for_array"
module Dynarray : sig
type 'a t
val make : int -> 'a -> 'a t
val length : 'a t -> int
val get : 'a t -> int -> 'a
val set : 'a t -> int -> 'a -> unit
val compare : ('a list -> 'a list -> int) -> 'a t -> 'a t -> int
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val fold_right : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val iteri : (int -> 'a -> unit) -> 'a t -> unit
end = struct
type 'a t = { size: int; mutable arr: 'a array; default: 'a }
let make size default = { size=size; arr=Array.make (min size 10) default; default=default}
let length arr = arr.size
let get arr idx = if idx >= Array.length arr.arr && idx < arr.size then arr.default else Array.get arr.arr idx
let calc_size arr at_least = let double = Array.length arr.arr * 2 in
let at_most = if double > arr.size then arr.size else double in
if at_least > at_most then at_least else at_most
let upgrade_size arr size = let old = arr.arr in arr.arr <- Array.make size arr.default; Array.blit old 0 arr.arr 0 (Array.length old)
let set arr idx value= if idx >= Array.length arr.arr && idx < arr.size then upgrade_size arr (calc_size arr (idx + 1));
Array.set arr.arr idx value
let compare_arr f a b = let smaller,larger = if Array.length a.arr < Array.length b.arr then a,b else b,a in
upgrade_size smaller (Array.length larger.arr);
f (Array.to_list a.arr) (Array.to_list b.arr)
let compare f a b = let v = Pervasives.compare a.size b.size in if v = 0 then compare_arr f a b else v
let fold_left f init arr = snd (Array.fold_left (fun (i,x) a -> if i > 0 then (i - 1, f x a) else (0,x)) (arr.size,init) arr.arr)
let fold_right f arr init = snd (Array.fold_right (fun a (i,x) -> if i > 0 then (i - 1, x) else (0, f a x)) arr.arr (Array.length arr.arr - arr.size, init))
let iteri f arr = Array.iteri (fun i a -> if i < arr.size then f i a else ()) arr.arr
end
module type S =
sig
type m
type s
type t = kitem list
and kitem = KToken of sort * string
| InjectedKLabel of klabel
| Map of sort * klabel * m
| List of sort * klabel * t list
| Set of sort * klabel * s
| Array of sort * t * t Dynarray.t
| Int of Z.t
| Float of Gmp.FR.t * int * int
| String of string
| Bytes of bytes
| StringBuffer of Buffer.t
| Bool of bool
| MInt of int * Z.t
| ThreadLocal
| Thread of t * t * t * t
| Bottom
| KApply0 of klabel
| KApply1 of klabel * t
| KApply2 of klabel * t * t
| KApply3 of klabel * t * t * t
| KApply4 of klabel * t * t * t * t
val compare : t -> t -> int
val compare_kitem : kitem -> kitem -> int
val compare_klist : t list -> t list -> int
val equal_k : t -> t -> bool
val hash_k : t -> int
val hash_k_param : int -> t -> int
end
module rec K : (S with type m = K.t Map.Make(K).t and type s = Set.Make(K).t) =
struct
module KMap = Map.Make(K)
module KSet = Set.Make(K)
type m = K.t KMap.t
and s = KSet.t
and t = kitem list
and kitem = KToken of sort * string
| InjectedKLabel of klabel
| Map of sort * klabel * m
| List of sort * klabel * t list
| Set of sort * klabel * s
| Array of sort * t * t Dynarray.t
| Int of Z.t
| Float of Gmp.FR.t * int * int
| String of string
| Bytes of bytes
| StringBuffer of Buffer.t
| Bool of bool
| MInt of int * Z.t
| ThreadLocal
| Thread of t * t * t * t
| Bottom
| KApply0 of klabel
| KApply1 of klabel * t
| KApply2 of klabel * t * t
| KApply3 of klabel * t * t * t
| KApply4 of klabel * t * t * t * t
let rec hash_k c = match c with
| [] -> 1
| hd :: tl -> (hash_k tl) * 31 + hash_kitem hd
and hash_kitem c = match c with
| KApply0(lbl) -> (Hashtbl.hash lbl)
| KApply1(lbl,k0) -> ((Hashtbl.hash lbl)) * 37 + hash_k k0
| KApply2(lbl,k0,k1) -> (((Hashtbl.hash lbl)) * 37 + hash_k k0) * 37 + hash_k k1
| KApply3(lbl,k0,k1,k2) -> ((((Hashtbl.hash lbl)) * 37 + hash_k k0) * 37 + hash_k k1) * 37 + hash_k k2
| KApply4(lbl,k0,k1,k2,k3) -> (((((Hashtbl.hash lbl)) * 37 + hash_k k0) * 37 + hash_k k1) * 37 + hash_k k2) * 37 + hash_k k3
| KToken(s, st) -> Hashtbl.hash s * 41 + Hashtbl.hash st
| InjectedKLabel kl -> Hashtbl.hash kl
| Map(_,k,m) -> Hashtbl.hash k * 43 + KMap.fold (fun k v accum -> accum + (hash_k k lxor hash_k v)) m 0
| List(_,k,l) -> Hashtbl.hash k * 47 + hash_klist l
| Set(_,k,s) -> Hashtbl.hash k * 53 + KSet.fold (fun k accum -> accum + hash_k k) s 0
| Array(k,_,l) -> Hashtbl.hash k * 61 + (Dynarray.length l)
| Int i -> Z.hash i
| Float (f,_,_) -> Hashtbl.hash (Gmp.FR.to_float f)
| String s -> Hashtbl.hash s
| StringBuffer s -> Hashtbl.hash (Buffer.contents s)
| Bytes b -> Hashtbl.hash b
| Bool b -> Hashtbl.hash b
| MInt (w,i) -> Hashtbl.hash w * 67 + Z.hash i
| Bottom -> 1
| ThreadLocal -> 2
| Thread(k1,k2,k3,k4) -> ((((Hashtbl.hash Lbl'Hash'Thread) * 37 + hash_k k1) * 37 + hash_k k2) * 37 + hash_k k3) * 36 + hash_k k4
and hash_klist c = match c with
| [] -> 1
| hd :: tl -> (hash_klist tl) * 59 + hash_k hd
let rec hash_k_param_fld ((l,max) as lmax) = function
| [] -> lmax
| h::t -> if max < 0 then lmax else hash_k_param_fld (h::l,max-1) t
let hash_k_param_add_kitem k max =
hash_k_param_fld max k
let rec qfld l1 h max = match l1 with
| [] -> let (l2,max) = max in if l2 = [] then h else qfld l2 h ([],max)
| ki :: kq -> match ki with
| KApply0(lbl) ->
qfld kq (31*h + Hashtbl.hash lbl) (
max)
| KApply1(lbl,k0) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
max))
| KApply2(lbl,k0,k1) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
hash_k_param_add_kitem k1 (
max)))
| KApply3(lbl,k0,k1,k2) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
hash_k_param_add_kitem k1 (
hash_k_param_add_kitem k2 (
max))))
| KApply4(lbl,k0,k1,k2,k3) ->
qfld kq (31*h + Hashtbl.hash lbl) (
hash_k_param_add_kitem k0 (
hash_k_param_add_kitem k1 (
hash_k_param_add_kitem k2 (
hash_k_param_add_kitem k3 (
max)))))
| KToken(s, st) ->
qfld kq (31*h + Hashtbl.hash s * 41 + Hashtbl.hash st) (
max)
| InjectedKLabel lbl ->
qfld kq (31*h + Hashtbl.hash lbl) (
max)
| Map(_,lbl,m) ->
qfld kq (31*h + 43 * Hashtbl.hash lbl) (
KMap.fold (fun k v max -> hash_k_param_add_kitem v (hash_k_param_add_kitem k max)) m max)
| List(_,lbl,l) ->
qfld kq (31*h + 47 * Hashtbl.hash lbl) (
List.fold_left (fun max k -> hash_k_param_add_kitem k max) max l)
| Set(_,lbl,s) ->
qfld kq (31*h + 53 * Hashtbl.hash lbl) (
KSet.fold (fun k max -> hash_k_param_add_kitem k max) s max)
| Array(lbl,_,l) ->
qfld kq (31*h + 61 * Hashtbl.hash lbl + Dynarray.length l) (
max)
| Int i -> qfld kq (31*h + Z.hash i) (
max)
| Float (f,_,_) -> qfld kq (31*h + Hashtbl.hash (Gmp.FR.to_float f)) (
max)
| String s -> qfld kq (31*h + Hashtbl.hash s) (
max)
| Bytes b -> qfld kq (31*h + Hashtbl.hash b) (
max)
| StringBuffer s -> qfld kq (31*h + Hashtbl.hash (Buffer.contents s)) (
max)
| Bool b -> qfld kq (31*h + Hashtbl.hash b) (
max)
| MInt (w,i) -> qfld kq ((31*h + (Hashtbl.hash w))*67 + Z.hash i) (
max)
| Bottom -> qfld kq (31*h + 1) (
max)
| ThreadLocal -> qfld kq (31*h + 2) (
max)
| Thread(k1,k2,k3,k4) -> qfld kq (31*h + Hashtbl.hash Lbl'Hash'Thread) (hash_k_param_add_kitem k1 (hash_k_param_add_kitem k2 (hash_k_param_add_kitem k3 (hash_k_param_add_kitem k4 max))))
let hash_k_param max k =
qfld [] 0 (hash_k_param_add_kitem k ([],max))
let rec equal_k c1 c2 = if c1 == c2 then true else match (c1, c2) with
| [], [] -> true
| (hd1 :: tl1), (hd2 :: tl2) -> equal_kitem hd1 hd2 && equal_k tl1 tl2
| _ -> false
and equal_kitem c1 c2 = if c1 == c2 then true else match (c1, c2) with
| KApply0(lbl1),KApply0(lbl2) -> lbl1 = lbl2
| KApply1(lbl1,k0_1),KApply1(lbl2,k0_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2
| KApply2(lbl1,k0_1,k1_1),KApply2(lbl2,k0_2,k1_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2 && equal_k k1_1 k1_2
| KApply3(lbl1,k0_1,k1_1,k2_1),KApply3(lbl2,k0_2,k1_2,k2_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2 && equal_k k1_1 k1_2 && equal_k k2_1 k2_2
| KApply4(lbl1,k0_1,k1_1,k2_1,k3_1),KApply4(lbl2,k0_2,k1_2,k2_2,k3_2) -> lbl1 = lbl2 && equal_k k0_1 k0_2 && equal_k k1_1 k1_2 && equal_k k2_1 k2_2 && equal_k k3_1 k3_2
| (KToken(s1, st1)), (KToken(s2, st2)) -> s1 = s2 && st1 = st2
| (InjectedKLabel kl1), (InjectedKLabel kl2) -> kl1 = kl2
| (Map (_,k1,m1)), (Map (_,k2,m2)) -> k1 = k2 && KMap.cardinal m1 = KMap.cardinal m2 && (KMap.equal) (equal_k) m1 m2
| (List (_,k1,l1)), (List (_,k2,l2)) -> k1 = k2 && equal_klist l1 l2
| (Set (_,k1,s1)), (Set (_,k2,s2)) -> k1 = k2 && KSet.cardinal s1 = KSet.cardinal s2 && (KSet.equal) s1 s2
| (Array (s1,k1,l1)), (Array (s2,k2,l2)) -> s1 = s2 && equal_k k1 k2 && l1 == l2
| (Int i1), (Int i2) -> Z.equal i1 i2
| (Float (f1,e1,p1)), (Float (f2,e2,p2)) -> e1 = e2 && p1 = p2 && Gmp.FR.compare f1 f2 = 0
| (String s1), (String s2) -> s1 = s2
| (Bytes b1), (Bytes b2) -> b1 == b2
| (StringBuffer s1), (StringBuffer s2) -> s1 == s2
| (Bool b1), (Bool b2) -> b1 = b2
| (MInt (w1,i1)), (MInt (w2,i2)) -> w1 = w2 && Z.equal i1 i2
| Bottom, Bottom -> true
| _ -> false
and equal_klist c1 c2 = if c1 == c2 then true else match (c1, c2) with
| [], [] -> true
| (hd1 :: tl1), (hd2 :: tl2) -> equal_k hd1 hd2 && equal_klist tl1 tl2
| _ -> false
let rec compare c1 c2 = if c1 == c2 then 0 else match (c1, c2) with
| [], [] -> 0
| (hd1 :: tl1), (hd2 :: tl2) -> let v = compare_kitem hd1 hd2 in if v = 0 then compare tl1 tl2 else v
| (_ :: _), _ -> -1
| _ -> 1
and compare_kitem c1 c2 = if c1 == c2 then 0 else match (c1, c2) with
| KApply0(lbl1),KApply0(lbl2) -> Pervasives.compare lbl1 lbl2
| KApply1(lbl1,k0_1),KApply1(lbl2,k0_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then compare k0_1 k0_2
else v)
| KApply2(lbl1,k0_1,k1_1),KApply2(lbl2,k0_2,k1_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then (let v = compare k0_1 k0_2 in if v = 0 then compare k1_1 k1_2
else v)
else v)
| KApply3(lbl1,k0_1,k1_1,k2_1),KApply3(lbl2,k0_2,k1_2,k2_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then (let v = compare k0_1 k0_2 in if v = 0 then (let v = compare k1_1 k1_2 in if v = 0 then compare k2_1 k2_2
else v)
else v)
else v)
| KApply4(lbl1,k0_1,k1_1,k2_1,k3_1),KApply4(lbl2,k0_2,k1_2,k2_2,k3_2) -> (let v = Pervasives.compare lbl1 lbl2 in if v = 0 then (let v = compare k0_1 k0_2 in if v = 0 then (let v = compare k1_1 k1_2 in if v = 0 then (let v = compare k2_1 k2_2 in if v = 0 then compare k3_1 k3_2
else v)
else v)
else v)
else v)
| (KToken(s1, st1)), (KToken(s2, st2)) -> let v = Pervasives.compare s1 s2 in if v = 0 then Pervasives.compare st1 st2 else v
| (InjectedKLabel kl1), (InjectedKLabel kl2) -> Pervasives.compare kl1 kl2
| (Map (_,k1,m1)), (Map (_,k2,m2)) -> let v = Pervasives.compare k1 k2 in if v = 0 then (KMap.compare) compare m1 m2 else v
| (List (_,k1,l1)), (List (_,k2,l2)) -> let v = Pervasives.compare k1 k2 in if v = 0 then compare_klist l1 l2 else v
| (Set (_,k1,s1)), (Set (_,k2,s2)) -> let v = Pervasives.compare k1 k2 in if v = 0 then (KSet.compare) s1 s2 else v
| (Array (s1,k1,l1)), (Array (s2,k2,l2)) -> let v = Pervasives.compare s1 s2 in if v = 0 then let v = compare k1 k2 in if v = 0 then Dynarray.compare compare_klist l1 l2 else v else v
| (Int i1), (Int i2) -> Z.compare i1 i2
| (Float (f1,e1,p1)), (Float (f2,e2,p2)) -> let v = e2 - e1 in if v = 0 then let v2 = p2 - p1 in if v2 = 0 then Gmp.FR.compare f1 f2 else v2 else v
| (String s1), (String s2) -> Pervasives.compare s1 s2
| (Bytes b1), (Bytes b2) -> Pervasives.compare b1 b2
| (StringBuffer s1), (StringBuffer s2) -> Pervasives.compare (Buffer.contents s1) (Buffer.contents s2)
| (Bool b1), (Bool b2) -> if b1 = b2 then 0 else if b1 then -1 else 1
| (MInt (w1,i1)), (MInt (w2,i2)) -> let v = Pervasives.compare w1 w2 in if v = 0 then Z.compare i1 i2 else v
| Bottom, Bottom -> 0
| ThreadLocal, ThreadLocal -> 0
| Thread (k11, k12, k13, k14), Thread (k21, k22, k23, k24) -> let v = compare k11 k21 in if v = 0 then let v = compare k12 k22 in if v = 0 then let v = compare k13 k23 in if v = 0 then compare k14 k24 else v else v else v
| KApply0 _, _ -> -1
| _, KApply0 _ -> 1
| KApply1 _, _ -> -1
| _, KApply1 _ -> 1
| KApply2 _, _ -> -1
| _, KApply2 _ -> 1
| KApply3 _, _ -> -1
| _, KApply3 _ -> 1
| KApply4 _, _ -> -1
| _, KApply4 _ -> 1
| KToken(_, _), _ -> -1
| _, KToken(_, _) -> 1
| InjectedKLabel(_), _ -> -1
| _, InjectedKLabel(_) -> 1
| Map(_), _ -> -1
| _, Map(_) -> 1
| List(_), _ -> -1
| _, List(_) -> 1
| Set(_), _ -> -1
| _, Set(_) -> 1
| Array(_), _ -> -1
| _, Array(_) -> 1
| Int(_), _ -> -1
| _, Int(_) -> 1
| Float(_), _ -> -1
| _, Float(_) -> 1
| String(_), _ -> -1
| _, String(_) -> 1
| Bytes(_), _ -> -1
| _, Bytes(_) -> 1
| StringBuffer(_), _ -> -1
| _, StringBuffer(_) -> 1
| Bool(_), _ -> -1
| _, Bool(_) -> 1
| MInt _, _ -> -1
| _, MInt _ -> 1
| Bottom, _ -> -1
| _, Bottom -> 1
| ThreadLocal, _ -> -1
| _, ThreadLocal -> 1
and compare_klist c1 c2 = match (c1, c2) with
| [], [] -> 0
| (hd1 :: tl1), (hd2 :: tl2) -> let v = compare hd1 hd2 in if v = 0 then compare_klist tl1 tl2 else v
| (_ :: _), _ -> -1
| _ -> 1
end
type normal_kitem = KApply of klabel * K.t list
| KItem of K.kitem
open K
let normalize (k: kitem) : normal_kitem = match k with
| KApply0(lbl) -> KApply (lbl, [])
| KApply1(lbl,k0) -> KApply (lbl, [k0])
| KApply2(lbl,k0,k1) -> KApply (lbl, [k0; k1])
| KApply3(lbl,k0,k1,k2) -> KApply (lbl, [k0; k1; k2])
| KApply4(lbl,k0,k1,k2,k3) -> KApply (lbl, [k0; k1; k2; k3])
| v -> KItem v
let denormalize (k: normal_kitem) : kitem = match k with
| KApply (lbl, []) -> KApply0(lbl)
| KApply (lbl, [k0]) -> KApply1(lbl,k0)
| KApply (lbl, [k0; k1]) -> KApply2(lbl,k0,k1)
| KApply (lbl, [k0; k1; k2]) -> KApply3(lbl,k0,k1,k2)
| KApply (lbl, [k0; k1; k2; k3]) -> KApply4(lbl,k0,k1,k2,k3)
| KItem v -> v
| KApply (_, _) -> invalid_arg "denormalize"
type k = K.t
let denormalize0 (c: unit) : k list = match c with () -> []
let normalize0 (c: k list) = match c with [] -> ()
| _ -> invalid_arg "normalize0"
let denormalize1 (c: k) : k list = match c with (k0) -> [k0]
let normalize1 (c: k list) = match c with [k0] -> (k0)
| _ -> invalid_arg "normalize1"
let denormalize2 (c: k * k) : k list = match c with (k0,k1) -> [k0; k1]
let normalize2 (c: k list) = match c with [k0; k1] -> (k0,k1)
| _ -> invalid_arg "normalize2"
let denormalize3 (c: k * k * k) : k list = match c with (k0,k1,k2) -> [k0; k1; k2]
let normalize3 (c: k list) = match c with [k0; k1; k2] -> (k0,k1,k2)
| _ -> invalid_arg "normalize3"
let denormalize4 (c: k * k * k * k) : k list = match c with (k0,k1,k2,k3) -> [k0; k1; k2; k3]
let normalize4 (c: k list) = match c with [k0; k1; k2; k3] -> (k0,k1,k2,k3)
| _ -> invalid_arg "normalize4"
let int0 = lazy (Int (Z.of_string "0"))
let int1 = lazy (Int (Z.of_string "1"))
let int'Hyph'1 = lazy (Int (Z.of_string "-1"))
let constnoKCell = KApply0(LblnoKCell)
let const'Hash'Bottom = KApply0(Lbl'Hash'Bottom)
let const'Stop'Map = KApply0(Lbl'Stop'Map)
let constnoSumCell = KApply0(LblnoSumCell)
let constnewUUID_STRING = KApply0(LblnewUUID_STRING)
let const'Stop'BoundCellBag = KApply0(Lbl'Stop'BoundCellBag)
let const'Stop'Set = KApply0(Lbl'Stop'Set)
let const'Stop'List = KApply0(Lbl'Stop'List)
let constinitBoundsCell = KApply0(LblinitBoundsCell)
let constinitSummandCell = KApply0(LblinitSummandCell)
let constnoParCell = KApply0(LblnoParCell)
let constnoBoundsCell = KApply0(LblnoBoundsCell)
let constNil_PI'Hyph'SYNTAX = KApply0(LblNil_PI'Hyph'SYNTAX)
let const'Stop'ProcCellBag = KApply0(Lbl'Stop'ProcCellBag)
let constinitBoundCell = KApply0(LblinitBoundCell)
let const'Hash'ThreadLocal = KApply0(Lbl'Hash'ThreadLocal)
let constinitSumCell = KApply0(LblinitSumCell)
let const'Stop'SummandCellBag = KApply0(Lbl'Stop'SummandCellBag)
let val_for (c: klabel) (k : k) (v : k) : normal_kitem = match c with
|_ -> KApply((el_for c), [k;v])
| |
73e4573fe2b4b5de9cc3f23ca9c022cc886b04bcf9348c56aa4c22fb721c6b69 | Metaxal/text-table | table.rkt | #lang racket
(require text-table
rackunit)
; to write/try test easily:
(define-syntax-rule (tbcheck expr)
(let ([res expr])
(displayln res)
`(check-equal? expr ,res)))
; Ex:
( tbcheck ( simple - table->string ' ( ( )
(1 2 3))))
(check-exn exn:fail? (λ () (table->string '())))
(check-exn exn:fail? (λ () (table->string '(a))))
(check-exn exn:fail? (λ () (table->string '([a b] [c]))))
(check-equal? (table->string '([a "b\nbbb"] [c 3]))
(string-join '("┌─┬───┐"
"│a│b │"
"│ │bbb│"
"├─┼───┤"
"│c│3 │"
"└─┴───┘")
"\n"))
; Check border-style1/c still works
(check-equal? (table->string '([a "b\nbbb"] [c 3])
#:border-style
'(#\─ ("│" "│" "│") ("┌" "┬" "┐") ("├" "┼" "┤") ("└" "┴" "┘"))
)
(string-join '("┌─┬───┐"
"│a│b │"
"│ │bbb│"
"├─┼───┤"
"│c│3 │"
"└─┴───┘")
"\n"))
(check-equal?
(table->string
'((a b c d e f gggg h)
(123 456 77 54 "a\nbbbb\nc" 5646547987 41 1)
(111 22 3333 44 5 6 7 8888))
#:border-style
'latex
#:framed?
#t
#:row-sep?
'(#t ...)
#:align
'(left center right center))
"\\begin{tabular}{|l|c|r|c|c|c|c|c|}\n\\hline\na & b & c & d & e & f & gggg & h \\\\\n\\hline\n123 & 456 & 77 & 54 & a & 5646547987 & 41 & 1 \\\\\n & & & & bbbb & & & \\\\\n & & & & c & & & \\\\\n\\hline\n111 & 22 & 3333 & 44 & 5 & 6 & 7 & 8888 \\\\\n\\hline\n\\end{tabular}")
(check-equal?
(table->string
(for/list ((i 5)) (for/list ((j 6)) (* (+ i 1) (+ j 1))))
#:align
'right
#:border-style
'latex)
"\\begin{tabular}{|r|r|r|r|r|r|}\n\\hline\n1 & 2 & 3 & 4 & 5 & 6 \\\\\n\\hline\n2 & 4 & 6 & 8 & 10 & 12 \\\\\n\\hline\n3 & 6 & 9 & 12 & 15 & 18 \\\\\n\\hline\n4 & 8 & 12 & 16 & 20 & 24 \\\\\n\\hline\n5 & 10 & 15 & 20 & 25 & 30 \\\\\n\\hline\n\\end{tabular}")
;; border-style-frame/c
(check-equal?
(table->string '((a b c d e f gggg h)
(123 456 77 54 "a\nbbb\nc" 123456 41 1)
(111 22 3333 44 5 6 7 8888))
#:border-style
'("<-+>"
"(.│)"
"[-+]"
"{-+}")
#:framed? #t
#:row-sep? #t
#:align '(left center right center))
"\
<---+---+----+--+---+------+----+---->
(a..│.b.│...c│d.│.e.│..f...│gggg│.h..)
[---+---+----+--+---+------+----+----]
(123│456│..77│54│.a.│123456│.41.│.1..)
(...│...│....│..│bbb│......│....│....)
(...│...│....│..│.c.│......│....│....)
[---+---+----+--+---+------+----+----]
(111│22.│3333│44│.5.│..6...│.7..│8888)
{---+---+----+--+---+------+----+----}")
(check-equal?
(simple-table->string '((aaa bbb ccc)))
"aaa bbb ccc")
(check-equal? (simple-table->string '((aaa bbb ccc) (1 2 3)))
"aaa bbb ccc\n1 2 3 ")
(check-equal?
(simple-table->string '((aaa bbb ccc "") (1 2 3 "")))
"aaa bbb ccc \n1 2 3 ")
(check-equal? (simple-table->string '((""))) "")
(check-equal?
(simple-table->string #:border-style 'empty '((a bb c d) (1 2 33 44)))
"abbc d \n12 3344")
(check-equal? (table->string '(("" "") ("" ""))) "┌┬┐\n│││\n├┼┤\n│││\n└┴┘")
(check-equal? (table->string '((b "") ("" a))) "┌─┬─┐\n│b│ │\n├─┼─┤\n│ │a│\n└─┴─┘")
;;; Check alignment
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align 'right)
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│ 1│ 22│ 3│ 33│\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align 'left)
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│1 │22 │3 │33 │\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align 'center)
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│ 1 │22 │ 3 │ 33 │\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align '(left right))
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│1 │ 22│ 3│ 33│\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align '(left ... right))
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│1 │22 │3 │ 33│\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbbb cccc dddd) (1 22 3 33)) #:align '(left center ... right))
"┌───┬────┬────┬────┐\n│aaa│bbbb│cccc│dddd│\n├───┼────┼────┼────┤\n│1 │ 22 │ 3 │ 33│\n└───┴────┴────┴────┘")
(check-equal?
(table->string
'((aaa bbbb cccc dddd eeee) (1 22 3 33 4))
#:align
'(left center ... ... right))
"┌───┬────┬────┬────┬────┐\n│aaa│bbbb│cccc│dddd│eeee│\n├───┼────┼────┼────┼────┤\n│1 │ 22 │3 │ 33 │ 4│\n└───┴────┴────┴────┴────┘")
(check-equal?
(table->string (for/list ((i 6)) (for/list ((j 5)) (* i j))) #:row-sep? '(#t #f ... ...))
"┌─┬─┬──┬──┬──┐\n│0│0│0 │0 │0 │\n├─┼─┼──┼──┼──┤\n│0│1│2 │3 │4 │\n│0│2│4 │6 │8 │\n├─┼─┼──┼──┼──┤\n│0│3│6 │9 │12│\n│0│4│8 │12│16│\n├─┼─┼──┼──┼──┤\n│0│5│10│15│20│\n└─┴─┴──┴──┴──┘")
(check-equal?
(table->string
(for/list ((i 5)) (for/list ((j 6)) (* (+ i 1) (+ j 1))))
#:align
'right
#:framed?
#f
#:row-sep?
'(#t #f)
#:col-sep?
'(#t #f)
#:border-style
'single)
"1│ 2 3 4 5 6\n─┼──────────────\n2│ 4 6 8 10 12\n3│ 6 9 12 15 18\n4│ 8 12 16 20 24\n5│10 15 20 25 30")
(check-equal?
(table->string
(for/list ((i 5)) (for/list ((j 6)) (* (+ i 1) (+ j 1))))
#:align
'right
#:framed?
#f
#:row-sep?
'(#t #f)
#:col-sep?
'(#t #f)
#:border-style
'latex)
"\\begin{tabular}{r|rrrrr}\n1 & 2 & 3 & 4 & 5 & 6 \\\\\n\\hline\n2 & 4 & 6 & 8 & 10 & 12 \\\\\n3 & 6 & 9 & 12 & 15 & 18 \\\\\n4 & 8 & 12 & 16 & 20 & 24 \\\\\n5 & 10 & 15 & 20 & 25 & 30 \\\\\n\\end{tabular}")
(check-equal? (table->string #:->string (λ _ "") '((1))) "┌┐\n││\n└┘")
(check-equal?
(table->string #:->string (list (λ (x) "a") (λ (x) "b")) '((1 2)))
"┌─┬─┐\n│a│b│\n└─┴─┘")
(check-equal?
(table->string #:->string (list (λ (x) "a") (λ (x) "b") '... (λ (x) "c")) '((1 2 3 4)))
"┌─┬─┬─┬─┐\n│a│b│b│c│\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc" "a" "b\nc" "d")))
"┌─┬─┬─┬─┐\n│a│a│b│d│\n│b│ │c│ │\n│c│ │ │ │\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc" "a" "b\nc" "d")) #:row-align 'bottom)
"┌─┬─┬─┬─┐\n│a│ │ │ │\n│b│ │b│ │\n│c│a│c│d│\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc" "a" "b\nc" "d")) #:row-align 'center)
"┌─┬─┬─┬─┐\n│a│ │b│ │\n│b│a│c│d│\n│c│ │ │ │\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc\nd" "a" "b\nc" "d")) #:row-align 'center)
"┌─┬─┬─┬─┐\n│a│ │ │ │\n│b│a│b│d│\n│c│ │c│ │\n│d│ │ │ │\n└─┴─┴─┴─┘")
(check-equal?
(table->string #:row-sep? '(#t #f ...) '(("header") ("first row") ("second row")))
"┌──────────┐\n│header │\n├──────────┤\n│first row │\n│second row│\n└──────────┘")
(check-equal?
(table->string #:row-sep? '(#t #f ...) '(("header") ("first row")))
"┌─────────┐\n│header │\n├─────────┤\n│first row│\n└─────────┘")
(check-equal?
(table->string #:row-sep? '(#t) '(("header")))
"┌──────┐\n│header│\n└──────┘")
(check-equal?
(table->string #:row-sep? '(#t #f ...) '(("header")))
"┌──────┐\n│header│\n└──────┘")
(check-equal?
(table->string #:row-sep? '() '(("header")))
"┌──────┐\n│header│\n└──────┘")
| null | https://raw.githubusercontent.com/Metaxal/text-table/b20f34b068aedbe6c1756628dc4c9df9b1cba2e1/tests/table.rkt | racket | to write/try test easily:
Ex:
Check border-style1/c still works
border-style-frame/c
Check alignment | #lang racket
(require text-table
rackunit)
(define-syntax-rule (tbcheck expr)
(let ([res expr])
(displayln res)
`(check-equal? expr ,res)))
( tbcheck ( simple - table->string ' ( ( )
(1 2 3))))
(check-exn exn:fail? (λ () (table->string '())))
(check-exn exn:fail? (λ () (table->string '(a))))
(check-exn exn:fail? (λ () (table->string '([a b] [c]))))
(check-equal? (table->string '([a "b\nbbb"] [c 3]))
(string-join '("┌─┬───┐"
"│a│b │"
"│ │bbb│"
"├─┼───┤"
"│c│3 │"
"└─┴───┘")
"\n"))
(check-equal? (table->string '([a "b\nbbb"] [c 3])
#:border-style
'(#\─ ("│" "│" "│") ("┌" "┬" "┐") ("├" "┼" "┤") ("└" "┴" "┘"))
)
(string-join '("┌─┬───┐"
"│a│b │"
"│ │bbb│"
"├─┼───┤"
"│c│3 │"
"└─┴───┘")
"\n"))
(check-equal?
(table->string
'((a b c d e f gggg h)
(123 456 77 54 "a\nbbbb\nc" 5646547987 41 1)
(111 22 3333 44 5 6 7 8888))
#:border-style
'latex
#:framed?
#t
#:row-sep?
'(#t ...)
#:align
'(left center right center))
"\\begin{tabular}{|l|c|r|c|c|c|c|c|}\n\\hline\na & b & c & d & e & f & gggg & h \\\\\n\\hline\n123 & 456 & 77 & 54 & a & 5646547987 & 41 & 1 \\\\\n & & & & bbbb & & & \\\\\n & & & & c & & & \\\\\n\\hline\n111 & 22 & 3333 & 44 & 5 & 6 & 7 & 8888 \\\\\n\\hline\n\\end{tabular}")
(check-equal?
(table->string
(for/list ((i 5)) (for/list ((j 6)) (* (+ i 1) (+ j 1))))
#:align
'right
#:border-style
'latex)
"\\begin{tabular}{|r|r|r|r|r|r|}\n\\hline\n1 & 2 & 3 & 4 & 5 & 6 \\\\\n\\hline\n2 & 4 & 6 & 8 & 10 & 12 \\\\\n\\hline\n3 & 6 & 9 & 12 & 15 & 18 \\\\\n\\hline\n4 & 8 & 12 & 16 & 20 & 24 \\\\\n\\hline\n5 & 10 & 15 & 20 & 25 & 30 \\\\\n\\hline\n\\end{tabular}")
(check-equal?
(table->string '((a b c d e f gggg h)
(123 456 77 54 "a\nbbb\nc" 123456 41 1)
(111 22 3333 44 5 6 7 8888))
#:border-style
'("<-+>"
"(.│)"
"[-+]"
"{-+}")
#:framed? #t
#:row-sep? #t
#:align '(left center right center))
"\
<---+---+----+--+---+------+----+---->
(a..│.b.│...c│d.│.e.│..f...│gggg│.h..)
[---+---+----+--+---+------+----+----]
(123│456│..77│54│.a.│123456│.41.│.1..)
(...│...│....│..│bbb│......│....│....)
(...│...│....│..│.c.│......│....│....)
[---+---+----+--+---+------+----+----]
(111│22.│3333│44│.5.│..6...│.7..│8888)
{---+---+----+--+---+------+----+----}")
(check-equal?
(simple-table->string '((aaa bbb ccc)))
"aaa bbb ccc")
(check-equal? (simple-table->string '((aaa bbb ccc) (1 2 3)))
"aaa bbb ccc\n1 2 3 ")
(check-equal?
(simple-table->string '((aaa bbb ccc "") (1 2 3 "")))
"aaa bbb ccc \n1 2 3 ")
(check-equal? (simple-table->string '((""))) "")
(check-equal?
(simple-table->string #:border-style 'empty '((a bb c d) (1 2 33 44)))
"abbc d \n12 3344")
(check-equal? (table->string '(("" "") ("" ""))) "┌┬┐\n│││\n├┼┤\n│││\n└┴┘")
(check-equal? (table->string '((b "") ("" a))) "┌─┬─┐\n│b│ │\n├─┼─┤\n│ │a│\n└─┴─┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align 'right)
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│ 1│ 22│ 3│ 33│\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align 'left)
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│1 │22 │3 │33 │\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align 'center)
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│ 1 │22 │ 3 │ 33 │\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align '(left right))
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│1 │ 22│ 3│ 33│\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbb cccc dddd) (1 22 3 33)) #:align '(left ... right))
"┌───┬───┬────┬────┐\n│aaa│bbb│cccc│dddd│\n├───┼───┼────┼────┤\n│1 │22 │3 │ 33│\n└───┴───┴────┴────┘")
(check-equal?
(table->string '((aaa bbbb cccc dddd) (1 22 3 33)) #:align '(left center ... right))
"┌───┬────┬────┬────┐\n│aaa│bbbb│cccc│dddd│\n├───┼────┼────┼────┤\n│1 │ 22 │ 3 │ 33│\n└───┴────┴────┴────┘")
(check-equal?
(table->string
'((aaa bbbb cccc dddd eeee) (1 22 3 33 4))
#:align
'(left center ... ... right))
"┌───┬────┬────┬────┬────┐\n│aaa│bbbb│cccc│dddd│eeee│\n├───┼────┼────┼────┼────┤\n│1 │ 22 │3 │ 33 │ 4│\n└───┴────┴────┴────┴────┘")
(check-equal?
(table->string (for/list ((i 6)) (for/list ((j 5)) (* i j))) #:row-sep? '(#t #f ... ...))
"┌─┬─┬──┬──┬──┐\n│0│0│0 │0 │0 │\n├─┼─┼──┼──┼──┤\n│0│1│2 │3 │4 │\n│0│2│4 │6 │8 │\n├─┼─┼──┼──┼──┤\n│0│3│6 │9 │12│\n│0│4│8 │12│16│\n├─┼─┼──┼──┼──┤\n│0│5│10│15│20│\n└─┴─┴──┴──┴──┘")
(check-equal?
(table->string
(for/list ((i 5)) (for/list ((j 6)) (* (+ i 1) (+ j 1))))
#:align
'right
#:framed?
#f
#:row-sep?
'(#t #f)
#:col-sep?
'(#t #f)
#:border-style
'single)
"1│ 2 3 4 5 6\n─┼──────────────\n2│ 4 6 8 10 12\n3│ 6 9 12 15 18\n4│ 8 12 16 20 24\n5│10 15 20 25 30")
(check-equal?
(table->string
(for/list ((i 5)) (for/list ((j 6)) (* (+ i 1) (+ j 1))))
#:align
'right
#:framed?
#f
#:row-sep?
'(#t #f)
#:col-sep?
'(#t #f)
#:border-style
'latex)
"\\begin{tabular}{r|rrrrr}\n1 & 2 & 3 & 4 & 5 & 6 \\\\\n\\hline\n2 & 4 & 6 & 8 & 10 & 12 \\\\\n3 & 6 & 9 & 12 & 15 & 18 \\\\\n4 & 8 & 12 & 16 & 20 & 24 \\\\\n5 & 10 & 15 & 20 & 25 & 30 \\\\\n\\end{tabular}")
(check-equal? (table->string #:->string (λ _ "") '((1))) "┌┐\n││\n└┘")
(check-equal?
(table->string #:->string (list (λ (x) "a") (λ (x) "b")) '((1 2)))
"┌─┬─┐\n│a│b│\n└─┴─┘")
(check-equal?
(table->string #:->string (list (λ (x) "a") (λ (x) "b") '... (λ (x) "c")) '((1 2 3 4)))
"┌─┬─┬─┬─┐\n│a│b│b│c│\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc" "a" "b\nc" "d")))
"┌─┬─┬─┬─┐\n│a│a│b│d│\n│b│ │c│ │\n│c│ │ │ │\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc" "a" "b\nc" "d")) #:row-align 'bottom)
"┌─┬─┬─┬─┐\n│a│ │ │ │\n│b│ │b│ │\n│c│a│c│d│\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc" "a" "b\nc" "d")) #:row-align 'center)
"┌─┬─┬─┬─┐\n│a│ │b│ │\n│b│a│c│d│\n│c│ │ │ │\n└─┴─┴─┴─┘")
(check-equal?
(table->string '(("a\nb\nc\nd" "a" "b\nc" "d")) #:row-align 'center)
"┌─┬─┬─┬─┐\n│a│ │ │ │\n│b│a│b│d│\n│c│ │c│ │\n│d│ │ │ │\n└─┴─┴─┴─┘")
(check-equal?
(table->string #:row-sep? '(#t #f ...) '(("header") ("first row") ("second row")))
"┌──────────┐\n│header │\n├──────────┤\n│first row │\n│second row│\n└──────────┘")
(check-equal?
(table->string #:row-sep? '(#t #f ...) '(("header") ("first row")))
"┌─────────┐\n│header │\n├─────────┤\n│first row│\n└─────────┘")
(check-equal?
(table->string #:row-sep? '(#t) '(("header")))
"┌──────┐\n│header│\n└──────┘")
(check-equal?
(table->string #:row-sep? '(#t #f ...) '(("header")))
"┌──────┐\n│header│\n└──────┘")
(check-equal?
(table->string #:row-sep? '() '(("header")))
"┌──────┐\n│header│\n└──────┘")
|
e0fb2ed53dde338f8b8a6624bb90d67b27ffb44955d56494a98bdb895d35494e | rob7hunter/leftparen | web-support.scm | #lang scheme/base
;; This differs from web-export.ss in that these are ones that we wrote and aren't
included in PLT libs .
(require (file "util.scm")
xml
net/url
scheme/serialize
"web-export.ss"
"contract-lp.ss"
)
(provide request-all-bindings
;; final-prep-of-response (via contract)
xexpr->de-grouped-xexprs
wrap-each-in-list
wrap-each-in-list-with-attrs
redirect-to
web-link
img
raw-str
;; basic-response (via contract)
xexpr-if
url+query
url->string
get-url
bindings/string
find-binding
;; list-response (via contract)
response-promise?
;; single-response-promise-in-list (via contract)
;; single-response/full-in-list (via contract)
;; response-promise-to-redirect (via contract)
;; response-from-promise (via contract)
)
;;
;; list-response
;;
(define (any-responses? lst)
(any (lambda (elt)
(or (response/full? elt) (response/incremental? elt) (response/basic? elt)))
lst))
(provide/contract
(list-response (->*
;; required
((not/c any-responses?))
;; optional
(#:type bytes? #:extras list?)
;; returns
response/c)))
;;
(define (list-response content-lst #:type (type #"text/html") #:extras (extras '()))
(basic-response (append-map (lambda (content)
(map (lambda (c) (string->bytes/utf-8 (xexpr->string c)))
(xexpr->de-grouped-xexprs content)))
content-lst)
#:type type
#:extras extras))
(provide/contract
(basic-response (->*
;; required
((listof bytes?))
;; optional
(#:type bytes? #:extras (listof header?))
;; returns
response/c)))
(define (basic-response content-lst #:type (type #"text/html") #:extras (extras '()))
;; right now we always no-cache. we'll probably eventually want something more
;; subtle.
(let ((no-cache (make-header #"Cache-Control" (string->bytes/utf-8 "no-cache;"))))
(make-response/full 200 #"all good" (current-seconds)
type (cons no-cache extras)
content-lst)))
(define-serializable-struct binding/string (id))
(define-serializable-struct (binding/string:form binding/string) (value))
(define-serializable-struct (binding/string:file binding/string) (filename content))
(provide/contract
[struct binding/string ([id string?])]
[struct (binding/string:form binding/string) ([id string?]
[value string?])]
[struct (binding/string:file binding/string) ([id string?]
[filename string?]
[content bytes?])])
(define (bindings/string req [localization-function bytes->string/utf-8])
(map (lambda (binding)
(if (binding:form? binding)
(make-binding/string:form (localization-function (binding-id binding))
(localization-function (binding:form-value binding)))
(make-binding/string:file (localization-function (binding-id binding))
(localization-function (binding:file-filename binding))
(binding:file-content binding))))
(request-bindings/raw req)))
(define (find-binding field bindings)
; strait from request-struct.ss
(match bindings
[(list)
#f]
[(list-rest (and b (struct binding/string (i))) bindings)
(if (string=? field i)
b
(find-binding field bindings))]))
;; if you are doing a post, this gives you post and get vars. if a get, it's just reg.
(define (request-all-bindings req)
(append (request-bindings req)
(if (request-post-data/raw req) ; there a better way to check if it's a post?
(url-query (request-uri req))
'())))
(define (group-tag? xexpr)
(match xexpr ((list-rest 'group children) #t) (else #f)))
(define (xexpr->de-grouped-xexprs xexpr)
(cond ((not xexpr) '())
response case
((group-tag? xexpr) (append-map xexpr->de-grouped-xexprs (rest xexpr)))
(else (receive (tag attrs children) (xexpr->tag*attrs*children xexpr)
(list (create-xexpr tag attrs
(append-map xexpr->de-grouped-xexprs children)))))))
(define (attrs? thing)
(and (list? thing)
(or (empty? thing) (not (symbol? (first thing))))))
(define (create-xexpr tag attrs children)
(if (empty? attrs)
`(,tag ,@children)
`(,tag ,attrs ,@children)))
(define (xexpr->tag*attrs*children xexpr)
(let ((tag (first xexpr))
(but-tag (rest xexpr)))
(if (empty? but-tag)
(values tag '() '())
(let ((next (first but-tag)))
(if (attrs? next)
(values tag next (rest but-tag))
(values tag '() but-tag))))))
the wrap - each - in * fns filter out # f values from elts :
(define (wrap-each-in-list tag elts)
(filter-map (lambda (e) (and e `(,tag ,e))) elts))
(define (wrap-each-in-list-with-attrs tag attrs elts)
(filter-map (lambda (e) (and e `(,tag ,attrs ,e))) elts))
(define (web-link label url #:class (class #f) #:extra-attrs (extra-attrs '()))
`(a ((href ,(if (string? url) url (url->string url)))
,@(append (if class `((class ,class)) '()) extra-attrs))
,label))
;; image-file is relative to /i/
(define (img image-file #:class (class #f))
`(img ((src ,(string-append "/i/" image-file)) (border "0")
,@(splice-if class `(class ,class)))))
(define (raw-str str)
(make-cdata #f #f str))
;;
;; xexpr-if
;;
;; Use if you only want to create an xexpr if a condition is true. E.g.,
( ul ( li " Item 1 " ) , ( - if (= 2 2 ) ` ( li " Item 2 " ) ) )
;;
(define-syntax xexpr-if
(syntax-rules ()
((_ test)
(or test ""))
((_ test body ...)
(if test (begin body ...) ""))))
;;
url+query
;;
;; query-alist is ((key . str) ...)
given query strs should * not * be url encoded ( this will be done by url+query ) .
;;
(define (url+query url-str query-alist)
(let ((tmp-url (string->url url-str)))
(make-url (url-scheme tmp-url)
(url-user tmp-url)
(url-host tmp-url)
(url-port tmp-url)
(url-path-absolute? tmp-url)
(url-path tmp-url)
(append (url-query tmp-url) query-alist)
(url-fragment tmp-url))))
;;
;; get-url
;;
;; exn-handler: exn -> any
;;
(define (get-url url port-handler #:exn-handler (exn-handler #f))
(let ((thunk (lambda () (call/input-url (if (url? url) url (string->url url))
get-pure-port
port-handler))))
(if exn-handler
(with-handlers ((exn:fail:network? exn-handler)) (thunk))
(thunk))))
(define-struct response-promise (fn))
;;
;; response-promise-to-redirect
;;
;; A relatively low-level tool for "promising" to construct a redirect response. The issue
;; is that at the time we know we want to redirect, we don't necessarily know all the
;; headers that we might want to go into the redirect response. For example, a cookie
;; may need to be set on the client. Response promises can never make it to the top-level
( the web server ) , since they are a LeftParen concept only . Thus , the promises must
;; be "response-from-promise"'d before that happens.
;;
(provide/contract (response-promise-to-redirect (-> string? response-promise?)))
;;
(define (response-promise-to-redirect redirect-to-uri)
(make-response-promise (lambda (#:headers (h '())) (redirect-to redirect-to-uri
#:headers h))))
;;
;; response-from-promise
;;
(provide/contract
(response-from-promise (->* (response-promise?) (#:headers (listof header?)) response/c)))
;;
(define (response-from-promise r-p #:headers (headers '()))
((response-promise-fn r-p) #:headers headers))
;;
;; single-response-promise-in-list
;;
(provide/contract
(single-response-promise-in-list (-> (listof any/c) (or/c #f response-promise?))))
;;
(define (single-response-promise-in-list lst)
(and-let* (((and (length= lst 1)))
(elt (first lst))
((response-promise? elt)))
elt))
;;
;; single-response/full-in-list
;;
(provide/contract
(single-response/full-in-list (-> (listof any/c) (or/c #f response/full?))))
;;
(define (single-response/full-in-list lst)
(and-let* (((and (length= lst 1)))
(elt (first lst))
((response/full? elt)))
elt))
;;
;; final-prep-of-response
;;
(provide/contract
(final-prep-of-response (-> (or/c response/c response-promise?) response/c)))
;;
(define (final-prep-of-response response-or-promise)
(if (response-promise? response-or-promise)
(response-from-promise response-or-promise)
(let ((result (xexpr->de-grouped-xexprs response-or-promise)))
(if (and (length= result 1) (response? (first result)))
(first result)
(list-response result)))))
| null | https://raw.githubusercontent.com/rob7hunter/leftparen/169c896bda989b6a049fe49253a04d6f8b62402b/web-support.scm | scheme | This differs from web-export.ss in that these are ones that we wrote and aren't
final-prep-of-response (via contract)
basic-response (via contract)
list-response (via contract)
single-response-promise-in-list (via contract)
single-response/full-in-list (via contract)
response-promise-to-redirect (via contract)
response-from-promise (via contract)
list-response
required
optional
returns
required
optional
returns
right now we always no-cache. we'll probably eventually want something more
subtle.
strait from request-struct.ss
if you are doing a post, this gives you post and get vars. if a get, it's just reg.
there a better way to check if it's a post?
image-file is relative to /i/
xexpr-if
Use if you only want to create an xexpr if a condition is true. E.g.,
query-alist is ((key . str) ...)
get-url
exn-handler: exn -> any
response-promise-to-redirect
A relatively low-level tool for "promising" to construct a redirect response. The issue
is that at the time we know we want to redirect, we don't necessarily know all the
headers that we might want to go into the redirect response. For example, a cookie
may need to be set on the client. Response promises can never make it to the top-level
be "response-from-promise"'d before that happens.
response-from-promise
single-response-promise-in-list
single-response/full-in-list
final-prep-of-response
| #lang scheme/base
included in PLT libs .
(require (file "util.scm")
xml
net/url
scheme/serialize
"web-export.ss"
"contract-lp.ss"
)
(provide request-all-bindings
xexpr->de-grouped-xexprs
wrap-each-in-list
wrap-each-in-list-with-attrs
redirect-to
web-link
img
raw-str
xexpr-if
url+query
url->string
get-url
bindings/string
find-binding
response-promise?
)
(define (any-responses? lst)
(any (lambda (elt)
(or (response/full? elt) (response/incremental? elt) (response/basic? elt)))
lst))
(provide/contract
(list-response (->*
((not/c any-responses?))
(#:type bytes? #:extras list?)
response/c)))
(define (list-response content-lst #:type (type #"text/html") #:extras (extras '()))
(basic-response (append-map (lambda (content)
(map (lambda (c) (string->bytes/utf-8 (xexpr->string c)))
(xexpr->de-grouped-xexprs content)))
content-lst)
#:type type
#:extras extras))
(provide/contract
(basic-response (->*
((listof bytes?))
(#:type bytes? #:extras (listof header?))
response/c)))
(define (basic-response content-lst #:type (type #"text/html") #:extras (extras '()))
(let ((no-cache (make-header #"Cache-Control" (string->bytes/utf-8 "no-cache;"))))
(make-response/full 200 #"all good" (current-seconds)
type (cons no-cache extras)
content-lst)))
(define-serializable-struct binding/string (id))
(define-serializable-struct (binding/string:form binding/string) (value))
(define-serializable-struct (binding/string:file binding/string) (filename content))
(provide/contract
[struct binding/string ([id string?])]
[struct (binding/string:form binding/string) ([id string?]
[value string?])]
[struct (binding/string:file binding/string) ([id string?]
[filename string?]
[content bytes?])])
(define (bindings/string req [localization-function bytes->string/utf-8])
(map (lambda (binding)
(if (binding:form? binding)
(make-binding/string:form (localization-function (binding-id binding))
(localization-function (binding:form-value binding)))
(make-binding/string:file (localization-function (binding-id binding))
(localization-function (binding:file-filename binding))
(binding:file-content binding))))
(request-bindings/raw req)))
(define (find-binding field bindings)
(match bindings
[(list)
#f]
[(list-rest (and b (struct binding/string (i))) bindings)
(if (string=? field i)
b
(find-binding field bindings))]))
(define (request-all-bindings req)
(append (request-bindings req)
(url-query (request-uri req))
'())))
(define (group-tag? xexpr)
(match xexpr ((list-rest 'group children) #t) (else #f)))
(define (xexpr->de-grouped-xexprs xexpr)
(cond ((not xexpr) '())
response case
((group-tag? xexpr) (append-map xexpr->de-grouped-xexprs (rest xexpr)))
(else (receive (tag attrs children) (xexpr->tag*attrs*children xexpr)
(list (create-xexpr tag attrs
(append-map xexpr->de-grouped-xexprs children)))))))
(define (attrs? thing)
(and (list? thing)
(or (empty? thing) (not (symbol? (first thing))))))
(define (create-xexpr tag attrs children)
(if (empty? attrs)
`(,tag ,@children)
`(,tag ,attrs ,@children)))
(define (xexpr->tag*attrs*children xexpr)
(let ((tag (first xexpr))
(but-tag (rest xexpr)))
(if (empty? but-tag)
(values tag '() '())
(let ((next (first but-tag)))
(if (attrs? next)
(values tag next (rest but-tag))
(values tag '() but-tag))))))
the wrap - each - in * fns filter out # f values from elts :
(define (wrap-each-in-list tag elts)
(filter-map (lambda (e) (and e `(,tag ,e))) elts))
(define (wrap-each-in-list-with-attrs tag attrs elts)
(filter-map (lambda (e) (and e `(,tag ,attrs ,e))) elts))
(define (web-link label url #:class (class #f) #:extra-attrs (extra-attrs '()))
`(a ((href ,(if (string? url) url (url->string url)))
,@(append (if class `((class ,class)) '()) extra-attrs))
,label))
(define (img image-file #:class (class #f))
`(img ((src ,(string-append "/i/" image-file)) (border "0")
,@(splice-if class `(class ,class)))))
(define (raw-str str)
(make-cdata #f #f str))
( ul ( li " Item 1 " ) , ( - if (= 2 2 ) ` ( li " Item 2 " ) ) )
(define-syntax xexpr-if
(syntax-rules ()
((_ test)
(or test ""))
((_ test body ...)
(if test (begin body ...) ""))))
url+query
given query strs should * not * be url encoded ( this will be done by url+query ) .
(define (url+query url-str query-alist)
(let ((tmp-url (string->url url-str)))
(make-url (url-scheme tmp-url)
(url-user tmp-url)
(url-host tmp-url)
(url-port tmp-url)
(url-path-absolute? tmp-url)
(url-path tmp-url)
(append (url-query tmp-url) query-alist)
(url-fragment tmp-url))))
(define (get-url url port-handler #:exn-handler (exn-handler #f))
(let ((thunk (lambda () (call/input-url (if (url? url) url (string->url url))
get-pure-port
port-handler))))
(if exn-handler
(with-handlers ((exn:fail:network? exn-handler)) (thunk))
(thunk))))
(define-struct response-promise (fn))
( the web server ) , since they are a LeftParen concept only . Thus , the promises must
(provide/contract (response-promise-to-redirect (-> string? response-promise?)))
(define (response-promise-to-redirect redirect-to-uri)
(make-response-promise (lambda (#:headers (h '())) (redirect-to redirect-to-uri
#:headers h))))
(provide/contract
(response-from-promise (->* (response-promise?) (#:headers (listof header?)) response/c)))
(define (response-from-promise r-p #:headers (headers '()))
((response-promise-fn r-p) #:headers headers))
(provide/contract
(single-response-promise-in-list (-> (listof any/c) (or/c #f response-promise?))))
(define (single-response-promise-in-list lst)
(and-let* (((and (length= lst 1)))
(elt (first lst))
((response-promise? elt)))
elt))
(provide/contract
(single-response/full-in-list (-> (listof any/c) (or/c #f response/full?))))
(define (single-response/full-in-list lst)
(and-let* (((and (length= lst 1)))
(elt (first lst))
((response/full? elt)))
elt))
(provide/contract
(final-prep-of-response (-> (or/c response/c response-promise?) response/c)))
(define (final-prep-of-response response-or-promise)
(if (response-promise? response-or-promise)
(response-from-promise response-or-promise)
(let ((result (xexpr->de-grouped-xexprs response-or-promise)))
(if (and (length= result 1) (response? (first result)))
(first result)
(list-response result)))))
|
f420b35314b497365c3f5821d9f04ddac825bbdeb1d8da0f98bb9417bd01ccc0 | flipstone/haskell-for-beginners | Play.hs | module AdventureGame.Play
( Game(..)
, play
, showRoom
, parseCommand
)
where
import AdventureGame.UI
import AdventureGame.World
data Game = Game {
currentRoom :: Room
}
data Command = Go Direction | Quit
play :: Command -> Game -> Action Game
play Quit = Action Done
play (Go dir) = takeExit dir
showRoom :: Game -> Action Game
showRoom game = Action (Print (description game)) game
where description = roomDescription . currentRoom
takeExit :: Direction -> Game -> Action Game
takeExit direction game =
case exitTo direction (currentRoom game) of
Just room -> showRoom $ Game room
Nothing -> Action (Print "You can't go that way") game
parseCommand :: String -> Maybe Command
parseCommand "north" = Just $ Go North
parseCommand "south" = Just $ Go South
parseCommand "east" = Just $ Go East
parseCommand "west" = Just $ Go West
parseCommand "quit" = Just Quit
parseCommand _ = Nothing
| null | https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/answers/midterm/AdventureGame/Play.hs | haskell | module AdventureGame.Play
( Game(..)
, play
, showRoom
, parseCommand
)
where
import AdventureGame.UI
import AdventureGame.World
data Game = Game {
currentRoom :: Room
}
data Command = Go Direction | Quit
play :: Command -> Game -> Action Game
play Quit = Action Done
play (Go dir) = takeExit dir
showRoom :: Game -> Action Game
showRoom game = Action (Print (description game)) game
where description = roomDescription . currentRoom
takeExit :: Direction -> Game -> Action Game
takeExit direction game =
case exitTo direction (currentRoom game) of
Just room -> showRoom $ Game room
Nothing -> Action (Print "You can't go that way") game
parseCommand :: String -> Maybe Command
parseCommand "north" = Just $ Go North
parseCommand "south" = Just $ Go South
parseCommand "east" = Just $ Go East
parseCommand "west" = Just $ Go West
parseCommand "quit" = Just Quit
parseCommand _ = Nothing
| |
b87f8af30988b0719137ba42b1b6e5f3b88771f15bcbaabafffa623567a88e53 | icicle-lang/icicle-ambiata | Fact.hs | # LANGUAGE NoImplicitPrelude #
module Icicle.Test.Gen.Data.Fact (
genEncoding
, genStructField
) where
import qualified Data.Map.Strict as Map
import Disorder.Corpus (colours)
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Icicle.Data.Fact
import P
genEncoding :: Gen Encoding
genEncoding =
Gen.recursive Gen.choice [
pure StringEncoding
, pure IntEncoding
, pure DoubleEncoding
, pure BooleanEncoding
, pure TimeEncoding
] [
StructEncoding . Map.elems . Map.fromList . fmap (\x -> (takeName x, x))
<$> Gen.list (Range.linear 1 10) genStructField
, ListEncoding <$> genEncoding
]
takeName :: StructField -> Text
takeName (StructField _ name _) =
name
genStructField :: Gen StructField
genStructField =
StructField
<$> Gen.element [Mandatory, Optional]
<*> Gen.element colours
<*> genEncoding
| null | https://raw.githubusercontent.com/icicle-lang/icicle-ambiata/9b9cc45a75f66603007e4db7e5f3ba908cae2df2/icicle-compiler/test/Icicle/Test/Gen/Data/Fact.hs | haskell | # LANGUAGE NoImplicitPrelude #
module Icicle.Test.Gen.Data.Fact (
genEncoding
, genStructField
) where
import qualified Data.Map.Strict as Map
import Disorder.Corpus (colours)
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Icicle.Data.Fact
import P
genEncoding :: Gen Encoding
genEncoding =
Gen.recursive Gen.choice [
pure StringEncoding
, pure IntEncoding
, pure DoubleEncoding
, pure BooleanEncoding
, pure TimeEncoding
] [
StructEncoding . Map.elems . Map.fromList . fmap (\x -> (takeName x, x))
<$> Gen.list (Range.linear 1 10) genStructField
, ListEncoding <$> genEncoding
]
takeName :: StructField -> Text
takeName (StructField _ name _) =
name
genStructField :: Gen StructField
genStructField =
StructField
<$> Gen.element [Mandatory, Optional]
<*> Gen.element colours
<*> genEncoding
| |
dcd728fd13a690b302c61698f688cf1d17a384aae3197b6aad5e6bfdcc0056d5 | slagyr/joodo | favicon.clj | (ns ^{:doc "This namespace is for favicon.ico requests."}
joodo.middleware.favicon)
(defn- is-favicon-request? [request]
(= [:get "/favicon.ico"] [(:request-method request) (:uri request)]))
(defn wrap-favicon-bouncer
"Responds with 404 for /favicon.ico requests."
[handler]
(fn [request]
(if (is-favicon-request? request)
{:status 404 :headers {} :body ""}
(handler request))))
| null | https://raw.githubusercontent.com/slagyr/joodo/e7edbc707a7901d1a1c5465382dd25db368f4596/joodo/src/joodo/middleware/favicon.clj | clojure | (ns ^{:doc "This namespace is for favicon.ico requests."}
joodo.middleware.favicon)
(defn- is-favicon-request? [request]
(= [:get "/favicon.ico"] [(:request-method request) (:uri request)]))
(defn wrap-favicon-bouncer
"Responds with 404 for /favicon.ico requests."
[handler]
(fn [request]
(if (is-favicon-request? request)
{:status 404 :headers {} :body ""}
(handler request))))
| |
b34875f51627f6ada5914f59101aa9882892ca1f8f549a3dc02886cd8154cbd6 | bitc/hs-vault-tool | Internal.hs | module Network.VaultTool.Internal where
import Control.Exception (throwIO)
import Control.Monad (when)
import Data.Aeson
import Network.HTTP.Client
import Network.HTTP.Types.Header
import Network.HTTP.Types.Method
import Network.HTTP.Types.Status
import qualified Data.ByteString.Lazy as BL
import Network.VaultTool.Types
vaultRequest :: ToJSON a => Manager -> Method -> String -> RequestHeaders -> Maybe a -> [Int] -> IO BL.ByteString
vaultRequest manager method_ path_ headers mbBody expectedStatus = do
initReq <- case parseRequest path_ of
Nothing -> throwIO $ VaultException_InvalidAddress method_ path_
Just initReq -> pure initReq
let reqBody = case mbBody of
Nothing -> BL.empty
Just b -> encode b
req = initReq
{ method = method_
, requestBody = RequestBodyLBS reqBody
, requestHeaders = requestHeaders initReq ++ headers
}
rsp <- httpLbs req manager
let s = statusCode (responseStatus rsp)
when (not (elem s expectedStatus)) $ do
throwIO $ VaultException_BadStatusCode method_ path_ reqBody s (responseBody rsp)
pure (responseBody rsp)
vaultRequestJSON :: (FromJSON b, ToJSON a) => Manager -> Method -> String -> RequestHeaders -> Maybe a -> [Int] -> IO b
vaultRequestJSON manager method_ path_ headers mbBody expectedStatus = do
rspBody <- vaultRequest manager method_ path_ headers mbBody expectedStatus
case eitherDecode' rspBody of
Left err -> throwIO $ VaultException_ParseBodyError method_ path_ rspBody err
Right x -> pure x
| null | https://raw.githubusercontent.com/bitc/hs-vault-tool/a474f11b94236455a7617b2d9a4eecbe1922ee58/vault-tool/src/Network/VaultTool/Internal.hs | haskell | module Network.VaultTool.Internal where
import Control.Exception (throwIO)
import Control.Monad (when)
import Data.Aeson
import Network.HTTP.Client
import Network.HTTP.Types.Header
import Network.HTTP.Types.Method
import Network.HTTP.Types.Status
import qualified Data.ByteString.Lazy as BL
import Network.VaultTool.Types
vaultRequest :: ToJSON a => Manager -> Method -> String -> RequestHeaders -> Maybe a -> [Int] -> IO BL.ByteString
vaultRequest manager method_ path_ headers mbBody expectedStatus = do
initReq <- case parseRequest path_ of
Nothing -> throwIO $ VaultException_InvalidAddress method_ path_
Just initReq -> pure initReq
let reqBody = case mbBody of
Nothing -> BL.empty
Just b -> encode b
req = initReq
{ method = method_
, requestBody = RequestBodyLBS reqBody
, requestHeaders = requestHeaders initReq ++ headers
}
rsp <- httpLbs req manager
let s = statusCode (responseStatus rsp)
when (not (elem s expectedStatus)) $ do
throwIO $ VaultException_BadStatusCode method_ path_ reqBody s (responseBody rsp)
pure (responseBody rsp)
vaultRequestJSON :: (FromJSON b, ToJSON a) => Manager -> Method -> String -> RequestHeaders -> Maybe a -> [Int] -> IO b
vaultRequestJSON manager method_ path_ headers mbBody expectedStatus = do
rspBody <- vaultRequest manager method_ path_ headers mbBody expectedStatus
case eitherDecode' rspBody of
Left err -> throwIO $ VaultException_ParseBodyError method_ path_ rspBody err
Right x -> pure x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.